Skip to main content

nsi_intermediate/resolve/weld/
mod.rs

1//! Weld declarations: which boundaries of which surfaces are one edge.
2//!
3//! The ɴsɪ draft [Shared Boundaries: Weld Declarations][draft] has a
4//! `weld` node act as a namespace. Each geometry connected to one carries
5//! a table of *boundary uses*; two uses with the same `(weld node, id)`
6//! are one joined boundary. This module reads and validates those tables
7//! and groups the uses. How a join survives tessellation is the
8//! tessellator's business -- see `nsi-tessellate`.
9//!
10//! [draft]: https://nsi.readthedocs.io/en/latest/design/shared-boundaries.html
11
12use super::*;
13use core::fmt;
14
15/// The attribute a geometry's `weld` connection arrives on.
16const WELD: &str = "weld";
17
18/// Which boundary a segment selects.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20#[non_exhaustive]
21pub enum WeldKind {
22    /// A complete trim loop of a `nurbs` node, in its stored curve order.
23    TrimLoop {
24        /// The loop, counted over `trimcurves.ncurves`.
25        loop_index: usize,
26    },
27    /// One curve in the flattened trim-curve arrays of a `nurbs` node.
28    TrimCurve {
29        /// The curve, counted over all loops.
30        curve_index: usize,
31    },
32    /// One side of a `nurbs` node's active domain.
33    NurbsSide {
34        /// Which side.
35        side: NurbsSide,
36    },
37    /// One directed edge of a polygon or subdivision `mesh` face.
38    MeshEdge {
39        /// The face.
40        face_index: usize,
41        /// The face's loop: 0 is the outer perimeter, later loops holes.
42        loop_index: usize,
43        /// The edge, from a loop vertex to the next one.
44        edge_index: usize,
45    },
46}
47
48/// A side of a `nurbs` node's active parametric domain.
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
50pub enum NurbsSide {
51    /// Where `u` is smallest; runs along increasing `v`.
52    UMin,
53    /// Where `u` is largest; runs along increasing `v`.
54    UMax,
55    /// Where `v` is smallest; runs along increasing `u`.
56    VMin,
57    /// Where `v` is largest; runs along increasing `u`.
58    VMax,
59}
60
61/// One segment of a boundary use.
62#[derive(Debug, Clone, Copy, PartialEq)]
63pub struct WeldSegment {
64    /// What the segment selects.
65    pub kind: WeldKind,
66    /// Whether the segment is traversed against its own direction.
67    pub reverse: bool,
68    /// The selected portion, normalized to `[0, 1]` over the selected
69    /// curve or edge, before reversal. `[0, 1]` is all of it.
70    pub range: [f32; 2],
71}
72
73/// One boundary use: a connected, ordered chain on one geometry.
74#[derive(Debug, Clone, PartialEq)]
75pub struct WeldUse<'a> {
76    /// The geometry the chain lies on.
77    pub geometry: &'a str,
78    /// The `weld` node whose namespace `id` belongs to.
79    pub weld: &'a str,
80    /// The identity within that namespace.
81    pub id: u32,
82    /// The use's position in its geometry's table.
83    pub use_index: usize,
84    /// The chain, in order.
85    pub segments: Vec<WeldSegment>,
86}
87
88/// One joined boundary: every use that shares a `(weld node, id)`.
89#[derive(Debug, Clone, PartialEq)]
90pub struct Weld<'a> {
91    /// The namespace.
92    pub weld: &'a str,
93    /// The identity within it.
94    pub id: u32,
95    /// The uses, in scene order.
96    pub uses: Vec<WeldUse<'a>>,
97}
98
99impl Weld<'_> {
100    /// A use without a counterpart: it joins nothing by itself.
101    pub fn is_open(&self) -> bool {
102        self.uses.len() < 2
103    }
104
105    /// More than two uses: a non-manifold join.
106    pub fn is_non_manifold(&self) -> bool {
107        2 < self.uses.len()
108    }
109}
110
111/// A geometry's weld table, read and checked.
112#[derive(Debug, Clone, Default, PartialEq)]
113pub struct WeldTable<'a> {
114    /// The valid uses.
115    pub uses: Vec<WeldUse<'a>>,
116    /// Everything wrong with the table. A problem that invalidates a
117    /// use drops that use; see [`WeldProblem::drops_use`].
118    pub problems: Vec<WeldProblem<'a>>,
119}
120
121/// Every joined boundary in a scene.
122#[derive(Debug, Clone, Default, PartialEq)]
123pub struct Welds<'a> {
124    /// The joined boundaries, grouped by `(weld node, id)`.
125    pub welds: Vec<Weld<'a>>,
126    /// Every problem found in any geometry's table.
127    pub problems: Vec<WeldProblem<'a>>,
128}
129
130/// Something wrong with a weld table.
131#[derive(Debug, Clone, PartialEq)]
132pub struct WeldProblem<'a> {
133    /// The geometry whose table it is.
134    pub geometry: &'a str,
135    /// The use, when the problem is in one.
136    pub use_index: Option<usize>,
137    /// What is wrong.
138    pub kind: WeldProblemKind,
139}
140
141/// What is wrong with a weld table.
142#[derive(Debug, Clone, PartialEq)]
143#[non_exhaustive]
144pub enum WeldProblemKind {
145    /// The draft allows one `weld` connection per geometry.
146    SeveralWeldNodes {
147        /// How many there are.
148        count: usize,
149    },
150    /// Weld attributes, but no `weld` connection to give their ids a
151    /// namespace.
152    NoWeldNode,
153    /// A table attribute is missing, of the wrong type, or has the wrong
154    /// number of values.
155    BadAttribute {
156        /// The attribute.
157        attribute: &'static str,
158        /// The number of values it should have, if it has another.
159        expected: Option<usize>,
160    },
161    /// A negative id.
162    NegativeId {
163        /// The id.
164        id: i32,
165    },
166    /// A use with no segments.
167    EmptyUse,
168    /// A `weld.kind` the draft does not define, or one the geometry's
169    /// type cannot have.
170    UnknownKind {
171        /// The kind as written.
172        kind: String,
173    },
174    /// A `weld.index` that selects nothing on this geometry.
175    BadIndex {
176        /// The index as written.
177        index: [i32; 3],
178    },
179    /// A `weld.range` outside `[0, 1]`, or empty.
180    BadRange {
181        /// The range as written.
182        range: [f32; 2],
183    },
184    /// A `trim-loop` segment that is not a complete use on its own: it
185    /// has company, or a partial range.
186    PartialLoop,
187    /// Consecutive segments that do not meet.
188    NotConnected {
189        /// The segment that does not continue the one before it.
190        segment: usize,
191    },
192    /// A chain whose connectivity cannot be checked from topology --
193    /// segments of different kinds, of different trim loops, or partial
194    /// ranges. The use is kept.
195    ConnectivityUnverified,
196}
197
198impl WeldProblem<'_> {
199    /// Whether the problem makes the use unusable, so it is not in
200    /// [`WeldTable::uses`].
201    pub fn drops_use(&self) -> bool {
202        !matches!(self.kind, WeldProblemKind::ConnectivityUnverified)
203    }
204}
205
206impl fmt::Display for WeldProblem<'_> {
207    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
208        write!(f, "ɴsɪ weld table on {:?}", self.geometry)?;
209        if let Some(index) = self.use_index {
210            write!(f, ", use {index}")?;
211        }
212        f.write_str(": ")?;
213        match &self.kind {
214            WeldProblemKind::SeveralWeldNodes { count } => write!(
215                f,
216                "{count} weld connections; a geometry takes one namespace"
217            ),
218            WeldProblemKind::NoWeldNode => f.write_str(
219                "weld attributes without a weld connection; the ids have no \
220                 namespace",
221            ),
222            WeldProblemKind::BadAttribute {
223                attribute,
224                expected: Some(expected),
225            } => write!(f, "{attribute:?} should have {expected} values"),
226            WeldProblemKind::BadAttribute {
227                attribute,
228                expected: None,
229            } => write!(f, "{attribute:?} is missing or of the wrong type"),
230            WeldProblemKind::NegativeId { id } => {
231                write!(f, "id {id} is negative")
232            }
233            WeldProblemKind::EmptyUse => f.write_str("the use has no segments"),
234            WeldProblemKind::UnknownKind { kind } => {
235                write!(f, "{kind:?} is not a boundary this geometry has")
236            }
237            WeldProblemKind::BadIndex { index } => {
238                write!(f, "index {index:?} selects nothing on this geometry")
239            }
240            WeldProblemKind::BadRange { range } => {
241                write!(f, "range {range:?} is not a sub-interval of [0, 1]")
242            }
243            WeldProblemKind::PartialLoop => f.write_str(
244                "a trim-loop segment must be a whole use with its full range",
245            ),
246            WeldProblemKind::NotConnected { segment } => write!(
247                f,
248                "segment {segment} does not continue the chain before it"
249            ),
250            WeldProblemKind::ConnectivityUnverified => f.write_str(
251                "the chain's connectivity cannot be checked from topology; \
252                 kept as declared",
253            ),
254        }
255    }
256}
257
258/// What a geometry has that a segment can select.
259enum Boundaries {
260    Nurbs {
261        /// Curves per trim loop, `trimcurves.ncurves`.
262        curves_per_loop: Vec<usize>,
263    },
264    Mesh {
265        /// Per face, the vertex count of each of its loops.
266        loops_per_face: Vec<Vec<usize>>,
267    },
268    None,
269}
270
271impl Boundaries {
272    fn of(node: &Node) -> Self {
273        let counts = |name: &str| {
274            node.attribute(name).and_then(OwnedArgument::as_i32s).map(
275                |values| {
276                    values
277                        .iter()
278                        .map(|&v| v.max(0) as usize)
279                        .collect::<Vec<_>>()
280                },
281            )
282        };
283        match node.node_type() {
284            "nurbs" => Self::Nurbs {
285                curves_per_loop: counts("trim-curves.curve-count")
286                    .unwrap_or_default(),
287            },
288            "mesh" => {
289                let vertices = counts("vertex-count").unwrap_or_default();
290                let loops_per_face = match counts("hole-count") {
291                    // With holes, each face takes its outer perimeter
292                    // plus one count per hole.
293                    Some(holes) => {
294                        let mut counts = vertices.into_iter();
295                        holes
296                            .into_iter()
297                            .map(|holes| {
298                                counts.by_ref().take(holes + 1).collect()
299                            })
300                            .collect()
301                    }
302                    None => {
303                        vertices.into_iter().map(|count| vec![count]).collect()
304                    }
305                };
306                Self::Mesh { loops_per_face }
307            }
308            _ => Self::None,
309        }
310    }
311
312    /// The segment kind `kind` with `index`, if this geometry has it.
313    fn select(
314        &self,
315        kind: &[u8],
316        index: [i32; 3],
317    ) -> Result<WeldKind, WeldProblemKind> {
318        let unknown = || WeldProblemKind::UnknownKind {
319            kind: String::from_utf8_lossy(kind).into_owned(),
320        };
321        let bad = || WeldProblemKind::BadIndex { index };
322        let at = |position: usize| {
323            usize::try_from(index[position]).map_err(|_| bad())
324        };
325        let unused_zero = |from: usize| {
326            if index[from..].iter().all(|&v| v == 0) {
327                Ok(())
328            } else {
329                Err(bad())
330            }
331        };
332
333        match (self, kind) {
334            (Self::Nurbs { curves_per_loop }, b"trim-loop") => {
335                let loop_index = at(0)?;
336                unused_zero(1)?;
337                (loop_index < curves_per_loop.len())
338                    .then_some(WeldKind::TrimLoop { loop_index })
339                    .ok_or_else(bad)
340            }
341            (Self::Nurbs { curves_per_loop }, b"trim-curve") => {
342                let curve_index = at(0)?;
343                unused_zero(1)?;
344                (curve_index < curves_per_loop.iter().sum())
345                    .then_some(WeldKind::TrimCurve { curve_index })
346                    .ok_or_else(bad)
347            }
348            (Self::Nurbs { .. }, b"nurbs-side") => {
349                unused_zero(1)?;
350                let side = match at(0)? {
351                    0 => NurbsSide::UMin,
352                    1 => NurbsSide::UMax,
353                    2 => NurbsSide::VMin,
354                    3 => NurbsSide::VMax,
355                    _ => return Err(bad()),
356                };
357                Ok(WeldKind::NurbsSide { side })
358            }
359            (Self::Mesh { loops_per_face }, b"mesh-edge") => {
360                let (face_index, loop_index, edge_index) =
361                    (at(0)?, at(1)?, at(2)?);
362                let vertices = loops_per_face
363                    .get(face_index)
364                    .and_then(|loops| loops.get(loop_index))
365                    .ok_or_else(bad)?;
366                (edge_index < *vertices)
367                    .then_some(WeldKind::MeshEdge {
368                        face_index,
369                        loop_index,
370                        edge_index,
371                    })
372                    .ok_or_else(bad)
373            }
374            _ => Err(unknown()),
375        }
376    }
377
378    /// The loop a trim curve belongs to, and the loop's first curve and
379    /// length.
380    fn loop_of(&self, curve_index: usize) -> Option<(usize, usize, usize)> {
381        let Self::Nurbs { curves_per_loop } = self else {
382            return None;
383        };
384        let mut first = 0;
385        for (loop_index, &count) in curves_per_loop.iter().enumerate() {
386            if curve_index < first + count {
387                return Some((loop_index, first, count));
388            }
389            first += count;
390        }
391        None
392    }
393}
394
395/// Whether `next` continues `previous` in a chain of whole trim curves
396/// of one loop: the next curve along the loop, or the previous one when
397/// both are reversed, with wraparound.
398fn trim_curves_continue(
399    boundaries: &Boundaries,
400    previous: &WeldSegment,
401    next: &WeldSegment,
402) -> Option<bool> {
403    let (
404        WeldKind::TrimCurve { curve_index: a },
405        WeldKind::TrimCurve { curve_index: b },
406    ) = (previous.kind, next.kind)
407    else {
408        return None;
409    };
410    let whole = |segment: &WeldSegment| segment.range == [0.0, 1.0];
411    let (loop_a, first, count) = boundaries.loop_of(a)?;
412    let (loop_b, ..) = boundaries.loop_of(b)?;
413    if loop_a != loop_b
414        || !whole(previous)
415        || !whole(next)
416        || previous.reverse != next.reverse
417    {
418        return None;
419    }
420    let step = |from: usize, forward: bool| {
421        let local = from - first;
422        first
423            + if forward {
424                (local + 1) % count
425            } else {
426                (local + count - 1) % count
427            }
428    };
429    Some(b == step(a, !previous.reverse))
430}
431
432impl Scene {
433    /// The weld table of `geometry`, read and checked against the
434    /// geometry's own boundaries.
435    ///
436    /// Empty, with no problems, for a geometry that declares no welds.
437    pub fn weld_table(&self, geometry: &str) -> WeldTable<'_> {
438        let Some((handle, node)) = self.node_entry(geometry) else {
439            return WeldTable::default();
440        };
441        let mut uses = Vec::new();
442        let mut problems = Vec::new();
443        // A macro rather than a closure: a closure would hold `problems`
444        // borrowed across the whole function.
445        macro_rules! problem {
446            ($use_index: expr, $kind: expr $(,)?) => {
447                problems.push(WeldProblem {
448                    geometry: handle,
449                    use_index: $use_index,
450                    kind: $kind,
451                })
452            };
453        }
454        // Every early exit hands back what was found so far.
455        macro_rules! done {
456            () => {
457                return WeldTable { uses, problems }
458            };
459        }
460
461        let ids = node.attribute("weld.id");
462        let welds = self
463            .edges_to_attribute(handle, WELD)
464            .filter(|edge| edge.kind == EdgeKind::Weld)
465            .collect::<Vec<_>>();
466
467        // No table: nothing declared. A `weld` connection without one is a
468        // namespace with nothing in it, which is harmless.
469        let Some(ids) = ids else { done!() };
470        let weld = match welds.as_slice() {
471            [weld] => weld.from(),
472            [] => {
473                problem!(None, WeldProblemKind::NoWeldNode);
474                done!();
475            }
476            several => {
477                problem!(
478                    None,
479                    WeldProblemKind::SeveralWeldNodes {
480                        count: several.len(),
481                    },
482                );
483                done!();
484            }
485        };
486
487        let Some(ids) = ids.as_i32s() else {
488            problem!(
489                None,
490                WeldProblemKind::BadAttribute {
491                    attribute: "weld.id",
492                    expected: None,
493                },
494            );
495            done!();
496        };
497        let use_count = ids.len();
498
499        let counts = match node.attribute("weld.segment-count") {
500            None => vec![1; use_count],
501            Some(counts) => match counts.as_i32s() {
502                Some(values) if values.len() == use_count => {
503                    values.iter().map(|&v| v.max(0) as usize).collect()
504                }
505                _ => {
506                    problem!(
507                        None,
508                        WeldProblemKind::BadAttribute {
509                            attribute: "weld.segment-count",
510                            expected: Some(use_count),
511                        },
512                    );
513                    done!();
514                }
515            },
516        };
517        let segments: usize = counts.iter().sum();
518
519        let kinds = node
520            .attribute("weld.kind")
521            .and_then(OwnedArgument::as_strings);
522        let Some(kinds) = kinds.filter(|kinds| kinds.len() == segments) else {
523            problem!(
524                None,
525                WeldProblemKind::BadAttribute {
526                    attribute: "weld.kind",
527                    expected: Some(segments),
528                },
529            );
530            done!();
531        };
532        let indices = node
533            .attribute("weld.index")
534            .and_then(OwnedArgument::as_i32s);
535        let Some(indices) =
536            indices.filter(|indices| indices.len() == 3 * segments)
537        else {
538            problem!(
539                None,
540                WeldProblemKind::BadAttribute {
541                    attribute: "weld.index",
542                    expected: Some(segments),
543                },
544            );
545            done!();
546        };
547        let reverse = match node.attribute("weld.reverse") {
548            None => vec![0; segments],
549            Some(values) => match values.as_i32s() {
550                Some(values) if values.len() == segments => values.to_vec(),
551                _ => {
552                    problem!(
553                        None,
554                        WeldProblemKind::BadAttribute {
555                            attribute: "weld.reverse",
556                            expected: Some(segments),
557                        },
558                    );
559                    done!();
560                }
561            },
562        };
563        let ranges = match node.attribute("weld.range") {
564            None => [0.0, 1.0].repeat(segments),
565            Some(values) => match values.as_f32s() {
566                Some(values) if values.len() == 2 * segments => values.to_vec(),
567                _ => {
568                    problem!(
569                        None,
570                        WeldProblemKind::BadAttribute {
571                            attribute: "weld.range",
572                            expected: Some(segments),
573                        },
574                    );
575                    done!();
576                }
577            },
578        };
579
580        let boundaries = Boundaries::of(node);
581        let mut first_segment = 0;
582        for (use_index, (&id, &count)) in ids.iter().zip(&counts).enumerate() {
583            let span = first_segment..first_segment + count;
584            first_segment += count;
585
586            let Ok(id) = u32::try_from(id) else {
587                problem!(Some(use_index), WeldProblemKind::NegativeId { id });
588                continue;
589            };
590            if count == 0 {
591                problem!(Some(use_index), WeldProblemKind::EmptyUse);
592                continue;
593            }
594
595            let mut chain = Vec::with_capacity(count);
596            let mut invalid = None;
597            for segment in span {
598                let index = [
599                    indices[3 * segment],
600                    indices[3 * segment + 1],
601                    indices[3 * segment + 2],
602                ];
603                let range = [ranges[2 * segment], ranges[2 * segment + 1]];
604                let kind = match boundaries.select(&kinds[segment], index) {
605                    Ok(kind) => kind,
606                    Err(kind) => {
607                        invalid = Some(kind);
608                        break;
609                    }
610                };
611                if !(0.0..=1.0).contains(&range[0])
612                    || !(0.0..=1.0).contains(&range[1])
613                    || range[0] >= range[1]
614                {
615                    invalid = Some(WeldProblemKind::BadRange { range });
616                    break;
617                }
618                chain.push(WeldSegment {
619                    kind,
620                    reverse: reverse[segment] != 0,
621                    range,
622                });
623            }
624            if let Some(kind) = invalid {
625                problem!(Some(use_index), kind);
626                continue;
627            }
628
629            // A closed loop is a complete use.
630            let partial_loop = chain.iter().any(|segment| {
631                matches!(segment.kind, WeldKind::TrimLoop { .. })
632                    && (1 < chain.len() || segment.range != [0.0, 1.0])
633            });
634            if partial_loop {
635                problem!(Some(use_index), WeldProblemKind::PartialLoop);
636                continue;
637            }
638
639            let mut unverified = false;
640            let mut broken = None;
641            for (position, pair) in chain.windows(2).enumerate() {
642                match trim_curves_continue(&boundaries, &pair[0], &pair[1]) {
643                    Some(true) => {}
644                    Some(false) => {
645                        broken = Some(position + 1);
646                        break;
647                    }
648                    None => unverified = true,
649                }
650            }
651            if let Some(segment) = broken {
652                problem!(
653                    Some(use_index),
654                    WeldProblemKind::NotConnected { segment },
655                );
656                continue;
657            }
658            if unverified {
659                problem!(
660                    Some(use_index),
661                    WeldProblemKind::ConnectivityUnverified,
662                );
663            }
664
665            uses.push(WeldUse {
666                geometry: handle,
667                weld,
668                id,
669                use_index,
670                segments: chain,
671            });
672        }
673        WeldTable { uses, problems }
674    }
675
676    /// Every joined boundary in the scene, grouped by `(weld node, id)`,
677    /// with every problem in every geometry's table.
678    pub fn welds(&self) -> Welds<'_> {
679        let mut welds = Welds::default();
680        // A scene can hold tens of thousands of joins; find each group by
681        // key rather than by scanning the groups found so far.
682        let mut position = crate::HashMap::<(&str, u32), usize>::default();
683        for (handle, _) in self.nodes() {
684            let table = self.weld_table(handle);
685            welds.problems.extend(table.problems);
686            for weld_use in table.uses {
687                let key = (weld_use.weld, weld_use.id);
688                match position.get(&key) {
689                    Some(&index) => welds.welds[index].uses.push(weld_use),
690                    None => {
691                        position.insert(key, welds.welds.len());
692                        welds.welds.push(Weld {
693                            weld: weld_use.weld,
694                            id: weld_use.id,
695                            uses: vec![weld_use],
696                        });
697                    }
698                }
699            }
700        }
701        welds
702    }
703}
704
705#[cfg(test)]
706mod tests;