meshbrep 0.4.0

Rebuild an exact B-rep (planes, cylinders, cones, spheres, tori, B-spline surfaces) from a triangle mesh tagged with the surface each triangle came from, write it as STEP AP214, and make fillet and chamfer tools
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
//! The plain data that goes in and comes out: surfaces, curves, the
//! tagged mesh and the B-rep. Every field is public; nothing here holds a
//! reference or a handle.

/// An exact surface, in model coordinates.
///
/// A surface has no orientation of its own: which side is outside is read
/// from the mesh triangles that carry it.
#[derive(Clone, Debug, PartialEq)]
pub enum Surface {
    /// The plane through `origin` with unit `normal`.
    Plane {
        /// A point on the plane.
        origin: [f64; 3],
        /// The unit normal.
        normal: [f64; 3],
    },
    /// The circular cylinder of `radius` about the line through `origin`
    /// along the unit `axis`.
    Cylinder {
        /// A point on the axis.
        origin: [f64; 3],
        /// The unit axis direction.
        axis: [f64; 3],
        /// The radius.
        radius: f64,
    },
    /// One nappe of a circular cone: the points `p` with
    /// `(p - apex) · axis = t >= 0` whose distance from the axis is
    /// `slope * t`. `slope` is the tangent of the half-angle.
    Cone {
        /// The apex.
        apex: [f64; 3],
        /// The unit axis, pointing from the apex into the nappe.
        axis: [f64; 3],
        /// The radius gained per unit length along the axis.
        slope: f64,
    },
    /// The sphere of `radius` about `center`.
    Sphere {
        /// The centre.
        center: [f64; 3],
        /// The radius.
        radius: f64,
    },
    /// A torus about the unit `axis` through `center`: what an arc off
    /// the axis sweeps in `rotate_extrude`. `major_radius` must be above
    /// zero. When it is no larger than `minor_radius` (a spindle or horn
    /// torus, which crosses its own axis) the surface is the torus's outer
    /// part only, the apple: the points nearer the tube's centre circle on
    /// their own side of the axis than on the other (a large fillet on a
    /// boss's top rim). Faces on it must keep off the axis. STEP writes it
    /// as a `DEGENERATE_TOROIDAL_SURFACE` selecting the outer part.
    ///
    /// Its frame (STEP's `TOROIDAL_SURFACE`) puts the point at
    /// `(u, v)` at `origin + (R + r cos v)(cos u x + sin u y) + r sin v z`.
    Torus {
        /// The centre.
        center: [f64; 3],
        /// The unit axis.
        axis: [f64; 3],
        /// The distance from the axis to the centre of the tube.
        major_radius: f64,
        /// The radius of the tube.
        minor_radius: f64,
    },
    /// A clamped B-spline surface patch, rational when it has weights: the
    /// exact form of a surface with no closed form (a blend between two
    /// curved faces), or a fit to one within a stated tolerance. Faces on
    /// it lie inside its parameter domain, which does not wrap: it has no
    /// seams. See [`BSplineSurface`].
    BSpline(BSplineSurface),
    /// The surface swept by `profile` moving along `direction`. Declared
    /// for extruded free-form 2D curves (text outlines); not accepted yet.
    LinearExtrusion {
        /// The swept curve.
        profile: Curve,
        /// The sweep direction (unit).
        direction: [f64; 3],
    },
    /// The surface swept by `profile` turning about the line through
    /// `origin` along `axis`. Declared for revolved 2D curves; not
    /// accepted yet.
    Revolution {
        /// The revolved curve.
        profile: Curve,
        /// A point on the axis.
        origin: [f64; 3],
        /// The unit axis.
        axis: [f64; 3],
    },
    /// No exact surface: the triangles carrying this entry are kept as
    /// they are, and become planar faces (coplanar neighbours merged).
    /// This is the fallback for mesh-only geometry (`polyhedron`, `hull`,
    /// imported meshes).
    Faceted,
}

impl Surface {
    /// A short name for reports: `"plane"`, `"cylinder"`, ...
    pub fn kind(&self) -> &'static str {
        match self {
            Surface::Plane { .. } => "plane",
            Surface::Cylinder { .. } => "cylinder",
            Surface::Cone { .. } => "cone",
            Surface::Sphere { .. } => "sphere",
            Surface::Torus { .. } => "torus",
            Surface::BSpline(_) => "bspline",
            Surface::LinearExtrusion { .. } => "linear extrusion",
            Surface::Revolution { .. } => "revolution",
            Surface::Faceted => "faceted",
        }
    }
}

/// A 3D curve. Each kind has a natural parameter `t`; an [`Edge`] uses
/// the interval [`Edge::range`] of it.
#[derive(Clone, Debug, PartialEq)]
pub enum Curve {
    /// `origin + t * direction`, `direction` a unit vector.
    Line {
        /// The point at `t = 0`.
        origin: [f64; 3],
        /// The unit direction.
        direction: [f64; 3],
    },
    /// `center + radius * (cos t * x_axis + sin t * (normal × x_axis))`.
    Circle {
        /// The centre.
        center: [f64; 3],
        /// The unit normal; the curve turns counter-clockwise about it.
        normal: [f64; 3],
        /// The unit direction of `t = 0`, perpendicular to `normal`.
        x_axis: [f64; 3],
        /// The radius.
        radius: f64,
    },
    /// `center + major * cos t * x_axis + minor * sin t * (normal × x_axis)`.
    Ellipse {
        /// The centre.
        center: [f64; 3],
        /// The unit normal.
        normal: [f64; 3],
        /// The unit direction of the major axis.
        x_axis: [f64; 3],
        /// The semi-major axis.
        major: f64,
        /// The semi-minor axis.
        minor: f64,
    },
    /// A non-rational B-spline: the fallback for intersections of two
    /// curved surfaces that have no closed form.
    BSpline(BSpline<3>),
}

impl Curve {
    /// A short name for reports: `"line"`, `"circle"`, ...
    pub fn kind(&self) -> &'static str {
        match self {
            Curve::Line { .. } => "line",
            Curve::Circle { .. } => "circle",
            Curve::Ellipse { .. } => "ellipse",
            Curve::BSpline(_) => "bspline",
        }
    }
}

/// A clamped, non-rational B-spline curve in `D` dimensions: 3 for edges,
/// 2 for curves in a surface's parameter space.
#[derive(Clone, Debug, PartialEq)]
pub struct BSpline<const D: usize> {
    /// The degree (1 or 3 here).
    pub degree: u32,
    /// The control points.
    pub control: Vec<[f64; D]>,
    /// The full knot vector, `control.len() + degree + 1` long, with the
    /// end knots repeated `degree + 1` times.
    pub knots: Vec<f64>,
}

/// A clamped B-spline surface, rational when `weights` is given: STEP's
/// `B_SPLINE_SURFACE_WITH_KNOTS` (with `RATIONAL_B_SPLINE_SURFACE`).
///
/// The point at `(u, v)` is `Σᵢⱼ Nᵢ(u) Nⱼ(v) wᵢⱼ Pᵢⱼ / Σᵢⱼ Nᵢ(u) Nⱼ(v) wᵢⱼ`,
/// with `i` along `u` (the outer index of `control`) and `j` along `v`.
/// Both knot vectors are clamped (each end knot repeated `degree + 1`
/// times), so the patch's four boundaries are its outer rows and columns
/// of control points, and its domain is
/// `[knots_u[degree_u], knots_u[len - degree_u - 1]]` by the same in `v`.
/// Its natural normal is `∂u × ∂v`. The patch must be regular (that
/// cross product non-zero everywhere, so no collapsed edge such as a
/// sphere's pole), and degrees are 1 to 7.
///
/// [`crate::spline`] evaluates, projects onto, fits and builds them.
#[derive(Clone, Debug, PartialEq)]
pub struct BSplineSurface {
    /// The degree along `u`.
    pub degree_u: u32,
    /// The degree along `v`.
    pub degree_v: u32,
    /// The control net: `control[i][j]`, every row the same length.
    pub control: Vec<Vec<[f64; 3]>>,
    /// Positive weights in the same layout as `control`; `None` for a
    /// non-rational surface (all weights 1).
    pub weights: Option<Vec<Vec<f64>>>,
    /// The knots along `u`: `control.len() + degree_u + 1` of them,
    /// non-decreasing.
    pub knots_u: Vec<f64>,
    /// The knots along `v`: `control[0].len() + degree_v + 1` of them.
    pub knots_v: Vec<f64>,
}

/// The input: a closed, oriented triangle mesh whose triangles each name
/// the exact surface they approximate.
///
/// The mesh must be a 2-manifold (every edge shared by exactly two
/// triangles, in opposite directions), with triangles counter-clockwise
/// seen from outside, as Manifold produces. Positions shared by triangles
/// must be shared indices.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct TaggedMesh {
    /// Vertex positions.
    pub positions: Vec<[f64; 3]>,
    /// Triangles as indices into `positions`.
    pub triangles: Vec<[u32; 3]>,
    /// For each triangle, an index into `surfaces`.
    pub triangle_surface: Vec<u32>,
    /// The surface table.
    pub surfaces: Vec<Surface>,
}

/// The parametrisation of a face's surface: the placement written to STEP
/// as its `AXIS2_PLACEMENT_3D`.
///
/// With `y = z × x`, the surface point at parameters `(u, v)` is
/// - plane: `origin + u x + v y`;
/// - cylinder of radius `r`: `origin + r (cos u x + sin u y) + v z`;
/// - cone: `origin + (r + v · slope) (cos u x + sin u y) + v z`, where `r`
///   is the radius at `origin` ([`Face::ref_radius`]);
/// - sphere of radius `r`: `origin + r cos v (cos u x + sin u y) + r sin v z`;
/// - torus of radii `R` and `r`:
///   `origin + (R + r cos v) (cos u x + sin u y) + r sin v z`.
///
/// `u` is in radians, and a face's curves on a periodic surface use `u` in
/// `[0, 2π]`, with the seam (if any) at `u = 0` and `u = 2π`. A torus's `v`
/// is an angle too: a face that wraps around the tube has a seam along a
/// parallel, at `v0` and `v0 + 2π`; one that does not uses any interval
/// of `v` clear of its cut.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Frame {
    /// The origin.
    pub origin: [f64; 3],
    /// The unit z axis (the plane normal, or the axis of revolution).
    pub z: [f64; 3],
    /// The unit x axis, perpendicular to `z`.
    pub x: [f64; 3],
}

/// The reconstructed boundary representation.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Brep {
    /// Vertex positions.
    pub vertices: Vec<[f64; 3]>,
    /// Edges.
    pub edges: Vec<Edge>,
    /// Faces.
    pub faces: Vec<Face>,
    /// Closed shells, as lists of face indices.
    pub shells: Vec<Shell>,
    /// Measurements and diagnostics from reconstruction.
    pub report: Report,
}

/// An edge: a bounded piece of a curve between two vertices.
#[derive(Clone, Debug, PartialEq)]
pub struct Edge {
    /// The start vertex.
    pub start: u32,
    /// The end vertex (equal to `start` for a closed edge).
    pub end: u32,
    /// The curve, oriented from `start` to `end`.
    pub curve: Curve,
    /// The parameter interval of `curve` used, increasing.
    pub range: [f64; 2],
    /// A seam: the edge where a periodic face meets itself. Used twice by
    /// the same face, once in each direction.
    pub seam: bool,
}

/// A face: a region of one surface bounded by loops.
#[derive(Clone, Debug, PartialEq)]
pub struct Face {
    /// The surface (never [`Surface::Faceted`]: faceted regions become
    /// planes).
    pub surface: Surface,
    /// The parametrisation the loops' parameter-space curves use.
    pub frame: Frame,
    /// For a cone, its radius at `frame.origin`; otherwise 0.
    pub ref_radius: f64,
    /// Whether the face's outward normal agrees with the surface's natural
    /// normal (`∂u × ∂v` of the frame's parametrisation).
    pub same_sense: bool,
    /// The boundary loops. Seen from outside, each runs counter-clockwise
    /// around the face, so the face is on its left.
    pub loops: Vec<Loop>,
    /// Built from [`Surface::Faceted`] triangles.
    pub faceted: bool,
}

/// A closed loop of oriented edges.
#[derive(Clone, Debug, PartialEq)]
pub struct Loop {
    /// The edge uses in order: each ends where the next starts.
    pub coedges: Vec<Coedge>,
    /// The outer boundary of its face (at most one per face; none for a
    /// face such as a sphere with holes, whose loops are all holes).
    pub outer: bool,
}

/// One use of an edge by a face.
#[derive(Clone, Debug, PartialEq)]
pub struct Coedge {
    /// The edge.
    pub edge: u32,
    /// Whether the loop runs along the edge's direction.
    pub forward: bool,
    /// The edge in the face's parameter space, oriented like the edge (not
    /// like the loop). Present on curved faces; planar faces have none.
    pub pcurve: Option<BSpline<2>>,
}

/// A connected closed shell.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Shell {
    /// Its faces.
    pub faces: Vec<u32>,
    /// A void: a cavity inside another shell, whose faces point inwards.
    pub void: bool,
}

/// What reconstruction measured and noticed.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Report {
    /// The largest edge length of the input's bounding box, which scales
    /// the relative tolerances.
    pub scale: f64,
    /// The input mesh's genus, from its Euler characteristic, summed over
    /// its connected components.
    pub mesh_genus: i64,
    /// The input mesh's connected components.
    pub mesh_components: usize,
    /// The largest distance of a vertex from one of its surfaces.
    pub max_vertex_residual: f64,
    /// The largest distance of a sampled edge point from one of its two
    /// surfaces.
    pub max_edge_deviation: f64,
    /// The largest distance of a parameter-space curve's image from its
    /// edge's other surface.
    pub max_pcurve_deviation: f64,
    /// The largest distance of a mesh vertex on an edge from the edge's
    /// exact curve: how far the tessellation is from the exact model.
    /// Only edges with a curved face count, and not those between tangent
    /// surfaces (there the mesh's curve wanders wherever its polygons
    /// cross); each is scaled by the sine of the angle its faces meet at,
    /// so a grazing intersection counts its distance across the surfaces,
    /// not along them. Much more than the
    /// tessellation's own sagitta means the mesh's topology differs from
    /// the exact model's even where reconstruction succeeded.
    pub max_chain_deviation: f64,
    /// Per edge of the B-rep, its share of `max_chain_deviation` (zero for
    /// edges that do not count, seams among them): which edges a caller
    /// that finds the maximum too large should not trust.
    pub edge_chain_deviation: Vec<f64>,
    /// Per face of the B-rep, the input triangles it was built from. A
    /// caller that cannot use part of the result (a face the validator
    /// rejects) can tag those triangles [`Surface::Faceted`] and try
    /// again with the rest exact.
    pub face_triangles: Vec<Vec<u32>>,
    /// Pairs of surfaces found tangent analytically.
    pub tangencies: Vec<Tangency>,
    /// Things worth a look, in words.
    pub notes: Vec<String>,
    /// Reconstruction checked that no face's boundary crosses itself in
    /// its parameter plane, the check [`crate::validate`] would make
    /// again (it has no tolerance, so the answer cannot differ), and which
    /// on a large faceted model was a fifth of validation. Set it to
    /// `false` after changing a B-rep's vertices, edges or loops, so that
    /// `validate` checks it again.
    pub faces_uncrossed: bool,
}

/// Two surfaces of the input that touch without crossing.
#[derive(Clone, Debug, PartialEq)]
pub struct Tangency {
    /// The surfaces, as indices into the input's table (the lower first).
    pub surfaces: [u32; 2],
    /// Where they touch.
    pub contact: Contact,
}

/// The set where two tangent surfaces touch.
#[derive(Clone, Debug, PartialEq)]
pub enum Contact {
    /// A line through `point` along the unit `direction`.
    Line {
        /// A point on the line.
        point: [f64; 3],
        /// The unit direction.
        direction: [f64; 3],
    },
    /// A circle.
    Circle {
        /// The centre.
        center: [f64; 3],
        /// The unit normal.
        normal: [f64; 3],
        /// The radius.
        radius: f64,
    },
    /// A single point.
    Point {
        /// The point.
        point: [f64; 3],
    },
    /// A boundary of a B-spline surface (an isoparametric curve at the
    /// end of its domain) along which it touches the other surface: a
    /// blend's contact with the face it rolls on.
    Boundary {
        /// The B-spline surface, as an index into the input's table (one
        /// of [`Tangency::surfaces`]).
        surface: u32,
        /// Whether the curve is at a fixed `u` (else at a fixed `v`).
        fixed_u: bool,
        /// That fixed parameter: one end of the surface's domain.
        parameter: f64,
    },
}