Skip to main content

brep_geometry/
lib.rs

1//! Geometry layer of the BREP kernel: vectors, tolerances, diagnostics, NURBS curves and surfaces, projection and intersection.
2//!
3//! It is one of the implementation crates the kernel is built from. Applications
4//! should depend on [`BREP_kernel`](https://crates.io/crates/BREP_kernel), which
5//! re-exports the public API of every kernel crate at its root (`brep_kernel::…`)
6//! and adds the feature pipeline and the STEP, IGES, Parasolid (import), 3MF,
7//! GLB, STL and OBJ exchange.
8//! Many items here are public only so the other kernel crates can reach them;
9//! those are hidden from the documentation and carry no stability promise beyond
10//! the kernel's own. The kernel crates are released together, at one version.
11//!
12//! It contains:
13//!
14//! - vectors, tolerances, diagnostics, runtime switches and text helpers;
15//! - exact rational NURBS curves and surfaces, curve and surface fitting, Coons and Gordon surfaces;
16//! - analytic carrier recognition (plane, cylinder, cone, sphere, torus) and sphere charts;
17//! - point projection onto curves and surfaces;
18//! - curve/curve, curve/surface and surface/surface intersection, tangent curves and crossing nodes;
19//! - bounding boxes and bounding-volume hierarchies, planar segment arrangements and polygons;
20//! - p-curves and offset-point evaluation;
21//! - small linear-algebra helpers, union-find, and the work-count and timing instruments the kernel reports.
22//!
23//! Kernel crates it requires: [`BREP_RANSAC`](https://crates.io/crates/BREP_RANSAC). It is required by [`BREP_topology`](https://crates.io/crates/BREP_topology), [`BREP_surface_offset`](https://crates.io/crates/BREP_surface_offset), [`BREP_boolean`](https://crates.io/crates/BREP_boolean), [`BREP_solvers`](https://crates.io/crates/BREP_solvers), [`BREP_construction`](https://crates.io/crates/BREP_construction), [`BREP_blend`](https://crates.io/crates/BREP_blend), [`BREP_offset`](https://crates.io/crates/BREP_offset), [`BREP_direct_edit`](https://crates.io/crates/BREP_direct_edit), [`BREP_kernel`](https://crates.io/crates/BREP_kernel).
24//!
25//! ## Building
26//!
27//! The crate builds natively and for `wasm32-unknown-unknown`. The `parallel`
28//! feature runs some per-face loops on rayon; `profile-wall` turns on a diagnostic
29//! wall-time partition. Both are off by default, and `BREP_kernel` forwards them.
30//!
31//! The packaged crate ships the library sources, the README, the licence and the
32//! manifest; it carries no test suite.
33//!
34//! ## License
35//!
36//! The Autodrop3d licence in `LICENSE.md`, shipped in the crate (`license-file` in
37//! the manifest). Source: <https://github.com/mmiscool/next.BREP.io_RUST_BREP_KERNEL>
38// Implementation crate of the kernel: its formerly crate-private items are public for the crates above
39// (documented hidden), and their docs may name private helpers.
40#![allow(rustdoc::private_intra_doc_links)]
41use serde::{Deserialize, Serialize};
42#[allow(unused_imports)]
43use wasm_bindgen::prelude::*;
44
45
46/// One environment variable read through its call site's once-cell
47/// ([`env_read::read`], lane O row 19): `std::env::var(name).ok()` as an
48/// `Option<Cow<str>>`, kept for the process when `BREP_ENV_READ_ONCE` is on.
49/// Only for variables nothing sets at run time.
50#[macro_export]
51macro_rules! env_read {
52    ($name:literal) => {{
53        static CELL: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
54        $crate::env_read::read($name, &CELL)
55    }};
56}
57/// One on/off switch (consolidation S1): `switch!("BREP_X", default)` reads
58/// `BREP_X` through its call site's once-cell ([`env_read::switch`], kept for
59/// the process while `BREP_ENV_READ_ONCE` is on); `switch!(live "BREP_X",
60/// default)` reads it on every call, for a variable a probe sets at run time.
61/// One grammar (owner decision 2026-11-01): `0|off|false` off, `1|on|true`
62/// on, unset or anything else the default. In the kernel's tests one keyed
63/// override (`env_read::with_switch_for_test`) forces either form.
64#[macro_export]
65macro_rules! switch {
66    (live $name:expr, $default:expr) => {
67        $crate::env_read::switch_live($name, $default, $crate::env_read::Grammar::Switch)
68    };
69    ($name:expr, $default:expr) => {{
70        static CELL: std::sync::OnceLock<Option<bool>> = std::sync::OnceLock::new();
71        $crate::env_read::switch($name, &CELL, $default, $crate::env_read::Grammar::Switch)
72    }};
73}
74
75/// One debug, trace or `BREP_NO_*` flag (consolidation S1): on when its
76/// variable is set to anything but `0`, `off` or `false`.
77/// `debug_flag!(live "BREP_X")` reads it on every call.
78#[macro_export]
79macro_rules! debug_flag {
80    (live $name:expr) => {
81        $crate::env_read::switch_live($name, false, $crate::env_read::Grammar::Flag)
82    };
83    ($name:expr) => {{
84        static CELL: std::sync::OnceLock<Option<bool>> = std::sync::OnceLock::new();
85        $crate::env_read::switch($name, &CELL, false, $crate::env_read::Grammar::Flag)
86    }};
87}
88
89/// One `0|off / check / on` mode (consolidation X1): an
90/// [`env_read::Mode`]; unset, `On` when `default_on` and `Off` otherwise.
91/// `mode_switch!(live "BREP_X", default_on)` reads it on every call.
92#[macro_export]
93macro_rules! mode_switch {
94    (live $name:expr, $default_on:expr) => {
95        $crate::env_read::mode_live($name, $default_on)
96    };
97    ($name:expr, $default_on:expr) => {{
98        static CELL: std::sync::OnceLock<Option<$crate::env_read::Mode>> = std::sync::OnceLock::new();
99        $crate::env_read::mode($name, &CELL, $default_on)
100    }};
101}
102
103/// `eprintln!` for a `BREP_PROFILE` line: buffered while a
104/// [`profile::ProfileSink`] is open (consolidation I8).
105#[macro_export]
106macro_rules! profile_line {
107    ($($arg:tt)*) => { $crate::profile::profile_emit(format_args!($($arg)*)) };
108}
109
110#[doc(hidden)]
111
112pub mod profile;
113#[doc(hidden)]
114pub mod claim_slots;
115#[cfg(feature = "profile-wall")]
116#[doc(hidden)]
117pub mod wall_profile;
118#[cfg(not(feature = "profile-wall"))]
119#[path = "wall_profile_off.rs"]
120#[doc(hidden)]
121pub mod wall_profile;
122#[cfg(feature = "profile-wall")]
123#[doc(hidden)]
124pub mod reader_profile;
125#[cfg(not(feature = "profile-wall"))]
126#[path = "reader_profile_off.rs"]
127#[doc(hidden)]
128pub mod reader_profile;
129
130
131/// Switch reading for the kernel's dependants ([`switch!`],
132/// [`debug_flag!`], [`mode_switch!`]); not a stable interface.
133#[doc(hidden)]
134#[doc(hidden)]
135pub mod env_read;
136
137
138/// The wasm panic hook every `#[wasm_bindgen]` entry point installs. Replaces
139/// the `console_error_panic_hook` crate for the whole BREP family — reached as
140/// `brep_kernel::panic_hook` and, through the render engine's re-export, as
141/// `brep_render::brep_kernel::panic_hook`.
142#[doc(hidden)]
143pub mod panic_hook;
144
145/// Plain-text formats shared by the CAD app and the PLM server
146/// (`text::delimited`: CSV and tab-separated text).
147#[doc(hidden)]
148pub mod text;
149
150#[path = "geometry/tolerance.rs"]
151#[doc(hidden)]
152pub mod tolerance;
153pub use tolerance::{
154    curve_model_scale, model_scale, report_scale_migration, SolidScale,
155    offset_construction_band, vertex_tolerance_from_edges, KernelTolerances,
156    MeasuredTolerance, OFFSET_CONSTRUCTION_FLOOR, OFFSET_CONSTRUCTION_REL,
157    VERTEX_MATCH_FLOOR, VOLUME_DRIFT_ABS, VOLUME_DRIFT_REL,
158};
159#[path = "props/diagnostics.rs"]
160#[doc(hidden)]
161pub mod diagnostics;
162pub use diagnostics::{
163    Approximation, ApproximationBudget, Backing, BudgetMechanism, BudgetReason, MeasuredComponent, DiagnosticEvent, DiagnosticSeverity, EdgeOrigin, KernelDiagnostics,
164    KernelOutcome, KernelRefusal, OffCarrierEdge,
165    KernelStage, OrRefuse, RefusalClass, SoundnessDefect, UndecidedCause,
166};
167#[path = "geometry/polygon.rs"]
168#[doc(hidden)]
169pub mod polygon;
170#[path = "geometry/curve.rs"]
171#[doc(hidden)]
172pub mod curve;
173pub use curve::{
174    make_arc, make_circle, make_hyperbola, make_line, make_parabola, uniform_clamped_knots,
175    KnotVector, NurbsCurve, Vec4, KNOT_DEDUP_EPS, KNOT_IDENTITY_TOL,
176};
177#[path = "geometry/fit.rs"]
178#[doc(hidden)]
179pub mod fit;
180pub use fit::{
181    fit_polyline, fit_polyline_at, fit_polyline_of_degree, interpolate_curve, interpolate_curve_closed,
182    interpolate_curve_local, interpolate_curve_thinned, interpolate_curve_with_end_tangents,
183    simplify_polyline, simplify_polyline_indices, solve_banded, solve_dense, PolylineFit,
184    PolylineFitExit, PolylineFitLedger, PolylineFitReport, PolylineFitScope, MAX_FIT_STATIONS,
185};
186#[path = "geometry/image_curve.rs"]
187#[doc(hidden)]
188pub mod image_curve;
189pub use image_curve::{affine_image_curve, image_curve, image_curve_pair, ImageCurve, ImageCurveTier};
190#[path = "geometry/surface.rs"]
191#[doc(hidden)]
192pub mod surface;
193pub use surface::{
194    carrier_preview_patch, make_cone_surface, make_cylinder_surface, make_extrusion, make_plane,
195    make_revolution, make_revolution_one_span, make_sphere_surface, make_sphere_surface_framed, make_torus_surface,
196    ExtendRefusal, KnotDirection, KnotRefinementRefusal, NurbsSurface, SurfaceSide, WeightSite,
197    MAXIMUM_FOLD_ANGLE, MAXIMUM_GROWTH_RATIO,
198};
199#[path = "geometry/deform.rs"]
200#[doc(hidden)]
201pub mod deform;
202pub use deform::{
203    deform_surface, deform_surface_where, deform_surfaces_tied, DeformPick, PoleSupport, SurfaceTie, TieContinuity,
204    TiedResult, TiedSurface, DeformRefusal, DeformResult, DeformSide, DeformSpec,
205    EdgeHold,
206};
207#[path = "geometry/bezier_triangle.rs"]
208#[doc(hidden)]
209pub mod bezier_triangle;
210pub use bezier_triangle::{BezierTriangle, BezierTriangleRefusal, TrianglePiece, TriangleSide};
211#[path = "geometry/t_spline.rs"]
212#[doc(hidden)]
213pub mod t_spline;
214pub use t_spline::{TAnchor, TMesh, TMeshSegment, TSpline, TSplineRefusal};
215#[path = "geometry/coons.rs"]
216#[doc(hidden)]
217pub mod coons;
218pub use coons::{
219    coons_bilinear, coons_bilinear_reported, coons_with_ribbons, CompatWork, CoonsRefusal,
220    CoonsReport, RibbonReport,
221};
222#[path = "geometry/gordon.rs"]
223#[doc(hidden)]
224pub mod gordon;
225pub use gordon::{gordon_surface, gordon_surface_reported, GordonRefusal, GordonReport};
226#[path = "geometry/n_sided.rs"]
227#[doc(hidden)]
228pub mod n_sided;
229pub use n_sided::{n_sided_fill, n_sided_fill_centre_solved, n_sided_fill_shortening_reach, n_sided_fill_shortening_reach_spokes_off_sides, reentrant_corners as n_sided_reentrant_corners, NSidedRefusal, NSidedReport};
230#[path = "geometry/regularity.rs"]
231#[doc(hidden)]
232pub mod regularity;
233pub use regularity::{certify_regular, Irregularity, RegularityReport};
234#[path = "geometry/analytic_surface.rs"]
235#[doc(hidden)]
236pub mod analytic_surface;
237pub use analytic_surface::{
238    circle_angle_to_parameter, intersect_analytic_pair, plane_ruled_section_arc,
239    revolution_structure, AnalyticSurface, RevolutionFrame, RevolutionStructure,
240};
241pub use analytic_surface::{
242    intersect_analytic_pair_with, ruled_gate,
243    ruled_gate_census, RuledGate,
244};
245#[path = "geometry/sphere_chart.rs"]
246#[doc(hidden)]
247pub mod sphere_chart;
248pub use sphere_chart::{
249    canonicalize_points, chart_grid_divisions, chart_grid_parameters, corner_index,
250    cube_edge_corner, cube_edge_divisions, cube_edge_index, cube_edge_parameters,
251    cube_edge_parts, Chart, ChartSegment, ChartSide, SphereAtlas,
252    SphericalRegion, CHART_COUNT, CUBE_CORNER_COUNT, CUBE_EDGE_COUNT,
253};
254#[path = "geometry/projection.rs"]
255#[doc(hidden)]
256pub mod projection;
257#[path = "geometry/projection_profile.rs"]
258#[doc(hidden)]
259pub mod projection_profile;
260#[doc(hidden)]
261pub use projection_profile::report as projection_profile_report;
262#[path = "geometry/affine_sphere.rs"]
263#[doc(hidden)]
264pub mod affine_sphere;
265pub use projection::{
266    project_point_to_curve, project_point_to_surface, project_point_to_surface_seeded,
267    CurveProjection, SurfaceProjection,
268};
269#[doc(hidden)]
270pub use projection::{
271    project_point_to_surface_basin_census, project_point_to_surface_general_lanes, BasinCensus,
272    GlobalStats,
273};
274#[path = "intersect/curve_surface_intersection.rs"]
275#[doc(hidden)]
276pub mod curve_surface_intersection;
277pub use curve_surface_intersection::{intersect_curve_surface, CurveSurfaceIntersection};
278#[path = "intersect/exact_line_surface.rs"]
279#[doc(hidden)]
280pub mod exact_line_surface;
281#[path = "intersect/curve_clear.rs"]
282#[doc(hidden)]
283pub mod curve_clear;
284#[path = "intersect/curve_curve_intersection.rs"]
285#[doc(hidden)]
286pub mod curve_curve_intersection;
287pub use curve_curve_intersection::{intersect_curves, CurveCurveIntersection};
288#[path = "intersect/certified_planar.rs"]
289#[doc(hidden)]
290pub mod certified_planar;
291#[path = "intersect/surface_surface_intersection.rs"]
292#[doc(hidden)]
293pub mod surface_surface_intersection;
294pub use surface_surface_intersection::{
295    intersect_surfaces, intersect_surfaces_supplemental, SurfaceIntersectionCurve,
296    SurfaceIntersectionOptions,
297};
298pub use surface_surface_intersection::TRANSVERSE_SEED_CROSS;
299pub use surface_surface_intersection::{carriers_proved_apart, hull_sets_proved_apart, separation_prefilter_enabled, SpanHullSet};
300#[path = "intersect/tangent_curve.rs"]
301#[doc(hidden)]
302pub mod tangent_curve;
303#[path = "intersect/crossing_node.rs"]
304#[doc(hidden)]
305pub mod crossing_node;
306pub use crossing_node::{crossing_node_split_enabled, split_at_crossing_nodes};
307pub use tangent_curve::{
308    classify_tangent_contact_at, find_tangent_contact, trace_tangent_curve, TangentContact,
309    EXTENDED_RANK_FLOOR,
310};
311#[path = "geometry/spatial.rs"]
312#[doc(hidden)]
313pub mod spatial;
314pub use spatial::{Aabb, Bvh};
315#[path = "intersect/arrangement.rs"]
316#[doc(hidden)]
317pub mod arrangement;
318pub use arrangement::{
319    arrange_segments, point_in_polygon, segment_intersection, ArrangementPiece, ArrangementRegion,
320    CycleUse, Segment2, Vec2,
321};
322#[path = "geometry/pcurve.rs"]
323#[doc(hidden)]
324pub mod pcurve;
325pub use pcurve::{
326    build_pcurve_on_surface, build_pcurve_on_surface_marched, build_pcurve_on_surface_range,
327    build_pcurve_on_surface_range_dense, build_pcurve_on_surface_stations, fit_pcurve_on_surface,
328    fit_pcurve_on_surface_marched, fit_pcurve_on_surface_range, fit_pcurve_on_surface_range_dense,
329    fit_pcurve_on_surface_stations, PcurveFit, PcurveFitExit, PcurveFitLedger, PcurveFitReport,
330    PcurveFitScope, PCURVE_OFF_BAR, PCURVE_REFINEMENT_TOLERANCE,
331};
332// The pointwise offset evaluator — ONE definition of "the offset of a surface
333// at a parameter", shared by `offset_surface`'s Greville sampling, the blend
334// march's tangency residual, and the push-face offset residual gates. Declared
335// before `offset` because that module is its first consumer.
336#[path = "offset/point.rs"]
337#[doc(hidden)]
338pub mod offset_point;
339pub use offset_point::{OffsetEvaluator, OffsetNormal, OffsetSample};
340// The LOCUS-level offset seam — ONE definition of "intersect two offset
341// analytic carriers in closed form", shared by the blend's corner closures.
342// The pointwise evaluator above answers "where is the offset at this (u, v)";
343// this answers "where do two offsets MEET", which is what the corner solves
344// need and what no pointwise evaluator can produce (audit §9.4, §11).
345// Crate-internal: no consumer outside the kernel names these.
346#[path = "offset/analytic_pair.rs"]
347#[doc(hidden)]
348pub mod offset_analytic_pair;
349#[path = "solvers/linear_algebra.rs"]
350#[doc(hidden)]
351pub mod solver_linear_algebra;
352
353#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize)]
354pub struct Vec3 {
355    pub x: f64,
356    pub y: f64,
357    pub z: f64,
358}
359
360impl Vec3 {
361    pub const ZERO: Self = Self { x: 0.0, y: 0.0, z: 0.0 };
362    pub const X: Self = Self { x: 1.0, y: 0.0, z: 0.0 };
363    pub const Y: Self = Self { x: 0.0, y: 1.0, z: 0.0 };
364    pub const Z: Self = Self { x: 0.0, y: 0.0, z: 1.0 };
365
366    /// Normalize using the standard vector guard, or return the caller's fallback.
367    pub fn normalized_or(self, fallback: Self) -> Self {
368        self.normalized().unwrap_or(fallback)
369    }
370
371    /// Rodrigues rotation about a unit axis through the origin.
372    #[inline]
373    pub fn rotate_about(self, axis: Self, angle: f64) -> Self {
374        let (sin, cos) = angle.sin_cos();
375        self.scale(cos)
376            .add(axis.cross(self).scale(sin))
377            .add(axis.scale(axis.dot(self) * (1.0 - cos)))
378    }
379
380    /// Distance to a segment. `guard` is the caller's squared-length threshold.
381    #[inline]
382    pub fn distance_to_segment(self, start: Self, end: Self, guard: f64) -> f64 {
383        let segment = end.sub(start);
384        let length_squared = segment.dot(segment);
385        if length_squared <= guard {
386            return self.sub(start).length();
387        }
388        let parameter = (self.sub(start).dot(segment) / length_squared).clamp(0.0, 1.0);
389        self.sub(start.add(segment.scale(parameter))).length()
390    }
391
392    /// Squared distance, retaining the seed sweep's projection on zero-length segments.
393    #[inline]
394    pub fn distance_to_segment_squared(self, start: Self, end: Self) -> f64 {
395        let segment = end.sub(start);
396        let length_squared = segment.dot(segment);
397        let parameter = if length_squared > 0.0 {
398            (self.sub(start).dot(segment) / length_squared).clamp(0.0, 1.0)
399        } else {
400            0.0
401        };
402        let residual = self.sub(start.add(segment.scale(parameter)));
403        residual.dot(residual)
404    }
405
406    pub fn new(x: f64, y: f64, z: f64) -> Self {
407        Self { x, y, z }
408    }
409    pub fn sub(self, rhs: Self) -> Self {
410        Self::new(self.x - rhs.x, self.y - rhs.y, self.z - rhs.z)
411    }
412    pub fn add(self, rhs: Self) -> Self {
413        Self::new(self.x + rhs.x, self.y + rhs.y, self.z + rhs.z)
414    }
415    pub fn scale(self, factor: f64) -> Self {
416        Self::new(self.x * factor, self.y * factor, self.z * factor)
417    }
418    pub fn cross(self, rhs: Self) -> Self {
419        Self::new(
420            self.y * rhs.z - self.z * rhs.y,
421            self.z * rhs.x - self.x * rhs.z,
422            self.x * rhs.y - self.y * rhs.x,
423        )
424    }
425    pub fn dot(self, rhs: Self) -> f64 {
426        self.x * rhs.x + self.y * rhs.y + self.z * rhs.z
427    }
428    pub fn length(self) -> f64 {
429        self.dot(self).sqrt()
430    }
431    pub fn length_squared(self) -> f64 {
432        self.dot(self)
433    }
434    pub fn normalized(self) -> Result<Self, String> {
435        let length = self.length();
436        if length <= 1e-12 {
437            return Err("Vec3.normalized: zero-length vector".into());
438        }
439        Ok(self.scale(1.0 / length))
440    }
441    pub fn perpendicular(self) -> Result<Self, String> {
442        let x = self.x.abs();
443        let y = self.y.abs();
444        let z = self.z.abs();
445        let axis = if x <= y && x <= z {
446            Self::new(1.0, 0.0, 0.0)
447        } else if y <= z {
448            Self::new(0.0, 1.0, 0.0)
449        } else {
450            Self::new(0.0, 0.0, 1.0)
451        };
452        self.cross(axis).normalized()
453    }
454}
455
456#[derive(Clone, Debug, Default, Deserialize, Serialize)]
457pub struct Mesh {
458    pub positions: Vec<f64>,
459    pub normals: Vec<f64>,
460    pub indices: Vec<u32>,
461    pub face_ids: Vec<u32>,
462}
463
464impl Mesh {
465    fn push_vertex(&mut self, point: Vec3, normal: Vec3) -> u32 {
466        self.positions.extend([point.x, point.y, point.z]);
467        self.normals.extend([normal.x, normal.y, normal.z]);
468        (self.positions.len() / 3 - 1) as u32
469    }
470
471    fn quad(&mut self, points: [Vec3; 4], normal: Vec3, face_id: u32) {
472        let base = self.push_vertex(points[0], normal);
473        for point in points.iter().skip(1) {
474            self.push_vertex(*point, normal);
475        }
476        self.indices
477            .extend([base, base + 1, base + 2, base, base + 2, base + 3]);
478        self.face_ids.extend([face_id, face_id]);
479    }
480
481    pub fn signed_volume(&self) -> f64 {
482        self.indices
483            .chunks_exact(3)
484            .map(|tri| {
485                let point = |index: u32| {
486                    let i = index as usize * 3;
487                    Vec3::new(
488                        self.positions[i],
489                        self.positions[i + 1],
490                        self.positions[i + 2],
491                    )
492                };
493                point(tri[0]).dot(point(tri[1]).cross(point(tri[2]))) / 6.0
494            })
495            .sum()
496    }
497
498    pub fn validate(&self) -> Result<(), String> {
499        if self.positions.len() % 3 != 0 || self.normals.len() != self.positions.len() {
500            return Err("invalid vertex or normal buffer".into());
501        }
502        self.validate_geometry()
503    }
504
505    /// Geometry-only validation for consumers that use positions + indices but
506    /// NOT normals (e.g. `signed_volume`, whose tetrahedron sum never reads a
507    /// normal). Mesh-only solids such as sheet-metal bodies supply metrics
508    /// meshes with an empty normal buffer, which is legitimate for volume.
509    pub fn validate_geometry(&self) -> Result<(), String> {
510        if self.positions.len() % 3 != 0 {
511            return Err("invalid vertex buffer".into());
512        }
513        if self.indices.len() % 3 != 0 {
514            return Err("index buffer is not triangular".into());
515        }
516        let count = self.positions.len() / 3;
517        if self.indices.iter().any(|index| *index as usize >= count) {
518            return Err("index outside vertex buffer".into());
519        }
520        if !self.positions.iter().all(|value| value.is_finite()) {
521            return Err("non-finite vertex".into());
522        }
523        Ok(())
524    }
525}
526
527pub fn make_box(size_x: f64, size_y: f64, size_z: f64) -> Mesh {
528    let x = size_x.abs();
529    let y = size_y.abs();
530    let z = size_z.abs();
531    let p = [
532        Vec3::new(0.0, 0.0, 0.0),
533        Vec3::new(x, 0.0, 0.0),
534        Vec3::new(x, y, 0.0),
535        Vec3::new(0.0, y, 0.0),
536        Vec3::new(0.0, 0.0, z),
537        Vec3::new(x, 0.0, z),
538        Vec3::new(x, y, z),
539        Vec3::new(0.0, y, z),
540    ];
541    let mut mesh = Mesh::default();
542    mesh.quad([p[0], p[3], p[2], p[1]], Vec3::new(0.0, 0.0, -1.0), 0);
543    mesh.quad([p[4], p[5], p[6], p[7]], Vec3::new(0.0, 0.0, 1.0), 1);
544    mesh.quad([p[0], p[1], p[5], p[4]], Vec3::new(0.0, -1.0, 0.0), 2);
545    mesh.quad([p[3], p[7], p[6], p[2]], Vec3::new(0.0, 1.0, 0.0), 3);
546    mesh.quad([p[0], p[4], p[7], p[3]], Vec3::new(-1.0, 0.0, 0.0), 4);
547    mesh.quad([p[1], p[2], p[6], p[5]], Vec3::new(1.0, 0.0, 0.0), 5);
548    mesh
549}
550
551pub fn make_cylinder(radius: f64, height: f64, segments: usize) -> Mesh {
552    let radius = radius.abs();
553    let height = height.abs();
554    let segments = segments.max(3);
555    let mut mesh = Mesh::default();
556    for i in 0..segments {
557        let a = std::f64::consts::TAU * i as f64 / segments as f64;
558        let b = std::f64::consts::TAU * (i + 1) as f64 / segments as f64;
559        let (sa, ca) = a.sin_cos();
560        let (sb, cb) = b.sin_cos();
561        let pa = Vec3::new(radius * ca, 0.0, -radius * sa);
562        let pb = Vec3::new(radius * cb, 0.0, -radius * sb);
563        let ta = Vec3::new(pa.x, height, pa.z);
564        let tb = Vec3::new(pb.x, height, pb.z);
565        mesh.quad(
566            [pa, pb, tb, ta],
567            Vec3::new((ca + cb) * 0.5, 0.0, -(sa + sb) * 0.5),
568            0,
569        );
570        let bottom = mesh.push_vertex(Vec3::default(), Vec3::new(0.0, -1.0, 0.0));
571        let bi = mesh.push_vertex(pb, Vec3::new(0.0, -1.0, 0.0));
572        let bj = mesh.push_vertex(pa, Vec3::new(0.0, -1.0, 0.0));
573        mesh.indices.extend([bottom, bi, bj]);
574        mesh.face_ids.push(1);
575        let top = mesh.push_vertex(Vec3::new(0.0, height, 0.0), Vec3::new(0.0, 1.0, 0.0));
576        let ti = mesh.push_vertex(ta, Vec3::new(0.0, 1.0, 0.0));
577        let tj = mesh.push_vertex(tb, Vec3::new(0.0, 1.0, 0.0));
578        mesh.indices.extend([top, ti, tj]);
579        mesh.face_ids.push(2);
580    }
581    mesh
582}
583
584#[path = "healing/curve_helpers.rs"]
585#[doc(hidden)]
586pub mod curve_helpers;
587
588#[path = "geometry/eigen2.rs"]
589#[doc(hidden)]
590pub mod eigen2;
591
592#[path = "geometry/union_find.rs"]
593#[doc(hidden)]
594pub mod union_find;
595pub use union_find::UnionFind;
596
597#[path = "geometry/poly.rs"]
598#[doc(hidden)]
599pub mod poly;
600
601pub use analytic_surface::{circumcenter, circumcenter_2d, recognize_circle, RecognizedCircle};
602
603#[path = "geometry/triangle.rs"]
604#[doc(hidden)]
605pub mod triangle;
606pub use triangle::closest_point_on_triangle;
607
608pub use tolerance::RIGID_TOL;
609
610impl std::ops::Index<usize> for Vec3 {
611    type Output = f64;
612    fn index(&self, index: usize) -> &Self::Output {
613        match index { 0 => &self.x, 1 => &self.y, 2 => &self.z, _ => panic!("Vec3 index out of bounds: {index}") }
614    }
615}
616impl std::ops::IndexMut<usize> for Vec3 {
617    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
618        match index { 0 => &mut self.x, 1 => &mut self.y, 2 => &mut self.z, _ => panic!("Vec3 index out of bounds: {index}") }
619    }
620}
621
622/// Hash of this crate's source (`build.rs`), one part of the kernel's source stamp.
623#[doc(hidden)]
624pub const SOURCE_HASH: Option<&str> = option_env!("BREP_KERNEL_SOURCE_HASH");
625#[doc(hidden)]
626#[path = "instrument/work_counts.rs"]
627pub mod work_counts;
628#[doc(hidden)]
629#[path = "instrument/reuse_profile.rs"]
630pub mod reuse_profile;
631#[doc(hidden)]
632#[path = "instrument/carried_uv.rs"]
633pub mod carried_uv;
634#[doc(hidden)]
635#[path = "instrument/blend_timing.rs"]
636pub mod blend_timing;
637#[doc(hidden)]
638#[path = "geometry/identity_hash.rs"]
639pub mod identity_hash;
640#[doc(hidden)]
641#[path = "geometry/trimmed_curve.rs"]
642pub mod trimmed_curve;