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