Skip to main content

brep_kernel/meshing/watertight_tessellation/
stride_encode.rs

1use super::*;
2
3/// Tessellate only the faces whose global sequential index `i` satisfies
4/// `i % stride == offset`, leaving every other face out of the returned mesh.
5///
6/// This exists so a large solid can be meshed in parallel across several
7/// worker WASM instances: dispatch `stride` calls with `offset` 0..stride-1
8/// and concatenate the fragments. Two properties make that safe:
9///  - Edge samples are recomputed here from the solid and are DETERMINISTIC
10///    (interior points from `curve.evaluate`, endpoints pinned to the exact
11///    shared vertex-record points), so two workers meshing disjoint face sets
12///    produce byte-identical boundary vertices that weld into a watertight
13///    whole — the same guarantee the single-call path relies on.
14///  - The union over `offset` 0..stride-1 is exactly the set of all faces, so
15///    coverage is complete even when the caller's face count is a stale
16///    estimate (the caller only needs to pick `stride`, never an exact range).
17///
18/// Sequential face ids are assigned over ALL faces (not just the meshed ones),
19/// so a fragment's `face_ids` match the single-call output for the same solid.
20/// Unlike [`tessellate_brep_watertight`] this does NOT validate the mesh — a
21/// face subset is not a closed shell; validate after concatenation.
22pub fn tessellate_brep_watertight_face_stride(
23    solid: &BrepSolid,
24    chord_tolerance: f64,
25    stride: usize,
26    offset: usize,
27) -> Result<Mesh, String> {
28    if !(chord_tolerance > 0.0) || !chord_tolerance.is_finite() {
29        return Err("tessellate_brep_watertight: chord tolerance must be positive".into());
30    }
31    let samples = sample_all_edges(solid, chord_tolerance)?;
32    tessellate_faces_stride(solid, &samples, chord_tolerance, stride, offset)
33}
34
35/// As [`tessellate_brep_watertight_face_stride`], but the caller supplies edge
36/// samples already computed (and serialized) by [`sample_edges_encoded`]. The
37/// worker-pool split uses this so `sample_all_edges` runs ONCE (in the prepare
38/// step) instead of redundantly in every face-range worker. The samples are
39/// deterministic, so meshing against a shared copy is identical to recomputing
40/// them locally.
41pub fn tessellate_brep_watertight_face_stride_with_samples(
42    solid: &BrepSolid,
43    chord_tolerance: f64,
44    stride: usize,
45    offset: usize,
46    encoded_samples: &[f64],
47) -> Result<Mesh, String> {
48    if !(chord_tolerance > 0.0) || !chord_tolerance.is_finite() {
49        return Err("tessellate_brep_watertight: chord tolerance must be positive".into());
50    }
51    let samples = decode_edge_samples(encoded_samples)?;
52    tessellate_faces_stride(solid, &samples, chord_tolerance, stride, offset)
53}
54
55/// A `(face_id, &FaceRecord)` that can cross rayon worker threads.
56///
57/// SAFETY: `FaceRecord` is `!Sync` only because its owned `NurbsSurface`
58/// memoizes derived data (analytic carrier, seam closure, projection grid) in
59/// `Cell`/`OnceCell` acceleration caches. Those caches live INSIDE each face's
60/// own surface (surfaces are stored inline per face, never shared or `Rc`'d),
61/// and `tessellate_faces_stride` hands each face to exactly one rayon task, so
62/// no cache is ever read or written by two threads at once. The only other
63/// shared input is the edge-sample map, which is immutable and free of interior
64/// mutability. Under those invariants sharing `&FaceRecord` across threads is
65/// sound; if faces ever come to share a surface, revisit this.
66#[cfg(feature = "parallel")]
67pub(super) struct SyncFace<'a>(u32, &'a FaceRecord);
68#[cfg(feature = "parallel")]
69unsafe impl Sync for SyncFace<'_> {}
70
71/// Mesh the faces of the stride/offset class against a shared edge-sample map.
72///
73/// Each face is meshed into its OWN fragment and the fragments are concatenated
74/// in face order — bit-identical to folding them one after another into a
75/// single mesh (a face's triangle indices are relative to its fragment's own
76/// vertex base, which the concat re-bases exactly as the sequential fold did).
77/// Because the fragments are independent, the map is a rayon `par_iter` under
78/// the `parallel` feature (shared-memory in-process threading), and an ordinary
79/// serial map otherwise — the DEFAULT build is unchanged.
80pub(super) fn tessellate_faces_stride(
81    solid: &BrepSolid,
82    samples: &HashMap<u64, EdgeSamples>,
83    chord_tolerance: f64,
84    stride: usize,
85    offset: usize,
86) -> Result<Mesh, String> {
87    let stride = stride.max(1);
88    let offset = offset % stride;
89    let mut work: Vec<(u32, &FaceRecord)> = Vec::new();
90    let mut sequential_face_id = 0u32;
91    for shell in &solid.shells {
92        for face in &shell.faces {
93            if (sequential_face_id as usize) % stride == offset {
94                work.push((sequential_face_id, face));
95            }
96            sequential_face_id += 1;
97        }
98    }
99    let mesh_one = |face_id: u32, face: &FaceRecord| -> Result<Mesh, String> {
100        let mut fragment = Mesh::default();
101        tessellate_face_watertight(face, samples, chord_tolerance, face_id, &mut fragment)?;
102        Ok(fragment)
103    };
104    #[cfg(feature = "parallel")]
105    let fragments = {
106        use rayon::prelude::*;
107        let sync_work: Vec<SyncFace> = work.iter().map(|&(id, face)| SyncFace(id, face)).collect();
108        sync_work
109            .par_iter()
110            .map(|face| mesh_one(face.0, face.1))
111            .collect::<Result<Vec<Mesh>, String>>()?
112    };
113    #[cfg(not(feature = "parallel"))]
114    let fragments = work
115        .iter()
116        .map(|&(id, face)| mesh_one(id, face))
117        .collect::<Result<Vec<Mesh>, String>>()?;
118    Ok(concatenate_meshes(fragments))
119}
120
121/// Concatenate mesh fragments in order, re-basing each fragment's triangle
122/// indices by the running vertex count (same math as the worker-split weld).
123pub(super) fn concatenate_meshes(fragments: Vec<Mesh>) -> Mesh {
124    let mut mesh = Mesh::default();
125    for fragment in fragments {
126        let base = (mesh.positions.len() / 3) as u32;
127        mesh.positions.extend_from_slice(&fragment.positions);
128        mesh.normals.extend_from_slice(&fragment.normals);
129        mesh.indices
130            .extend(fragment.indices.iter().map(|index| index + base));
131        mesh.face_ids.extend_from_slice(&fragment.face_ids);
132    }
133    mesh
134}
135
136/// Display edge polylines for native in-process consumers (brep-render): every
137/// NON-degenerate edge's chord-tolerance samples as `(edge_id, points)`, sorted
138/// by edge id so the output is deterministic (the sample map is a HashMap).
139/// The samples are the same shared samples the watertight tessellation uses, so
140/// the displayed edges lie exactly on the mesh's face boundaries.
141pub fn sample_edge_polylines(
142    solid: &BrepSolid,
143    chord_tolerance: f64,
144) -> Result<Vec<(u64, Vec<Vec3>)>, String> {
145    if !(chord_tolerance > 0.0) || !chord_tolerance.is_finite() {
146        return Err("tessellate_brep_watertight: chord tolerance must be positive".into());
147    }
148    let samples = sample_all_edges(solid, chord_tolerance)?;
149    let degenerate: std::collections::HashSet<u64> = solid
150        .edges
151        .iter()
152        .filter(|edge| edge.degenerate)
153        .map(|edge| edge.id)
154        .collect();
155    let mut out: Vec<(u64, Vec<Vec3>)> = samples
156        .into_iter()
157        .filter(|(id, samples)| !degenerate.contains(id) && samples.positions.len() >= 2)
158        .map(|(id, samples)| (id, samples.positions))
159        .collect();
160    out.sort_by_key(|(id, _)| *id);
161    Ok(out)
162}
163
164/// Compute every edge's shared samples and serialize them into a flat f64
165/// buffer for transfer to face-range workers. Layout:
166/// `[edge_count, (edge_id, sample_count, frac_0..n, x_0,y_0,z_0, ...), ...]`
167/// (`fractions.len() == positions.len()`, so one count per edge). Edge ids ride
168/// as f64 exactly as the solid codec already carries them.
169pub fn sample_edges_encoded(solid: &BrepSolid, chord_tolerance: f64) -> Result<Vec<f64>, String> {
170    if !(chord_tolerance > 0.0) || !chord_tolerance.is_finite() {
171        return Err("tessellate_brep_watertight: chord tolerance must be positive".into());
172    }
173    let samples = sample_all_edges(solid, chord_tolerance)?;
174    Ok(encode_edge_samples(&samples))
175}
176
177pub(super) fn encode_edge_samples(samples: &HashMap<u64, EdgeSamples>) -> Vec<f64> {
178    let mut out = Vec::new();
179    out.push(samples.len() as f64);
180    for (edge_id, edge) in samples {
181        out.push(*edge_id as f64);
182        out.push(edge.fractions.len() as f64);
183        out.extend_from_slice(&edge.fractions);
184        for position in &edge.positions {
185            out.push(position.x);
186            out.push(position.y);
187            out.push(position.z);
188        }
189    }
190    out
191}
192
193pub(super) fn decode_edge_samples(data: &[f64]) -> Result<HashMap<u64, EdgeSamples>, String> {
194    let mut cursor = 0usize;
195    let mut take = |count: usize| -> Result<&[f64], String> {
196        let end = cursor
197            .checked_add(count)
198            .filter(|end| *end <= data.len())
199            .ok_or("watertight tessellation: truncated edge-sample buffer")?;
200        let slice = &data[cursor..end];
201        cursor = end;
202        Ok(slice)
203    };
204    let edge_count = take(1)?[0] as usize;
205    let mut samples = HashMap::with_capacity(edge_count);
206    for _ in 0..edge_count {
207        let header = take(2)?;
208        let edge_id = header[0] as u64;
209        let sample_count = header[1] as usize;
210        let fractions = take(sample_count)?.to_vec();
211        let position_values = take(sample_count * 3)?;
212        let positions = position_values
213            .chunks_exact(3)
214            .map(|chunk| Vec3::new(chunk[0], chunk[1], chunk[2]))
215            .collect();
216        samples.insert(
217            edge_id,
218            EdgeSamples {
219                fractions,
220                positions,
221            },
222        );
223    }
224    Ok(samples)
225}