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/// The wasm panic hook every `#[wasm_bindgen]` entry point installs. Replaces
138/// the `console_error_panic_hook` crate for the whole BREP family — reached as
139/// `brep_kernel::panic_hook` and, through the render engine's re-export, as
140/// `brep_render::brep_kernel::panic_hook`.
141#[doc(hidden)]
142pub mod panic_hook;
143
144/// Plain-text formats shared by the CAD app and the PLM server
145/// (`text::delimited`: CSV and tab-separated text).
146#[doc(hidden)]
147pub mod text;
148
149#[path = "geometry/tolerance.rs"]
150#[doc(hidden)]
151pub mod tolerance;
152pub use tolerance::{
153    curve_model_scale, model_scale, report_scale_migration, SolidScale,
154    offset_construction_band, vertex_tolerance_from_edges, KernelTolerances,
155    MeasuredTolerance, OFFSET_CONSTRUCTION_FLOOR, OFFSET_CONSTRUCTION_REL,
156    VERTEX_MATCH_FLOOR, VOLUME_DRIFT_ABS, VOLUME_DRIFT_REL,
157};
158#[path = "props/diagnostics.rs"]
159#[doc(hidden)]
160pub mod diagnostics;
161pub use diagnostics::{
162    Approximation, ApproximationBudget, Backing, BudgetMechanism, BudgetReason, MeasuredComponent, DiagnosticEvent, DiagnosticSeverity, EdgeOrigin, KernelDiagnostics,
163    KernelOutcome, KernelRefusal, OffCarrierEdge,
164    KernelStage, OrRefuse, RefusalClass, SoundnessDefect, UndecidedCause,
165};
166#[path = "geometry/polygon.rs"]
167#[doc(hidden)]
168pub mod polygon;
169#[path = "geometry/curve.rs"]
170#[doc(hidden)]
171pub mod curve;
172pub use curve::{
173    make_arc, make_circle, make_hyperbola, make_line, make_parabola, uniform_clamped_knots,
174    KnotVector, NurbsCurve, Vec4, KNOT_DEDUP_EPS, KNOT_IDENTITY_TOL,
175};
176#[path = "geometry/fit.rs"]
177#[doc(hidden)]
178pub mod fit;
179pub use fit::{
180    fit_polyline, fit_polyline_at, fit_polyline_of_degree, interpolate_curve, interpolate_curve_closed,
181    interpolate_curve_local, interpolate_curve_thinned, interpolate_curve_with_end_tangents,
182    simplify_polyline, simplify_polyline_indices, solve_banded, solve_dense, PolylineFit,
183    PolylineFitExit, PolylineFitLedger, PolylineFitReport, PolylineFitScope, MAX_FIT_STATIONS,
184};
185#[path = "geometry/image_curve.rs"]
186#[doc(hidden)]
187pub mod image_curve;
188pub use image_curve::{affine_image_curve, image_curve, image_curve_pair, ImageCurve, ImageCurveTier};
189#[path = "geometry/surface.rs"]
190#[doc(hidden)]
191pub mod surface;
192pub use surface::{
193    carrier_preview_patch, make_cone_surface, make_cylinder_surface, make_extrusion, make_plane,
194    make_revolution, make_revolution_one_span, make_sphere_surface, make_sphere_surface_framed, make_torus_surface,
195    ExtendRefusal, KnotDirection, KnotRefinementRefusal, NurbsSurface, SurfaceSide, WeightSite,
196    MAXIMUM_FOLD_ANGLE, MAXIMUM_GROWTH_RATIO,
197};
198#[path = "geometry/deform.rs"]
199#[doc(hidden)]
200pub mod deform;
201pub use deform::{
202    deform_surface, deform_surface_where, deform_surfaces_tied, DeformPick, PoleSupport, SurfaceTie, TieContinuity,
203    TiedResult, TiedSurface, DeformRefusal, DeformResult, DeformSide, DeformSpec,
204    EdgeHold,
205};
206#[path = "geometry/bezier_triangle.rs"]
207#[doc(hidden)]
208pub mod bezier_triangle;
209pub use bezier_triangle::{BezierTriangle, BezierTriangleRefusal, TrianglePiece, TriangleSide};
210#[path = "geometry/t_spline.rs"]
211#[doc(hidden)]
212pub mod t_spline;
213pub use t_spline::{TAnchor, TMesh, TMeshSegment, TSpline, TSplineRefusal};
214#[path = "geometry/coons.rs"]
215#[doc(hidden)]
216pub mod coons;
217pub use coons::{
218    coons_bilinear, coons_bilinear_reported, coons_with_ribbons, CompatWork, CoonsRefusal,
219    CoonsReport, RibbonReport,
220};
221#[path = "geometry/gordon.rs"]
222#[doc(hidden)]
223pub mod gordon;
224pub use gordon::{gordon_surface, gordon_surface_reported, GordonRefusal, GordonReport};
225#[path = "geometry/n_sided.rs"]
226#[doc(hidden)]
227pub mod n_sided;
228pub use n_sided::{n_sided_fill, n_sided_fill_shortening_reach, n_sided_fill_shortening_reach_spokes_off_sides, reentrant_corners as n_sided_reentrant_corners, NSidedRefusal, NSidedReport};
229#[path = "geometry/regularity.rs"]
230#[doc(hidden)]
231pub mod regularity;
232pub use regularity::{certify_regular, Irregularity, RegularityReport};
233#[path = "geometry/analytic_surface.rs"]
234#[doc(hidden)]
235pub mod analytic_surface;
236pub use analytic_surface::{
237    circle_angle_to_parameter, intersect_analytic_pair, plane_ruled_section_arc,
238    revolution_structure, AnalyticSurface, RevolutionFrame, RevolutionStructure,
239};
240pub use analytic_surface::{
241    intersect_analytic_pair_with, ruled_gate,
242    ruled_gate_census, RuledGate,
243};
244#[path = "geometry/sphere_chart.rs"]
245#[doc(hidden)]
246pub mod sphere_chart;
247pub use sphere_chart::{
248    canonicalize_points, chart_grid_divisions, chart_grid_parameters, corner_index,
249    cube_edge_corner, cube_edge_divisions, cube_edge_index, cube_edge_parameters,
250    cube_edge_parts, Chart, ChartSegment, ChartSide, SphereAtlas,
251    SphericalRegion, CHART_COUNT, CUBE_CORNER_COUNT, CUBE_EDGE_COUNT,
252};
253#[path = "geometry/projection.rs"]
254#[doc(hidden)]
255pub mod projection;
256#[path = "geometry/projection_profile.rs"]
257#[doc(hidden)]
258pub mod projection_profile;
259#[doc(hidden)]
260pub use projection_profile::report as projection_profile_report;
261#[path = "geometry/affine_sphere.rs"]
262#[doc(hidden)]
263pub mod affine_sphere;
264pub use projection::{
265    project_point_to_curve, project_point_to_surface, project_point_to_surface_seeded,
266    CurveProjection, SurfaceProjection,
267};
268#[doc(hidden)]
269pub use projection::{
270    project_point_to_surface_basin_census, project_point_to_surface_general_lanes, BasinCensus,
271    GlobalStats,
272};
273#[path = "intersect/curve_surface_intersection.rs"]
274#[doc(hidden)]
275pub mod curve_surface_intersection;
276pub use curve_surface_intersection::{intersect_curve_surface, CurveSurfaceIntersection};
277#[path = "intersect/exact_line_surface.rs"]
278#[doc(hidden)]
279pub mod exact_line_surface;
280#[path = "intersect/curve_clear.rs"]
281#[doc(hidden)]
282pub mod curve_clear;
283#[path = "intersect/curve_curve_intersection.rs"]
284#[doc(hidden)]
285pub mod curve_curve_intersection;
286pub use curve_curve_intersection::{intersect_curves, CurveCurveIntersection};
287#[path = "intersect/surface_surface_intersection.rs"]
288#[doc(hidden)]
289pub mod surface_surface_intersection;
290pub use surface_surface_intersection::{
291    intersect_surfaces, intersect_surfaces_supplemental, SurfaceIntersectionCurve,
292    SurfaceIntersectionOptions,
293};
294pub use surface_surface_intersection::TRANSVERSE_SEED_CROSS;
295pub use surface_surface_intersection::{carriers_proved_apart, hull_sets_proved_apart, separation_prefilter_enabled, SpanHullSet};
296#[path = "intersect/tangent_curve.rs"]
297#[doc(hidden)]
298pub mod tangent_curve;
299#[path = "intersect/crossing_node.rs"]
300#[doc(hidden)]
301pub mod crossing_node;
302pub use crossing_node::{crossing_node_split_enabled, split_at_crossing_nodes};
303pub use tangent_curve::{
304    classify_tangent_contact_at, find_tangent_contact, trace_tangent_curve, TangentContact,
305    EXTENDED_RANK_FLOOR,
306};
307#[path = "geometry/spatial.rs"]
308#[doc(hidden)]
309pub mod spatial;
310pub use spatial::{Aabb, Bvh};
311#[path = "intersect/arrangement.rs"]
312#[doc(hidden)]
313pub mod arrangement;
314pub use arrangement::{
315    arrange_segments, point_in_polygon, segment_intersection, ArrangementPiece, ArrangementRegion,
316    CycleUse, Segment2, Vec2,
317};
318#[path = "geometry/pcurve.rs"]
319#[doc(hidden)]
320pub mod pcurve;
321pub use pcurve::{
322    build_pcurve_on_surface, build_pcurve_on_surface_marched, build_pcurve_on_surface_range,
323    build_pcurve_on_surface_range_dense, build_pcurve_on_surface_stations, fit_pcurve_on_surface,
324    fit_pcurve_on_surface_marched, fit_pcurve_on_surface_range, fit_pcurve_on_surface_range_dense,
325    fit_pcurve_on_surface_stations, PcurveFit, PcurveFitExit, PcurveFitLedger, PcurveFitReport,
326    PcurveFitScope, PCURVE_OFF_BAR, PCURVE_REFINEMENT_TOLERANCE,
327};
328// The pointwise offset evaluator — ONE definition of "the offset of a surface
329// at a parameter", shared by `offset_surface`'s Greville sampling, the blend
330// march's tangency residual, and the push-face offset residual gates. Declared
331// before `offset` because that module is its first consumer.
332#[path = "offset/point.rs"]
333#[doc(hidden)]
334pub mod offset_point;
335pub use offset_point::{OffsetEvaluator, OffsetNormal, OffsetSample};
336// The LOCUS-level offset seam — ONE definition of "intersect two offset
337// analytic carriers in closed form", shared by the blend's corner closures.
338// The pointwise evaluator above answers "where is the offset at this (u, v)";
339// this answers "where do two offsets MEET", which is what the corner solves
340// need and what no pointwise evaluator can produce (audit §9.4, §11).
341// Crate-internal: no consumer outside the kernel names these.
342#[path = "offset/analytic_pair.rs"]
343#[doc(hidden)]
344pub mod offset_analytic_pair;
345#[path = "solvers/linear_algebra.rs"]
346#[doc(hidden)]
347pub mod solver_linear_algebra;
348
349#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize)]
350pub struct Vec3 {
351    pub x: f64,
352    pub y: f64,
353    pub z: f64,
354}
355
356impl Vec3 {
357    pub const ZERO: Self = Self { x: 0.0, y: 0.0, z: 0.0 };
358    pub const X: Self = Self { x: 1.0, y: 0.0, z: 0.0 };
359    pub const Y: Self = Self { x: 0.0, y: 1.0, z: 0.0 };
360    pub const Z: Self = Self { x: 0.0, y: 0.0, z: 1.0 };
361
362    /// Normalize using the standard vector guard, or return the caller's fallback.
363    pub fn normalized_or(self, fallback: Self) -> Self {
364        self.normalized().unwrap_or(fallback)
365    }
366
367    /// Rodrigues rotation about a unit axis through the origin.
368    #[inline]
369    pub fn rotate_about(self, axis: Self, angle: f64) -> Self {
370        let (sin, cos) = angle.sin_cos();
371        self.scale(cos)
372            .add(axis.cross(self).scale(sin))
373            .add(axis.scale(axis.dot(self) * (1.0 - cos)))
374    }
375
376    /// Distance to a segment. `guard` is the caller's squared-length threshold.
377    #[inline]
378    pub fn distance_to_segment(self, start: Self, end: Self, guard: f64) -> f64 {
379        let segment = end.sub(start);
380        let length_squared = segment.dot(segment);
381        if length_squared <= guard {
382            return self.sub(start).length();
383        }
384        let parameter = (self.sub(start).dot(segment) / length_squared).clamp(0.0, 1.0);
385        self.sub(start.add(segment.scale(parameter))).length()
386    }
387
388    /// Squared distance, retaining the seed sweep's projection on zero-length segments.
389    #[inline]
390    pub fn distance_to_segment_squared(self, start: Self, end: Self) -> f64 {
391        let segment = end.sub(start);
392        let length_squared = segment.dot(segment);
393        let parameter = if length_squared > 0.0 {
394            (self.sub(start).dot(segment) / length_squared).clamp(0.0, 1.0)
395        } else {
396            0.0
397        };
398        let residual = self.sub(start.add(segment.scale(parameter)));
399        residual.dot(residual)
400    }
401
402    pub fn new(x: f64, y: f64, z: f64) -> Self {
403        Self { x, y, z }
404    }
405    pub fn sub(self, rhs: Self) -> Self {
406        Self::new(self.x - rhs.x, self.y - rhs.y, self.z - rhs.z)
407    }
408    pub fn add(self, rhs: Self) -> Self {
409        Self::new(self.x + rhs.x, self.y + rhs.y, self.z + rhs.z)
410    }
411    pub fn scale(self, factor: f64) -> Self {
412        Self::new(self.x * factor, self.y * factor, self.z * factor)
413    }
414    pub fn cross(self, rhs: Self) -> Self {
415        Self::new(
416            self.y * rhs.z - self.z * rhs.y,
417            self.z * rhs.x - self.x * rhs.z,
418            self.x * rhs.y - self.y * rhs.x,
419        )
420    }
421    pub fn dot(self, rhs: Self) -> f64 {
422        self.x * rhs.x + self.y * rhs.y + self.z * rhs.z
423    }
424    pub fn length(self) -> f64 {
425        self.dot(self).sqrt()
426    }
427    pub fn length_squared(self) -> f64 {
428        self.dot(self)
429    }
430    pub fn normalized(self) -> Result<Self, String> {
431        let length = self.length();
432        if length <= 1e-12 {
433            return Err("Vec3.normalized: zero-length vector".into());
434        }
435        Ok(self.scale(1.0 / length))
436    }
437    pub fn perpendicular(self) -> Result<Self, String> {
438        let x = self.x.abs();
439        let y = self.y.abs();
440        let z = self.z.abs();
441        let axis = if x <= y && x <= z {
442            Self::new(1.0, 0.0, 0.0)
443        } else if y <= z {
444            Self::new(0.0, 1.0, 0.0)
445        } else {
446            Self::new(0.0, 0.0, 1.0)
447        };
448        self.cross(axis).normalized()
449    }
450}
451
452#[derive(Clone, Debug, Default, Deserialize, Serialize)]
453pub struct Mesh {
454    pub positions: Vec<f64>,
455    pub normals: Vec<f64>,
456    pub indices: Vec<u32>,
457    pub face_ids: Vec<u32>,
458}
459
460impl Mesh {
461    fn push_vertex(&mut self, point: Vec3, normal: Vec3) -> u32 {
462        self.positions.extend([point.x, point.y, point.z]);
463        self.normals.extend([normal.x, normal.y, normal.z]);
464        (self.positions.len() / 3 - 1) as u32
465    }
466
467    fn quad(&mut self, points: [Vec3; 4], normal: Vec3, face_id: u32) {
468        let base = self.push_vertex(points[0], normal);
469        for point in points.iter().skip(1) {
470            self.push_vertex(*point, normal);
471        }
472        self.indices
473            .extend([base, base + 1, base + 2, base, base + 2, base + 3]);
474        self.face_ids.extend([face_id, face_id]);
475    }
476
477    pub fn signed_volume(&self) -> f64 {
478        self.indices
479            .chunks_exact(3)
480            .map(|tri| {
481                let point = |index: u32| {
482                    let i = index as usize * 3;
483                    Vec3::new(
484                        self.positions[i],
485                        self.positions[i + 1],
486                        self.positions[i + 2],
487                    )
488                };
489                point(tri[0]).dot(point(tri[1]).cross(point(tri[2]))) / 6.0
490            })
491            .sum()
492    }
493
494    pub fn validate(&self) -> Result<(), String> {
495        if self.positions.len() % 3 != 0 || self.normals.len() != self.positions.len() {
496            return Err("invalid vertex or normal buffer".into());
497        }
498        self.validate_geometry()
499    }
500
501    /// Geometry-only validation for consumers that use positions + indices but
502    /// NOT normals (e.g. `signed_volume`, whose tetrahedron sum never reads a
503    /// normal). Mesh-only solids such as sheet-metal bodies supply metrics
504    /// meshes with an empty normal buffer, which is legitimate for volume.
505    pub fn validate_geometry(&self) -> Result<(), String> {
506        if self.positions.len() % 3 != 0 {
507            return Err("invalid vertex buffer".into());
508        }
509        if self.indices.len() % 3 != 0 {
510            return Err("index buffer is not triangular".into());
511        }
512        let count = self.positions.len() / 3;
513        if self.indices.iter().any(|index| *index as usize >= count) {
514            return Err("index outside vertex buffer".into());
515        }
516        if !self.positions.iter().all(|value| value.is_finite()) {
517            return Err("non-finite vertex".into());
518        }
519        Ok(())
520    }
521}
522
523pub fn make_box(size_x: f64, size_y: f64, size_z: f64) -> Mesh {
524    let x = size_x.abs();
525    let y = size_y.abs();
526    let z = size_z.abs();
527    let p = [
528        Vec3::new(0.0, 0.0, 0.0),
529        Vec3::new(x, 0.0, 0.0),
530        Vec3::new(x, y, 0.0),
531        Vec3::new(0.0, y, 0.0),
532        Vec3::new(0.0, 0.0, z),
533        Vec3::new(x, 0.0, z),
534        Vec3::new(x, y, z),
535        Vec3::new(0.0, y, z),
536    ];
537    let mut mesh = Mesh::default();
538    mesh.quad([p[0], p[3], p[2], p[1]], Vec3::new(0.0, 0.0, -1.0), 0);
539    mesh.quad([p[4], p[5], p[6], p[7]], Vec3::new(0.0, 0.0, 1.0), 1);
540    mesh.quad([p[0], p[1], p[5], p[4]], Vec3::new(0.0, -1.0, 0.0), 2);
541    mesh.quad([p[3], p[7], p[6], p[2]], Vec3::new(0.0, 1.0, 0.0), 3);
542    mesh.quad([p[0], p[4], p[7], p[3]], Vec3::new(-1.0, 0.0, 0.0), 4);
543    mesh.quad([p[1], p[2], p[6], p[5]], Vec3::new(1.0, 0.0, 0.0), 5);
544    mesh
545}
546
547pub fn make_cylinder(radius: f64, height: f64, segments: usize) -> Mesh {
548    let radius = radius.abs();
549    let height = height.abs();
550    let segments = segments.max(3);
551    let mut mesh = Mesh::default();
552    for i in 0..segments {
553        let a = std::f64::consts::TAU * i as f64 / segments as f64;
554        let b = std::f64::consts::TAU * (i + 1) as f64 / segments as f64;
555        let (sa, ca) = a.sin_cos();
556        let (sb, cb) = b.sin_cos();
557        let pa = Vec3::new(radius * ca, 0.0, -radius * sa);
558        let pb = Vec3::new(radius * cb, 0.0, -radius * sb);
559        let ta = Vec3::new(pa.x, height, pa.z);
560        let tb = Vec3::new(pb.x, height, pb.z);
561        mesh.quad(
562            [pa, pb, tb, ta],
563            Vec3::new((ca + cb) * 0.5, 0.0, -(sa + sb) * 0.5),
564            0,
565        );
566        let bottom = mesh.push_vertex(Vec3::default(), Vec3::new(0.0, -1.0, 0.0));
567        let bi = mesh.push_vertex(pb, Vec3::new(0.0, -1.0, 0.0));
568        let bj = mesh.push_vertex(pa, Vec3::new(0.0, -1.0, 0.0));
569        mesh.indices.extend([bottom, bi, bj]);
570        mesh.face_ids.push(1);
571        let top = mesh.push_vertex(Vec3::new(0.0, height, 0.0), Vec3::new(0.0, 1.0, 0.0));
572        let ti = mesh.push_vertex(ta, Vec3::new(0.0, 1.0, 0.0));
573        let tj = mesh.push_vertex(tb, Vec3::new(0.0, 1.0, 0.0));
574        mesh.indices.extend([top, ti, tj]);
575        mesh.face_ids.push(2);
576    }
577    mesh
578}
579
580#[path = "healing/curve_helpers.rs"]
581#[doc(hidden)]
582pub mod curve_helpers;
583
584#[path = "geometry/eigen2.rs"]
585#[doc(hidden)]
586pub mod eigen2;
587
588#[path = "geometry/union_find.rs"]
589#[doc(hidden)]
590pub mod union_find;
591pub use union_find::UnionFind;
592
593#[path = "geometry/poly.rs"]
594#[doc(hidden)]
595pub mod poly;
596
597pub use analytic_surface::{circumcenter, circumcenter_2d, recognize_circle, RecognizedCircle};
598
599#[path = "geometry/triangle.rs"]
600#[doc(hidden)]
601pub mod triangle;
602pub use triangle::closest_point_on_triangle;
603
604pub use tolerance::RIGID_TOL;
605
606impl std::ops::Index<usize> for Vec3 {
607    type Output = f64;
608    fn index(&self, index: usize) -> &Self::Output {
609        match index { 0 => &self.x, 1 => &self.y, 2 => &self.z, _ => panic!("Vec3 index out of bounds: {index}") }
610    }
611}
612impl std::ops::IndexMut<usize> for Vec3 {
613    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
614        match index { 0 => &mut self.x, 1 => &mut self.y, 2 => &mut self.z, _ => panic!("Vec3 index out of bounds: {index}") }
615    }
616}
617
618/// Hash of this crate's source (`build.rs`), one part of the kernel's source stamp.
619#[doc(hidden)]
620pub const SOURCE_HASH: Option<&str> = option_env!("BREP_KERNEL_SOURCE_HASH");
621#[doc(hidden)]
622#[path = "instrument/work_counts.rs"]
623pub mod work_counts;
624#[doc(hidden)]
625#[path = "instrument/reuse_profile.rs"]
626pub mod reuse_profile;
627#[doc(hidden)]
628#[path = "instrument/carried_uv.rs"]
629pub mod carried_uv;
630#[doc(hidden)]
631#[path = "instrument/blend_timing.rs"]
632pub mod blend_timing;
633#[doc(hidden)]
634#[path = "geometry/identity_hash.rs"]
635pub mod identity_hash;
636#[doc(hidden)]
637#[path = "geometry/trimmed_curve.rs"]
638pub mod trimmed_curve;