Skip to main content

kernel_api/
import.rs

1//! What an import reads: bodies, their health and repair, physical
2//! properties, the assembly tree and annotations.
3
4use serde::{Deserialize, Serialize};
5
6use crate::*;
7
8/// A single body produced by an external import (e.g. STEP).
9///
10/// The kernel returns one entry per placed body in the source file, meshed.
11/// [`Self::brep_blob`] is empty when no snapshot was kept:
12/// [`TessellationSettings::persist_brep_snapshot`] off, a full-mesh import,
13/// or a mesh file, which has no shape.
14#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct ImportedBody {
16    /// Optional name extracted from the source file (e.g. STEP product label).
17    pub name: Option<String>,
18    /// Tessellated mesh ready for the viewport.
19    #[serde(default)]
20    pub mesh: TriMesh,
21    /// Serialized shape snapshot for this body, when one was kept: ogeom
22    /// native-format text bytes (`ogeom::io::native`, one root shape per
23    /// blob).
24    #[serde(default, skip_serializing_if = "Vec::is_empty")]
25    pub brep_blob: Vec<u8>,
26    /// Per-face linear RGB albedo in face-exploration order
27    /// (`ogeom::topo::explore` with a Face filter) over the matching shape
28    /// snapshot.
29    #[serde(default, skip_serializing_if = "Vec::is_empty")]
30    pub face_colors: Vec<[f32; 3]>,
31    /// Axis-aligned bounds in millimetres from the raw BRep (before tessellation).
32    #[serde(default, skip_serializing_if = "Option::is_none")]
33    pub bounds_mm: Option<([f32; 3], [f32; 3])>,
34    /// What the kernel's checker found in the body's shape as read.
35    #[serde(default, skip_serializing_if = "Option::is_none")]
36    pub health: Option<ShapeHealth>,
37    /// The names of the layers the file puts the body on.
38    #[serde(default, skip_serializing_if = "Vec::is_empty")]
39    pub layers: Vec<String>,
40}
41
42/// What the kernel's checker found in a shape.
43///
44/// The checker sorts its findings in two: *broken*, where an algorithm
45/// reading the shape gets a wrong answer rather than an error, and
46/// *suspect*, out of order but harmless to every operation. Only broken
47/// findings ask for a repair.
48#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
49pub struct ShapeHealth {
50    /// Findings that make an algorithm reading the shape answer wrongly.
51    pub broken: usize,
52    /// Findings that are out of order but harmless.
53    pub suspect: usize,
54    /// The first findings, a sentence each, broken first.
55    #[serde(default, skip_serializing_if = "Vec::is_empty")]
56    pub findings: Vec<String>,
57    /// The kernel's repair has run on the shape these findings describe.
58    #[serde(default)]
59    pub repaired: bool,
60    /// The shape is a mesh converted as it is: its flat stretches are
61    /// faces and its curved ones still the mesh's facets, which a refine
62    /// can rebuild on the surfaces they approximate.
63    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
64    pub faceted: bool,
65}
66
67impl ShapeHealth {
68    /// How many findings a health record keeps as sentences.
69    pub const KEPT_FINDINGS: usize = 8;
70
71    /// Whether the shape has anything a repair is for.
72    pub fn is_broken(&self) -> bool {
73        self.broken > 0
74    }
75
76    /// One line for a tooltip: the counts, then the findings kept.
77    pub fn describe(&self) -> String {
78        let mut lines = Vec::new();
79        let counts = match (self.broken, self.suspect) {
80            (0, 0) => "The shape checks clean".to_string(),
81            (b, 0) => format!("{b} shape defect(s) that make operations answer wrongly"),
82            (0, s) => format!("{s} shape irregularity(ies), harmless to operations"),
83            (b, s) => format!(
84                "{b} shape defect(s) that make operations answer wrongly, \
85                 and {s} harmless irregularity(ies)"
86            ),
87        };
88        lines.push(counts);
89        if self.repaired && self.is_broken() {
90            lines.push("Repaired; these remain, beyond what the repair mends".to_string());
91        }
92        lines.extend(self.findings.iter().cloned());
93        let shown = self.findings.len();
94        let total = self.broken + self.suspect;
95        if total > shown {
96            lines.push(format!("… and {} more", total - shown));
97        }
98        lines.join("\n")
99    }
100}
101
102/// A shape run through the kernel's repair: the mended snapshot, its mesh,
103/// what the repair did, and what the checker finds afterwards.
104#[derive(Debug, Clone, Default, Serialize, Deserialize)]
105pub struct RepairResult {
106    /// Native-format snapshot of the mended shape.
107    pub brep_blob: Vec<u8>,
108    /// Per-face colours for the mended shape, in its face order; empty when
109    /// the repair changed the faces too much to carry them over.
110    pub face_colors: Vec<[f32; 3]>,
111    /// Render mesh of the mended shape.
112    pub mesh: TriMesh,
113    /// Axis-aligned bounds in millimetres.
114    pub bounds_mm: Option<([f32; 3], [f32; 3])>,
115    /// The checker's findings on the mended shape, marked repaired.
116    pub health: ShapeHealth,
117    /// What was mended, a phrase each ("12 tolerances tightened").
118    pub mended: Vec<String>,
119}
120
121/// A mesh body turned into a B-rep by the kernel: the shape, its mesh, the
122/// checker's verdict, and what the conversion found.
123#[derive(Debug, Clone, Default, Serialize, Deserialize)]
124pub struct MeshSolidResult {
125    /// Native-format snapshot of the shape.
126    pub brep_blob: Vec<u8>,
127    /// Per-face colours in the shape's face order: the mesh's colour on
128    /// every face when it had one colour, else empty.
129    pub face_colors: Vec<[f32; 3]>,
130    /// Render mesh of the shape, with its kernel faces and edges.
131    pub mesh: TriMesh,
132    /// Axis-aligned bounds in millimetres.
133    pub bounds_mm: Option<([f32; 3], [f32; 3])>,
134    /// The checker's findings on the shape.
135    pub health: ShapeHealth,
136    /// Every piece of the mesh closed and became a solid; otherwise the
137    /// shape is the open shell(s) the mesh makes.
138    pub closed: bool,
139    /// What the conversion did and where the mesh does not close, a phrase
140    /// each ("12 triangles into 6 faces", "3 hole edges").
141    pub summary: Vec<String>,
142}
143
144/// A body's measure: its volume, surface area and centre of mass, exact
145/// where the kernel has a closed form for its faces.
146#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
147pub struct PhysicalProperties {
148    /// Enclosed volume in mm³; `None` when the shape encloses none (an open
149    /// shell, a sheet) or its shell is wound inside out.
150    pub volume_mm3: Option<f64>,
151    /// Total surface area in mm².
152    pub area_mm2: f64,
153    /// Centre of mass at uniform density, in mm; the centre of the surface
154    /// when there is no volume.
155    pub centre_mm: [f64; 3],
156    /// Some face had no closed form, so the figures were integrated over a
157    /// tessellation and are close rather than exact (within a fraction of a
158    /// percent on curved walls).
159    #[serde(default)]
160    pub approximate: bool,
161    /// The inertia of the volume at unit density, when there is one.
162    #[serde(default)]
163    pub inertia: Option<Inertia>,
164}
165
166/// A solid's inertia at unit density, in mm⁵ (times a density in mass per
167/// mm³ gives mass times mm²), in the solid's frame.
168#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
169pub struct Inertia {
170    /// The inertia tensor about the centre of mass, row by row.
171    pub about_centre: [[f64; 3]; 3],
172    /// The principal moments, smallest first, each with its axis through
173    /// the centre of mass (unit length; right-handed in that order).
174    pub principal: [(f64, [f64; 3]); 3],
175}
176
177/// Node type emitted by STEP import hierarchy reconstruction.
178#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
179#[serde(rename_all = "snake_case")]
180pub enum ImportedNodeKind {
181    #[default]
182    Assembly,
183    Part,
184    Instance,
185    /// The group holding an import's annotations.
186    Annotations,
187    /// One annotation the file carries: a dimension, a tolerance, a datum
188    /// or a note.
189    Annotation,
190}
191
192/// What an imported annotation states.
193#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
194#[serde(rename_all = "snake_case")]
195pub enum AnnotationKind {
196    /// A size or a location, with its value.
197    Dimension,
198    /// A geometric tolerance: flatness, position, profile and their kin.
199    Tolerance,
200    /// A datum letter, or a target a datum is contacted at.
201    Datum,
202    /// Text with nothing measured behind it.
203    Note,
204    /// A drawn annotation the file does not say more about.
205    #[default]
206    Other,
207}
208
209impl AnnotationKind {
210    /// The kind as a word for the interface.
211    pub fn label(self) -> &'static str {
212        match self {
213            AnnotationKind::Dimension => "Dimension",
214            AnnotationKind::Tolerance => "Tolerance",
215            AnnotationKind::Datum => "Datum",
216            AnnotationKind::Note => "Note",
217            AnnotationKind::Other => "Annotation",
218        }
219    }
220}
221
222/// One annotation an imported file carries (a dimension, a tolerance, a
223/// datum or a note), with what it draws.
224///
225/// The polylines and the anchor are in document millimetres, placed where
226/// the file's bodies are placed, so an annotation drawn on an assembly's
227/// part sits on that part.
228#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
229pub struct ImportedAnnotation {
230    /// The name the file gives it (`Linear Size.3`, `Flatness.1`), or the
231    /// text it shows where the file names it by that.
232    pub name: String,
233    pub kind: AnnotationKind,
234    /// What a label shows: `Ø 35 ±0.2`, `Flatness 0.2`, `A`.
235    pub text: String,
236    /// The drawn geometry: leaders, frames, witness lines and whatever
237    /// strokes the file draws its text with.
238    #[serde(default, skip_serializing_if = "Vec::is_empty")]
239    pub polylines: Vec<Vec<[f32; 3]>>,
240    /// Where the label goes; `None` for an annotation that draws nothing.
241    #[serde(default, skip_serializing_if = "Option::is_none")]
242    pub anchor: Option<[f32; 3]>,
243    /// The body the annotation describes, as an index into
244    /// [`ImportedModel::bodies`], where the file says which.
245    #[serde(default, skip_serializing_if = "Option::is_none")]
246    pub body_index: Option<usize>,
247}
248
249/// One hierarchy node from the imported file's product structure.
250///
251/// Nodes can either be pure containers (`body_index = None`) or reference a
252/// renderable payload in [`ImportedModel::bodies`].
253#[derive(Debug, Clone, Serialize, Deserialize)]
254pub struct ImportedNode {
255    /// Stable id scoped to one import result.
256    pub id: u64,
257    /// Parent node id; None means root.
258    #[serde(default, skip_serializing_if = "Option::is_none")]
259    pub parent_id: Option<u64>,
260    /// Human-readable name from the file's product labels when available.
261    #[serde(default, skip_serializing_if = "Option::is_none")]
262    pub name: Option<String>,
263    /// Structural type of this node.
264    #[serde(default)]
265    pub kind: ImportedNodeKind,
266    /// Initial visibility from source file metadata (if available).
267    #[serde(default = "default_imported_node_visible")]
268    pub visible: bool,
269    /// Index into [`ImportedModel::bodies`] when this node owns geometry.
270    #[serde(default, skip_serializing_if = "Option::is_none")]
271    pub body_index: Option<usize>,
272    /// Local transform matrix (row-major) relative to parent, if known.
273    #[serde(default, skip_serializing_if = "Option::is_none")]
274    pub local_transform: Option<[[f32; 4]; 4]>,
275}
276
277fn default_imported_node_visible() -> bool {
278    true
279}
280
281/// Length unit declared by an imported source file.
282///
283/// This is a thin mirror of `core_document::Unit` that lives in `kernel_api`
284/// to avoid pulling document-side types into the kernel crate. App code is
285/// responsible for translating it into the document's display unit.
286#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
287#[serde(rename_all = "snake_case")]
288pub enum LengthUnit {
289    Millimetre,
290    Centimetre,
291    Metre,
292    Inch,
293    Foot,
294}
295
296/// Result of importing an external CAD file.
297#[derive(Debug, Clone, Default, Serialize, Deserialize)]
298pub struct ImportedModel {
299    /// One entry per top-level body in the source file.
300    pub bodies: Vec<ImportedBody>,
301    /// Everything the reader had to say about the file, kept whole so it
302    /// can be handed to whoever maintains the kernel rather than scrolled
303    /// past in a terminal.
304    #[serde(default)]
305    pub report: ImportReport,
306    /// Optional assembly/object tree reconstructed from the file's product
307    /// structure.
308    #[serde(default)]
309    pub nodes: Vec<ImportedNode>,
310    /// Length unit declared by the source file, when detectable. Geometry in
311    /// `bodies` is *always* expressed in millimetres regardless; this field
312    /// is purely informational and used by the UI to pick a display unit.
313    #[serde(default)]
314    pub source_unit: Option<LengthUnit>,
315    /// The file's annotations (dimensions, tolerances, datums and notes)
316    /// in file order, the drawn ones first.
317    #[serde(default, skip_serializing_if = "Vec::is_empty")]
318    pub annotations: Vec<ImportedAnnotation>,
319}
320
321/// What the reader had to say about a file.
322///
323/// A community STEP file routinely produces a thousand lines of "this edge
324/// misses its vertex by a micron"; each one is true and none is actionable
325/// on its own. The kernel counts them by kind, and the whole prose stays
326/// here for the report a user can send along with the file.
327#[derive(Debug, Clone, Default, Serialize, Deserialize)]
328pub struct ImportReport {
329    /// The kernel that read the file, by name and version.
330    pub kernel: String,
331    /// One entry per kind of imperfection, largest count first.
332    pub summary: Vec<ImportWarningKind>,
333    /// Every warning, one line each, in the order the reader met them.
334    pub warnings: Vec<String>,
335    /// STEP entity ids of faces that read without a complete trim, so they
336    /// draw with gaps unless healed.
337    pub untrimmed_faces: Vec<u64>,
338    /// Entity keywords the reader never visited, with counts. Presentation
339    /// and annotation land here by design; geometry landing here is a gap.
340    pub skipped: Vec<(String, usize)>,
341}
342
343impl ImportReport {
344    /// Whether there is anything worth writing down.
345    pub fn is_clean(&self) -> bool {
346        self.warnings.is_empty() && self.untrimmed_faces.is_empty()
347    }
348}
349
350/// One kind of imperfect import, counted rather than repeated.
351#[derive(Debug, Clone, Serialize, Deserialize)]
352pub struct ImportWarningKind {
353    /// Stable across runs: `vertex-miss`, `boundary-slop`, `fit-short`,
354    /// `untrimmed`.
355    pub kind: String,
356    pub count: usize,
357    /// The worst measured value among them, in millimetres, for the kinds
358    /// that measure one; zero otherwise.
359    pub worst: f64,
360    /// One entity id to look at first.
361    pub exemplar: u64,
362}