Skip to main content

kernel_api/
lib.rs

1//! printCAD's geometry interface: meshes, profiles and solid operations
2//! as plain data, with no geometry code. The app's kernel adapter answers
3//! it, and workbench packages build their solids as [`SolidOp`] plans
4//! through `printcad-bench-api`.
5//!
6//! Versions follow `printcad-bench-api`'s: 0.1.x speaks the workbench
7//! contract `printcad:workbench@0.1`, and a patch release only adds.
8//! [`FaceSurface`] and [`ProfileSegment`], which the app sends a package,
9//! are `#[non_exhaustive]` unless the `exhaustive` feature (printCAD's
10//! own) is on; [`SolidOp`] and the enums inside it keep their variants'
11//! fields within a minor version.
12
13use serde::{Deserialize, Serialize};
14use std::path::Path;
15use thiserror::Error;
16
17pub mod naming;
18pub mod pmi;
19pub use naming::TopoName;
20pub use pmi::{PmiDatum, PmiDimension, PmiTolerance, SemanticPmi};
21
22/// Convenience alias for kernel fallible operations.
23pub type KernelResult<T> = Result<T, KernelError>;
24
25/// Handle to a body managed by the kernel.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
27pub struct BodyHandle(pub u64);
28
29/// Request describing which features or bodies must be recomputed.
30#[derive(Debug, Clone, Default, Serialize, Deserialize)]
31pub struct RebuildRequest {
32    /// Feature identifiers that triggered the rebuild.
33    pub dirty_features: Vec<String>,
34    /// Whether dependent features should be recomputed automatically.
35    pub propagate: bool,
36}
37
38/// Response returned for every rebuild invocation.
39#[derive(Debug, Clone, Default, Serialize, Deserialize)]
40pub struct RebuildResponse {
41    /// Bodies that were modified or regenerated.
42    pub updated_bodies: Vec<BodyHandle>,
43    /// Kernel provided diagnostics or warnings.
44    pub diagnostics: Vec<String>,
45}
46
47/// How linear (chord) deflection is chosen for kernel meshing.
48///
49/// The default is **bbox-scaled** deflection: absolute chord height is derived
50/// from the sum of the shape's bounding-box extents and a dimensionless
51/// multiplier ([`TessellationSettings::mesh_deviation`], typically `0.2`).
52/// This produces visually consistent tessellation across small and large
53/// parts without per-model tuning.
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
55#[serde(rename_all = "snake_case")]
56pub enum LinearDeflectionMode {
57    /// Bounding-box scaled: linear deflection = `(dx + dy + dz) / 300 ×`
58    /// [`TessellationSettings::mesh_deviation`].
59    #[default]
60    BboxScaled,
61    /// Fixed absolute linear deflection in model units (millimetres for STEP geometry).
62    AbsoluteMm,
63}
64
65/// Parameters controlling tessellation quality for viewport rendering.
66#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
67pub struct TessellationSettings {
68    #[serde(default)]
69    pub linear_deflection_mode: LinearDeflectionMode,
70    /// Dimensionless multiplier applied to the bbox-derived chord height when
71    /// [`Self::linear_deflection_mode`] is [`LinearDeflectionMode::BboxScaled`].
72    /// Typical range `0.05..=1.0`; smaller values yield finer triangulation.
73    #[serde(default = "default_mesh_deviation")]
74    pub mesh_deviation: f32,
75    /// Absolute chord height in model units when using [`LinearDeflectionMode::AbsoluteMm`].
76    pub chord_tolerance: f32,
77    pub angular_tolerance_deg: f32,
78    /// When true, the kernel collapses vertices that share a position across
79    /// multiple faces *and* whose face normals are within
80    /// [`Self::weld_angle_threshold_deg`] of each other. This typically
81    /// shrinks vertex counts by 4–6× on dense CAD models without flattening
82    /// genuine sharp edges, since dissimilar face normals stay separate.
83    #[serde(default = "default_weld_cross_face")]
84    pub weld_cross_face: bool,
85    /// Maximum angle between two face normals at a shared position for them
86    /// to be merged into a single welded vertex. Above this angle the kernel
87    /// keeps them separate so hard CAD edges stay crisp under shading.
88    /// Defaults to 30°.
89    #[serde(default = "default_weld_angle_threshold_deg")]
90    pub weld_angle_threshold_deg: f32,
91    /// When true, import keeps each body's shape snapshot in `brep_blob`
92    /// beside its mesh. Meshing happens during the import either way;
93    /// serializing the snapshots is most of the work of reading a large
94    /// assembly, and turning this off skips it. The STEP asset remains
95    /// available in the document regardless.
96    #[serde(default = "default_persist_brep_snapshot")]
97    pub persist_brep_snapshot: bool,
98    /// When true, compute mesh outline / edge segments for the viewport (face
99    /// boundaries). Skipping saves CPU on huge imports when outlines are not needed.
100    #[serde(default = "default_generate_boundary_edges")]
101    pub generate_boundary_edges: bool,
102}
103
104fn default_weld_cross_face() -> bool {
105    false
106}
107
108fn default_weld_angle_threshold_deg() -> f32 {
109    30.0
110}
111
112fn default_mesh_deviation() -> f32 {
113    0.2
114}
115
116fn default_persist_brep_snapshot() -> bool {
117    true
118}
119
120fn default_generate_boundary_edges() -> bool {
121    true
122}
123
124impl Default for TessellationSettings {
125    fn default() -> Self {
126        Self {
127            linear_deflection_mode: LinearDeflectionMode::default(),
128            mesh_deviation: default_mesh_deviation(),
129            chord_tolerance: 0.1,
130            angular_tolerance_deg: 28.65,
131            weld_cross_face: default_weld_cross_face(),
132            weld_angle_threshold_deg: default_weld_angle_threshold_deg(),
133            persist_brep_snapshot: default_persist_brep_snapshot(),
134            generate_boundary_edges: default_generate_boundary_edges(),
135        }
136    }
137}
138
139/// Triangular mesh generated from kernel bodies for viewports and export.
140#[derive(Debug, Clone, Default, Serialize, Deserialize)]
141pub struct TriMesh {
142    pub positions: Vec<[f32; 3]>,
143    pub normals: Vec<[f32; 3]>,
144    pub indices: Vec<u32>,
145    /// Optional line-list of feature edges that should be drawn as outlines on
146    /// top of the shaded surface (e.g. face boundaries from a STEP import).
147    /// Stored as flat pairs of indices into [`Self::positions`]; the slice
148    /// length is therefore always a multiple of two. Empty when the source has
149    /// no edge information available.
150    #[serde(default)]
151    pub edges: Vec<u32>,
152    /// Optional per-vertex linear RGB albedo in 0..1 (same length as [`Self::positions`] when set).
153    /// Empty means the renderer uses the body tint from push constants only.
154    #[serde(default)]
155    pub colors: Vec<[f32; 3]>,
156    /// Which kernel face each triangle was cut from: one entry per triangle
157    /// (`indices.len() / 3`), an index into the body's faces in the kernel's
158    /// own order. A curved face is many triangles with many normals, and
159    /// this is what lets a click on one of them select the whole face.
160    /// Empty when the source has no faces (a sketch, a datum, a mesh saved
161    /// before faces were recorded), and a consumer falls back to geometry.
162    #[serde(default)]
163    pub faces: Vec<u32>,
164    /// Which kernel edge each outline segment belongs to: one entry per
165    /// pair in [`Self::edges`], an index into the body's edges in the
166    /// kernel's own order. A curved edge is many segments, and this is what
167    /// lets a click on one of them select the whole edge. Empty when the
168    /// outline came from triangle boundaries rather than kernel edges.
169    #[serde(default)]
170    pub edge_ids: Vec<u32>,
171    /// The exact surface of each kernel face, indexed like [`Self::faces`]:
172    /// what a picked face is, beyond the triangles drawn for it. Empty when
173    /// the source has no faces.
174    #[serde(default, skip_serializing_if = "Vec::is_empty")]
175    pub face_surfaces: Vec<FaceSurface>,
176    /// The name of each kernel face, indexed like [`Self::faces`]: what a
177    /// pick keeps so a rebuild finds the face again. Zero where a face has
178    /// none; empty when the source names none.
179    #[serde(default, skip_serializing_if = "Vec::is_empty")]
180    pub face_names: Vec<TopoName>,
181    /// The tag of the op that made each kernel face, indexed like
182    /// [`Self::faces`]: the name of the feature a body's chain built it
183    /// under (`naming::name_of_id` of its id), kept by a face a later op
184    /// splits or trims. Zero where unknown; empty when the source names
185    /// none.
186    #[serde(default, skip_serializing_if = "Vec::is_empty")]
187    pub face_makers: Vec<TopoName>,
188    /// The names of the two faces each kernel edge runs between, indexed
189    /// like [`Self::edge_ids`].
190    #[serde(default, skip_serializing_if = "Vec::is_empty")]
191    pub edge_faces: Vec<[TopoName; 2]>,
192}
193
194/// The kind and placement of a kernel face's surface, in the mesh's frame.
195#[cfg_attr(not(feature = "exhaustive"), non_exhaustive)]
196#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
197pub enum FaceSurface {
198    /// A plane through `origin`, with the face's outward `normal`.
199    Plane { origin: [f32; 3], normal: [f32; 3] },
200    /// A circular cylinder about the line through `origin` along `axis`.
201    Cylinder {
202        origin: [f32; 3],
203        axis: [f32; 3],
204        radius: f32,
205    },
206    /// A circular cone about the line through `apex` along `axis`, its
207    /// wall `half_angle` (radians, positive) off the axis.
208    Cone {
209        apex: [f32; 3],
210        axis: [f32; 3],
211        #[serde(default)]
212        half_angle: f32,
213    },
214    /// A sphere.
215    Sphere { center: [f32; 3], radius: f32 },
216    /// A torus about the line through `center` along `axis`: its tube's
217    /// centre `major_radius` from the axis, the tube `minor_radius` round.
218    Torus {
219        center: [f32; 3],
220        axis: [f32; 3],
221        #[serde(default)]
222        major_radius: f32,
223        #[serde(default)]
224        minor_radius: f32,
225    },
226    /// Any other surface: a spline, a sweep.
227    #[default]
228    Other,
229}
230
231impl FaceSurface {
232    /// The axis a turned face turns about, as a point on it and its
233    /// direction: a cylinder's, a cone's or a torus's.
234    pub fn axis(&self) -> Option<([f32; 3], [f32; 3])> {
235        match *self {
236            FaceSurface::Cylinder { origin, axis, .. } => Some((origin, axis)),
237            FaceSurface::Cone { apex, axis, .. } => Some((apex, axis)),
238            FaceSurface::Torus { center, axis, .. } => Some((center, axis)),
239            _ => None,
240        }
241    }
242
243    /// The same surface moved: `point` maps points, `direction` maps
244    /// directions (a rigid motion, so lengths stay).
245    pub fn moved(
246        &self,
247        point: impl Fn([f32; 3]) -> [f32; 3],
248        direction: impl Fn([f32; 3]) -> [f32; 3],
249    ) -> Self {
250        match *self {
251            FaceSurface::Plane { origin, normal } => FaceSurface::Plane {
252                origin: point(origin),
253                normal: direction(normal),
254            },
255            FaceSurface::Cylinder {
256                origin,
257                axis,
258                radius,
259            } => FaceSurface::Cylinder {
260                origin: point(origin),
261                axis: direction(axis),
262                radius,
263            },
264            FaceSurface::Cone {
265                apex,
266                axis,
267                half_angle,
268            } => FaceSurface::Cone {
269                apex: point(apex),
270                axis: direction(axis),
271                half_angle,
272            },
273            FaceSurface::Sphere { center, radius } => FaceSurface::Sphere {
274                center: point(center),
275                radius,
276            },
277            FaceSurface::Torus {
278                center,
279                axis,
280                major_radius,
281                minor_radius,
282            } => FaceSurface::Torus {
283                center: point(center),
284                axis: direction(axis),
285                major_radius,
286                minor_radius,
287            },
288            FaceSurface::Other => FaceSurface::Other,
289        }
290    }
291}
292
293impl TriMesh {
294    /// Compute axis-aligned bounding box `(min, max)` of the mesh, if non-empty.
295    pub fn bounds(&self) -> Option<([f32; 3], [f32; 3])> {
296        if self.positions.is_empty() {
297            return None;
298        }
299        let mut min = self.positions[0];
300        let mut max = self.positions[0];
301        for &[x, y, z] in &self.positions {
302            if x < min[0] {
303                min[0] = x;
304            }
305            if y < min[1] {
306                min[1] = y;
307            }
308            if z < min[2] {
309                min[2] = z;
310            }
311            if x > max[0] {
312                max[0] = x;
313            }
314            if y > max[1] {
315                max[1] = y;
316            }
317            if z > max[2] {
318                max[2] = z;
319            }
320        }
321        Some((min, max))
322    }
323}
324
325/// A single body produced by an external import (e.g. STEP).
326///
327/// The kernel returns one entry per placed body in the source file, meshed.
328/// [`Self::brep_blob`] is empty when no snapshot was kept:
329/// [`TessellationSettings::persist_brep_snapshot`] off, a full-mesh import,
330/// or a mesh file, which has no shape.
331#[derive(Debug, Clone, Serialize, Deserialize)]
332pub struct ImportedBody {
333    /// Optional name extracted from the source file (e.g. STEP product label).
334    pub name: Option<String>,
335    /// Tessellated mesh ready for the viewport.
336    #[serde(default)]
337    pub mesh: TriMesh,
338    /// Serialized shape snapshot for this body, when one was kept: ogeom
339    /// native-format text bytes (`ogeom::io::native`, one root shape per
340    /// blob).
341    #[serde(default, skip_serializing_if = "Vec::is_empty")]
342    pub brep_blob: Vec<u8>,
343    /// Per-face linear RGB albedo in face-exploration order
344    /// (`ogeom::topo::explore` with a Face filter) over the matching shape
345    /// snapshot.
346    #[serde(default, skip_serializing_if = "Vec::is_empty")]
347    pub face_colors: Vec<[f32; 3]>,
348    /// Axis-aligned bounds in millimetres from the raw BRep (before tessellation).
349    #[serde(default, skip_serializing_if = "Option::is_none")]
350    pub bounds_mm: Option<([f32; 3], [f32; 3])>,
351    /// What the kernel's checker found in the body's shape as read.
352    #[serde(default, skip_serializing_if = "Option::is_none")]
353    pub health: Option<ShapeHealth>,
354    /// The names of the layers the file puts the body on.
355    #[serde(default, skip_serializing_if = "Vec::is_empty")]
356    pub layers: Vec<String>,
357}
358
359/// What the kernel's checker found in a shape.
360///
361/// The checker sorts its findings in two: *broken*, where an algorithm
362/// reading the shape gets a wrong answer rather than an error, and
363/// *suspect*, out of order but harmless to every operation. Only broken
364/// findings ask for a repair.
365#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
366pub struct ShapeHealth {
367    /// Findings that make an algorithm reading the shape answer wrongly.
368    pub broken: usize,
369    /// Findings that are out of order but harmless.
370    pub suspect: usize,
371    /// The first findings, a sentence each, broken first.
372    #[serde(default, skip_serializing_if = "Vec::is_empty")]
373    pub findings: Vec<String>,
374    /// The kernel's repair has run on the shape these findings describe.
375    #[serde(default)]
376    pub repaired: bool,
377    /// The shape is a mesh converted as it is: its flat stretches are
378    /// faces and its curved ones still the mesh's facets, which a refine
379    /// can rebuild on the surfaces they approximate.
380    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
381    pub faceted: bool,
382}
383
384impl ShapeHealth {
385    /// How many findings a health record keeps as sentences.
386    pub const KEPT_FINDINGS: usize = 8;
387
388    /// Whether the shape has anything a repair is for.
389    pub fn is_broken(&self) -> bool {
390        self.broken > 0
391    }
392
393    /// One line for a tooltip: the counts, then the findings kept.
394    pub fn describe(&self) -> String {
395        let mut lines = Vec::new();
396        let counts = match (self.broken, self.suspect) {
397            (0, 0) => "The shape checks clean".to_string(),
398            (b, 0) => format!("{b} shape defect(s) that make operations answer wrongly"),
399            (0, s) => format!("{s} shape irregularity(ies), harmless to operations"),
400            (b, s) => format!(
401                "{b} shape defect(s) that make operations answer wrongly, \
402                 and {s} harmless irregularity(ies)"
403            ),
404        };
405        lines.push(counts);
406        if self.repaired && self.is_broken() {
407            lines.push("Repaired; these remain, beyond what the repair mends".to_string());
408        }
409        lines.extend(self.findings.iter().cloned());
410        let shown = self.findings.len();
411        let total = self.broken + self.suspect;
412        if total > shown {
413            lines.push(format!("… and {} more", total - shown));
414        }
415        lines.join("\n")
416    }
417}
418
419/// A shape run through the kernel's repair: the mended snapshot, its mesh,
420/// what the repair did, and what the checker finds afterwards.
421#[derive(Debug, Clone, Default, Serialize, Deserialize)]
422pub struct RepairResult {
423    /// Native-format snapshot of the mended shape.
424    pub brep_blob: Vec<u8>,
425    /// Per-face colours for the mended shape, in its face order; empty when
426    /// the repair changed the faces too much to carry them over.
427    pub face_colors: Vec<[f32; 3]>,
428    /// Render mesh of the mended shape.
429    pub mesh: TriMesh,
430    /// Axis-aligned bounds in millimetres.
431    pub bounds_mm: Option<([f32; 3], [f32; 3])>,
432    /// The checker's findings on the mended shape, marked repaired.
433    pub health: ShapeHealth,
434    /// What was mended, a phrase each ("12 tolerances tightened").
435    pub mended: Vec<String>,
436}
437
438/// A mesh body turned into a B-rep by the kernel: the shape, its mesh, the
439/// checker's verdict, and what the conversion found.
440#[derive(Debug, Clone, Default, Serialize, Deserialize)]
441pub struct MeshSolidResult {
442    /// Native-format snapshot of the shape.
443    pub brep_blob: Vec<u8>,
444    /// Per-face colours in the shape's face order: the mesh's colour on
445    /// every face when it had one colour, else empty.
446    pub face_colors: Vec<[f32; 3]>,
447    /// Render mesh of the shape, with its kernel faces and edges.
448    pub mesh: TriMesh,
449    /// Axis-aligned bounds in millimetres.
450    pub bounds_mm: Option<([f32; 3], [f32; 3])>,
451    /// The checker's findings on the shape.
452    pub health: ShapeHealth,
453    /// Every piece of the mesh closed and became a solid; otherwise the
454    /// shape is the open shell(s) the mesh makes.
455    pub closed: bool,
456    /// What the conversion did and where the mesh does not close, a phrase
457    /// each ("12 triangles into 6 faces", "3 hole edges").
458    pub summary: Vec<String>,
459}
460
461/// A body's measure: its volume, surface area and centre of mass, exact
462/// where the kernel has a closed form for its faces.
463#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
464pub struct PhysicalProperties {
465    /// Enclosed volume in mm³; `None` when the shape encloses none (an open
466    /// shell, a sheet) or its shell is wound inside out.
467    pub volume_mm3: Option<f64>,
468    /// Total surface area in mm².
469    pub area_mm2: f64,
470    /// Centre of mass at uniform density, in mm; the centre of the surface
471    /// when there is no volume.
472    pub centre_mm: [f64; 3],
473    /// Some face had no closed form, so the figures were integrated over a
474    /// tessellation and are close rather than exact (within a fraction of a
475    /// percent on curved walls).
476    #[serde(default)]
477    pub approximate: bool,
478    /// The inertia of the volume at unit density, when there is one.
479    #[serde(default)]
480    pub inertia: Option<Inertia>,
481}
482
483/// A solid's inertia at unit density, in mm⁵ (times a density in mass per
484/// mm³ gives mass times mm²), in the solid's frame.
485#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
486pub struct Inertia {
487    /// The inertia tensor about the centre of mass, row by row.
488    pub about_centre: [[f64; 3]; 3],
489    /// The principal moments, smallest first, each with its axis through
490    /// the centre of mass (unit length; right-handed in that order).
491    pub principal: [(f64, [f64; 3]); 3],
492}
493
494/// Node type emitted by STEP import hierarchy reconstruction.
495#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
496#[serde(rename_all = "snake_case")]
497pub enum ImportedNodeKind {
498    #[default]
499    Assembly,
500    Part,
501    Instance,
502    /// The group holding an import's annotations.
503    Annotations,
504    /// One annotation the file carries: a dimension, a tolerance, a datum
505    /// or a note.
506    Annotation,
507}
508
509/// What an imported annotation states.
510#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
511#[serde(rename_all = "snake_case")]
512pub enum AnnotationKind {
513    /// A size or a location, with its value.
514    Dimension,
515    /// A geometric tolerance: flatness, position, profile and their kin.
516    Tolerance,
517    /// A datum letter, or a target a datum is contacted at.
518    Datum,
519    /// Text with nothing measured behind it.
520    Note,
521    /// A drawn annotation the file does not say more about.
522    #[default]
523    Other,
524}
525
526impl AnnotationKind {
527    /// The kind as a word for the interface.
528    pub fn label(self) -> &'static str {
529        match self {
530            AnnotationKind::Dimension => "Dimension",
531            AnnotationKind::Tolerance => "Tolerance",
532            AnnotationKind::Datum => "Datum",
533            AnnotationKind::Note => "Note",
534            AnnotationKind::Other => "Annotation",
535        }
536    }
537}
538
539/// One annotation an imported file carries (a dimension, a tolerance, a
540/// datum or a note), with what it draws.
541///
542/// The polylines and the anchor are in document millimetres, placed where
543/// the file's bodies are placed, so an annotation drawn on an assembly's
544/// part sits on that part.
545#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
546pub struct ImportedAnnotation {
547    /// The name the file gives it (`Linear Size.3`, `Flatness.1`), or the
548    /// text it shows where the file names it by that.
549    pub name: String,
550    pub kind: AnnotationKind,
551    /// What a label shows: `Ø 35 ±0.2`, `Flatness 0.2`, `A`.
552    pub text: String,
553    /// The drawn geometry: leaders, frames, witness lines and whatever
554    /// strokes the file draws its text with.
555    #[serde(default, skip_serializing_if = "Vec::is_empty")]
556    pub polylines: Vec<Vec<[f32; 3]>>,
557    /// Where the label goes; `None` for an annotation that draws nothing.
558    #[serde(default, skip_serializing_if = "Option::is_none")]
559    pub anchor: Option<[f32; 3]>,
560    /// The body the annotation describes, as an index into
561    /// [`ImportedModel::bodies`], where the file says which.
562    #[serde(default, skip_serializing_if = "Option::is_none")]
563    pub body_index: Option<usize>,
564}
565
566/// One hierarchy node from the imported file's product structure.
567///
568/// Nodes can either be pure containers (`body_index = None`) or reference a
569/// renderable payload in [`ImportedModel::bodies`].
570#[derive(Debug, Clone, Serialize, Deserialize)]
571pub struct ImportedNode {
572    /// Stable id scoped to one import result.
573    pub id: u64,
574    /// Parent node id; None means root.
575    #[serde(default, skip_serializing_if = "Option::is_none")]
576    pub parent_id: Option<u64>,
577    /// Human-readable name from the file's product labels when available.
578    #[serde(default, skip_serializing_if = "Option::is_none")]
579    pub name: Option<String>,
580    /// Structural type of this node.
581    #[serde(default)]
582    pub kind: ImportedNodeKind,
583    /// Initial visibility from source file metadata (if available).
584    #[serde(default = "default_imported_node_visible")]
585    pub visible: bool,
586    /// Index into [`ImportedModel::bodies`] when this node owns geometry.
587    #[serde(default, skip_serializing_if = "Option::is_none")]
588    pub body_index: Option<usize>,
589    /// Local transform matrix (row-major) relative to parent, if known.
590    #[serde(default, skip_serializing_if = "Option::is_none")]
591    pub local_transform: Option<[[f32; 4]; 4]>,
592}
593
594fn default_imported_node_visible() -> bool {
595    true
596}
597
598/// Length unit declared by an imported source file.
599///
600/// This is a thin mirror of `core_document::Unit` that lives in `kernel_api`
601/// to avoid pulling document-side types into the kernel crate. App code is
602/// responsible for translating it into the document's display unit.
603#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
604#[serde(rename_all = "snake_case")]
605pub enum LengthUnit {
606    Millimetre,
607    Centimetre,
608    Metre,
609    Inch,
610    Foot,
611}
612
613/// Result of importing an external CAD file.
614#[derive(Debug, Clone, Default, Serialize, Deserialize)]
615pub struct ImportedModel {
616    /// One entry per top-level body in the source file.
617    pub bodies: Vec<ImportedBody>,
618    /// Everything the reader had to say about the file, kept whole so it
619    /// can be handed to whoever maintains the kernel rather than scrolled
620    /// past in a terminal.
621    #[serde(default)]
622    pub report: ImportReport,
623    /// Optional assembly/object tree reconstructed from the file's product
624    /// structure.
625    #[serde(default)]
626    pub nodes: Vec<ImportedNode>,
627    /// Length unit declared by the source file, when detectable. Geometry in
628    /// `bodies` is *always* expressed in millimetres regardless; this field
629    /// is purely informational and used by the UI to pick a display unit.
630    #[serde(default)]
631    pub source_unit: Option<LengthUnit>,
632    /// The file's annotations (dimensions, tolerances, datums and notes)
633    /// in file order, the drawn ones first.
634    #[serde(default, skip_serializing_if = "Vec::is_empty")]
635    pub annotations: Vec<ImportedAnnotation>,
636}
637
638/// What the reader had to say about a file.
639///
640/// A community STEP file routinely produces a thousand lines of "this edge
641/// misses its vertex by a micron"; each one is true and none is actionable
642/// on its own. The kernel counts them by kind, and the whole prose stays
643/// here for the report a user can send along with the file.
644#[derive(Debug, Clone, Default, Serialize, Deserialize)]
645pub struct ImportReport {
646    /// The kernel that read the file, by name and version.
647    pub kernel: String,
648    /// One entry per kind of imperfection, largest count first.
649    pub summary: Vec<ImportWarningKind>,
650    /// Every warning, one line each, in the order the reader met them.
651    pub warnings: Vec<String>,
652    /// STEP entity ids of faces that read without a complete trim, so they
653    /// draw with gaps unless healed.
654    pub untrimmed_faces: Vec<u64>,
655    /// Entity keywords the reader never visited, with counts. Presentation
656    /// and annotation land here by design; geometry landing here is a gap.
657    pub skipped: Vec<(String, usize)>,
658}
659
660impl ImportReport {
661    /// Whether there is anything worth writing down.
662    pub fn is_clean(&self) -> bool {
663        self.warnings.is_empty() && self.untrimmed_faces.is_empty()
664    }
665}
666
667/// One kind of imperfect import, counted rather than repeated.
668#[derive(Debug, Clone, Serialize, Deserialize)]
669pub struct ImportWarningKind {
670    /// Stable across runs: `vertex-miss`, `boundary-slop`, `fit-short`,
671    /// `untrimmed`.
672    pub kind: String,
673    pub count: usize,
674    /// The worst measured value among them, in millimetres, for the kinds
675    /// that measure one; zero otherwise.
676    pub worst: f64,
677    /// One entity id to look at first.
678    pub exemplar: u64,
679}
680
681/// One segment of a closed 2D profile wire, in sketch-plane coordinates
682/// (millimetres). Arcs are encoded as three on-curve points so consumers
683/// never have to agree on a winding convention.
684#[cfg_attr(not(feature = "exhaustive"), non_exhaustive)]
685#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
686pub enum ProfileSegment {
687    Line {
688        start: [f64; 2],
689        end: [f64; 2],
690    },
691    /// Circular arc through three points (start → mid → end).
692    Arc {
693        start: [f64; 2],
694        mid: [f64; 2],
695        end: [f64; 2],
696    },
697    Circle {
698        center: [f64; 2],
699        radius: f64,
700    },
701    /// Full ellipse. `major` is the vector from the center to a major-axis
702    /// vertex; the minor radius is `|major| * ratio` with `ratio` in (0, 1].
703    Ellipse {
704        center: [f64; 2],
705        major: [f64; 2],
706        ratio: f64,
707    },
708    /// Elliptical arc between two parameter angles (radians, counter-clockwise
709    /// in the ellipse frame where the major axis is at parameter 0).
710    EllipseArc {
711        center: [f64; 2],
712        major: [f64; 2],
713        ratio: f64,
714        start_param: f64,
715        end_param: f64,
716    },
717    /// Cubic B-spline through the given control points. A periodic spline
718    /// closes smoothly on itself; an open one runs first → last control point.
719    BSpline {
720        control_points: Vec<[f64; 2]>,
721        periodic: bool,
722    },
723    /// A B-spline of any degree over its own knots, rational when it has
724    /// weights: an exact conic arc, a spline drawn through points. An open
725    /// one's knots are clamped (`control points + degree + 1` of them), so
726    /// it runs first → last control point; a periodic one is a uniform ring
727    /// over its control points closing smoothly on itself, and its knots
728    /// are not used.
729    Nurbs {
730        degree: u32,
731        knots: Vec<f64>,
732        control_points: Vec<[f64; 2]>,
733        /// One per control point; empty when every weight is one.
734        #[serde(default, skip_serializing_if = "Vec::is_empty")]
735        weights: Vec<f64>,
736        #[serde(default)]
737        periodic: bool,
738    },
739}
740
741/// What a [`SolidOp::PipeThrough`] runs along.
742#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
743pub enum PipePath {
744    /// A sketch's wire.
745    Profile(Profile),
746    /// Edges of the running solid, joined end to end.
747    Edges(Vec<EdgeProbe>),
748    /// Edges of another solid (a native-format snapshot, moved by
749    /// `transform` into the body's frame), joined end to end; the probes
750    /// are in the body's frame.
751    EdgesOf {
752        shape: Vec<u8>,
753        transform: Option<Box<[[f64; 4]; 4]>>,
754        edges: Vec<EdgeProbe>,
755    },
756}
757
758/// One section of a [`SolidOp::LoftThrough`].
759#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
760pub enum LoftSection {
761    Profile(Profile),
762    /// The flat face of the running solid the probe finds, by its outer
763    /// and inner boundaries.
764    Face(FaceProbe),
765    /// A point the loft closes to, in the body's frame.
766    Point([f64; 3]),
767}
768
769/// A closed loop of profile segments. Consecutive segments share endpoints;
770/// a single `Circle` segment is a wire by itself.
771#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
772pub struct ProfileWire {
773    pub segments: Vec<ProfileSegment>,
774    /// The name of each segment, one per segment, by what it was drawn from
775    /// (a sketch element): the faces a feature sweeps from it are named by
776    /// it, so they keep their names while dimensions change. Empty, or a
777    /// zero, where a segment has no such name.
778    #[serde(default, skip_serializing_if = "Vec::is_empty")]
779    pub names: Vec<TopoName>,
780}
781
782impl ProfileWire {
783    /// A wire of `segments` with no names.
784    pub fn new(segments: Vec<ProfileSegment>) -> Self {
785        Self {
786            segments,
787            names: Vec::new(),
788        }
789    }
790
791    /// The name of segment `index`, when it has one.
792    pub fn name_of(&self, index: usize) -> Option<TopoName> {
793        self.names.get(index).copied().filter(|n| *n != 0)
794    }
795}
796
797/// The plane a profile lives on, in world coordinates (millimetres).
798#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
799pub struct ProfilePlane {
800    pub origin: [f64; 3],
801    pub x_axis: [f64; 3],
802    pub y_axis: [f64; 3],
803    pub normal: [f64; 3],
804}
805
806/// The XY plane through the origin.
807impl Default for ProfilePlane {
808    fn default() -> Self {
809        Self {
810            origin: [0.0; 3],
811            x_axis: [1.0, 0.0, 0.0],
812            y_axis: [0.0, 1.0, 0.0],
813            normal: [0.0, 0.0, 1.0],
814        }
815    }
816}
817
818/// How an extrusion combines with the body's existing solid.
819#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
820pub enum BooleanOp {
821    /// Replace / start the body's solid (first feature).
822    NewSolid,
823    /// Union with the existing solid (Pad on an existing body).
824    Fuse,
825    /// Subtract from the existing solid (Pocket).
826    Cut,
827    /// Keep only what the existing solid and the tool share.
828    Common,
829}
830
831/// A set of closed wires on one plane. The largest-area wire is the outer
832/// boundary, the rest become holes.
833#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
834pub struct Profile {
835    pub plane: ProfilePlane,
836    pub wires: Vec<ProfileWire>,
837}
838
839/// Where a one-directional extrusion stops.
840#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
841pub enum ExtrudeTermination {
842    /// Fixed length in millimetres.
843    Blind { distance: f64 },
844    /// Extend well past the base solid's bounding box in this direction.
845    ThroughAll,
846    /// Stop on the given world-space plane, shifted by `offset` along its
847    /// normal (a picked planar face plus an offset-to-face value).
848    UpToPlane {
849        point: [f64; 3],
850        normal: [f64; 3],
851        offset: f64,
852    },
853    /// Stop on the base solid's face named `name`, else the one nearest
854    /// `point` (a picked face, where it was picked), exactly on its surface
855    /// whatever its shape, pushed `offset` out along its outward normal.
856    /// With no base solid, or no face of it there, the plane through
857    /// `point` square to `normal`.
858    UpToFace {
859        point: [f64; 3],
860        normal: [f64; 3],
861        offset: f64,
862        #[serde(default)]
863        name: TopoName,
864    },
865    /// Stop at the first face of the base solid hit along the extrusion
866    /// direction, on its surface.
867    ToFirst,
868    /// Stop at the last face of the base solid hit along the extrusion
869    /// direction, on its surface.
870    ToLast,
871    /// Stop on a set of the base solid's faces: every line of the sweep
872    /// ends at the first of them it meets, moved `offset` further along the
873    /// sweep (a negative offset stops short).
874    UpToShape { faces: Vec<FaceProbe>, offset: f64 },
875    /// Stop on a face of another shape: the face of `shape` (a native-format
876    /// snapshot, moved by `transform`, a rigid row-major 4×4 matrix, into
877    /// the body's frame) nearest `point`, exactly on its surface whatever
878    /// its shape, pushed `offset` out along its outward normal.
879    UpToFaceOf {
880        shape: Vec<u8>,
881        transform: Option<Box<[[f64; 4]; 4]>>,
882        point: [f64; 3],
883        offset: f64,
884    },
885    /// Stop on a set of faces as `UpToShape` does, some of them the base
886    /// solid's (`faces`) and some of other shapes (`others`, faces other
887    /// bodies lend this one). Needs no base solid when every face is
888    /// another shape's.
889    UpToShapeOf {
890        faces: Vec<FaceProbe>,
891        others: Vec<FacesOf>,
892        offset: f64,
893    },
894}
895
896/// Faces of another shape: the faces of `shape` (a native-format snapshot,
897/// moved by `transform`, a rigid row-major 4×4 matrix, into the body's
898/// frame) nearest each of `points`.
899#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
900pub struct FacesOf {
901    pub shape: Vec<u8>,
902    pub transform: Option<Box<[[f64; 4]; 4]>>,
903    pub points: Vec<[f64; 3]>,
904}
905
906/// Where a revolution stops turning.
907#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
908pub enum RevolveTermination {
909    /// Through the sweep's own angles.
910    #[default]
911    Angle,
912    /// On the first face of the base solid the profile's centre meets as it
913    /// turns.
914    ToFirst,
915    /// On the last face of the base solid the profile's centre meets as it
916    /// turns.
917    ToLast,
918    /// On the base solid's face nearest the probe.
919    UpToFace(FaceProbe),
920}
921
922/// How a profile is swept into a solid.
923#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
924pub enum SweepKind {
925    /// Linear extrusion along `plane.normal` (or `direction` when set).
926    Extrude {
927        termination: ExtrudeTermination,
928        /// Independent termination for the opposite side of the sketch plane
929        /// (two-sided extrusion). `None` extrudes one side only.
930        second_side: Option<ExtrudeTermination>,
931        /// Extrude half the blind distance to each side of the sketch plane.
932        symmetric: bool,
933        /// Swap which side of the sketch plane is "forward".
934        reversed: bool,
935        /// Draft angle applied along the sweep; positive widens the far end.
936        taper_deg: f64,
937        /// Custom world-space sweep direction; `None` uses the plane normal.
938        direction: Option<[f64; 3]>,
939    },
940    /// Revolution about an axis lying IN the sketch plane, given in sketch
941    /// 2D coordinates (point + direction). `angle_deg` in (0, 360].
942    Revolve {
943        axis_origin: [f64; 2],
944        axis_dir: [f64; 2],
945        angle_deg: f64,
946        /// Independent sweep angle for the opposite rotation direction.
947        second_angle_deg: Option<f64>,
948        /// Center the sweep on the sketch plane (half the angle each way).
949        midplane: bool,
950        reversed: bool,
951        /// Where the turn stops; anything but `Angle` takes the angle from
952        /// what the profile meets and leaves the angles above unused.
953        #[serde(default)]
954        termination: RevolveTermination,
955    },
956    /// Sweep the profile along a helix whose axis lies in the sketch plane.
957    /// A cone angle moves every point away from the axis by tan(angle) of
958    /// every pitch it climbs.
959    Helix {
960        axis_origin: [f64; 2],
961        axis_dir: [f64; 2],
962        pitch: f64,
963        height: f64,
964        left_handed: bool,
965        cone_angle_deg: f64,
966        reversed: bool,
967        /// How many turns, when given: the pitch is then `height / turns`
968        /// and `pitch` is not read. A height of 0 with turns and growth is
969        /// a flat spiral.
970        #[serde(default)]
971        turns: Option<f64>,
972        /// How far every point moves away from the axis per turn, when
973        /// given, in place of `cone_angle_deg`.
974        #[serde(default)]
975        growth: Option<f64>,
976    },
977    /// Sweep the profile along a helix whose axis runs square to the sketch
978    /// plane through `axis_origin` (sketch 2D coordinates): every point of
979    /// the profile climbs its own helix about it, the profile staying
980    /// level. The rest reads as for `Helix`.
981    HelixNormal {
982        axis_origin: [f64; 2],
983        pitch: f64,
984        height: f64,
985        left_handed: bool,
986        cone_angle_deg: f64,
987        reversed: bool,
988        #[serde(default)]
989        turns: Option<f64>,
990        #[serde(default)]
991        growth: Option<f64>,
992    },
993}
994
995/// How a pipe's section turns as it runs down its path.
996#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
997pub enum PipeFrame {
998    /// Rotation-minimizing: the section neither twists nor kinks where the
999    /// path bends.
1000    #[default]
1001    RotationMinimizing,
1002    /// The path's own curvature frame, turning with it.
1003    Frenet,
1004    /// The section turns about the path so that one direction of it keeps
1005    /// pointing at a second path running beside the first.
1006    Auxiliary { path: Profile },
1007    /// The section keeps a fixed binormal: the world-space direction square
1008    /// to the path that the section's frame holds all the way.
1009    Binormal { direction: [f64; 3] },
1010    /// The section keeps its orientation in space: carried along the path
1011    /// without ever turning, as it is drawn.
1012    Fixed,
1013}
1014
1015impl PipeFrame {
1016    /// The frame an older `frenet` flag named.
1017    pub fn from_frenet(frenet: bool) -> Self {
1018        if frenet {
1019            PipeFrame::Frenet
1020        } else {
1021            PipeFrame::RotationMinimizing
1022        }
1023    }
1024}
1025
1026/// Reads a [`PipeFrame`] or the `frenet` flag it stands in for.
1027pub fn deserialize_pipe_frame<'de, D>(deserializer: D) -> Result<PipeFrame, D::Error>
1028where
1029    D: serde::Deserializer<'de>,
1030{
1031    #[derive(Deserialize)]
1032    #[serde(untagged)]
1033    enum Stored {
1034        Flag(bool),
1035        Frame(PipeFrame),
1036    }
1037    Ok(match Stored::deserialize(deserializer)? {
1038        Stored::Flag(frenet) => PipeFrame::from_frenet(frenet),
1039        Stored::Frame(frame) => frame,
1040    })
1041}
1042
1043/// How a pipe's section turns a sharp corner of its path.
1044#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
1045pub enum PipeCorner {
1046    /// The section is carried into the corner and sheared onto the plane
1047    /// bisecting it: the two legs meet on that mitre.
1048    #[default]
1049    Transformed,
1050    /// Each leg runs on straight past the corner and the two are fused,
1051    /// leaving the outside of the corner square.
1052    Right,
1053    /// The section turns about the corner, the outside of it rounded.
1054    Round,
1055}
1056
1057/// Parametric primitive shapes (dimensions in millimetres, angles degrees).
1058#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
1059pub enum PrimitiveKind {
1060    Box {
1061        length: f64,
1062        width: f64,
1063        height: f64,
1064    },
1065    Cylinder {
1066        radius: f64,
1067        height: f64,
1068        angle_deg: f64,
1069    },
1070    Sphere {
1071        radius: f64,
1072        /// Latitude range and longitude sweep (three-angle parameterization).
1073        angle1_deg: f64,
1074        angle2_deg: f64,
1075        angle3_deg: f64,
1076    },
1077    Cone {
1078        radius1: f64,
1079        radius2: f64,
1080        height: f64,
1081        angle_deg: f64,
1082    },
1083    Torus {
1084        radius1: f64,
1085        radius2: f64,
1086        angle1_deg: f64,
1087        angle2_deg: f64,
1088        angle3_deg: f64,
1089    },
1090    /// An ellipsoid, cut as a sphere is: between two latitudes about its
1091    /// third axis and through a sweep round it.
1092    Ellipsoid {
1093        radius1: f64,
1094        radius2: f64,
1095        radius3: f64,
1096        #[serde(default = "south_pole")]
1097        angle1_deg: f64,
1098        #[serde(default = "north_pole")]
1099        angle2_deg: f64,
1100        #[serde(default = "full_turn")]
1101        angle3_deg: f64,
1102    },
1103    /// A regular prism, its top shifted by the skew angles: leaning that
1104    /// far from its axis toward its x and its y.
1105    Prism {
1106        sides: u32,
1107        circumradius: f64,
1108        height: f64,
1109        #[serde(default)]
1110        skew_x_deg: f64,
1111        #[serde(default)]
1112        skew_y_deg: f64,
1113    },
1114    /// A hollow cylinder: a wall between the radii `inner` and `outer`
1115    /// about its axis, `height` tall. The inner radius is above zero and
1116    /// below the outer.
1117    Tube { outer: f64, inner: f64, height: f64 },
1118    /// Box with an independently sized top rectangle (zero top spans give a
1119    /// pyramid). Spans are along local X (`x2*`) and Z (`z2*`) at height Y.
1120    Wedge {
1121        xmin: f64,
1122        xmax: f64,
1123        ymin: f64,
1124        ymax: f64,
1125        zmin: f64,
1126        zmax: f64,
1127        x2min: f64,
1128        x2max: f64,
1129        z2min: f64,
1130        z2max: f64,
1131    },
1132}
1133
1134fn south_pole() -> f64 {
1135    -90.0
1136}
1137
1138fn north_pole() -> f64 {
1139    90.0
1140}
1141
1142fn full_turn() -> f64 {
1143    360.0
1144}
1145
1146/// A right-handed placement frame in world coordinates (millimetres).
1147#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
1148pub struct Placement {
1149    pub origin: [f64; 3],
1150    pub x_axis: [f64; 3],
1151    pub z_axis: [f64; 3],
1152}
1153
1154impl Default for Placement {
1155    fn default() -> Self {
1156        Self {
1157            origin: [0.0; 3],
1158            x_axis: [1.0, 0.0, 0.0],
1159            z_axis: [0.0, 0.0, 1.0],
1160        }
1161    }
1162}
1163
1164/// Which edges of the current solid a dress-up applies to. Edges are
1165/// identified geometrically: by a face they border (sample point on the
1166/// face) or by a point near the edge itself.
1167#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1168pub enum EdgeSelection {
1169    All,
1170    OfFaces(Vec<[f64; 3]>),
1171    /// The edges bordering the picked faces, each found by its name when
1172    /// it has one.
1173    OfPickedFaces(Vec<FaceProbe>),
1174    Near(Vec<[f64; 3]>),
1175    /// Edges picked one by one: each the nearest edge to its point that
1176    /// runs along its direction there.
1177    Picked(Vec<EdgeProbe>),
1178}
1179
1180/// A picked edge, as a point beside it and the way it runs there, and the
1181/// names of the two faces it runs between. A rebuild finds the edge
1182/// between faces of those names, the point choosing among several; without
1183/// names, the nearest edge. A zero direction leaves the way open.
1184#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
1185pub struct EdgeProbe {
1186    pub point: [f64; 3],
1187    pub direction: [f64; 3],
1188    #[serde(default)]
1189    pub faces: [TopoName; 2],
1190}
1191
1192/// How a thickness's walls meet across an edge of the solid.
1193#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
1194pub enum ThicknessJoin {
1195    /// The walls run on until they meet: sharp corners.
1196    #[default]
1197    Intersection,
1198    /// The walls round about the edge, the wall thickness its radius.
1199    Arc,
1200}
1201
1202impl ThicknessJoin {
1203    pub const ALL: [ThicknessJoin; 2] = [ThicknessJoin::Intersection, ThicknessJoin::Arc];
1204
1205    pub fn label(&self) -> &'static str {
1206        match self {
1207            ThicknessJoin::Intersection => "Intersection",
1208            ThicknessJoin::Arc => "Arc",
1209        }
1210    }
1211}
1212
1213/// Chamfer sizing, mirroring the three standard input styles.
1214#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
1215pub enum ChamferSpec {
1216    EqualDistance { distance: f64 },
1217    TwoDistances { distance1: f64, distance2: f64 },
1218    DistanceAngle { distance: f64, angle_deg: f64 },
1219}
1220
1221/// Boolean between the running solid and an external tool solid.
1222#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1223pub enum BoolKind {
1224    Fuse,
1225    Cut,
1226    Common,
1227}
1228
1229/// One step in a body's build history. Shape-producing steps (`Sweep`,
1230/// `Loft`, `Pipe`, `Primitive`) carry a [`BooleanOp`]; the remaining steps
1231/// modify or combine the running solid directly.
1232///
1233/// A package builds these, so a variant keeps its fields for as long as
1234/// the contract's minor version holds: a new option comes as a new
1235/// variant, or as a new struct that derives `Default`.
1236#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1237pub enum SolidOp {
1238    /// Start the chain from a snapshot of another solid, in the native
1239    /// format `SolidBuildResult::brep_blob` carries. Only ever the first op.
1240    Shape { brep: Vec<u8> },
1241    Sweep {
1242        profile: Profile,
1243        kind: SweepKind,
1244        op: BooleanOp,
1245    },
1246    /// Extrude a flat face of the running solid: its outer and inner
1247    /// boundaries are the profile and its outward normal the sketch
1248    /// normal. `kind` is an `Extrude`.
1249    SweepFace {
1250        face: FaceProbe,
1251        kind: SweepKind,
1252        op: BooleanOp,
1253    },
1254    /// Extrude a flat face of another shape (native-format `shape`, moved by
1255    /// `transform` into this body's frame): the face of it at `point`, a
1256    /// face another body lends this one.
1257    SweepFaceOf {
1258        shape: Vec<u8>,
1259        transform: Option<Box<[[f64; 4]; 4]>>,
1260        point: [f64; 3],
1261        kind: SweepKind,
1262        op: BooleanOp,
1263    },
1264    /// Revolve a profile until it meets a face of another shape
1265    /// (native-format `shape`, moved by `transform` into this body's frame):
1266    /// the face of it nearest `point`, a face another body lends this one.
1267    /// `kind` is a `Revolve`, whose own termination is not read.
1268    RevolveToFaceOf {
1269        profile: Profile,
1270        kind: SweepKind,
1271        shape: Vec<u8>,
1272        transform: Option<Box<[[f64; 4]; 4]>>,
1273        point: [f64; 3],
1274        op: BooleanOp,
1275    },
1276    /// Skin through two or more sections (in order), each a profile, a
1277    /// flat face of the running solid (its boundary) or a point, which
1278    /// only the first or last may be.
1279    LoftThrough {
1280        sections: Vec<LoftSection>,
1281        ruled: bool,
1282        closed: bool,
1283        op: BooleanOp,
1284    },
1285    /// Skin through two or more section profiles (in order).
1286    Loft {
1287        sections: Vec<Profile>,
1288        ruled: bool,
1289        closed: bool,
1290        op: BooleanOp,
1291    },
1292    /// Sweep a profile along an open or closed spine wire from another
1293    /// sketch, the section turning as `frame` says and turning its corners
1294    /// as `corner` says. With `sections`, the section changes shape down
1295    /// the path, passing through each of them where it crosses the path,
1296    /// in order, the profile first.
1297    Pipe {
1298        profile: Profile,
1299        spine: Profile,
1300        #[serde(default, alias = "frenet", deserialize_with = "deserialize_pipe_frame")]
1301        frame: PipeFrame,
1302        #[serde(default)]
1303        corner: PipeCorner,
1304        #[serde(default)]
1305        sections: Vec<Profile>,
1306        op: BooleanOp,
1307    },
1308    /// A pipe whose profile may be a flat face of the running solid, whose
1309    /// path may be edges of a solid, and whose last section may be a point
1310    /// it closes to; the rest reads as for `Pipe`.
1311    PipeThrough {
1312        profile: LoftSection,
1313        path: PipePath,
1314        #[serde(default)]
1315        frame: PipeFrame,
1316        #[serde(default)]
1317        corner: PipeCorner,
1318        #[serde(default)]
1319        sections: Vec<LoftSection>,
1320        op: BooleanOp,
1321    },
1322    Primitive {
1323        kind: PrimitiveKind,
1324        placement: Placement,
1325        op: BooleanOp,
1326    },
1327    /// Round the selected edges; with `follow_tangent`, every edge meeting
1328    /// one of them tangentially joins the selection, and so on along the
1329    /// chain.
1330    Fillet {
1331        radius: f64,
1332        edges: EdgeSelection,
1333        #[serde(default)]
1334        follow_tangent: bool,
1335    },
1336    /// Round between two faces of the running solid, which need share no
1337    /// edge: the ball rolling between them, its round filling or taking off
1338    /// what lies between it and the faces' meeting (a step across a groove).
1339    BlendFaces { radius: f64, faces: [FaceProbe; 2] },
1340    /// Bevel the selected edges, taking tangent chains as a fillet does.
1341    Chamfer {
1342        spec: ChamferSpec,
1343        flip: bool,
1344        edges: EdgeSelection,
1345        #[serde(default)]
1346        follow_tangent: bool,
1347    },
1348    /// Tilt the selected faces by `angle_deg` about their intersection with
1349    /// the neutral plane.
1350    Draft {
1351        angle_deg: f64,
1352        neutral_point: [f64; 3],
1353        neutral_normal: [f64; 3],
1354        pull_dir: Option<[f64; 3]>,
1355        faces: Vec<[f64; 3]>,
1356        /// The name of each face, one per point, found by name first; empty
1357        /// or zero where a face has none.
1358        #[serde(default, skip_serializing_if = "Vec::is_empty")]
1359        face_names: Vec<TopoName>,
1360    },
1361    /// Merge adjacent faces of the solid that lie on one plane: the split
1362    /// a fuse or cut leaves where two pieces meet flush.
1363    Refine,
1364    /// Offset faces of the running solid along their outward normals by
1365    /// `distance` (negative into the material), the faces around them
1366    /// following on their own surfaces.
1367    OffsetFaces {
1368        faces: Vec<[f64; 3]>,
1369        #[serde(default, skip_serializing_if = "Vec::is_empty")]
1370        face_names: Vec<TopoName>,
1371        distance: f64,
1372    },
1373    /// Move faces of the running solid rigidly by `transform` (row-major,
1374    /// a translation or a rotation), the faces around them following.
1375    MoveFaces {
1376        faces: Vec<[f64; 3]>,
1377        #[serde(default, skip_serializing_if = "Vec::is_empty")]
1378        face_names: Vec<TopoName>,
1379        transform: [[f64; 4]; 4],
1380    },
1381    /// Remove faces of the running solid and close the openings from the
1382    /// neighbouring faces' own geometry: a hole, a boss or a fillet taken
1383    /// away. Faces as points on them, named where they have names.
1384    RemoveFaces {
1385        faces: Vec<[f64; 3]>,
1386        #[serde(default, skip_serializing_if = "Vec::is_empty")]
1387        face_names: Vec<TopoName>,
1388    },
1389    /// Hollow the solid, removing the faces sampled by `open_faces`.
1390    Thickness {
1391        value: f64,
1392        open_faces: Vec<[f64; 3]>,
1393        /// The name of each open face, one per point; empty or zero where
1394        /// a face has none.
1395        #[serde(default, skip_serializing_if = "Vec::is_empty")]
1396        open_face_names: Vec<TopoName>,
1397        inward: bool,
1398        /// How the walls meet where the solid's faces meet.
1399        #[serde(default)]
1400        join: ThicknessJoin,
1401        /// The walls stand on both sides of the solid's faces, `value` each
1402        /// way, rather than on the one `inward` says.
1403        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1404        both_sides: bool,
1405    },
1406    /// Re-apply earlier steps' tool solids (or the whole current solid when
1407    /// `originals` is empty) under each transform, fusing additive tools and
1408    /// cutting subtractive ones. `originals` holds chain indices of earlier
1409    /// shape-producing steps.
1410    Transform {
1411        transforms: Vec<[[f64; 4]; 4]>,
1412        originals: Vec<usize>,
1413    },
1414    /// [`SolidOp::Transform`] with the originals themselves left out: the
1415    /// steps `originals` names build their tools without adding or cutting
1416    /// them, so only the transformed copies go in. With `originals` empty
1417    /// the running solid gives way to its copies.
1418    TransformCopies {
1419        transforms: Vec<[[f64; 4]; 4]>,
1420        originals: Vec<usize>,
1421    },
1422    /// [`SolidOp::Transform`] whose transforms the chain works out from
1423    /// `steps` where the op stands, so a step may follow an edge of the
1424    /// solid as it is there. Occurrence 0 is the original; with it among
1425    /// `skipped`, only the copies go in, as [`SolidOp::TransformCopies`].
1426    Pattern {
1427        steps: Vec<PatternStep>,
1428        originals: Vec<usize>,
1429        /// Occurrences left out, by index: 0 the original, then each copy
1430        /// in the order the steps make them.
1431        #[serde(default, skip_serializing_if = "Vec::is_empty")]
1432        skipped: Vec<u32>,
1433    },
1434    /// Boolean against an external solid (another body's shape snapshot,
1435    /// ogeom native-format text bytes).
1436    Boolean {
1437        tool_brep: Vec<u8>,
1438        kind: BoolKind,
1439        /// Where the tool sits in this chain's frame, when the two bodies
1440        /// are placed differently: a rigid row-major 4×4 matrix.
1441        #[serde(default)]
1442        tool_transform: Option<[[f64; 4]; 4]>,
1443    },
1444    /// A surface step: a sheet added to the body, or the body's sheets
1445    /// joined, trimmed or mirrored.
1446    Surface(SurfaceOp),
1447    /// `op` with its booleans run at a stated tolerance: geometry within
1448    /// `tolerance` mm of touching counts as touching, so faces that nearly
1449    /// meet are joined rather than left with a gap or a sliver between
1450    /// them. The op keeps its place in the chain, as a pattern's
1451    /// `originals` count it.
1452    WithTolerance { tolerance: f64, op: Box<SolidOp> },
1453    /// A sketch carried along its plane's normal onto faces of the running
1454    /// solid, each face split along the curves where they land; `mode`
1455    /// says whether the regions the curves enclose then stand out of the
1456    /// faces or sink into them by `height`.
1457    Project {
1458        profile: Profile,
1459        faces: Vec<FaceProbe>,
1460        mode: ProjectMode,
1461        height: f64,
1462    },
1463    /// A sketch unrolled onto the cylinder or cone its `faces` lie on, so
1464    /// its lengths are kept on the surface: the sketch's middle lands where
1465    /// a straight projection along its plane's normal puts it, and the
1466    /// rest is laid round the surface from there, the way across the
1467    /// axis turning about it and the way along the axis following it.
1468    /// Otherwise as [`SolidOp::Project`].
1469    Wrap {
1470        profile: Profile,
1471        faces: Vec<FaceProbe>,
1472        mode: ProjectMode,
1473        height: f64,
1474    },
1475    /// Keep the running solid's material on one side of a plane: the side
1476    /// `normal` points to from `origin`. A plane that leaves nothing on
1477    /// that side fails, saying so.
1478    HalfSpace { origin: [f64; 3], normal: [f64; 3] },
1479    /// Grow the running solid by `distance` everywhere along its faces'
1480    /// outward normals, or shrink it with a negative one: every face moved
1481    /// that far and the faces around it following, its topology kept.
1482    OffsetSolid { distance: f64 },
1483    /// Scale the running solid by `factors` along the body's X, Y and Z
1484    /// about `centre`, or about the middle of its bounding box when that
1485    /// is `None`. Equal factors keep its surfaces' kinds; unequal ones
1486    /// restate them as the kernel's general transform does.
1487    Scale {
1488        factors: [f64; 3],
1489        centre: Option<[f64; 3]>,
1490    },
1491    /// Keep one piece of the running shape: of its solids, the one
1492    /// nearest `near`, the others left out.
1493    KeepPiece { near: [f64; 3] },
1494}
1495
1496/// What a [`SolidOp::Project`] makes of the faces a sketch lands on.
1497#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
1498pub enum ProjectMode {
1499    /// The faces split along the sketch's curves, the solid's shape
1500    /// unchanged: lines later features and face colours can use.
1501    #[default]
1502    Split,
1503    /// The regions the curves enclose raised out of the faces.
1504    Emboss,
1505    /// The regions the curves enclose sunk into the faces.
1506    Deboss,
1507}
1508
1509impl ProjectMode {
1510    pub const ALL: [ProjectMode; 3] =
1511        [ProjectMode::Split, ProjectMode::Emboss, ProjectMode::Deboss];
1512
1513    pub fn label(&self) -> &'static str {
1514        match self {
1515            ProjectMode::Split => "Split lines",
1516            ProjectMode::Emboss => "Emboss",
1517            ProjectMode::Deboss => "Deboss",
1518        }
1519    }
1520}
1521
1522/// A curve a surface is built from.
1523#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1524pub enum CurveSource {
1525    /// A chain of a sketch's curves, open or closed, on its plane.
1526    Sketch {
1527        plane: ProfilePlane,
1528        wire: ProfileWire,
1529    },
1530    /// An edge of the body's own shape as it stands where the step comes,
1531    /// found as a fillet's picked edges are.
1532    Edge(EdgeProbe),
1533    /// An edge of another body's shape: `brep` is that body's snapshot,
1534    /// `edge` finds the edge in its own frame, and `transform` (a rigid
1535    /// row-major 4×4 matrix) carries it to where it sits in this chain's
1536    /// frame, when the two bodies are placed differently.
1537    BodyEdge {
1538        brep: Vec<u8>,
1539        edge: EdgeProbe,
1540        #[serde(default)]
1541        transform: Option<Box<[[f64; 4]; 4]>>,
1542    },
1543}
1544
1545/// How a surface meets the faces beside it across a shared edge.
1546#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
1547pub enum Continuity {
1548    /// Touching: no gap, a crease allowed.
1549    #[default]
1550    G0,
1551    /// Tangent: no crease.
1552    G1,
1553    /// Curvature continuous: no change in how sharply it bends.
1554    G2,
1555}
1556
1557/// The steps of surface modelling. A constructive step (every one but
1558/// `Sew`, `TrimByPlane` and `Mirror`) adds its sheet to the body beside
1559/// what is there; the rest act on all of the body's shape.
1560#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1561pub enum SurfaceOp {
1562    /// Each curve swept straight along `direction` by `length`, both ways
1563    /// by half of it when `symmetric`.
1564    Extrude {
1565        curves: Vec<CurveSource>,
1566        direction: [f64; 3],
1567        length: f64,
1568        #[serde(default)]
1569        symmetric: bool,
1570    },
1571    /// Each curve turned by `angle_deg` about the axis through `origin`
1572    /// along `axis`.
1573    Revolve {
1574        curves: Vec<CurveSource>,
1575        origin: [f64; 3],
1576        axis: [f64; 3],
1577        angle_deg: f64,
1578    },
1579    /// The flat face closed planar loops bound, a loop inside another a
1580    /// hole in it.
1581    PlanarFill { curves: Vec<CurveSource> },
1582    /// The surface curves meeting end to end bound, meeting the faces the
1583    /// boundary edges belong to with `continuity`.
1584    Fill {
1585        boundary: Vec<CurveSource>,
1586        #[serde(default)]
1587        continuity: Continuity,
1588    },
1589    /// The surface of straight lines between two curves, end to end.
1590    Ruled {
1591        first: CurveSource,
1592        second: CurveSource,
1593    },
1594    /// A surface through section curves in order, closing back to the first
1595    /// when `closed`.
1596    Loft {
1597        sections: Vec<CurveSource>,
1598        #[serde(default)]
1599        closed: bool,
1600    },
1601    /// A profile curve swept along a path.
1602    Sweep {
1603        profile: Vec<CurveSource>,
1604        path: Vec<CurveSource>,
1605        #[serde(default)]
1606        frame: PipeFrame,
1607    },
1608    /// A surface through section curves in order that also follows guide
1609    /// curves, each crossing every section once: one face.
1610    GuidedLoft {
1611        sections: Vec<CurveSource>,
1612        guides: Vec<CurveSource>,
1613    },
1614    /// A profile running from the first rail's start to the second's,
1615    /// swept along both: at each point along them it is turned and scaled
1616    /// so its ends ride the rails.
1617    SweepTwoRails {
1618        profile: Vec<CurveSource>,
1619        first_rail: Vec<CurveSource>,
1620        second_rail: Vec<CurveSource>,
1621    },
1622    /// Faces carried off along their normals by `distance`, as new faces.
1623    Offset {
1624        faces: Vec<FaceProbe>,
1625        distance: f64,
1626    },
1627    /// Faces carried past picked edges of their boundary by `length`.
1628    Extend {
1629        edges: Vec<EdgeProbe>,
1630        length: f64,
1631        #[serde(default)]
1632        continuity: Continuity,
1633    },
1634    /// A surface bridging two edges, meeting each edge's face with
1635    /// `continuity`.
1636    Blend {
1637        first: EdgeProbe,
1638        second: EdgeProbe,
1639        #[serde(default)]
1640        continuity: Continuity,
1641    },
1642    /// Picked faces split along curves projected onto them.
1643    Split {
1644        faces: Vec<FaceProbe>,
1645        curves: Vec<CurveSource>,
1646    },
1647    /// The body's faces joined where their edges meet, or come within
1648    /// `gap` of each other (0 for exactly); a shell that closes becomes a
1649    /// solid.
1650    Sew {
1651        #[serde(default)]
1652        gap: f64,
1653    },
1654    /// A round of `radius` along picked edges where two faces of a sheet
1655    /// meet.
1656    Fillet { edges: Vec<EdgeProbe>, radius: f64 },
1657    /// A round of `radius` between two faces of the body that need share
1658    /// no edge, such as two separate surfaces, each cut back to where it
1659    /// meets the round. The ball rolls on the side each face's normal
1660    /// points to, on the other where `flip` says so.
1661    FilletFaces {
1662        first: FaceProbe,
1663        second: FaceProbe,
1664        radius: f64,
1665        #[serde(default)]
1666        flip: [bool; 2],
1667    },
1668    /// The body's sheets given `thickness` along their normals (both ways
1669    /// by half when `both_sides`): a solid.
1670    Thicken {
1671        thickness: f64,
1672        #[serde(default)]
1673        both_sides: bool,
1674    },
1675    /// The body's sheets cut by the plane through `origin`, the side
1676    /// `normal` points to kept.
1677    TrimByPlane { origin: [f64; 3], normal: [f64; 3] },
1678    /// The body's shape and its reflection in the plane through `origin`
1679    /// square to `normal`.
1680    Mirror { origin: [f64; 3], normal: [f64; 3] },
1681    /// The body's sheets cut by each other, the faces lying on `scan`
1682    /// kept (at least `share` of each face's area within `tolerance` of
1683    /// it) and sewn: a closed shell becomes a solid. The scan's
1684    /// triangles, `scan` vertices taken three by three from `triangles`,
1685    /// are in the body's frame.
1686    TrimByScan {
1687        scan: Vec<[f32; 3]>,
1688        triangles: Vec<u32>,
1689        tolerance: f64,
1690        share: f64,
1691    },
1692    /// A free-form (B-spline) sheet fitted to scattered `points`, such as
1693    /// a region of a scan, within `tolerance` of them where it can.
1694    FitScattered {
1695        points: Vec<[f64; 3]>,
1696        tolerance: f64,
1697    },
1698    /// A network of B-spline patches fitted to `points` at once, each
1699    /// patch bounded by curves of the network and meeting its neighbours
1700    /// across them without a gap, tangent unless the curve is a crease.
1701    /// The network's curves are `curves`, one chain each, then
1702    /// `polylines`; a patch names its sides in order round it as curve
1703    /// numbers from 1, negative where the curve runs against the walk and 0
1704    /// for a side shrunk to a point.
1705    FitNetwork {
1706        curves: Vec<CurveSource>,
1707        polylines: Vec<Vec<[f64; 3]>>,
1708        #[serde(default)]
1709        patches: Vec<[i32; 4]>,
1710        /// Additional patches with each side a chain in walking order.
1711        /// An empty side is shrunk to a point; chain entries are nonzero
1712        /// signed curve numbers, as in `patches`.
1713        #[serde(default)]
1714        chained: Vec<[Vec<i32>; 4]>,
1715        /// Parameter-correction passes after refinement.
1716        #[serde(default)]
1717        corrections: u32,
1718        points: Vec<[f64; 3]>,
1719        tolerance: f64,
1720        smoothing: f64,
1721        /// The curves, numbered from 1, the patches meet across creased.
1722        creases: Vec<u32>,
1723    },
1724}
1725
1726impl SurfaceOp {
1727    /// Whether the step makes a new sheet (and so may begin a chain).
1728    pub fn constructs(&self) -> bool {
1729        !matches!(
1730            self,
1731            SurfaceOp::Sew { .. }
1732                | SurfaceOp::Fillet { .. }
1733                | SurfaceOp::FilletFaces { .. }
1734                | SurfaceOp::Thicken { .. }
1735                | SurfaceOp::TrimByPlane { .. }
1736                | SurfaceOp::Mirror { .. }
1737                | SurfaceOp::Split { .. }
1738                | SurfaceOp::Extend { .. }
1739                | SurfaceOp::TrimByScan { .. }
1740        )
1741    }
1742}
1743
1744/// One step of a [`SolidOp::Pattern`]: each applies to every occurrence of
1745/// the steps before it, the original among them, which stands first.
1746#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1747pub enum PatternStep {
1748    /// A copy under each transform (rigid or not, row-major), the
1749    /// original, untransformed, left out.
1750    Transforms(Vec<[[f64; 4]; 4]>),
1751    /// Copies along a path.
1752    Path(PathLayout),
1753}
1754
1755/// The path a [`PathLayout`] runs along, in the chain's frame.
1756#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1757pub enum PatternPath {
1758    /// A chain of curves on a plane, walked from its first segment's
1759    /// start.
1760    Wire {
1761        plane: ProfilePlane,
1762        wire: ProfileWire,
1763    },
1764    /// The edge of the solid, where the step stands, that the probe finds,
1765    /// walked from its curve's start.
1766    Edge(EdgeProbe),
1767}
1768
1769/// Occurrences at stations along a path by arc length, the original at
1770/// the first: occurrence k is moved from where the first station stands
1771/// to where the k-th does, turned as the path turns between them when
1772/// `align`.
1773#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1774pub struct PathLayout {
1775    pub path: PatternPath,
1776    /// Occurrences, the original counted.
1777    pub count: u32,
1778    /// Millimetres between neighbours along the path; `None` spreads them
1779    /// over the whole of it, evenly round it when it closes.
1780    #[serde(default, skip_serializing_if = "Option::is_none")]
1781    pub spacing: Option<f64>,
1782    /// Walk the path from its end.
1783    #[serde(default)]
1784    pub reversed: bool,
1785    /// Turn each copy as the path's direction turns from the first
1786    /// station to its own, carried along the path without twisting.
1787    #[serde(default)]
1788    pub align: bool,
1789}
1790
1791impl SolidOp {
1792    /// The op itself, out of any [`SolidOp::WithTolerance`] around it.
1793    pub fn inner(&self) -> &SolidOp {
1794        match self {
1795            SolidOp::WithTolerance { op, .. } => op.inner(),
1796            op => op,
1797        }
1798    }
1799
1800    /// The tolerance the op's booleans run at, when one is stated: the
1801    /// outermost [`SolidOp::WithTolerance`]'s.
1802    pub fn boolean_tolerance(&self) -> Option<f64> {
1803        match self {
1804            SolidOp::WithTolerance { tolerance, .. } => Some(*tolerance),
1805            _ => None,
1806        }
1807    }
1808
1809    /// The op with its booleans run at `tolerance`, or as it is with none.
1810    pub fn with_boolean_tolerance(self, tolerance: Option<f64>) -> SolidOp {
1811        match tolerance {
1812            Some(tolerance) => SolidOp::WithTolerance {
1813                tolerance,
1814                op: Box::new(self),
1815            },
1816            None => self,
1817        }
1818    }
1819
1820    /// Whether the step makes a shape of its own, so a chain may begin with
1821    /// it: a new solid, or a surface step that adds a sheet.
1822    pub fn starts_shape(&self) -> bool {
1823        match self.inner() {
1824            SolidOp::Surface(op) => op.constructs(),
1825            _ => self.boolean_op() == Some(BooleanOp::NewSolid),
1826        }
1827    }
1828
1829    /// The boolean role of a shape-producing step; `None` for modifiers.
1830    pub fn boolean_op(&self) -> Option<BooleanOp> {
1831        match self.inner() {
1832            SolidOp::Sweep { op, .. }
1833            | SolidOp::SweepFace { op, .. }
1834            | SolidOp::SweepFaceOf { op, .. }
1835            | SolidOp::RevolveToFaceOf { op, .. }
1836            | SolidOp::Loft { op, .. }
1837            | SolidOp::LoftThrough { op, .. }
1838            | SolidOp::PipeThrough { op, .. }
1839            | SolidOp::Pipe { op, .. }
1840            | SolidOp::Primitive { op, .. } => Some(*op),
1841            // A snapshot is a solid in itself: it begins a chain.
1842            SolidOp::Shape { .. } => Some(BooleanOp::NewSolid),
1843            _ => None,
1844        }
1845    }
1846}
1847
1848/// Error from executing a body's solid-op chain, attributed to the failing
1849/// step so the caller can mark the matching feature.
1850#[derive(Debug, Clone, Default, Error)]
1851#[error("op {op_index}: {message}")]
1852pub struct ChainError {
1853    pub op_index: usize,
1854    pub message: String,
1855    /// The edges a refused fillet or chamfer took, and those it could not
1856    /// round or bevel.
1857    pub edges: EdgeRefusal,
1858}
1859
1860/// The edges of a fillet or chamfer the kernel refused.
1861#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1862pub struct EdgeRefusal {
1863    /// Every edge the op took, in its order, tangent chains followed: what
1864    /// it rounds without the failing ones is these less those.
1865    pub request: Vec<EdgeProbe>,
1866    /// The edges that fail.
1867    pub failing: Vec<FailingEdge>,
1868    /// The largest share of the asked size at which every edge of the
1869    /// request builds, when it does at some: the size times it fits.
1870    #[serde(default)]
1871    pub fits: Option<f64>,
1872}
1873
1874/// An edge a fillet or chamfer could not round or bevel: refused alone, or
1875/// in a group of the op's edges meeting at a vertex.
1876#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1877pub struct FailingEdge {
1878    /// Its place among the edges the op rounds, from zero.
1879    pub index: usize,
1880    /// How many edges the op rounds.
1881    pub of: usize,
1882    /// A pick that names it in the body's own frame: a point halfway
1883    /// along, the way it runs there and its faces' names.
1884    pub probe: EdgeProbe,
1885    /// Points along it in the body's own frame, to draw it by.
1886    pub points: Vec<[f64; 3]>,
1887    /// Why the kernel refused it.
1888    pub reason: String,
1889    /// The largest share of the asked size at which it builds on its own,
1890    /// when it does at some.
1891    #[serde(default)]
1892    pub fits: Option<f64>,
1893}
1894
1895/// Result of executing a body's solid-op chain.
1896#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1897pub struct SolidBuildResult {
1898    /// Native-format shape snapshot of the final solid (for later
1899    /// re-tessellation, persistence, and downstream booleans).
1900    pub brep_blob: Vec<u8>,
1901    /// Render mesh of the final solid.
1902    pub mesh: TriMesh,
1903    /// Axis-aligned bounds in millimetres.
1904    pub bounds_mm: Option<([f32; 3], [f32; 3])>,
1905    /// What the feature being edited does, when the build was asked for it.
1906    pub preview: Option<Box<FeaturePreview>>,
1907    /// The answers to the chain's probes, in the order they were asked.
1908    pub probes: Vec<Result<ProbeAnswer, String>>,
1909    /// The curves the chain's projections came to, in the order they were
1910    /// asked.
1911    #[serde(default)]
1912    pub projections: Vec<Result<Vec<ProjectedEdge>, String>>,
1913}
1914
1915/// What a feature being edited does to its body, beside the body without
1916/// it: the view while it is edited.
1917#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1918pub struct FeaturePreview {
1919    /// The body to show meanwhile: as it stood before a feature that adds,
1920    /// after one that cuts. None when an adding feature is the body's
1921    /// first.
1922    pub shown: Option<Box<SolidBuildResult>>,
1923    /// The feature's own tool solid, meshed: the material it adds or takes.
1924    pub tool: TriMesh,
1925    /// The feature cuts.
1926    pub cuts: bool,
1927}
1928
1929/// Trait implemented by any geometry kernel that can serve the application.
1930pub trait Kernel: Send {
1931    /// Human-friendly identifier for logging purposes.
1932    fn name(&self) -> &str;
1933
1934    /// Called once before any geometry work happens.
1935    fn initialize(&mut self) -> KernelResult<()>;
1936
1937    /// Recompute dirty features/bodies and return the affected handles.
1938    fn rebuild(&mut self, request: &RebuildRequest) -> KernelResult<RebuildResponse>;
1939
1940    /// Produce a triangular mesh for the provided body handle.
1941    fn tessellate(&self, body: BodyHandle, detail: &TessellationSettings) -> KernelResult<TriMesh>;
1942
1943    /// Read a STEP/STP file from disk and return tessellated bodies.
1944    ///
1945    /// Implementations that do not support STEP import should return
1946    /// [`KernelError::Unsupported`].
1947    fn import_step(
1948        &mut self,
1949        _path: &Path,
1950        _detail: &TessellationSettings,
1951    ) -> KernelResult<ImportedModel> {
1952        Err(KernelError::Unsupported(
1953            "STEP import is not implemented by this kernel".into(),
1954        ))
1955    }
1956}
1957
1958/// An edge of a solid projected onto a plane, in the plane's own 2D
1959/// coordinates (along its `x_axis` and `y_axis`).
1960#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1961pub enum ProjectedEdge {
1962    /// The edge runs along the plane's normal, so it projects to a point.
1963    Point([f64; 2]),
1964    /// A segment.
1965    Line { start: [f64; 2], end: [f64; 2] },
1966    /// A circle or circular arc, `centre + radius (cos t, sin t)`, turning
1967    /// counter-clockwise from `range.0` to `range.1`; a full circle when the
1968    /// range spans a turn.
1969    Circle {
1970        centre: [f64; 2],
1971        radius: f64,
1972        range: (f64, f64),
1973    },
1974    /// An ellipse or elliptical arc, `centre + major cos t + minor sin t`,
1975    /// `minor` the major axis turned a quarter counter-clockwise and scaled
1976    /// by `ratio`, from `range.0` to `range.1`.
1977    Ellipse {
1978        centre: [f64; 2],
1979        major: [f64; 2],
1980        ratio: f64,
1981        range: (f64, f64),
1982    },
1983    /// A piece of a parabola, `vertex + axis s² / (4 focal) + side s`,
1984    /// `axis` a unit vector the way it opens and `side` it turned a quarter
1985    /// counter-clockwise, from `s = range.0` to `range.1`.
1986    Parabola {
1987        vertex: [f64; 2],
1988        axis: [f64; 2],
1989        focal: f64,
1990        range: (f64, f64),
1991    },
1992    /// A piece of one branch of a hyperbola, `centre + major cosh s +
1993    /// minor sinh s`, `major` (centre to the branch's vertex) square to
1994    /// `minor`, from `s = range.0` to `range.1`.
1995    Hyperbola {
1996        centre: [f64; 2],
1997        major: [f64; 2],
1998        minor: [f64; 2],
1999        range: (f64, f64),
2000    },
2001    /// A B-spline, as the kernel projects it: `degree`, its clamped
2002    /// `knots` (`control_points + degree + 1` of them), and a weight per
2003    /// control point when rational (empty when every weight is one).
2004    Spline {
2005        degree: u32,
2006        knots: Vec<f64>,
2007        control_points: Vec<[f64; 2]>,
2008        weights: Vec<f64>,
2009    },
2010    /// Any other curve, as points along it: exact at each point, straight
2011    /// between.
2012    Polyline(Vec<[f64; 2]>),
2013}
2014
2015/// One curve where a plane crosses a shape.
2016#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2017pub struct SectionCurve {
2018    /// The exact curve, in the plane's own 2D coordinates.
2019    pub curve: ProjectedEdge,
2020    /// Points along it, in the shape's own frame, in the order its run
2021    /// goes.
2022    pub points: Vec<[f64; 3]>,
2023    /// The run goes against the way `curve` runs.
2024    #[serde(default)]
2025    pub reversed: bool,
2026}
2027
2028/// Curves where a plane crosses a shape, end to end: a closed loop round
2029/// a solid's cut, or an open run where a sheet's edge stops it.
2030#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2031pub struct SectionRun {
2032    pub curves: Vec<SectionCurve>,
2033    pub closed: bool,
2034}
2035
2036/// One edge of a face's boundary loop.
2037#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2038pub struct LoopEdge {
2039    /// Points along it, in the shape's own frame, in the order the loop
2040    /// walks it.
2041    pub points: Vec<[f64; 3]>,
2042    /// The edge a round face meets itself along: it turns up twice in
2043    /// its loop, once each way.
2044    #[serde(default)]
2045    pub seam: bool,
2046}
2047
2048/// The curves and texts of a 2D drawing file, in the drawing's own
2049/// coordinates.
2050#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
2051pub struct Drawing2d {
2052    /// Millimetres per drawing unit, when the drawing names its unit.
2053    pub unit_mm: Option<f64>,
2054    /// Every curve, in the order the file has them.
2055    pub curves: Vec<DrawingCurve>,
2056    /// Every line of text, in the order the file has them.
2057    #[serde(default)]
2058    pub texts: Vec<DrawingText>,
2059}
2060
2061/// One curve of a drawing, and whether the drawing marks it hidden
2062/// (a hidden layer, or a dashed line type).
2063#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2064pub struct DrawingCurve {
2065    pub hidden: bool,
2066    pub shape: DrawingShape,
2067    /// The layer it is drawn on; empty for the drawing's default layer.
2068    #[serde(default)]
2069    pub layer: String,
2070}
2071
2072/// A line of text on a drawing.
2073#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2074pub struct DrawingText {
2075    /// The start of its baseline.
2076    pub at: [f64; 2],
2077    /// The height of its capitals.
2078    pub height: f64,
2079    /// Its baseline's direction, radians counter-clockwise from x.
2080    pub angle: f64,
2081    pub text: String,
2082    /// The layer it is written on; empty for the drawing's default layer.
2083    #[serde(default)]
2084    pub layer: String,
2085}
2086
2087/// The kinds of curve a drawing carries. Angles are radians, arcs run
2088/// counter-clockwise.
2089#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2090pub enum DrawingShape {
2091    /// Points in order, each segment a line, or an arc where the bulge of
2092    /// the segment starting at that point (the tangent of a quarter of its
2093    /// included angle, positive counter-clockwise) is not zero. `bulges`
2094    /// is as long as `points`, or empty for straight segments only.
2095    Polyline {
2096        points: Vec<[f64; 2]>,
2097        bulges: Vec<f64>,
2098        closed: bool,
2099    },
2100    Arc {
2101        centre: [f64; 2],
2102        radius: f64,
2103        start_angle: f64,
2104        end_angle: f64,
2105    },
2106    Circle {
2107        centre: [f64; 2],
2108        radius: f64,
2109    },
2110    /// Points `centre + major cos t + ratio perp(major) sin t` for `t`
2111    /// from `start_param` to `end_param`; the whole ellipse when those span
2112    /// a full turn.
2113    Ellipse {
2114        centre: [f64; 2],
2115        major: [f64; 2],
2116        ratio: f64,
2117        start_param: f64,
2118        end_param: f64,
2119    },
2120    /// A spline, as points along the exact curve.
2121    Spline {
2122        points: Vec<[f64; 2]>,
2123        closed: bool,
2124    },
2125}
2126
2127/// A connected volume where a scan and a solid differ the same way, in the
2128/// solid's frame.
2129#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2130pub struct VolumeRegion {
2131    /// In the solid and out of the scan; else in the scan and out of the
2132    /// solid.
2133    pub missing: bool,
2134    /// In mm³.
2135    pub volume: f64,
2136    /// How far apart the two surfaces stand across it, in mm.
2137    pub depth: f64,
2138    /// Wider than twice its depth: a face standing off, rather than a boss
2139    /// or a pocket.
2140    pub layer: bool,
2141    pub min: [f64; 3],
2142    pub max: [f64; 3],
2143    /// It rests on a hole of the scan, or is too shallow for its volume to
2144    /// be read.
2145    pub unsure: bool,
2146}
2147
2148/// The solid two shapes share: its volume, its centre and its mesh, in
2149/// the first shape's frame.
2150#[derive(Debug, Clone)]
2151pub struct Overlap {
2152    pub volume_mm3: f64,
2153    pub centre_mm: [f64; 3],
2154    pub mesh: TriMesh,
2155}
2156
2157/// How near two shapes come: the distance between their boundaries and a
2158/// nearest point on each, in the first shape's frame. Zero where the
2159/// boundaries touch or cross.
2160#[derive(Debug, Clone, Copy, PartialEq)]
2161pub struct Gap {
2162    pub distance_mm: f64,
2163    pub on_a: [f64; 3],
2164    pub on_b: [f64; 3],
2165}
2166
2167/// A stretch of a region's medial axis, in the profile plane's own 2D
2168/// coordinates: points along one branch with the clearance at each, the
2169/// radius of the largest disc centred there that stays inside the region.
2170#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2171pub struct MedialPath {
2172    pub points: Vec<[f64; 2]>,
2173    /// One per point, in millimetres.
2174    pub clearance: Vec<f64>,
2175    /// Whether the first and the last point end the axis on the boundary
2176    /// (a corner, or a rounded end's centre) rather than meet other
2177    /// branches: towards such an end the clearance falls without the
2178    /// region getting thinner.
2179    pub boundary_ends: [bool; 2],
2180}
2181
2182/// Where a region is narrowest, and how narrow: the smallest clearance on
2183/// its medial axis away from the branch ends at its corners (where the
2184/// clearance runs down to nothing without the region getting any thinner).
2185/// The wall there is twice the clearance.
2186#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
2187pub struct Narrowest {
2188    pub at: [f64; 2],
2189    pub clearance: f64,
2190}
2191
2192/// The medial axis of one region of a profile: an outer wire and its holes.
2193#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2194pub struct MedialRegion {
2195    /// The profile's wires that bound it, by index, the outer one first.
2196    pub wires: Vec<usize>,
2197    pub paths: Vec<MedialPath>,
2198    /// `None` only when the axis has no place away from the corners.
2199    pub narrowest: Option<Narrowest>,
2200}
2201
2202/// A picked face: its name, and a point on it with its outward normal.
2203/// A rebuild finds the face by its name, the point choosing among the
2204/// pieces of a face that split; without a name (or when no face bears it
2205/// any more), the face nearest the point.
2206#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
2207pub struct FaceProbe {
2208    pub point: [f64; 3],
2209    pub normal: [f64; 3],
2210    #[serde(default)]
2211    pub name: TopoName,
2212}
2213
2214/// A question about a solid a reference stands on, named geometrically so
2215/// it can be asked again of the solid a rebuild makes.
2216#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
2217pub enum ShapeProbe {
2218    /// The face named `name`, else the face nearest `point` (among faces
2219    /// as near, the one whose outward normal agrees best with `normal`),
2220    /// and where on it `point` falls.
2221    Face {
2222        point: [f64; 3],
2223        normal: [f64; 3],
2224        #[serde(default)]
2225        name: TopoName,
2226    },
2227    /// The edge between faces named `faces`, else the edge nearest `point`
2228    /// that runs along `direction` there (a zero direction takes the
2229    /// nearest edge whichever way it runs).
2230    Edge {
2231        point: [f64; 3],
2232        direction: [f64; 3],
2233        #[serde(default)]
2234        faces: [TopoName; 2],
2235        /// A share along the edge from its start (0 to 1) whose point and
2236        /// tangent the answer also gives.
2237        #[serde(default, skip_serializing_if = "Option::is_none")]
2238        along: Option<f64>,
2239    },
2240    /// The solid's centre of mass and principal axes of inertia.
2241    Mass,
2242}
2243
2244/// What a solid answers to a [`ShapeProbe`], in the solid's own frame.
2245#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
2246pub enum ProbeAnswer {
2247    /// The point of the face nearest the probe's, the face's outward normal
2248    /// there, and the face's surface.
2249    Face {
2250        point: [f64; 3],
2251        normal: [f64; 3],
2252        surface: FaceSurface,
2253    },
2254    /// The point of the edge nearest the probe's and the way the edge runs
2255    /// there, its two ends and its middle (halfway along its parameter,
2256    /// which is halfway along an arc), and the circle it runs round when
2257    /// it is a circle or an arc of one.
2258    Edge {
2259        point: [f64; 3],
2260        direction: [f64; 3],
2261        start: [f64; 3],
2262        end: [f64; 3],
2263        middle: [f64; 3],
2264        circle: Option<ProbedCircle>,
2265        /// The point and tangent the probe's share along gives, when it
2266        /// asked for one.
2267        #[serde(default, skip_serializing_if = "Option::is_none")]
2268        along: Option<([f64; 3], [f64; 3])>,
2269    },
2270    /// The centre of mass and the principal axes of inertia, the axis of
2271    /// the smallest moment first.
2272    Mass {
2273        centre: [f64; 3],
2274        axes: [[f64; 3]; 3],
2275    },
2276}
2277
2278/// The circle an edge runs round.
2279#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
2280pub struct ProbedCircle {
2281    pub centre: [f64; 3],
2282    pub normal: [f64; 3],
2283    pub radius: f64,
2284}
2285
2286/// A probe asked part way through a solid-op chain: of the solid the first
2287/// `after_op` ops make.
2288#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
2289pub struct ChainProbe {
2290    pub after_op: usize,
2291    pub probe: ShapeProbe,
2292}
2293
2294/// A solid's edge projected onto a plane, or the curves where one of its
2295/// faces crosses the plane: what a sketch takes from the solid it stands
2296/// on, asked again of the solid a rebuild makes.
2297#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
2298pub struct ProjectionProbe {
2299    /// A point on the edge (on the face, for a section), in the solid's
2300    /// own frame.
2301    pub point: [f64; 3],
2302    /// The names of the two faces the edge runs between: the edge is found
2303    /// by them first, `point` choosing among its pieces, and by `point`
2304    /// alone without them or when no edge runs between them.
2305    #[serde(default)]
2306    pub faces: [TopoName; 2],
2307    /// The face nearest `point` is cut by the plane, in place of an edge
2308    /// projected onto it.
2309    #[serde(default)]
2310    pub section: bool,
2311    /// The plane, in the solid's own frame: the curves come in its own 2D
2312    /// coordinates.
2313    pub plane: ProfilePlane,
2314}
2315
2316/// A projection asked part way through a solid-op chain: of the solid the
2317/// first `after_op` ops make.
2318#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
2319pub struct ChainProjection {
2320    pub after_op: usize,
2321    pub probe: ProjectionProbe,
2322}
2323
2324/// The centre line of a pipe-like solid between two of its faces.
2325#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2326pub struct CentreLine {
2327    /// Points along it, from the first face to the second, in the shape's
2328    /// frame.
2329    pub points: Vec<[f64; 3]>,
2330    /// Its length, in millimetres.
2331    pub length: f64,
2332    /// The largest distance measured from the centroid of a section cut
2333    /// square to the line to the line itself.
2334    pub deviation: f64,
2335    /// It is one straight segment.
2336    pub straight: bool,
2337}
2338
2339/// A round hole found in a solid: a full bore, open at one end (blind)
2340/// or both (through), closed by a flat bottom or a drill point.
2341#[derive(Debug, Clone, PartialEq)]
2342pub struct RecognizedHole {
2343    /// The centre of its opening, on its axis.
2344    pub entry: [f64; 3],
2345    /// Along its axis, into the material.
2346    pub direction: [f64; 3],
2347    pub diameter: f64,
2348    /// The bore's length from the opening, not counting a drill point.
2349    pub depth: f64,
2350    /// Open at both ends.
2351    pub through: bool,
2352    /// The included angle of the cone that ends a blind hole, degrees;
2353    /// `None` for a flat bottom or a through hole.
2354    pub drill_point_deg: Option<f64>,
2355    /// A point on each face the hole is made of (its bore, its bottom),
2356    /// with that face's outward normal.
2357    pub faces: Vec<([f64; 3], [f64; 3])>,
2358}
2359
2360/// Geometry questions a workbench may ask while it runs, answered by the
2361/// kernel at once. Shapes arrive as the snapshot bytes the document keeps.
2362/// How two faces of a shape meet across an edge they share: a point
2363/// halfway along it, in the shape's own frame, the largest gap between the
2364/// edge and the faces, the largest angle between the faces' normals along
2365/// it (zero where they meet tangent), and the largest difference in how
2366/// sharply they bend square to it (1/mm; zero where they meet curvature
2367/// continuous, `None` where it could not be read).
2368#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
2369pub struct EdgeContinuity {
2370    pub point: [f64; 3],
2371    pub gap: f64,
2372    pub angle_deg: f64,
2373    #[serde(default)]
2374    pub curvature: Option<f64>,
2375}
2376
2377/// A face of a shape, named by a point inside it, and points on it, each
2378/// with the normal its curvature is signed against.
2379pub type FacePoints = ([f64; 3], Vec<([f64; 3], [f64; 3])>);
2380
2381/// A point on a path and the way the path runs there.
2382#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
2383pub struct PathFrame {
2384    pub point: [f64; 3],
2385    /// A unit vector along the path, the way it is walked.
2386    pub tangent: [f64; 3],
2387}
2388
2389/// Stations along a path, by arc length: what is repeated along a curve
2390/// stands at them.
2391#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2392pub struct PathFrames {
2393    /// The path's whole length, mm.
2394    pub length: f64,
2395    /// Whether the path ends where it starts.
2396    pub closed: bool,
2397    /// One per station asked for, in the order asked.
2398    pub frames: Vec<PathFrame>,
2399}
2400
2401/// How a shape is fitted to measured points.
2402#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
2403#[serde(rename_all = "snake_case")]
2404pub enum FitMethod {
2405    /// Orthogonal least squares: the mean shape.
2406    #[default]
2407    LeastSquares,
2408    /// The middle of the narrowest zone holding every point (flatness,
2409    /// straightness, circularity, cylindricity, sphericity).
2410    MinimumZone,
2411    /// The largest circle or cylinder with every point outside it (a
2412    /// hole's mating size).
2413    Inscribed,
2414    /// The smallest circle or cylinder with every point inside it (a
2415    /// boss's mating size).
2416    Circumscribed,
2417}
2418
2419/// What shape a set of measured points is fitted to.
2420#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
2421pub enum FitKind {
2422    Plane,
2423    Sphere,
2424    Cylinder,
2425    Cone,
2426    Torus,
2427    /// A circle in space: its plane and its round together.
2428    Circle,
2429    Line,
2430}
2431
2432impl FitKind {
2433    pub const ALL: [FitKind; 7] = [
2434        FitKind::Plane,
2435        FitKind::Sphere,
2436        FitKind::Cylinder,
2437        FitKind::Cone,
2438        FitKind::Torus,
2439        FitKind::Circle,
2440        FitKind::Line,
2441    ];
2442}
2443
2444/// Points to fit a shape to, and how.
2445#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2446pub struct FitRequest {
2447    pub kind: FitKind,
2448    /// In millimetres, in whatever frame the answer is wanted in.
2449    pub points: Vec<[f64; 3]>,
2450    /// A normal per point, out of the material, or empty.
2451    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2452    pub normals: Vec<[f64; 3]>,
2453    /// Points farther than this many sigmas from the fit are left out and
2454    /// it is fitted again, until what is kept stops changing; `None` keeps
2455    /// every point.
2456    #[serde(default)]
2457    pub sigma_cutoff: Option<f64>,
2458    /// A sphere, cylinder or circle's radius held, only the rest fitted.
2459    #[serde(default)]
2460    pub fixed_radius: Option<f64>,
2461}
2462
2463/// A fitted shape, in the request's frame. Directions are unit length.
2464#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2465pub enum FittedShape {
2466    Plane {
2467        origin: [f64; 3],
2468        normal: [f64; 3],
2469    },
2470    Sphere {
2471        centre: [f64; 3],
2472        radius: f64,
2473    },
2474    Cylinder {
2475        point: [f64; 3],
2476        axis: [f64; 3],
2477        radius: f64,
2478    },
2479    /// `half_angle` in radians, between the axis and the wall.
2480    Cone {
2481        apex: [f64; 3],
2482        axis: [f64; 3],
2483        half_angle: f64,
2484    },
2485    Torus {
2486        centre: [f64; 3],
2487        axis: [f64; 3],
2488        major: f64,
2489        minor: f64,
2490    },
2491    Circle {
2492        centre: [f64; 3],
2493        normal: [f64; 3],
2494        radius: f64,
2495    },
2496    Line {
2497        point: [f64; 3],
2498        direction: [f64; 3],
2499    },
2500}
2501
2502/// A least-squares fit and what it rests on.
2503#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2504pub struct FitAnswer {
2505    pub shape: FittedShape,
2506    /// RMS distance of the points used from the shape.
2507    pub sigma: f64,
2508    /// The most negative and most positive signed distance of the points
2509    /// used: the form error is their difference.
2510    pub form: (f64, f64),
2511    /// Which points the fit used, one per point given.
2512    pub used: Vec<bool>,
2513    /// Each point's signed distance from the shape, used or not.
2514    pub residuals: Vec<f64>,
2515    pub converged: bool,
2516}
2517
2518/// A region to grow over a mesh from points near it, and how.
2519#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2520pub struct GrowRequest {
2521    /// The surface to grow: a plane, sphere, cylinder, cone or torus.
2522    pub kind: FitKind,
2523    /// Points on or near the mesh the region starts from.
2524    pub seeds: Vec<[f64; 3]>,
2525    /// Points farther from the fit than this many sigmas are left out and
2526    /// stop growth; the kernel's own gate when `None`.
2527    #[serde(default, skip_serializing_if = "Option::is_none")]
2528    pub sigma_cutoff: Option<f64>,
2529    /// The largest turn, in degrees, between a triangle's normal and the
2530    /// surface's for the triangle to join; the kernel's default when
2531    /// `None`.
2532    #[serde(default, skip_serializing_if = "Option::is_none")]
2533    pub normal_limit_deg: Option<f64>,
2534    /// Take off the rim while it turns away from the surface (a face's
2535    /// rounds).
2536    #[serde(default)]
2537    pub peel: bool,
2538    #[serde(default, skip_serializing_if = "Option::is_none")]
2539    pub max_triangles: Option<usize>,
2540}
2541
2542/// A grown region and its fit.
2543#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2544pub struct GrowAnswer {
2545    /// The fit; its `used` and `residuals` go with `vertices`.
2546    pub fit: FitAnswer,
2547    /// The mesh's triangles in the region.
2548    pub triangles: Vec<u32>,
2549    /// The mesh vertex each of the fit's points is.
2550    pub vertices: Vec<u32>,
2551    /// Whether each seed's triangle ended up in the region.
2552    pub seeds_in_region: Vec<bool>,
2553}
2554
2555/// Points to measure to a reference surface, and how.
2556#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
2557pub struct DistanceRequest {
2558    pub points: Vec<[f64; 3]>,
2559    /// One per point, or none; needed for `facing_limit_deg`.
2560    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2561    pub normals: Vec<[f64; 3]>,
2562    /// A point with nothing nearer reads unmeasured; any distance when
2563    /// `None`.
2564    #[serde(default, skip_serializing_if = "Option::is_none")]
2565    pub max: Option<f64>,
2566    /// Only surface turned within this many degrees of a point's own
2567    /// normal counts for it.
2568    #[serde(default, skip_serializing_if = "Option::is_none")]
2569    pub facing_limit_deg: Option<f64>,
2570}
2571
2572/// Points to bring onto a reference surface by a rigid motion, and how.
2573#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
2574pub struct RegisterRequest {
2575    pub points: Vec<[f64; 3]>,
2576    /// One per point, or none.
2577    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2578    pub normals: Vec<[f64; 3]>,
2579    /// Try every way of matching the points' principal axes with the
2580    /// reference's as well as the points where they are, and keep the best.
2581    #[serde(default)]
2582    pub search: bool,
2583    /// Pairs farther apart than this are not used.
2584    #[serde(default, skip_serializing_if = "Option::is_none")]
2585    pub max_distance: Option<f64>,
2586    /// Pair a point only with reference surface turned within this many
2587    /// degrees of its own normal.
2588    #[serde(default, skip_serializing_if = "Option::is_none")]
2589    pub facing_limit_deg: Option<f64>,
2590}
2591
2592/// A rigid motion that brings points onto a reference, and how well.
2593#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2594pub struct Registration {
2595    /// Row-major, the last row left out: the points' frame to where they
2596    /// fit.
2597    pub transform: [[f64; 4]; 3],
2598    /// RMS distance of the pairs kept, mm.
2599    pub rms: f64,
2600    pub inliers: usize,
2601    pub sampled: usize,
2602    pub converged: bool,
2603    /// Motions the fit cannot pin down (a cylinder turning about its axis,
2604    /// a plane sliding along itself), each a turn about `about` with a
2605    /// slide; empty when the fit is held every way.
2606    #[serde(default)]
2607    pub free: Vec<FreeMotion>,
2608}
2609
2610#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2611pub struct FreeMotion {
2612    pub about: [f64; 3],
2613    pub rotation: [f64; 3],
2614    pub translation: [f64; 3],
2615}
2616
2617/// Points on a part whose wall thickness is read, and how.
2618#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
2619pub struct ThicknessRequest {
2620    pub points: Vec<[f64; 3]>,
2621    /// Outward, one per point.
2622    pub normals: Vec<[f64; 3]>,
2623    /// The largest ball touching the point inside the material, in place
2624    /// of rays.
2625    #[serde(default)]
2626    pub sphere: bool,
2627    /// Rays spread within this many degrees of the inward normal, the
2628    /// shortest kept; along the normal alone at 0.
2629    #[serde(default)]
2630    pub cone_deg: f64,
2631    #[serde(default)]
2632    pub rays: u32,
2633    /// Surfaces within this many degrees of edge-on to a ray are passed
2634    /// over.
2635    #[serde(default)]
2636    pub facing_limit_deg: f64,
2637    /// A wall thicker than this reads unmeasured.
2638    #[serde(default, skip_serializing_if = "Option::is_none")]
2639    pub max: Option<f64>,
2640}
2641
2642/// What distances are measured to.
2643#[derive(Debug, Clone, Copy)]
2644pub enum DistanceTarget<'a> {
2645    /// Triangles, closed or not.
2646    Mesh(&'a TriMesh),
2647    /// A native-format solid, meshed finely by curvature for the purpose.
2648    Shape(&'a [u8]),
2649}
2650
2651/// A scan's proposed upright frame, expressed in its own coordinates.
2652#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2653pub struct Orientation {
2654    /// Bounding-box centre on the standing face.
2655    pub origin: [f64; 3],
2656    pub x_axis: [f64; 3],
2657    pub z_axis: [f64; 3],
2658    /// What supports the proposal, including a principal-axis fallback.
2659    pub said: String,
2660}
2661
2662/// One connected polyline of a mesh's section by a plane, in the mesh's
2663/// own frame.
2664#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
2665pub struct SectionChain {
2666    /// In order along the chain; a closed chain does not repeat its first
2667    /// point.
2668    pub points: Vec<[f64; 3]>,
2669    /// At each point, the unit direction in the plane pointing out of the
2670    /// material.
2671    pub outward: Vec<[f64; 3]>,
2672    pub closed: bool,
2673}
2674
2675/// The shadow a mesh casts on a plane, and an outline fitted around it.
2676#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2677pub struct ShadowRequest {
2678    /// The plane, in the mesh's frame; the answer's points are along its
2679    /// `x_axis` and `y_axis` from its `origin`.
2680    pub plane: ProfilePlane,
2681    /// The outline's least clearance from the shadow, mm; negative inside
2682    /// it, a press fit.
2683    pub play: f64,
2684    /// Half the outline's band: every point of it lies between `play` and
2685    /// `play + 2 tolerance` outside the shadow.
2686    pub tolerance: f64,
2687    /// Corners turning less than this, degrees, take the largest tangent
2688    /// arc that fits the band.
2689    pub round_below_deg: f64,
2690    /// Holes and notches no wider across than this, mm, are filled before
2691    /// the outline is fitted (its inner corners rounded to half of it);
2692    /// 0 fills nothing.
2693    #[serde(default)]
2694    pub fill_below: f64,
2695}
2696
2697/// What a mesh's shadow is: its loops as traced (outer boundaries
2698/// counter-clockwise, holes clockwise) and the outline of lines, arcs and
2699/// circles fitted around them.
2700#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
2701pub struct ShadowAnswer {
2702    pub silhouette: Vec<Vec<[f64; 2]>>,
2703    pub outline: Vec<ProfileWire>,
2704}
2705
2706/// How a chain of points is fitted with lines and arcs.
2707#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
2708pub struct ChainFit {
2709    /// Every point lies within this distance of its piece, mm.
2710    pub tolerance: f64,
2711    /// Pieces turning against each other meet where their curves cross,
2712    /// bringing back a corner the points round off.
2713    pub corners: bool,
2714    /// Lines within this many degrees of the plane's axes are turned onto
2715    /// them where they still hold their points.
2716    pub axis_snap_deg: Option<f64>,
2717    /// An arc bowing from its chord by no more than this is taken as
2718    /// lines, mm.
2719    pub min_bow: f64,
2720    pub closed: bool,
2721}
2722
2723/// Part of a mesh, by where its points are: a face is in it when all
2724/// three of its corners are.
2725#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2726pub enum MeshRegion {
2727    All,
2728    Box {
2729        min: [f64; 3],
2730        max: [f64; 3],
2731    },
2732    Ball {
2733        centre: [f64; 3],
2734        radius: f64,
2735    },
2736    /// Vertices of the history's start mesh, by number (a marking).
2737    Vertices(Vec<u32>),
2738}
2739
2740/// One step of a mesh's history, in the mesh's own frame.
2741#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2742#[cfg_attr(not(feature = "exhaustive"), non_exhaustive)]
2743pub enum MeshOp {
2744    /// Pieces whose bounding box's diagonal is shorter than this removed.
2745    RemoveIslands { smaller_than: f64 },
2746    /// The region's faces removed, the hole left open.
2747    Delete { region: MeshRegion },
2748    /// The region's faces turned over.
2749    Flip { region: MeshRegion },
2750    /// Fill open rims whose longest span is at most `holes_up_to`, or the
2751    /// nearest such rim to `near` when given. Existing vertices stay fixed.
2752    Fill {
2753        holes_up_to: f64,
2754        #[serde(default)]
2755        near: Option<[f64; 3]>,
2756        #[serde(default)]
2757        fairing: MeshFairing,
2758    },
2759    /// Project the region onto local quadrics, with a bounded movement.
2760    Smooth {
2761        region: MeshRegion,
2762        bumps_up_to: f64,
2763        move_at_most: f64,
2764        #[serde(default)]
2765        keep_edges_deg: Option<f64>,
2766    },
2767    /// Move faces by a normal distance; a marking gets a joining wall.
2768    Offset { region: MeshRegion, distance: f64 },
2769    /// The boolean `operation` of the closed mesh (first) and a bounded
2770    /// solid in the mesh's frame, the solid meshed to `chord` first. An
2771    /// open mesh, and an operand it does not meet, are refused.
2772    Boolean {
2773        operand: MeshOperand,
2774        operation: BooleanOp,
2775        chord: f64,
2776    },
2777    /// A closed mesh hollowed: its surface kept, an inner wall `thickness`
2778    /// inside it bounding a sealed cavity. An open sheet thickened to the
2779    /// `side` given, rim walls closing it.
2780    Shell {
2781        thickness: f64,
2782        #[serde(default)]
2783        side: MeshSide,
2784    },
2785    /// Decimate and measure both ways at the 99.9th percentile. The
2786    /// triangle limit takes priority over the tolerance; the report says
2787    /// how far the resulting surface lies from its input.
2788    Reduce {
2789        tolerance: f64,
2790        triangle_limit: usize,
2791    },
2792    /// Cut by the plane through `origin` square to `normal`, the side
2793    /// `normal` points to kept when `keep_above`; with `close`, every loop
2794    /// of the cut capped flat, gaps in its rim up to `bridge` closed.
2795    Cut {
2796        origin: [f64; 3],
2797        normal: [f64; 3],
2798        keep_above: bool,
2799        close: bool,
2800        bridge: f64,
2801    },
2802}
2803
2804/// A bounded solid a mesh boolean takes, as it stood when the step was
2805/// made.
2806#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2807pub enum MeshOperand {
2808    /// A solid in the kernel's native text format, moved by the row-major
2809    /// rigid `transform` into the frame it is used in.
2810    Shape {
2811        brep: String,
2812        transform: [[f64; 4]; 4],
2813    },
2814    /// A primitive at its placement.
2815    Primitive {
2816        kind: PrimitiveKind,
2817        placement: Placement,
2818    },
2819}
2820
2821/// Which side of an open sheet a shell thickens: inward is against the
2822/// way its triangles face.
2823#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
2824pub enum MeshSide {
2825    Inward,
2826    Outward,
2827    #[default]
2828    Both,
2829}
2830
2831/// A solid trimmed where a scan breaks off: the scan's triangles lying
2832/// deeper than `depth` inside the solid are the break, which is extended
2833/// past the solid, thickened by `gap` to each side and cut away. Both in
2834/// the solid's frame.
2835#[derive(Debug, Clone, Serialize, Deserialize)]
2836pub struct TrimRequest {
2837    /// The solid, in the kernel's native format.
2838    pub solid: Vec<u8>,
2839    pub scan: TriMesh,
2840    pub depth: f64,
2841    pub gap: f64,
2842    /// Keep what lies on the side of the break away from the scan (the
2843    /// piece); otherwise the side toward it.
2844    pub away: bool,
2845}
2846
2847/// A trimmed solid and how it meets the scan.
2848#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2849pub struct TrimAnswer {
2850    /// The trimmed solid, as a `.brep` file holds it.
2851    pub brep: Vec<u8>,
2852    /// Its volume, mm³.
2853    pub volume: f64,
2854    /// The area of its faces that lie along the break, mm².
2855    pub mating_area: f64,
2856    /// The distance from the break's points to the mating faces: median
2857    /// and the range holding the middle 90 %, mm.
2858    pub gap_median: f64,
2859    pub gap_range: [f64; 2],
2860}
2861
2862/// How a hole's added vertices settle.
2863#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
2864pub enum MeshFairing {
2865    #[default]
2866    Curved,
2867    Flat,
2868}
2869
2870/// Measurements made by a mesh step, in millimetres.
2871#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2872pub enum MeshStepReport {
2873    Cut {
2874        capped_loops: usize,
2875        bridged: usize,
2876        open_loops: usize,
2877    },
2878    /// `volume` in mm³; `cut_triangles` the result's triangles the other
2879    /// operand cut.
2880    Boolean {
2881        cut_triangles: usize,
2882        volume: f64,
2883    },
2884    /// `hollow` for a closed part, otherwise a sheet thickened.
2885    Shell {
2886        hollow: bool,
2887        volume: f64,
2888    },
2889    Smooth {
2890        max: f64,
2891        rms: f64,
2892    },
2893    Reduce {
2894        within_share: f64,
2895        p999: f64,
2896        furthest: [f64; 3],
2897        max: f64,
2898        rms: f64,
2899        target_met: bool,
2900    },
2901}
2902
2903/// What one step of a mesh history did.
2904#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
2905pub struct MeshStep {
2906    /// Faces after it.
2907    pub faces: usize,
2908    pub note: String,
2909    #[serde(default)]
2910    pub report: Option<MeshStepReport>,
2911}
2912
2913/// A mesh history built: the mesh at its end, what each step did, and the
2914/// step that failed, when one did (the mesh is then the one before it).
2915#[derive(Debug, Clone, Default)]
2916pub struct MeshChainAnswer {
2917    pub mesh: TriMesh,
2918    /// The start vertex behind each displayed vertex, where the kernel
2919    /// preserves it. Added surface has no source vertex.
2920    pub sources: Vec<Option<u32>>,
2921    pub steps: Vec<MeshStep>,
2922    pub failed: Option<(usize, String)>,
2923}
2924
2925/// Reference geometry with no topology: what STEP and IGES files carry as
2926/// construction geometry beside (or instead of) a part's solid.
2927#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2928pub enum ConstructionShape {
2929    Point([f64; 3]),
2930    /// An axis placement: `z` its axis, `x` its reference direction.
2931    Axis {
2932        origin: [f64; 3],
2933        z: [f64; 3],
2934        x: [f64; 3],
2935    },
2936    /// Straight pieces through the points; closed back to the first.
2937    Polyline {
2938        points: Vec<[f64; 3]>,
2939        closed: bool,
2940    },
2941    Circle {
2942        centre: [f64; 3],
2943        normal: [f64; 3],
2944        radius: f64,
2945    },
2946    /// A plane over `u` along `x_axis` and `v` along `normal × x_axis`
2947    /// from `origin`.
2948    Plane {
2949        origin: [f64; 3],
2950        normal: [f64; 3],
2951        x_axis: [f64; 3],
2952        u: [f64; 2],
2953        v: [f64; 2],
2954    },
2955}
2956
2957/// A named item of construction geometry.
2958#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2959pub struct ConstructionItem {
2960    pub name: String,
2961    pub shape: ConstructionShape,
2962}
2963
2964/// Construction geometry written as IGES, with any omitted geometry or names reported.
2965#[derive(Debug, Clone, Default)]
2966pub struct IgesExport {
2967    pub text: String,
2968    pub warnings: Vec<String>,
2969}
2970
2971/// A scan's mirror plane, expressed in its own coordinates.
2972#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2973pub struct SymmetryPlane {
2974    pub point: [f64; 3],
2975    pub normal: [f64; 3],
2976    /// RMS mirror residual in millimetres.
2977    pub rms: f64,
2978}
2979
2980pub trait KernelQueries: Send + Sync {
2981    /// The wall thickness of `target` at each point, `NaN` where none is
2982    /// found within reach.
2983    fn thickness(
2984        &self,
2985        _target: DistanceTarget<'_>,
2986        _request: &ThicknessRequest,
2987    ) -> KernelResult<Vec<f64>> {
2988        Err(KernelError::Unsupported("thickness".into()))
2989    }
2990
2991    /// The sections of `mesh` by the plane through `origin` square to
2992    /// `normal`, moved along it by each of `offsets`: one list of chains
2993    /// per offset, in their order. Each chain runs with the material on
2994    /// its left seen from the side `normal` points to.
2995    fn mesh_sections(
2996        &self,
2997        _mesh: &TriMesh,
2998        _origin: [f64; 3],
2999        _normal: [f64; 3],
3000        _offsets: &[f64],
3001    ) -> KernelResult<Vec<Vec<SectionChain>>> {
3002        Err(KernelError::Unsupported("mesh_sections".into()))
3003    }
3004
3005    /// The shadow `mesh` casts on `request.plane` seen along its normal,
3006    /// and an outline fitted around it within `request`'s band.
3007    fn mesh_shadow(&self, _mesh: &TriMesh, _request: &ShadowRequest) -> KernelResult<ShadowAnswer> {
3008        Err(KernelError::Unsupported("mesh_shadow".into()))
3009    }
3010
3011    /// Lines and arcs fitted to a 2D chain of points, every point within
3012    /// `fit.tolerance` of its piece and the pieces meeting end to end: a
3013    /// polyline whose bulges give the arcs, or a circle where one holds a
3014    /// closed chain.
3015    fn fit_chain_2d(&self, _points: &[[f64; 2]], _fit: &ChainFit) -> KernelResult<DrawingShape> {
3016        Err(KernelError::Unsupported("fit_chain_2d".into()))
3017    }
3018
3019    /// `start` with `ops` applied in turn: a mesh body's history.
3020    fn build_mesh_chain(&self, _start: &TriMesh, _ops: &[MeshOp]) -> KernelResult<MeshChainAnswer> {
3021        Err(KernelError::Unsupported("build_mesh_chain".into()))
3022    }
3023
3024    /// The mesh as a file of `format` (`stl`, `3mf`, `ply` or `obj`),
3025    /// its triangles as they are, in millimetres.
3026    fn write_mesh(&self, _mesh: &TriMesh, _format: &str) -> KernelResult<Vec<u8>> {
3027        Err(KernelError::Unsupported("write_mesh".into()))
3028    }
3029
3030    /// A solid trimmed to where a scan breaks off.
3031    fn trim_to_scan(&self, _request: &TrimRequest) -> KernelResult<TrimAnswer> {
3032        Err(KernelError::Unsupported("trim_to_scan".into()))
3033    }
3034
3035    /// A DXF drawing of polylines in millimetres: `visible` continuous,
3036    /// `hidden` dashed, each on a layer of its own.
3037    fn write_dxf(
3038        &self,
3039        _visible: &[Vec<[f64; 2]>],
3040        _hidden: &[Vec<[f64; 2]>],
3041    ) -> KernelResult<String> {
3042        Err(KernelError::Unsupported("write_dxf".into()))
3043    }
3044
3045    /// A drawing as an R2000 DXF, each curve and text as itself on its
3046    /// layer (a layer draws dashed when its curves are hidden), its unit
3047    /// declared from `unit_mm` (1 millimetres, 25.4 inches, none
3048    /// unitless).
3049    fn write_dxf_drawing(&self, _drawing: &Drawing2d) -> KernelResult<String> {
3050        Err(KernelError::Unsupported("write_dxf_drawing".into()))
3051    }
3052
3053    /// A STEP file of one part, `part`, holding `items` as its construction
3054    /// geometry and no solid.
3055    fn write_construction_step(
3056        &self,
3057        _part: &str,
3058        _items: &[ConstructionItem],
3059    ) -> KernelResult<Vec<u8>> {
3060        Err(KernelError::Unsupported("write_construction_step".into()))
3061    }
3062
3063    /// An IGES file holding `items` as construction geometry and no solid,
3064    /// with warnings for geometry or names the writer cannot carry in full.
3065    fn write_construction_iges(
3066        &self,
3067        _part: &str,
3068        _items: &[ConstructionItem],
3069    ) -> KernelResult<IgesExport> {
3070        Err(KernelError::Unsupported("write_construction_iges".into()))
3071    }
3072
3073    /// An upright frame inferred from the scan's faces, walls and open rims.
3074    fn orient(&self, _mesh: &TriMesh) -> KernelResult<Orientation> {
3075        Err(KernelError::Unsupported("orient".into()))
3076    }
3077
3078    /// The best mirror plane seeded from the scan's principal frame.
3079    fn symmetry_plane(&self, _mesh: &TriMesh) -> KernelResult<SymmetryPlane> {
3080        Err(KernelError::Unsupported("symmetry_plane".into()))
3081    }
3082
3083    /// The rigid motion that brings `request`'s points best onto
3084    /// `target`'s surface.
3085    fn register(
3086        &self,
3087        _target: DistanceTarget<'_>,
3088        _request: &RegisterRequest,
3089    ) -> KernelResult<Registration> {
3090        Err(KernelError::Unsupported("register".into()))
3091    }
3092
3093    /// Where `scan`, given in the solid's frame, and the native-format
3094    /// solid `solid` differ, as regions on a grid of cells `cell` wide,
3095    /// largest first. Holes in the scan read as the solid.
3096    fn volume_difference(
3097        &self,
3098        _scan: &TriMesh,
3099        _solid: &[u8],
3100        _cell: f64,
3101    ) -> KernelResult<Vec<VolumeRegion>> {
3102        Err(KernelError::Unsupported("volume_difference".into()))
3103    }
3104
3105    /// Each point's signed distance to `target`'s surface, positive
3106    /// outside it, `NaN` where nothing lies within reach.
3107    fn signed_distance(
3108        &self,
3109        _target: DistanceTarget<'_>,
3110        _request: &DistanceRequest,
3111    ) -> KernelResult<Vec<f64>> {
3112        Err(KernelError::Unsupported("signed_distance".into()))
3113    }
3114
3115    /// Grow a region of `request.kind` over `mesh` from its seeds, joining
3116    /// triangles while they lie on one surface, and fit it.
3117    fn grow(&self, _mesh: &TriMesh, _request: &GrowRequest) -> KernelResult<GrowAnswer> {
3118        Err(KernelError::Unsupported("grow".into()))
3119    }
3120
3121    /// Every edge two faces of `brep` share, with how they meet there.
3122    fn continuity(&self, _brep: &[u8]) -> KernelResult<Vec<EdgeContinuity>> {
3123        Err(KernelError::Unsupported("continuity".into()))
3124    }
3125
3126    /// The shape of `request.kind` that fits its points best: orthogonal
3127    /// least squares, started robustly, with what it rests on.
3128    fn fit(&self, _request: &FitRequest) -> KernelResult<FitAnswer> {
3129        Err(KernelError::Unsupported("fit".into()))
3130    }
3131
3132    /// `kind` fitted to every one of `points` by `method`, a zone or a
3133    /// mating fit rather than a mean one; `converged` says whether the zone
3134    /// is certified optimal. `form` is the zone's two boundaries as signed
3135    /// distances from the shape, its width their difference.
3136    fn zone_fit(
3137        &self,
3138        _kind: FitKind,
3139        _method: FitMethod,
3140        _points: &[[f64; 3]],
3141    ) -> KernelResult<FitAnswer> {
3142        Err(KernelError::Unsupported("zone_fit".into()))
3143    }
3144
3145    /// The principal curvatures of `brep`'s faces at points on them. Each
3146    /// entry names a face by a point inside it (the face nearest that
3147    /// point) and lists points on it, each with the normal it is signed
3148    /// against, in the shape's own frame; the answer gives, per point, the
3149    /// largest and the smallest normal curvature (1/mm): negative where the
3150    /// face bulges toward that normal, positive where it hollows away.
3151    /// `None` where the surface has no normal (a pole, an apex).
3152    fn curvature(
3153        &self,
3154        _brep: &[u8],
3155        _faces: &[FacePoints],
3156    ) -> KernelResult<Vec<Vec<Option<[f64; 2]>>>> {
3157        Err(KernelError::Unsupported("curvature".into()))
3158    }
3159
3160    /// The edges bounding the face of `brep` nearest `near`: a point on
3161    /// each, halfway along, and its direction there, in the shape's own
3162    /// frame. A seam (the edge a round face meets itself along) and an
3163    /// edge with no curve (a pole) are left out.
3164    fn face_edges(&self, _brep: &[u8], _near: [f64; 3]) -> KernelResult<Vec<([f64; 3], [f64; 3])>> {
3165        Err(KernelError::Unsupported("face_edges".into()))
3166    }
3167
3168    /// The round holes of `brep`, in its own frame, and how many bores it
3169    /// has that are not holes it can describe (a counterbore, a slot).
3170    fn recognize_holes(&self, _brep: &[u8]) -> KernelResult<(Vec<RecognizedHole>, usize)> {
3171        Err(KernelError::Unsupported("recognize_holes".into()))
3172    }
3173
3174    /// What `a` and `b` share when `b` sits where `b_in_a` (a rigid
3175    /// row-major 4×4 matrix) puts it in `a`'s frame; `None` when they only
3176    /// touch or are apart.
3177    fn overlap(
3178        &self,
3179        _a: &[u8],
3180        _b: &[u8],
3181        _b_in_a: &[[f64; 4]; 4],
3182    ) -> KernelResult<Option<Overlap>> {
3183        Err(KernelError::Unsupported("overlap".into()))
3184    }
3185
3186    /// How near `a` and `b` come when `b` sits where `b_in_a` puts it in
3187    /// `a`'s frame.
3188    fn gap(&self, _a: &[u8], _b: &[u8], _b_in_a: &[[f64; 4]; 4]) -> KernelResult<Gap> {
3189        Err(KernelError::Unsupported("gap".into()))
3190    }
3191
3192    /// `brep` mirrored across the plane through `point` with `normal`, in
3193    /// its own frame, as a snapshot of its own.
3194    fn mirror(&self, _brep: &[u8], _point: [f64; 3], _normal: [f64; 3]) -> KernelResult<Vec<u8>> {
3195        Err(KernelError::Unsupported("mirror".into()))
3196    }
3197
3198    /// The volume, area and centre of mass of `brep`, in its own frame.
3199    fn measure(&self, _brep: &[u8]) -> KernelResult<PhysicalProperties> {
3200        Err(KernelError::Unsupported("measure".into()))
3201    }
3202
3203    /// The edge of `brep` nearest `near`, projected orthogonally onto
3204    /// `plane`. Both are in the shape's own frame.
3205    fn project_edge(
3206        &self,
3207        brep: &[u8],
3208        near: [f64; 3],
3209        plane: &ProfilePlane,
3210    ) -> KernelResult<ProjectedEdge>;
3211
3212    /// Points and tangents along the edge of `brep` nearest `near` (within
3213    /// a pick's reach of it), from the start of its curve: one per entry of
3214    /// `stations`, each a fraction of the edge's length (0 its start, 1 its
3215    /// end) placed by arc length, not by the curve's parameter. Everything
3216    /// is in the shape's own frame.
3217    fn edge_frames(
3218        &self,
3219        _brep: &[u8],
3220        _near: [f64; 3],
3221        _stations: &[f64],
3222    ) -> KernelResult<PathFrames> {
3223        Err(KernelError::Unsupported("points along an edge".into()))
3224    }
3225
3226    /// Points and tangents along `wire` on `plane`, walked from its first
3227    /// segment's start: one per entry of `stations`, each a fraction of the
3228    /// wire's whole length placed by arc length, as `edge_frames`.
3229    fn wire_frames(
3230        &self,
3231        _plane: &ProfilePlane,
3232        _wire: &ProfileWire,
3233        _stations: &[f64],
3234    ) -> KernelResult<PathFrames> {
3235        Err(KernelError::Unsupported("points along a wire".into()))
3236    }
3237
3238    /// Where every occurrence of a [`SolidOp::Pattern`] with `steps` stands,
3239    /// as row-major transforms from the original's place, the original's
3240    /// (the identity) first: what the chain works out, with `brep` (in the
3241    /// pattern's frame) as the solid a step's edge is found on.
3242    fn pattern_transforms(
3243        &self,
3244        _brep: Option<&[u8]>,
3245        _steps: &[PatternStep],
3246    ) -> KernelResult<Vec<[[f64; 4]; 4]>> {
3247        Err(KernelError::Unsupported("pattern transforms".into()))
3248    }
3249
3250    /// The face of `brep` nearest `near` (in the shape's own frame), as a
3251    /// native-format snapshot of its own: what a face taken from a solid
3252    /// keeps once the solid moves on.
3253    fn face_of(&self, _brep: &[u8], _near: [f64; 3]) -> KernelResult<Vec<u8>> {
3254        Err(KernelError::Unsupported(
3255            "taking a face out of a solid".into(),
3256        ))
3257    }
3258
3259    /// The edge of `brep` nearest `near` (in the shape's own frame), as a
3260    /// native-format snapshot of its own.
3261    fn edge_of(&self, _brep: &[u8], _near: [f64; 3]) -> KernelResult<Vec<u8>> {
3262        Err(KernelError::Unsupported(
3263            "taking an edge out of a solid".into(),
3264        ))
3265    }
3266
3267    /// Where the face of `brep` nearest `near` crosses `plane`, as the
3268    /// curves the plane cuts from it, in the plane's own 2D coordinates:
3269    /// each the exact line, circle or ellipse it is, or points along any
3270    /// other. Empty when the face does not reach the plane. Both are in the
3271    /// shape's own frame.
3272    fn section_face(
3273        &self,
3274        _brep: &[u8],
3275        _near: [f64; 3],
3276        _plane: &ProfilePlane,
3277    ) -> KernelResult<Vec<ProjectedEdge>> {
3278        Err(KernelError::Unsupported("face section".into()))
3279    }
3280
3281    /// A point on each solid of `brep`, one per solid in the order the
3282    /// shape holds them, in its own frame: where each piece of a shape of
3283    /// several stands.
3284    fn solid_pieces(&self, _brep: &[u8]) -> KernelResult<Vec<[f64; 3]>> {
3285        Err(KernelError::Unsupported("solid pieces".into()))
3286    }
3287
3288    /// Where `plane` crosses `brep`, chained end to end, each curve exact
3289    /// in the plane's own 2D coordinates and drawn in the shape's own
3290    /// frame: the whole shape's section, or with `near` only the face
3291    /// nearest it. Empty when the plane misses.
3292    fn section(
3293        &self,
3294        _brep: &[u8],
3295        _plane: &ProfilePlane,
3296        _near: Option<[f64; 3]>,
3297    ) -> KernelResult<Vec<SectionRun>> {
3298        Err(KernelError::Unsupported("section".into()))
3299    }
3300
3301    /// The boundary loops of the face of `brep` nearest `near`, the outer
3302    /// one first, each edge in loop order, in the shape's own frame.
3303    fn face_loops(&self, _brep: &[u8], _near: [f64; 3]) -> KernelResult<Vec<Vec<LoopEdge>>> {
3304        Err(KernelError::Unsupported("face loops".into()))
3305    }
3306
3307    /// The curves of a DXF drawing, given as its text.
3308    fn read_dxf(&self, _text: &str) -> KernelResult<Drawing2d> {
3309        Err(KernelError::Unsupported("reading DXF".into()))
3310    }
3311
3312    /// The regions `profile` encloses, meshed where they stand in its
3313    /// plane: what a feature swept from it takes, holes left open.
3314    fn profile_mesh(&self, _profile: &Profile) -> KernelResult<TriMesh> {
3315        Err(KernelError::Unsupported("profile mesh".into()))
3316    }
3317
3318    /// The medial axis of each region of `profile`, held to `tolerance`
3319    /// (mm), in the profile plane's own 2D coordinates.
3320    fn medial_axis(&self, _profile: &Profile, _tolerance: f64) -> KernelResult<Vec<MedialRegion>> {
3321        Err(KernelError::Unsupported("medial axis".into()))
3322    }
3323
3324    /// The centre line of the solid in `brep` from the face `from` names to
3325    /// the face `to` names, held to `tolerance` (mm). Everything is in the
3326    /// shape's own frame.
3327    fn centre_line(
3328        &self,
3329        _brep: &[u8],
3330        _from: &FaceProbe,
3331        _to: &FaceProbe,
3332        _tolerance: f64,
3333    ) -> KernelResult<CentreLine> {
3334        Err(KernelError::Unsupported("centre line".into()))
3335    }
3336
3337    /// What the shape in `brep` answers to `probe`, in the shape's own
3338    /// frame.
3339    fn probe(&self, _brep: &[u8], _probe: &ShapeProbe) -> KernelResult<ProbeAnswer> {
3340        Err(KernelError::Unsupported("probing a shape".into()))
3341    }
3342}
3343
3344/// Standardized error type for kernel interactions.
3345#[derive(Debug, Error)]
3346pub enum KernelError {
3347    #[error("kernel initialization failed: {0}")]
3348    Initialization(String),
3349    #[error("kernel not initialized")]
3350    NotInitialized,
3351    #[error("operation unsupported: {0}")]
3352    Unsupported(String),
3353    #[error("invalid kernel input: {0}")]
3354    InvalidInput(String),
3355    #[error("import failed: {0}")]
3356    Import(String),
3357    #[error(transparent)]
3358    Other(#[from] anyhow::Error),
3359}
3360
3361#[cfg(test)]
3362mod tests {
3363    use super::*;
3364
3365    fn pipe_json(frame: &str) -> String {
3366        let plane = r#"{"origin":[0,0,0],"x_axis":[1,0,0],"y_axis":[0,1,0],"normal":[0,0,1]}"#;
3367        let profile = format!(
3368            r#"{{"plane":{plane},"wires":[{{"segments":[{{"Circle":{{"center":[0,0],"radius":1}}}}]}}]}}"#
3369        );
3370        format!(r#"{{"Pipe":{{"profile":{profile},"spine":{profile},{frame}"op":"NewSolid"}}}}"#)
3371    }
3372
3373    fn frame_of(json: &str) -> PipeFrame {
3374        match serde_json::from_str::<SolidOp>(json).unwrap() {
3375            SolidOp::Pipe { frame, .. } => frame,
3376            other => panic!("not a pipe: {other:?}"),
3377        }
3378    }
3379
3380    #[test]
3381    fn a_pipe_written_with_the_frenet_flag_reads_as_its_frame() {
3382        assert_eq!(frame_of(&pipe_json(r#""frenet":true,"#)), PipeFrame::Frenet);
3383        assert_eq!(
3384            frame_of(&pipe_json(r#""frenet":false,"#)),
3385            PipeFrame::RotationMinimizing
3386        );
3387        assert_eq!(frame_of(&pipe_json("")), PipeFrame::RotationMinimizing);
3388    }
3389
3390    #[test]
3391    fn a_pipe_frame_round_trips() {
3392        let frame = PipeFrame::Binormal {
3393            direction: [0.0, 0.0, 1.0],
3394        };
3395        let text = serde_json::to_string(&frame).unwrap();
3396        assert_eq!(frame_of(&pipe_json(&format!(r#""frame":{text},"#))), frame);
3397    }
3398}