Skip to main content

quiddity/features/
interior_voids.rs

1//! Interior voids (`quiddity.interior_voids`, `quiddity._interior_void_grid`): enclosed air
2//! inside a solid, found by sampling the solid on a grid of lines cast through the exact B-rep,
3//! then traced to the original faces that bound it and the faces through which it opens.
4
5use std::collections::{BTreeMap, BTreeSet, BinaryHeap, VecDeque};
6
7use serde::Serialize;
8
9use super::Context;
10use super::body::BodyKey;
11use super::evidence::{self, EvidenceError, Occurrence};
12use super::policy::length_tol;
13use super::probes::probe_samples;
14use crate::kernel::brep::Part;
15use crate::kernel::classify::State;
16use crate::kernel::geom::{self, Bounds, COORD_FLOOR, Surface, V3};
17
18const AXES: [V3; 6] = [
19    [1.0, 0.0, 0.0],
20    [-1.0, 0.0, 0.0],
21    [0.0, 1.0, 0.0],
22    [0.0, -1.0, 0.0],
23    [0.0, 0.0, 1.0],
24    [0.0, 0.0, -1.0],
25];
26const CELLS_ON_LONGEST_AXIS: f64 = 64.0;
27/// Fewer cells cannot establish a three-dimensional region.
28const MIN_COMPONENT_SPAN: i64 = 3;
29
30#[derive(Clone, Debug, PartialEq, Serialize)]
31#[non_exhaustive]
32pub struct InteriorVoid {
33    pub body_index: usize,
34    pub body_key: Option<BodyKey>,
35    pub void_faces: Vec<usize>,
36    pub openings: Vec<Vec<usize>>,
37    pub estimated_volume: f64,
38    pub volume_method: &'static str,
39    pub grid_pitch: f64,
40    pub enclosed_samples: usize,
41    pub air_samples: usize,
42}
43
44/// A bounded-air candidate whose sampled throat does not establish an interior chamber.
45/// Retain its complete measurements and source anatomy in the recognition document.
46#[derive(Clone, Debug, PartialEq, Serialize)]
47#[non_exhaustive]
48pub struct InteriorVoidRefusal {
49    #[serde(flatten)]
50    pub candidate: InteriorVoid,
51    pub reason: &'static str,
52}
53
54#[derive(Default)]
55pub(super) struct Analysis {
56    pub accepted: Vec<Occurrence<InteriorVoid>>,
57    pub refusals: Vec<InteriorVoidRefusal>,
58}
59
60/// Keep the grid's historical record slots, replacing sampled sealed skins in place.
61/// Only previously undetected shells are appended, so they cannot renumber existing voids.
62fn with_sealed_shells(mut sampled: Analysis, sealed: Vec<Occurrence<InteriorVoid>>) -> Analysis {
63    let faces: BTreeSet<_> = sealed
64        .iter()
65        .flat_map(|s| s.defining.iter().copied())
66        .collect();
67    let mut emitted = BTreeSet::new();
68    sampled.accepted.retain_mut(|occurrence| {
69        if let Some((index, replacement)) = sealed.iter().enumerate().find(|(_, s)| {
70            s.record.body_index == occurrence.record.body_index && s.defining == occurrence.defining
71        }) {
72            if !emitted.insert(index) {
73                return false;
74            }
75            *occurrence = replacement.clone();
76            true
77        } else {
78            // A coarse component spanning a proved shell and other air cannot own that skin.
79            !occurrence.defining.iter().any(|f| faces.contains(f))
80        }
81    });
82    sampled
83        .refusals
84        .retain(|r| !r.candidate.void_faces.iter().any(|f| faces.contains(f)));
85    sampled.accepted.extend(
86        sealed
87            .into_iter()
88            .enumerate()
89            .filter_map(|(index, occurrence)| (!emitted.contains(&index)).then_some(occurrence)),
90    );
91    sampled
92}
93
94internal_entry! {
95/// `recognise_interior_voids`.
96pub fn recognise_interior_voids(part: &Part) -> Vec<InteriorVoid> {
97    super::records(discover(&Context::new(part)))
98}
99}
100
101type Cell = [i64; 3];
102
103/// The sampled grid (`VoidGrid`): cells are material, air, or neither (no clean evidence).
104struct Grid {
105    origin: V3,
106    pitch: f64,
107    dims: [i64; 3],
108    material: Vec<bool>,
109    air: Vec<bool>,
110    components: Vec<Vec<Cell>>,
111    air_samples: usize,
112}
113
114impl Grid {
115    fn index(&self, c: Cell) -> Option<usize> {
116        let [nx, ny, nz] = self.dims;
117        ((0..nx).contains(&c[0]) && (0..ny).contains(&c[1]) && (0..nz).contains(&c[2]))
118            .then(|| ((c[0] * ny + c[1]) * nz + c[2]) as usize)
119    }
120    fn is_material(&self, c: Cell) -> bool {
121        self.index(c).is_some_and(|i| self.material[i])
122    }
123    fn is_air(&self, c: Cell) -> bool {
124        self.index(c).is_some_and(|i| self.air[i])
125    }
126    fn centre(&self, c: Cell) -> V3 {
127        [0, 1, 2].map(|a| self.origin[a] + (c[a] as f64 + 0.5) * self.pitch)
128    }
129}
130
131fn neighbours(c: Cell) -> [Cell; 6] {
132    let [x, y, z] = c;
133    [
134        [x - 1, y, z],
135        [x + 1, y, z],
136        [x, y - 1, z],
137        [x, y + 1, z],
138        [x, y, z - 1],
139        [x, y, z + 1],
140    ]
141}
142
143/// A box-centred lattice, including stable cell counts at integral pitch ratios.
144fn grid_layout(bounds: &Bounds) -> Option<(V3, f64, [i64; 3])> {
145    let extents = geom::sub(bounds.max, bounds.min);
146    let longest = extents[0].max(extents[1]).max(extents[2]);
147    if !longest.is_finite() || longest <= COORD_FLOOR {
148        return None;
149    }
150    let pitch = longest / CELLS_ON_LONGEST_AXIS;
151    let dims = extents.map(|e| {
152        let cells = e / pitch;
153        let nearest = cells.round();
154        if (cells - nearest).abs() * pitch <= COORD_FLOOR {
155            nearest as i64
156        } else {
157            cells.ceil() as i64
158        }
159    });
160    // Equal padding on both sides makes the sample lattice map onto itself under
161    // axis reversal and interchange, even when an extent is not a multiple of pitch.
162    let origin = [0, 1, 2].map(|a| 0.5 * (bounds.min[a] + bounds.max[a] - dims[a] as f64 * pitch));
163    Some((origin, pitch, dims))
164}
165
166/// `sample_void_grid`: lines along each axis through every cell centre; a cell is material when
167/// all three lines through it say so, air when all three say not, and bounded air when on every
168/// axis there is material on both sides.
169fn sample_grid(ctx: &Context<'_>, solid: usize, bounds: &Bounds) -> Option<Grid> {
170    let (origin, pitch, dims) = grid_layout(bounds)?;
171    let [nx, ny, nz] = dims;
172    let size = (nx * ny * nz) as usize;
173    let (mut valid, mut material_votes, mut bounded_votes) =
174        (vec![0u8; size], vec![0u8; size], vec![0u8; size]);
175    let rays = ctx.solid_rays(solid);
176    let coincidence = length_tol(pitch, 1e-6);
177    for axis in 0..3 {
178        let other: Vec<usize> = (0..3).filter(|&a| a != axis).collect();
179        let dir = [0, 1, 2].map(|a| if a == axis { 1.0 } else { 0.0 });
180        for first in 0..dims[other[0]] {
181            for second in 0..dims[other[1]] {
182                let mut start = [0.0; 3];
183                start[axis] = origin[axis] - pitch;
184                start[other[0]] = origin[other[0]] + (first as f64 + 0.5) * pitch;
185                start[other[1]] = origin[other[1]] + (second as f64 + 0.5) * pitch;
186                let Some(hits) = rays.hits(start, dir, (dims[axis] + 2) as f64 * pitch) else {
187                    continue;
188                };
189                let mut crossings: Vec<f64> = Vec::new();
190                for t in hits.iter().map(|h| h.t).filter(|&t| t > COORD_FLOOR) {
191                    if crossings.last().is_none_or(|&last| t - last > coincidence) {
192                        crossings.push(t);
193                    }
194                }
195                // A generic line through a valid solid crosses it an even number of times; an
196                // odd count is a graze or an edge, and no evidence.
197                if crossings.len() % 2 == 1 {
198                    continue;
199                }
200                for position in 0..dims[axis] {
201                    let distance = (position as f64 + 1.5) * pitch;
202                    if crossings
203                        .iter()
204                        .any(|h| (distance - h).abs() <= coincidence)
205                    {
206                        continue;
207                    }
208                    let mut c = [0i64; 3];
209                    c[axis] = position;
210                    c[other[0]] = first;
211                    c[other[1]] = second;
212                    let i = ((c[0] * ny + c[1]) * nz + c[2]) as usize;
213                    valid[i] += 1;
214                    let before = crossings.partition_point(|&h| h <= distance);
215                    material_votes[i] += (before % 2) as u8;
216                    bounded_votes[i] += u8::from(
217                        !crossings.is_empty()
218                            && crossings[0] < distance
219                            && distance < crossings[crossings.len() - 1],
220                    );
221                }
222            }
223        }
224    }
225    let (mut material, mut air) = (vec![false; size], vec![false; size]);
226    let mut bounded: BTreeSet<Cell> = BTreeSet::new();
227    let mut air_samples = 0;
228    for x in 0..nx {
229        for y in 0..ny {
230            for z in 0..nz {
231                let i = ((x * ny + y) * nz + z) as usize;
232                if valid[i] != 3 {
233                    continue;
234                }
235                if material_votes[i] == 3 {
236                    material[i] = true;
237                } else if material_votes[i] == 0 {
238                    air_samples += 1;
239                    air[i] = true;
240                    if bounded_votes[i] == 3 {
241                        bounded.insert([x, y, z]);
242                    }
243                }
244            }
245        }
246    }
247    Some(Grid {
248        origin,
249        pitch,
250        dims,
251        material,
252        air,
253        components: components(bounded),
254        air_samples,
255    })
256}
257
258/// `_components`: face-connected groups of cells at least three cells across on every axis,
259/// ordered by their smallest cell.
260fn components(mut remaining: BTreeSet<Cell>) -> Vec<Vec<Cell>> {
261    let mut out: Vec<Vec<Cell>> = Vec::new();
262    while let Some(seed) = remaining.pop_first() {
263        let mut found = vec![seed];
264        let mut pending = vec![seed];
265        while let Some(current) = pending.pop() {
266            for n in neighbours(current) {
267                if remaining.remove(&n) {
268                    found.push(n);
269                    pending.push(n);
270                }
271            }
272        }
273        let spans = (0..3).all(|a| {
274            let (lo, hi) = found.iter().fold((i64::MAX, i64::MIN), |(lo, hi), c| {
275                (lo.min(c[a]), hi.max(c[a]))
276            });
277            hi - lo + 1 >= MIN_COMPONENT_SPAN
278        });
279        if spans {
280            found.sort_unstable();
281            out.push(found);
282        }
283    }
284    out.sort_by_key(|c| c[0]);
285    out
286}
287
288/// `expanded_air_components`: the components whose core is wider than every sampled route to
289/// the outside — a cavity behind a throat, not a constant-width pocket.
290fn expanded_components(grid: &Grid) -> BTreeSet<usize> {
291    let [nx, ny, nz] = grid.dims;
292    let cells =
293        || (0..nx).flat_map(move |x| (0..ny).flat_map(move |y| (0..nz).map(move |z| [x, y, z])));
294    // Clearance: the grid distance to material.
295    let mut clearance: BTreeMap<Cell, i64> = BTreeMap::new();
296    let mut pending: VecDeque<Cell> = VecDeque::new();
297    for c in cells().filter(|&c| grid.is_air(c)) {
298        if neighbours(c).iter().any(|&n| grid.is_material(n)) {
299            clearance.insert(c, 1);
300            pending.push_back(c);
301        }
302    }
303    while let Some(c) = pending.pop_front() {
304        let d = clearance[&c] + 1;
305        for n in neighbours(c) {
306            if grid.is_air(n) && !clearance.contains_key(&n) {
307                clearance.insert(n, d);
308                pending.push_back(n);
309            }
310        }
311    }
312    // Widest path from the box boundary: the largest clearance a route in can keep.
313    let infinity = nx.max(ny).max(nz) + 1;
314    let mut widest: BTreeMap<Cell, i64> = BTreeMap::new();
315    let mut frontier: BinaryHeap<(i64, std::cmp::Reverse<Cell>)> = BinaryHeap::new();
316    for c in cells().filter(|&c| grid.is_air(c)) {
317        if c.contains(&0) || c[0] == nx - 1 || c[1] == ny - 1 || c[2] == nz - 1 {
318            widest.insert(c, infinity);
319            frontier.push((infinity, std::cmp::Reverse(c)));
320        }
321    }
322    while let Some((width, std::cmp::Reverse(c))) = frontier.pop() {
323        if width < widest[&c] {
324            continue;
325        }
326        for n in neighbours(c) {
327            let Some(&clear) = clearance.get(&n) else {
328                continue;
329            };
330            if !grid.is_air(n) {
331                continue;
332            }
333            let next = width.min(clear);
334            if next > widest.get(&n).copied().unwrap_or(0) {
335                widest.insert(n, next);
336                frontier.push((next, std::cmp::Reverse(n)));
337            }
338        }
339    }
340    grid.components
341        .iter()
342        .enumerate()
343        .filter(|(_, comp)| {
344            let core = comp
345                .iter()
346                .map(|c| clearance.get(c).copied().unwrap_or(0))
347                .max()
348                .unwrap_or(0);
349            let throat = comp
350                .iter()
351                .map(|c| widest.get(c).copied().unwrap_or(0))
352                .max()
353                .unwrap_or(0);
354            core > 0 && (throat == 0 || core as f64 >= 1.5 * throat as f64)
355        })
356        .map(|(i, _)| i)
357        .collect()
358}
359
360/// `_escapes`: from just outside the face, does some axis (or the face's own cylinder axis)
361/// reach open air? `Some(false)` when every probe was bounded on every direction, `None` when
362/// no probe could be made (or the face's area, which sets the probe offset, is unknown).
363fn escapes(
364    ctx: &Context<'_>,
365    solid: usize,
366    face: usize,
367    pitch: f64,
368    max_distance: f64,
369) -> Option<bool> {
370    let part = ctx.part;
371    let mut directions: Vec<V3> = AXES.to_vec();
372    if let Surface::Cylinder { frame, .. } = part.faces[face].surface {
373        directions.extend([frame.z, geom::scale(frame.z, -1.0)]);
374    }
375    let area = part.face_mass(face)?[0];
376    let offset = (COORD_FLOOR * 10.0).max(pitch.min(area.sqrt()) * 1e-3);
377    let mut bounded_sample = false;
378    for s in probe_samples(part, face) {
379        let Some(normal) = part.face_normal(face, s.uv.0, s.uv.1) else {
380            continue;
381        };
382        let outside: Vec<_> = [-1.0, 1.0]
383            .iter()
384            .map(|sign| geom::add(s.point, geom::scale(normal, sign * offset)))
385            .filter(|&p| ctx.solid_classifier(solid).classify(p) == State::Out)
386            .collect();
387        let [outside] = outside.as_slice() else {
388            continue;
389        };
390        let outside = *outside;
391        let mut all_hit = true;
392        for &dir in &directions {
393            let Some(hits) = ctx.solid_rays(solid).hits(outside, dir, max_distance) else {
394                all_hit = false;
395                continue;
396            };
397            if !hits.iter().any(|h| h.t > 2.0 * offset) {
398                return Some(true);
399            }
400        }
401        bounded_sample |= all_hit;
402    }
403    bounded_sample.then_some(false)
404}
405
406/// `_contact_faces`: from each cell of the component next to material, the first face along
407/// the axis towards it.
408fn contact_faces(
409    ctx: &Context<'_>,
410    solid: usize,
411    component: &[Cell],
412    grid: &Grid,
413) -> Option<BTreeSet<usize>> {
414    let mut found = BTreeSet::new();
415    for &cell in component {
416        let source = grid.centre(cell);
417        for dir in AXES {
418            let n = [0, 1, 2].map(|a| cell[a] + dir[a] as i64);
419            if !grid.is_material(n) {
420                continue;
421            }
422            let hits = ctx.solid_rays(solid).hits(source, dir, grid.pitch)?;
423            let contacts: Vec<_> = hits
424                .iter()
425                .filter(|h| COORD_FLOOR * 10.0 < h.t && h.t < grid.pitch)
426                .map(|h| (h.t, h.face))
427                .collect();
428            let nearest = nearest_contacts(&contacts)?;
429            found.extend(nearest);
430        }
431    }
432    (!found.is_empty()).then_some(found)
433}
434
435/// A ray through a shared boundary may meet several source faces at once. All equally near
436/// faces are evidence of the same contact; neither ray hit order nor face number owns it.
437fn nearest_contacts(hits: &[(f64, usize)]) -> Option<BTreeSet<usize>> {
438    let first = hits.iter().map(|h| h.0).min_by(f64::total_cmp)?;
439    Some(
440        hits.iter()
441            .filter(|h| (h.0 - first).abs() <= COORD_FLOOR)
442            .map(|h| h.1)
443            .collect(),
444    )
445}
446
447/// `_opening_regions`: the faces next to the void's skin but not in it, grouped by adjacency.
448fn opening_regions(
449    skin: &BTreeSet<usize>,
450    adjacent: &BTreeMap<usize, BTreeSet<usize>>,
451) -> Vec<Vec<usize>> {
452    let mut remaining: BTreeSet<usize> = skin
453        .iter()
454        .flat_map(|f| &adjacent[f])
455        .filter(|o| !skin.contains(o))
456        .copied()
457        .collect();
458    let mut regions = Vec::new();
459    while let Some(seed) = remaining.pop_first() {
460        let mut region = BTreeSet::from([seed]);
461        let mut pending = vec![seed];
462        while let Some(f) = pending.pop() {
463            for o in &adjacent[&f] {
464                if remaining.remove(o) {
465                    region.insert(*o);
466                    pending.push(*o);
467                }
468            }
469        }
470        regions.push(region.into_iter().collect::<Vec<_>>());
471    }
472    regions.sort();
473    regions
474}
475
476/// `_region_faces`: grow the seed faces through every neighbour that cannot escape.
477fn region_faces(
478    ctx: &Context<'_>,
479    solid: usize,
480    seeds: &BTreeSet<usize>,
481    adjacent: &BTreeMap<usize, BTreeSet<usize>>,
482    pitch: f64,
483    max_distance: f64,
484) -> Option<(Vec<usize>, Vec<Vec<usize>>)> {
485    let mut skin = seeds.clone();
486    let mut decisions: BTreeMap<usize, Option<bool>> = BTreeMap::new();
487    loop {
488        let boundary: BTreeSet<usize> = skin
489            .iter()
490            .flat_map(|f| &adjacent[f])
491            .filter(|o| !skin.contains(o))
492            .copied()
493            .collect();
494        let mut enclosed = Vec::new();
495        for f in boundary {
496            let d = *decisions
497                .entry(f)
498                .or_insert_with(|| escapes(ctx, solid, f, pitch, max_distance));
499            match d {
500                None => return None,
501                Some(false) => enclosed.push(f),
502                Some(true) => {}
503            }
504        }
505        if enclosed.is_empty() {
506            break;
507        }
508        skin.extend(enclosed);
509    }
510    let openings = opening_regions(&skin, adjacent);
511    Some((skin.into_iter().collect(), openings))
512}
513
514internal_entry! {
515/// The evidence path: each interior void with its faces, published only from one valid solid.
516pub fn discover_verified(
517    ctx: &Context<'_>,
518) -> Result<Vec<Occurrence<InteriorVoid>>, EvidenceError> {
519    evidence::verified(ctx.part, discover(ctx))
520}
521}
522
523internal_entry! {
524/// Every interior void, its skin faces defining it and its opening faces consulted.
525pub fn discover(ctx: &Context<'_>) -> Vec<Occurrence<InteriorVoid>> {
526    analyse(ctx).accepted
527}
528}
529
530pub(super) fn analyse(ctx: &Context<'_>) -> Analysis {
531    let part = ctx.part;
532    let keys = ctx.body_keys(true);
533    let sealed = ctx.sealed_void_shells();
534    let sealed_records: Vec<_> = sealed
535        .iter()
536        .map(|shell| Occurrence {
537            record: InteriorVoid {
538                body_index: shell.solid,
539                body_key: keys[shell.solid].clone(),
540                void_faces: shell.faces.clone(),
541                openings: Vec::new(),
542                estimated_volume: shell.volume,
543                volume_method: "closed_shell",
544                grid_pitch: 0.0,
545                enclosed_samples: 0,
546                air_samples: 0,
547            },
548            defining: shell.faces.clone(),
549            context: Vec::new(),
550        })
551        .collect();
552    let mut out = Vec::new();
553    let mut refusals = Vec::new();
554    for (body_index, key) in keys.into_iter().enumerate() {
555        if !part.solid_is_valid(body_index) {
556            continue;
557        }
558        let faces = &part.solids[body_index].faces;
559        let bounds = part.solid_bounds(body_index);
560        let size = geom::sub(bounds.max, bounds.min);
561        let max_distance = (size[0] * size[0] + size[1] * size[1] + size[2] * size[2]).sqrt() * 2.0;
562        // A cheap original-face witness gates the much larger volume sample.
563        if !faces
564            .iter()
565            .any(|&f| escapes(ctx, body_index, f, max_distance / 64.0, max_distance) == Some(false))
566        {
567            continue;
568        }
569        let Some(grid) = sample_grid(ctx, body_index, &bounds) else {
570            continue;
571        };
572        if grid.components.is_empty() {
573            continue;
574        }
575        let body: BTreeSet<usize> = faces.iter().copied().collect();
576        let adjacent: BTreeMap<usize, BTreeSet<usize>> = faces
577            .iter()
578            .map(|&f| {
579                let n = part
580                    .neighbours(f)
581                    .into_iter()
582                    .filter(|o| body.contains(o))
583                    .collect();
584                (f, n)
585            })
586            .collect();
587        let mut expanded: Option<BTreeSet<usize>> = None;
588        let mut seen: BTreeSet<Vec<usize>> = BTreeSet::new();
589        for (index, component) in grid.components.iter().enumerate() {
590            // Spot-check the grid's parity against the solid itself.
591            let picks: BTreeSet<usize> = [0, component.len() / 2, component.len() - 1].into();
592            if picks.iter().any(|&i| {
593                ctx.solid_classifier(body_index)
594                    .classify(grid.centre(component[i]))
595                    != State::Out
596            }) {
597                continue;
598            }
599            let Some(seeds) = contact_faces(ctx, body_index, component, &grid) else {
600                continue;
601            };
602            if !seeds.is_subset(&body) {
603                continue;
604            }
605            let Some((skin, openings)) =
606                region_faces(ctx, body_index, &seeds, &adjacent, grid.pitch, max_distance)
607            else {
608                continue;
609            };
610            if seen.contains(&skin) {
611                continue;
612            }
613            let record = InteriorVoid {
614                body_index,
615                body_key: key.clone(),
616                void_faces: skin.clone(),
617                openings,
618                estimated_volume: component.len() as f64 * grid.pitch.powf(3.0),
619                volume_method: "six_axis_grid",
620                grid_pitch: grid.pitch,
621                enclosed_samples: component.len(),
622                air_samples: grid.air_samples,
623            };
624            // A curved core can stay broad right to its opening; otherwise require a sampled
625            // widening behind a throat. Refused candidates remain visible, without claiming
626            // recognised geometry or acquiring a feature fingerprint.
627            let spheres = skin
628                .iter()
629                .filter(|&&f| matches!(part.faces[f].surface, Surface::Sphere { .. }))
630                .count();
631            if spheres < 2 && !record.openings.is_empty() {
632                let wide = expanded.get_or_insert_with(|| expanded_components(&grid));
633                if !wide.contains(&index) {
634                    refusals.push(InteriorVoidRefusal {
635                        candidate: record,
636                        reason: "widening_behind_throat_unproved",
637                    });
638                    continue;
639                }
640            }
641            seen.insert(skin.clone());
642            let context: Vec<usize> = record.openings.iter().flatten().copied().collect();
643            out.push(Occurrence {
644                record,
645                defining: skin,
646                context,
647            });
648        }
649    }
650    refusals.sort_by(|a, b| {
651        a.candidate.void_faces.cmp(&b.candidate.void_faces).then(
652            a.candidate
653                .enclosed_samples
654                .cmp(&b.candidate.enclosed_samples),
655        )
656    });
657    with_sealed_shells(
658        Analysis {
659            accepted: out,
660            refusals,
661        },
662        sealed_records,
663    )
664}
665
666#[cfg(test)]
667mod tests {
668    use super::*;
669
670    #[test]
671    fn sampled_void_ids_survive_sealed_replacements_and_new_shells() {
672        let occurrence = |body_index, face, volume_method| Occurrence {
673            record: InteriorVoid {
674                body_index,
675                body_key: None,
676                void_faces: vec![face],
677                openings: if volume_method == "six_axis_grid" {
678                    vec![vec![face + 1]]
679                } else {
680                    vec![]
681                },
682                estimated_volume: 12.0,
683                volume_method,
684                grid_pitch: if volume_method == "six_axis_grid" {
685                    1.0
686                } else {
687                    0.0
688                },
689                enclosed_samples: if volume_method == "six_axis_grid" {
690                    12
691                } else {
692                    0
693                },
694                air_samples: if volume_method == "six_axis_grid" {
695                    24
696                } else {
697                    0
698                },
699            },
700            defining: vec![face],
701            context: Vec::new(),
702        };
703        let open = occurrence(0, 20, "six_axis_grid");
704        let mut sampled_sealed = occurrence(0, 10, "six_axis_grid");
705        sampled_sealed.record.openings.clear();
706        let other_body = occurrence(1, 40, "six_axis_grid");
707        let canonical = occurrence(0, 10, "closed_shell");
708        let unseen = occurrence(0, 5, "closed_shell");
709        let merged = with_sealed_shells(
710            Analysis {
711                accepted: vec![open.clone(), sampled_sealed, other_body.clone()],
712                refusals: Vec::new(),
713            },
714            vec![unseen.clone(), canonical.clone()],
715        );
716        // /0 and /2 remain the old open records; /1 is updated in place. The new
717        // shell is /3 even though it precedes all of them in body/face ordering.
718        assert_eq!(merged.accepted, [open, canonical, other_body, unseen]);
719    }
720
721    #[test]
722    fn lattice_maps_onto_itself_when_a_nonintegral_box_is_turned_over() {
723        let bounds = Bounds {
724            min: [-3.1, -1.7, 0.3],
725            max: [6.4, 2.9, 4.6],
726        };
727        let (o, pitch, dims) = grid_layout(&bounds).unwrap();
728        let translated = Bounds {
729            min: bounds.max.map(|v| 123.456 - v),
730            max: bounds.min.map(|v| 123.456 - v),
731        };
732        let (other, other_pitch, other_dims) = grid_layout(&translated).unwrap();
733        assert_eq!(dims, other_dims);
734        assert!((pitch - other_pitch).abs() < 1e-12);
735        for axis in 0..3 {
736            for cell in 0..dims[axis] {
737                let point = o[axis] + (cell as f64 + 0.5) * pitch;
738                let mirrored = other[axis] + (dims[axis] as f64 - cell as f64 - 0.5) * other_pitch;
739                assert!((point + mirrored - 123.456).abs() < 1e-12);
740            }
741        }
742    }
743}
744
745#[cfg(test)]
746mod contact_tie_tests {
747    use super::*;
748    #[test]
749    fn equal_contact_faces_survive_motion_and_hit_permutation() {
750        for angle in [0_f64, 30., 90.] {
751            let (s, c) = angle.to_radians().sin_cos();
752            let moved = |p: V3| {
753                [
754                    c * p[0] - s * p[1] + 123.456,
755                    s * p[0] + c * p[1] - 78.9,
756                    p[2] + 41.3,
757                ]
758            };
759            let origin = moved([0.; 3]);
760            let contact = moved([1., 0., 0.]);
761            let distance = geom::dist(origin, contact);
762            let mut hits = vec![(distance, 7), (distance, 2), (distance + 1., 5)];
763            assert_eq!(nearest_contacts(&hits), Some(BTreeSet::from([2, 7])));
764            hits.reverse();
765            assert_eq!(nearest_contacts(&hits), Some(BTreeSet::from([2, 7])));
766        }
767    }
768}