Skip to main content

brep_topology/brep/
solid_codec.rs

1//! Flat `f64` binary encoding of a `BrepSolid` for zero-JSON WASM transfer.
2//!
3//! Every numeric field of the topology (ids, flags, knots, weighted control
4//! points) is written into one `Vec<f64>` in a fixed traversal order; the
5//! only non-numeric payload — face/edge names — travels in a tiny JSON side
6//! channel keyed by entity id.  The decoder reads the same layout
7//! straight out of a `Float64Array`, replacing `JSON.parse` of megabyte-scale
8//! numeric text with sequential typed-array reads.
9//!
10//! Layout (all values f64):
11//!   header:  [VERSION, solid_id, genus, n_vertices, n_edges, n_shells]
12//!            at version 1.0, written for every `Solid` body: the bytes of
13//!            every payload written before the kind existed, unchanged;
14//!            [VERSION, solid_id, genus, kind, n_vertices, n_edges, n_shells]
15//!            at version 1.1, written only when the body's kind is not
16//!            `Solid` (kind: Solid 0, Sheet 1, Cellular 2, Wire 3). The
17//!            reader accepts both; a 1.0 payload reads as `Solid`.
18//!   vertex:  [id, x, y, z]
19//!   edge:    [id, t0, t1, start_vertex_id, end_vertex_id, degenerate] curve
20//!   shell:   [id, n_faces] face*
21//!   face:    [id, same_sense] surface \[n_loops\] loop*
22//!   loop:    [id, n_coedges] coedge*
23//!   coedge:  [id, edge_id, forward] pcurve
24//!   curve:   [degree, n_knots, knots..., n_control, (x, y, z, w)...]
25//!   surface: [degree_u, degree_v, n_knots_u, knots_u..., n_knots_v,
26//!             knots_v..., n_rows, n_columns, (x, y, z, w)... row-major]
27
28use crate::topology::{
29    BodyKind, BrepSolid, CellRecord, CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord, ShellRecord,
30    VertexRecord,
31};
32pub use crate::{NurbsCurve, NurbsSurface, Vec3, Vec4};
33use std::collections::BTreeMap;
34
35/// The header a `Solid` body writes, and the oldest version the reader
36/// accepts. The snapshot container (`io/snapshot.rs`) names this format
37/// durable: a Solid keeps writing 1.0 so no stored payload moves.
38pub const SOLID_CODEC_VERSION: f64 = 1.0;
39/// The header a body of any other kind writes: the kind slot follows `genus`.
40pub const SOLID_CODEC_VERSION_KIND: f64 = 1.1;
41
42/// Largest integer f64 represents exactly. Ids above this would silently
43/// round during encode (and the decoder's integrality check cannot detect
44/// it), corrupting edge/vertex cross-references.
45pub const MAX_EXACT_ID: u64 = 1 << 53;
46
47pub fn id_to_f64(id: u64) -> Result<f64, String> {
48    if id > MAX_EXACT_ID {
49        return Err(format!(
50            "solid codec: id {id} exceeds 2^53 and cannot round-trip through f64"
51        ));
52    }
53    Ok(id as f64)
54}
55
56#[derive(serde::Serialize, serde::Deserialize, Default, Debug)]
57pub struct SolidNames {
58    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
59    pub faces: BTreeMap<u64, String>,
60    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
61    pub edges: BTreeMap<u64, String>,
62    /// Edges whose curve was read from a file ([`NurbsCurve::is_imported`]).
63    /// The flat image carries geometry only, so provenance rides here, and
64    /// a kernel-built solid's names keep their bytes.
65    #[serde(default, skip_serializing_if = "std::collections::BTreeSet::is_empty")]
66    pub imported_edges: std::collections::BTreeSet<u64>,
67    /// Coedges whose pcurve was read from a file.
68    #[serde(default, skip_serializing_if = "std::collections::BTreeSet::is_empty")]
69    pub imported_coedges: std::collections::BTreeSet<u64>,
70}
71
72fn push_curve(data: &mut Vec<f64>, curve: &NurbsCurve) {
73    data.push(curve.degree as f64);
74    data.push(curve.knots.len() as f64);
75    data.extend_from_slice(&curve.knots);
76    data.push(curve.control_points.len() as f64);
77    for point in &curve.control_points {
78        data.extend_from_slice(&[point.x, point.y, point.z, point.w]);
79    }
80}
81
82fn push_surface(data: &mut Vec<f64>, surface: &NurbsSurface) {
83    data.push(surface.degree_u as f64);
84    data.push(surface.degree_v as f64);
85    data.push(surface.knots_u.len() as f64);
86    data.extend_from_slice(&surface.knots_u);
87    data.push(surface.knots_v.len() as f64);
88    data.extend_from_slice(&surface.knots_v);
89    data.push(surface.control_points.len() as f64);
90    data.push(surface.control_points[0].len() as f64);
91    for row in &surface.control_points {
92        for point in row {
93            data.extend_from_slice(&[point.x, point.y, point.z, point.w]);
94        }
95    }
96}
97
98pub fn encode_solid(solid: &BrepSolid) -> Result<(Vec<f64>, SolidNames), String> {
99    if !solid.cells.is_empty() && solid.kind != BodyKind::Cellular {
100        return Err("solid codec: cells require declared Cellular kind".into());
101    }
102    let mut names = SolidNames::default();
103    let mut data = Vec::with_capacity(4096);
104    if solid.kind.is_solid() {
105        data.extend_from_slice(&[SOLID_CODEC_VERSION, id_to_f64(solid.id)?, solid.genus as f64]);
106    } else {
107        data.extend_from_slice(&[
108            SOLID_CODEC_VERSION_KIND,
109            id_to_f64(solid.id)?,
110            solid.genus as f64,
111            solid.kind.codec_code(),
112        ]);
113    }
114    data.extend_from_slice(&[
115        solid.vertices.len() as f64,
116        solid.edges.len() as f64,
117        solid.shells.len() as f64,
118    ]);
119    for vertex in &solid.vertices {
120        data.extend_from_slice(&[
121            id_to_f64(vertex.id)?,
122            vertex.point.x,
123            vertex.point.y,
124            vertex.point.z,
125        ]);
126    }
127    for edge in &solid.edges {
128        data.extend_from_slice(&[
129            id_to_f64(edge.id)?,
130            edge.t0,
131            edge.t1,
132            id_to_f64(edge.start_vertex_id)?,
133            id_to_f64(edge.end_vertex_id)?,
134            if edge.degenerate { 1.0 } else { 0.0 },
135        ]);
136        push_curve(&mut data, &edge.curve);
137        if edge.curve.is_imported() {
138            names.imported_edges.insert(edge.id);
139        }
140        if let Some(name) = &edge.name {
141            names.edges.insert(edge.id, name.clone());
142        }
143    }
144    for shell in &solid.shells {
145        data.push(id_to_f64(shell.id)?);
146        data.push(shell.faces.len() as f64);
147        for face in &shell.faces {
148            data.push(id_to_f64(face.id)?);
149            data.push(if face.same_sense { 1.0 } else { 0.0 });
150            push_surface(&mut data, &face.surface);
151            data.push(face.loops.len() as f64);
152            for loop_record in &face.loops {
153                data.push(id_to_f64(loop_record.id)?);
154                data.push(loop_record.coedges.len() as f64);
155                for coedge in &loop_record.coedges {
156                    data.extend_from_slice(&[
157                        id_to_f64(coedge.id)?,
158                        id_to_f64(coedge.edge_id)?,
159                        if coedge.forward { 1.0 } else { 0.0 },
160                    ]);
161                    push_curve(&mut data, &coedge.pcurve);
162                    if coedge.pcurve.is_imported() {
163                        names.imported_coedges.insert(coedge.id);
164                    }
165                }
166            }
167            if let Some(name) = &face.name {
168                names.faces.insert(face.id, name.clone());
169            }
170        }
171    }
172    // Optional region trailer on a declared Cellular 1.1 image only.
173    // Cell-less 1.0/1.1 images retain their exact layout and version.
174    if !solid.cells.is_empty() {
175        data.push(solid.cells.len() as f64);
176        for cell in &solid.cells {
177            data.extend_from_slice(&[id_to_f64(cell.id)?, if cell.void { 1.0 } else { 0.0 },
178                cell.faces.len() as f64]);
179            for &(face, forward) in &cell.faces {
180                data.extend_from_slice(&[id_to_f64(face)?, if forward { 1.0 } else { 0.0 }]);
181            }
182        }
183    }
184    Ok((data, names))
185}
186
187struct Reader<'a> {
188    data: &'a [f64],
189    cursor: usize,
190}
191
192impl<'a> Reader<'a> {
193    fn next(&mut self) -> Result<f64, String> {
194        let value = *self
195            .data
196            .get(self.cursor)
197            .ok_or("solid codec: truncated buffer")?;
198        self.cursor += 1;
199        Ok(value)
200    }
201
202    fn next_usize(&mut self) -> Result<usize, String> {
203        let value = self.next()?;
204        if value < 0.0 || value.fract() != 0.0 {
205            return Err(format!("solid codec: expected count, got {value}"));
206        }
207        Ok(value as usize)
208    }
209
210    fn next_id(&mut self) -> Result<u64, String> {
211        let value = self.next()?;
212        if value < 0.0 || value.fract() != 0.0 || value > MAX_EXACT_ID as f64 {
213            return Err(format!("solid codec: expected id, got {value}"));
214        }
215        Ok(value as u64)
216    }
217
218    fn next_slice(&mut self, count: usize) -> Result<&'a [f64], String> {
219        // Checked: a corrupted count (up to 2^53 passes the integrality test)
220        // must fail as a truncation error, never wrap the cursor on 32-bit.
221        let end = self
222            .cursor
223            .checked_add(count)
224            .ok_or("solid codec: truncated buffer")?;
225        let slice = self
226            .data
227            .get(self.cursor..end)
228            .ok_or("solid codec: truncated buffer")?;
229        self.cursor = end;
230        Ok(slice)
231    }
232
233    fn curve(&mut self) -> Result<NurbsCurve, String> {
234        let degree = self.next_usize()?;
235        let knot_count = self.next_usize()?;
236        let knots = self.next_slice(knot_count)?.to_vec();
237        let control_count = self.next_usize()?;
238        let raw = self.next_slice(
239            control_count
240                .checked_mul(4)
241                .ok_or("solid codec: truncated buffer")?,
242        )?;
243        let control_points = raw
244            .chunks_exact(4)
245            .map(|chunk| Vec4 {
246                x: chunk[0],
247                y: chunk[1],
248                z: chunk[2],
249                w: chunk[3],
250            })
251            .collect();
252        NurbsCurve::new(degree, knots, control_points)
253    }
254
255    fn surface(&mut self) -> Result<NurbsSurface, String> {
256        let degree_u = self.next_usize()?;
257        let degree_v = self.next_usize()?;
258        let knots_u_count = self.next_usize()?;
259        let knots_u = self.next_slice(knots_u_count)?.to_vec();
260        let knots_v_count = self.next_usize()?;
261        let knots_v = self.next_slice(knots_v_count)?.to_vec();
262        let rows = self.next_usize()?;
263        let columns = self.next_usize()?;
264        // A zero dimension would make the chunks_exact below panic; no valid
265        // surface has an empty control net, so reject corrupted payloads here.
266        if rows == 0 || columns == 0 {
267            return Err("solid codec: surface with empty control net".into());
268        }
269        let raw = self.next_slice(
270            rows.checked_mul(columns)
271                .and_then(|cells| cells.checked_mul(4))
272                .ok_or("solid codec: truncated buffer")?,
273        )?;
274        let control_points = raw
275            .chunks_exact(columns * 4)
276            .map(|row| {
277                row.chunks_exact(4)
278                    .map(|chunk| Vec4 {
279                        x: chunk[0],
280                        y: chunk[1],
281                        z: chunk[2],
282                        w: chunk[3],
283                    })
284                    .collect()
285            })
286            .collect();
287        NurbsSurface::new(degree_u, degree_v, knots_u, knots_v, control_points)
288    }
289}
290
291pub fn decode_solid(data: &[f64], names: &SolidNames) -> Result<BrepSolid, String> {
292    let mut reader = Reader { data, cursor: 0 };
293    let version = reader.next()?;
294    if version != SOLID_CODEC_VERSION && version != SOLID_CODEC_VERSION_KIND {
295        return Err(format!("solid codec: unsupported version {version}"));
296    }
297    let id = reader.next_id()?;
298    let genus = reader.next()? as i64;
299    let kind = if version == SOLID_CODEC_VERSION_KIND {
300        let code = reader.next()?;
301        BodyKind::from_codec_code(code)
302            .ok_or_else(|| format!("solid codec: unknown body kind {code}"))?
303    } else {
304        BodyKind::Solid
305    };
306    let vertex_count = reader.next_usize()?;
307    let edge_count = reader.next_usize()?;
308    let shell_count = reader.next_usize()?;
309    let mut vertices = Vec::with_capacity(vertex_count);
310    for _ in 0..vertex_count {
311        vertices.push(VertexRecord {
312            id: reader.next_id()?,
313            point: Vec3::new(reader.next()?, reader.next()?, reader.next()?),
314        });
315    }
316    let mut edges = Vec::with_capacity(edge_count);
317    for _ in 0..edge_count {
318        let id = reader.next_id()?;
319        let t0 = reader.next()?;
320        let t1 = reader.next()?;
321        let start_vertex_id = reader.next_id()?;
322        let end_vertex_id = reader.next_id()?;
323        let degenerate = reader.next()? != 0.0;
324        let mut curve = reader.curve()?;
325        curve.set_imported(names.imported_edges.contains(&id));
326        edges.push(EdgeRecord {
327            id,
328            curve,
329            t0,
330            t1,
331            start_vertex_id,
332            end_vertex_id,
333            degenerate,
334            name: names.edges.get(&id).cloned(),
335        });
336    }
337    let mut shells = Vec::with_capacity(shell_count);
338    for _ in 0..shell_count {
339        let shell_id = reader.next_id()?;
340        let face_count = reader.next_usize()?;
341        let mut faces = Vec::with_capacity(face_count);
342        for _ in 0..face_count {
343            let face_id = reader.next_id()?;
344            let same_sense = reader.next()? != 0.0;
345            let surface = reader.surface()?;
346            let loop_count = reader.next_usize()?;
347            let mut loops = Vec::with_capacity(loop_count);
348            for _ in 0..loop_count {
349                let loop_id = reader.next_id()?;
350                let coedge_count = reader.next_usize()?;
351                let mut coedges = Vec::with_capacity(coedge_count);
352                for _ in 0..coedge_count {
353                    let coedge_id = reader.next_id()?;
354                    let edge_id = reader.next_id()?;
355                    let forward = reader.next()? != 0.0;
356                    let mut pcurve = reader.curve()?;
357                    pcurve.set_imported(names.imported_coedges.contains(&coedge_id));
358                    coedges.push(CoedgeRecord {
359                        id: coedge_id,
360                        edge_id,
361                        forward,
362                        pcurve,
363                    });
364                }
365                loops.push(LoopRecord {
366                    id: loop_id,
367                    coedges,
368                });
369            }
370            faces.push(FaceRecord {
371                id: face_id,
372                surface,
373                same_sense,
374                loops,
375                name: names.faces.get(&face_id).cloned(),
376            });
377        }
378        shells.push(ShellRecord {
379            id: shell_id,
380            faces,
381        });
382    }
383    let mut cells = Vec::new();
384    if kind == BodyKind::Cellular && reader.cursor < data.len() {
385        let count = reader.next_usize()?;
386        if count == 0 || count > (data.len()-reader.cursor)/3 {
387            return Err("solid codec: invalid cell count".into());
388        }
389        for _ in 0..count {
390            let id = reader.next_id()?;
391            let void = match reader.next()? {
392                0.0 => false, 1.0 => true,
393                _ => return Err("solid codec: invalid cell void flag".into()),
394            };
395            let face_count = reader.next_usize()?;
396            if face_count > (data.len()-reader.cursor)/2 {
397                return Err("solid codec: truncated cell faces".into());
398            }
399            let mut faces = Vec::with_capacity(face_count);
400            for _ in 0..face_count {
401                let face = reader.next_id()?;
402                let forward = match reader.next()? {
403                    0.0 => false, 1.0 => true,
404                    _ => return Err("solid codec: invalid cell face sense".into()),
405                };
406                faces.push((face, forward));
407            }
408            cells.push(CellRecord { id, faces, void });
409        }
410    }
411    if reader.cursor != data.len() {
412        return Err("solid codec: trailing data".into());
413    }
414    Ok(BrepSolid {
415        mass_properties_cache: Default::default(),
416        id,
417        vertices,
418        edges,
419        shells,
420        genus,
421        kind,
422        cells,
423    })
424}