Skip to main content

brep_kernel/
lib.rs

1//! A native and WebAssembly boundary-representation (B-rep) geometry kernel.
2//!
3//! Published as `BREP_kernel`; the library name is `brep_kernel`. It is the exact
4//! geometry engine of the BREP CAD application and is usable on its own:
5//!
6//! - exact rational NURBS curves and surfaces with recognised analytic carriers;
7//! - manifold B-rep topology with validation ([`BrepSolid`]), and primitives
8//!   ([`make_box_brep`], [`make_cylinder_brep`], [`make_sphere_brep`], ...);
9//! - booleans ([`boolean_operation`]), fillets and chamfers ([`fillet_edges`],
10//!   [`chamfer_edge`]), sweeps ([`sweep_profile_along_path`],
11//!   [`sweep_profile_helix`]), lofts including guide curves ([`loft_profile_brep`],
12//!   [`loft_profile_brep_on_guides`]), offsets ([`offset_shell`]) and thickening;
13//! - mass properties ([`solid_mass_properties`]) and watertight tessellation
14//!   ([`tessellate_brep_watertight`]);
15//! - STEP ([`import_step`], [`export_step`]), IGES ([`import_iges`],
16//!   [`export_iges`]), STL, OBJ and 3MF exchange;
17//! - a JSON feature-history pipeline ([`execute_history_json`]).
18//!
19//! Booleans, blends, sweeps and lofts refuse with a typed [`KernelRefusal`]
20//! rather than returning a wrong body; many other entry points return
21//! `Result<_, String>`.
22//!
23//! ```
24//! use brep_kernel::{
25//!     boolean_operation, make_box_brep, make_cylinder_brep, solid_mass_properties,
26//!     tessellate_brep_watertight, BooleanOperation, BooleanOptions, Vec3,
27//! };
28//!
29//! fn main() -> Result<(), String> {
30//!     // A 40 x 30 x 20 block with a vertical radius-8 hole through it.
31//!     let block = make_box_brep(Vec3::new(0.0, 0.0, 0.0), 40.0, 30.0, 20.0)?;
32//!     let hole = make_cylinder_brep(
33//!         Vec3::new(20.0, 15.0, -1.0), // base point
34//!         Vec3::new(0.0, 0.0, 1.0),    // axis direction
35//!         8.0,                         // radius
36//!         22.0,                        // height (through the block)
37//!     )?;
38//!     let part = boolean_operation(&block, &hole, BooleanOperation::Subtract, &BooleanOptions::default())
39//!         .map_err(|error| error.to_string())?;
40//!
41//!     // Mass properties integrated from the B-rep (no display mesh involved).
42//!     let props = solid_mass_properties(&part)?;
43//!     let expected = 40.0 * 30.0 * 20.0 - std::f64::consts::PI * 8.0 * 8.0 * 20.0;
44//!     assert!((props.volume - expected).abs() < 1e-6 * expected);
45//!
46//!     // Watertight display mesh at a 0.05 chord tolerance.
47//!     let mesh = tessellate_brep_watertight(&part, 0.05)?;
48//!     assert!(!mesh.indices.is_empty());
49//!     Ok(())
50//! }
51//! ```
52//!
53//! The crate README lists the capabilities in detail.
54
55
56#[macro_use]
57extern crate brep_solvers;
58#[allow(unused_imports)]
59use brep_solvers::*;
60
61// The public root API of the kernel, from the crates below.
62pub use brep_solvers::sketch_solver::{
63    is_sketch_origin_point_id, sketch_id_key, mint_sketch_id, solve_sketch, solve_sketch_from_json,
64    SketchSolverSettings, SolveSketchRequest, SKETCH_ORIGIN_POINT_ID,
65};
66pub use brep_solvers::assembly_solver::{
67    solve_assembly, AssemblyBody, AssemblyMate, AssemblySolution, AssemblySolveOptions, BodyFreedom, BodyPose,
68    LinearAlgebra, MateAlign, MateAxis, MateCurve, MateKind, MatePlane, MateResidualReport,
69    SolveStrategy, SymmetricElement,
70};
71pub use brep_solvers::sketch3d_solver::{
72    sketch3d_constraint_type, solve_sketch3d, solve_sketch3d_doc, solve_sketch3d_from_json,
73    Sketch3dConstraint, Sketch3dConstraintType, Sketch3dDiagnostics, Sketch3dDoc,
74    Sketch3dGeometry, Sketch3dPoint, Sketch3dSolveOptions, SolveSketch3dRequest,
75    SKETCH3D_CONSTRAINT_TYPES,
76};
77pub use brep_solvers::assembly_resolve::{
78    is_component_reference, resolve_component_point, resolve_edge_selection,
79    resolve_face_selection, resolve_named_selection, resolve_vertex_selection,
80    split_component_namespace, ResolveError, SelectionGeometry,
81};
82
83
84#[macro_use]
85extern crate brep_surface_offset;
86#[allow(unused_imports)]
87use brep_surface_offset::*;
88#[macro_use]
89extern crate brep_boolean;
90#[allow(unused_imports)]
91use brep_boolean::*;
92#[macro_use]
93extern crate brep_construction;
94#[allow(unused_imports)]
95use brep_construction::*;
96#[macro_use]
97extern crate brep_blend;
98#[allow(unused_imports)]
99use brep_blend::*;
100#[macro_use]
101extern crate brep_offset;
102#[allow(unused_imports)]
103use brep_offset::*;
104#[macro_use]
105extern crate brep_direct_edit;
106#[allow(unused_imports)]
107use brep_direct_edit::*;
108
109// The public root API of the kernel, from the crates below.
110pub use brep_surface_offset::offset::{
111    offset_face_carrier, offset_face_carrier_measured, offset_face_carrier_sided, offset_surface,
112    offset_surface_measured, offset_surface_measured_sided, CarrierDeviation, CarrierExtension,
113    MeasuredOffsetSurface, OffsetFaceCarrier, OffsetSurfaceLane,
114};
115pub use brep_boolean::split::{
116    split_solid_by_face_surface, solid_piece_by_plane, split_solid_by_plane, split_solid_by_surface, SplitSurface,
117};
118pub use brep_boolean::imprint::{
119    build_imprints, EdgeSplitRecord, FaceImprints, FaceKey, FacePcurve, ImprintOptions,
120    ImprintPieceRecord, ImprintResultRecord, ImprintVertex, TangentSectionRecord,
121};
122pub use brep_boolean::edge_split::{apply_edge_splits, apply_edge_splits_with_map};
123pub use brep_boolean::fragment::{
124    fragment_face, fragment_solid, FaceFragmentRecord, FragmentCoedge, FragmentEdgeSource,
125    FragmentLoop, FragmentOrder,
126};
127pub use brep_boolean::boolean::{
128    boolean_operation, boolean_operation_nary, boolean_operation_nary_with_options, boolean_operation_with_diagnostics, boolean_operation_with_diagnostics_at_offset, boolean_split_operands,
129    BooleanOperation, BooleanOptions,
130};
131pub use brep_boolean::oracle::{
132    boolean_residual_fusables, boolean_semantic_disagreement, boolean_semantic_disagreement_nary,
133    OracleReport, ResidualFusable, ResidualKind, SemanticDisagreement, DISAGREEMENT_THRESHOLD,
134};
135pub use brep_boolean::accept::{
136    accept_sound, accept_sound_against, accept_sound_against_scoped, resolve_face_crossing, resolve_face_crossing_between,
137    take_crossing_repairs,
138    CrossingRepairRecord,
139};
140pub use brep_boolean::coalesce::{concatenate_exact_curve_pieces, merge_curve_continuation_edges};
141pub use brep_boolean::face_merge::{merge_faces_within, merge_same_surface_faces, merge_same_surface_faces_excluding, merge_same_surface_faces_scoped};
142pub use brep_boolean::faceted_repair::{mesh_to_faceted_brep, repair_triangle_soup, MeshRepairReport};
143pub use brep_boolean::sew::{sew_rotated_copies, sew_solid, split_pinched_vertices, SewReport};
144pub use brep_boolean::mesh_segment::{
145    mesh_regions_to_brep, segment_mesh_faces, MeshRegion, MeshSegmentation, RegionCarrier,
146    SegmentOptions, UNASSIGNED_REGION,
147};
148pub use brep_boolean::spherical_union::reconstruct_spherical_mesh_union;
149pub use brep_construction::solid_sweep::{
150    clip_less_on, screw_profile_brep, sweep_clip_less, sweep_solid_within, OutlinePiece, ScrewStep, SolidMotion, SweepClip, SweptTool, SOLID_SWEEP_REFUSAL,
151};
152pub use brep_construction::solid_sweep_notch::{notch_less, notch_less_on};
153pub use brep_construction::solid_sweep_upright::sweep_upright_along;
154pub use brep_construction::gears;
155pub use brep_construction::gears::{helical_solid, Hand, HelicalGear, rack_section, rack_solid, ring_section, ring_solid, sprocket_section, sprocket_solid, spur_section, spur_solid, GearData, GearSection, Rack, RingGear, Sprocket, SprocketForm, SpurGear};
156pub use brep_construction::mill_program::{flat_mill_region_prisms, MillMove, MILL_REGION_REFUSAL};
157pub use brep_construction::{mill_dome, mill_envelope, mill_faces, mill_plan};
158pub use brep_construction::solid_sweep_thread;
159pub use brep_construction::solid_sweep_apex::{sweep_pyramid_within, Pyramid, APEX_SWEEP_REFUSAL};
160pub use brep_construction::solid_sweep_caps::{sweep_solid, sweep_prism_along, sweep_solid_along, sweep_solid_clipped, sweep_solid_parts, sweep_solid_rising, sweep_solid_tumbled, sweep_tube_slid_across, FrameCurve, RisingTurn, TwoTurns, SolidTool, SOLID_SWEEP_WHOLE_REFUSAL};
161pub use brep_construction::closed_curves::{make_ellipse, make_ellipse_arc, make_ellipsoid_brep, make_periodic_bspline};
162pub use brep_construction::planar_region::{cut_planar_sweep_from_prism, region_cut_on, swept_region_holds, target_outline_holds};
163pub use brep_construction::surface_faces::{face_from_surface, face_from_surface_trimmed, sheet_from_sheets, solid_from_sheets, SURFACE_FACE_REFUSAL};
164pub use brep_construction::slab::{make_slab_brep, SLAB_REFUSAL};
165pub use brep_construction::polyhedron::{make_polyhedron_brep, POLYHEDRON_REFUSAL};
166pub use brep_construction::polygon_solids::{make_pyramid_on_polygon, solid_from_polygons};
167pub use brep_construction::loft_guide_chain::loft_profile_brep_guided_chain;
168pub use brep_construction::loft_guides::{loft_profile_brep_on_guide_chains, loft_profile_brep_on_guides, loft_profile_brep_on_loose_guide_chains, GuideLoftWall, LOFT_ON_GUIDES_REFUSAL};
169pub use brep_construction::extrude_up_to::{extrude_profile_up_to_face, solid_pieces, EXTRUDE_UP_TO_REFUSAL};
170pub use brep_construction::sweep_round_corners::{sweep_profile_round_corners, SWEEP_ROUND_CORNERS_REFUSAL};
171pub use brep_construction::sweep_ellipsoid::sweep_ellipsoid_along_line;
172pub use brep_construction::profile_holes::{extrude_profile_with_holes, revolve_profile_with_holes};
173pub use brep_construction::sweep_topology::{
174    extrude_profile_brep, extrude_profile_brep_draft, fit_helix_curve, helix_sample_points,
175    profile_anchor, rib_from_profile, sweep_bend_profile, sweep_closure, BendStation,
176    JointContinuity, PathJoint, SweepClosure,
177    RibExtrusion, RibNames, SweepPath, MAX_JOINT_TANGENT_BREAK, SWEEP_TIGHT_BEND_REFUSAL,
178    SWEEP_TWIST_CLOSURE_REFUSAL,
179    build_swept_envelope, recognize_swept_envelope, swept_envelope_volume, SweptEnvelope,
180    SWEEP_ENVELOPE_REFUSAL, sweep_envelope_bodies,
181    sweep_profile_along_chain, sweep_profile_along_chain_reported,
182    sweep_profile_along_chain_with_stations, sweep_profile_along_chain_with_stations_reported,
183    sweep_profile_along_path,
184    sweep_profile_along_path_anchored,
185    sweep_profile_helix,
186    sweep_profile_twisted, sweep_profile_twisted_anchored, sweep_profile_twisted_within, sweep_profile_twisted_scaled,
187    ProfileAnchor, SectionPlacement,
188    StationBudget, SweepStationReport, SweptChain, SWEEP_DEFAULT_TOLERANCE, SWEEP_MAX_STATIONS,
189    SWEEP_REFINEMENT_ROUNDS,
190};
191pub use brep_construction::revolve_topology::{revolve_profile_brep, revolve_profile_brep_named};
192pub use brep_construction::loft_topology::{
193    loft_profile_brep, loft_profile_brep_closed, loft_profile_brep_guided,
194    loft_profile_brep_guided_frame, loft_profile_brep_tangent,
195};
196pub use brep_blend::blend::{
197    take_blend_approximations, take_blend_notes,
198    blend_timing_capture, take_blend_timings, BlendTiming,
199    blend_closed_edge, blend_edge_variable, blend_open_edge, blend_smooth_chain,
200    round_convex_corner,
201};
202pub use brep_blend::fillet::{
203    chamfer_edge, chamfer_edge_angle, chamfer_edge_asymmetric, chamfer_edges_angle,
204    chamfer_edges_asymmetric, chamfer_edges_asymmetric_linear, fillet_edge, fillet_edge_conic, fillet_edges, fillet_edges_conic, fillet_edges_conic_distances, fillet_edges_conic_setback, fillet_edges_reported, fillet_edges_reported_at_offset,
205    fillet_edge_g2, fillet_edges_g2, fillet_faces, full_round, fillet_edges_radii, fillet_edges_setback, fillet_edges_setback_g2, fillet_edges_variable, fillet_edges_variable_law, fillet_edges_variable_vertex_radii,
206    BlendSelection,
207};
208pub use brep_blend::law::{LawSegment, RadiusLaw};
209pub use brep_offset::thicken_faces::{extrude_curves_to_sheet, thicken_sheet_faces, THICKEN_FACES_REFUSAL};
210pub use brep_offset::shell_rounded::{offset_shell_rounded, SHELL_ROUNDED_REFUSAL};
211pub use brep_offset::thicken::{thicken_face_sheet, thicken_trimmed_sheet};
212pub use brep_offset::offset_shell::{
213    offset_shell, offset_shell_by_boolean, offset_shell_closed, offset_shell_with_diagnostics, offset_shell_with_options, offset_solid, OffsetCorners, ShellOptions,
214    OffsetFaceRole, OffsetShellFaceImageRecord, OffsetShellResultRecord,
215};
216pub use brep_direct_edit::direct_edit::{
217    delete_face_and_heal, delete_faces_and_heal, draft_faces, draft_faces_parted, draft_faces_unchecked, move_faces, move_faces_unchecked,
218    offset_freeform_face, offset_freeform_face_unchecked,
219    offset_revolution_face, offset_revolution_face_unchecked, offset_ruled_face, offset_ruled_face_unchecked, offset_sphere_face,
220    offset_sphere_face_unchecked, offset_torus_face, offset_torus_face_unchecked,
221    rebuild_displaced_blends, with_blend_rebuild_decline,
222    recut_moved_planes, recut_moved_planes_rigid, recut_moved_planes_unchecked, redrill_moved_bore, recut_convex_body, reblend_lost_fillets, resolve_face_by_point, rotate_faces, rotate_faces_unchecked,
223    route_reading, RouteReading,
224};
225pub use brep_direct_edit::direct_edit::{face_refusal_slugs, face_transform_reason, FaceTransformReason};
226pub use brep_direct_edit::direct_edit::{deform_shell, ShellDeformPick, ShellDeformReport, ShellDeformSpec};
227pub use brep_direct_edit::direct_edit::{deform_face, face_deform_default_anchor, FaceDeformPick, FaceDeformReport, FaceDeformSpec};
228pub use brep_direct_edit::direct_edit::{
229    refit_faces_as_one, refit_refusal_phrases, RefitCarrier, RefitReport, RefitSurfaceKind,
230};
231
232
233#[macro_use]
234extern crate brep_geometry;
235#[allow(unused_imports)]
236use brep_geometry::*;
237#[macro_use]
238extern crate brep_topology;
239#[allow(unused_imports)]
240use brep_topology::*;
241
242// The public root API of the kernel, from the crates below.
243pub use brep_topology::{display_chord_tolerance, solid_model_scale, solid_scale};
244pub use brep_topology::{
245    nearest_boundary_point, solid_closest_points, solid_gap, solid_least_box, solid_outward_normals, solid_principal_curvatures, BoundaryFoot,
246    BoundaryPlace,
247};
248pub use brep_geometry::switch;
249pub use brep_geometry::debug_flag;
250pub use brep_geometry::mode_switch;
251pub use brep_geometry::env_read;
252pub use brep_geometry::panic_hook;
253pub use brep_geometry::text;
254pub use brep_geometry::tolerance::{
255    curve_model_scale, model_scale, report_scale_migration, SolidScale,
256    offset_construction_band, vertex_tolerance_from_edges, KernelTolerances,
257    MeasuredTolerance, OFFSET_CONSTRUCTION_FLOOR, OFFSET_CONSTRUCTION_REL,
258    VERTEX_MATCH_FLOOR, VOLUME_DRIFT_ABS, VOLUME_DRIFT_REL,
259};
260pub use brep_geometry::diagnostics::{
261    Approximation, ApproximationBudget, Backing, BudgetMechanism, BudgetReason, MeasuredComponent, DiagnosticEvent, DiagnosticSeverity, EdgeOrigin, KernelDiagnostics,
262    KernelOutcome, KernelRefusal, OffCarrierEdge,
263    KernelStage, OrRefuse, RefusalClass, SoundnessDefect, UndecidedCause,
264};
265pub use brep_geometry::polygon;
266pub use brep_geometry::curve::{
267    make_arc, make_circle, make_hyperbola, make_line, make_parabola, uniform_clamped_knots,
268    KnotVector, NurbsCurve, Vec4, KNOT_DEDUP_EPS, KNOT_IDENTITY_TOL,
269};
270pub use brep_geometry::fit::{
271    fit_polyline, fit_polyline_at, fit_polyline_of_degree, interpolate_curve, interpolate_curve_closed,
272    interpolate_curve_local, interpolate_curve_thinned, interpolate_curve_with_end_tangents,
273    simplify_polyline, simplify_polyline_indices, solve_banded, solve_dense, PolylineFit,
274    PolylineFitExit, PolylineFitLedger, PolylineFitReport, PolylineFitScope, MAX_FIT_STATIONS,
275};
276pub use brep_geometry::image_curve::{affine_image_curve, image_curve, image_curve_pair, ImageCurve, ImageCurveTier};
277pub use brep_geometry::surface::{
278    carrier_preview_patch, make_cone_surface, make_cylinder_surface, make_extrusion, make_plane,
279    make_revolution, make_sphere_surface, make_sphere_surface_framed, make_torus_surface,
280    ExtendRefusal, KnotDirection, KnotRefinementRefusal, NurbsSurface, SurfaceSide, WeightSite,
281    MAXIMUM_FOLD_ANGLE, MAXIMUM_GROWTH_RATIO,
282};
283pub use brep_geometry::deform::{
284    deform_surface, deform_surface_where, deform_surfaces_tied, DeformPick, PoleSupport, SurfaceTie, TieContinuity,
285    TiedResult, TiedSurface, DeformRefusal, DeformResult, DeformSide, DeformSpec,
286    EdgeHold,
287};
288pub use brep_geometry::coons::{
289    coons_bilinear, coons_bilinear_reported, coons_with_ribbons, CompatWork, CoonsRefusal,
290    CoonsReport, RibbonReport,
291};
292pub use brep_geometry::gordon::{gordon_surface, gordon_surface_reported, GordonRefusal, GordonReport};
293pub use brep_geometry::n_sided::{n_sided_fill, reentrant_corners as n_sided_reentrant_corners, NSidedRefusal, NSidedReport};
294pub use brep_geometry::regularity::{certify_regular, Irregularity, RegularityReport};
295pub use brep_geometry::analytic_surface::{
296    circle_angle_to_parameter, intersect_analytic_pair, plane_ruled_section_arc,
297    revolution_structure, AnalyticSurface, RevolutionFrame, RevolutionStructure,
298};
299pub use brep_geometry::sphere_chart::{
300    canonicalize_points, chart_grid_divisions, chart_grid_parameters, corner_index,
301    cube_edge_corner, cube_edge_divisions, cube_edge_index, cube_edge_parameters,
302    cube_edge_parts, Chart, ChartSegment, ChartSide, SphereAtlas,
303    SphericalRegion, CHART_COUNT, CUBE_CORNER_COUNT, CUBE_EDGE_COUNT,
304};
305#[doc(hidden)]
306pub use brep_geometry::projection_profile::report as projection_profile_report;
307pub use brep_geometry::projection::{
308    project_point_to_curve, project_point_to_surface, project_point_to_surface_seeded,
309    CurveProjection, SurfaceProjection,
310};
311#[doc(hidden)]
312pub use brep_geometry::projection::{
313    project_point_to_surface_basin_census, project_point_to_surface_general_lanes, BasinCensus,
314    GlobalStats,
315};
316pub use brep_geometry::curve_surface_intersection::{intersect_curve_surface, CurveSurfaceIntersection};
317pub use brep_geometry::curve_curve_intersection::{intersect_curves, CurveCurveIntersection};
318pub use brep_geometry::surface_surface_intersection::{
319    intersect_surfaces, intersect_surfaces_supplemental, SurfaceIntersectionCurve,
320    SurfaceIntersectionOptions,
321};
322pub use brep_geometry::crossing_node::{crossing_node_split_enabled, split_at_crossing_nodes};
323pub use brep_geometry::tangent_curve::{
324    classify_tangent_contact_at, find_tangent_contact, trace_tangent_curve, TangentContact,
325    EXTENDED_RANK_FLOOR,
326};
327pub use brep_geometry::spatial::{Aabb, Bvh};
328pub use brep_geometry::arrangement::{
329    arrange_segments, point_in_polygon, segment_intersection, ArrangementPiece, ArrangementRegion,
330    CycleUse, Segment2, Vec2,
331};
332pub use brep_geometry::pcurve::{
333    build_pcurve_on_surface, build_pcurve_on_surface_marched, build_pcurve_on_surface_range,
334    build_pcurve_on_surface_range_dense, build_pcurve_on_surface_stations, fit_pcurve_on_surface,
335    fit_pcurve_on_surface_marched, fit_pcurve_on_surface_range, fit_pcurve_on_surface_range_dense,
336    fit_pcurve_on_surface_stations, PcurveFit, PcurveFitExit, PcurveFitLedger, PcurveFitReport,
337    PcurveFitScope, PCURVE_OFF_BAR, PCURVE_REFINEMENT_TOLERANCE,
338};
339pub use brep_geometry::offset_point::{OffsetEvaluator, OffsetNormal, OffsetSample};
340pub use brep_geometry::Vec3;
341pub use brep_geometry::Mesh;
342pub use brep_geometry::make_box;
343pub use brep_geometry::make_cylinder;
344pub use brep_geometry::union_find;
345pub use brep_geometry::union_find::UnionFind;
346pub use brep_geometry::poly;
347pub use brep_geometry::analytic_surface::{circumcenter, circumcenter_2d, recognize_circle, RecognizedCircle};
348pub use brep_geometry::triangle::closest_point_on_triangle;
349pub use brep_geometry::tolerance::RIGID_TOL;
350pub use brep_topology::entity_tolerance::{EntityTolerances, EDGE_CAP_FRACTION, VERTEX_CAP_FRACTION};
351pub use brep_topology::control_cage::{
352    CagePoint, CagePrimitive, ControlCage, CAGE_DEGREE, MAX_RINGS, MAX_SEGMENTS, MIN_RINGS,
353    MIN_SEGMENTS,
354};
355pub use brep_topology::solid_codec::{decode_solid, encode_solid, SolidNames, SOLID_CODEC_VERSION, SOLID_CODEC_VERSION_KIND};
356pub use brep_topology::topology::{
357    make_box_brep, make_cylinder_brep, make_pyramid_brep, topology_kind, BodyKind, BrepSolid, CellRecord, CoedgeRecord,
358    FaceRecord, IssueKind, KindReport, LoopRecord, TopologyKind, ValidationReport,
359};
360pub use brep_topology::soundness::{
361    face_self_intersections, loop_self_crossings, shell_vector_areas, solid_connectivity,
362    solid_euler, solid_self_intersections, ConnectivityReport, CrossingConfirmation, EulerReport,
363    CertificateScope, CertifiedFacePair, FaceCrossing, FaceFold, FaceVectorArea,
364    LoopCrossing, LoopCrossingReport, SelfIntersectionOptions, SelfIntersectionReport,
365    ClosureReading, ShellConnectivity, ShellVectorArea, VectorAreaReport, CrossingUndecidedCause, UndecidedCrossing,
366    MAX_LISTED_UNDECIDED,
367};
368pub use brep_topology::topology_arena::{
369    ArenaCoedge, ArenaEdge, ArenaFace, ArenaLoop, ArenaShell, ArenaVertex, CoedgeId, EdgeId,
370    FaceId, LoopId, ShellId, TopologyArena, VertexId,
371};
372pub use brep_topology::analytic_topology::{
373    make_cone_brep, make_sphere_brep, make_sphere_brep_framed, make_torus_brep,
374};
375pub use brep_topology::curve_chain::{join_curve_chain, split_surface};
376pub use brep_topology::transform_topology::{mirror_brep, transform_brep, AffineTransform};
377pub use brep_topology::mass_properties::{
378    curve_arc_length, edge_arc_length, face_area, face_boundary_length, face_volume_contribution,
379    face_set_identity, mass_caller, parameter_space_area, solid_edge_length_total,
380    solid_mass_properties,
381    solid_mass_properties_full, signed_volume_against, solid_signed_volume, solid_signed_volume_for_sign, trim_polygons,
382    DensityMassProperties,
383    FaceSetIdentity, FullMassProperties, MassCaller, MassProperties, MassPropertiesCache,
384};
385pub use brep_topology::carrier_dimensions::{curve_carrier_dimensions, surface_carrier_dimensions, CarrierDimensions};
386pub use brep_topology::tessellation::{tessellate_brep, tessellate_face, TessellationOptions};
387pub use brep_topology::watertight_tessellation::{
388    sample_edge_polyline_checked, EdgeChordError, EdgeChordFailure, TessellationError,
389    tessellate_brep_watertight_checked,
390    sample_edge_polylines, sample_edges_encoded, tessellate_brep_watertight,
391    tessellate_brep_watertight_face_stride, tessellate_brep_watertight_face_stride_with_samples,
392};
393pub use brep_topology::classification::{
394    classify_point, containment_lane, horizon_cross_frame, parameter_point_in_face,
395    trim_sample_count, trim_station, ContainmentLane, PointClass, PointClassification,
396    PolygonClass, SolidClassifier, COVERING_RIM_STRIP_SWITCH, HORIZON_CONTAINMENT_SWITCH,
397    HORIZON_CROSS_FRAME_SWITCH, HORIZON_SINGLE_LOOP_SWITCH, NO_SPHERE_CHART_TRIM_SWITCH,
398    SEAM_BAND_MERGED_SWITCH,
399};
400#[doc(hidden)]
401pub use brep_topology::classification::parameter_point_in_face_scan;
402pub use brep_topology::pair_classification::{
403    classify_surface_pair, classify_surface_pair_cached, SurfaceClassifyData,
404    SurfacePairClassification, SurfacePairRelation,
405};
406pub use brep_topology::offset_measure::{
407    measure_edge_against_pcurve_image, measure_surface_fit_against_pointwise_offset,
408    span_midpoint_error, vertex_endpoint_gap,
409};
410pub use brep_topology::mesh_weld::{canonical_bits, VertexWeld};
411
412
413use serde::{Deserialize, Serialize};
414use wasm_bindgen::prelude::*;
415
416// The wasm global allocator, when the `wasm-talc` feature asks for it.
417#[cfg(all(feature = "wasm-talc", target_family = "wasm", not(target_feature = "atomics")))]
418#[global_allocator]
419static TALC: talc::wasm::WasmDynamicTalc = talc::wasm::new_wasm_dynamic_allocator();
420
421// The native global allocator, when the `native-rusty-alloc` feature asks for it.
422#[cfg(all(feature = "native-rusty-alloc", not(target_family = "wasm")))]
423#[cfg(not(feature = "profile-wall"))]
424#[global_allocator]
425static RUSTY_ALLOC: rusty_alloc_api::RustyAlloc = rusty_alloc_api::RustyAlloc;
426
427#[cfg(all(feature = "native-rusty-alloc", not(target_family = "wasm"), feature = "profile-wall"))]
428#[global_allocator]
429static RUSTY_ALLOC: wall_profile::Allocator<rusty_alloc_api::RustyAlloc> = wall_profile::Allocator(rusty_alloc_api::RustyAlloc);
430#[path = "construction/draft_roof.rs"]
431mod draft_roof;
432#[path = "blending/fillet_tangent_chains.rs"]
433mod fillet_tangent_chains;
434pub use fillet_tangent_chains::{chamfer_edges_with_options, fillet_edges_tangent_chains, fillet_edges_with_options, ChamferOptions, FilletOptions};
435pub use draft_roof::{extrude_profile_brep_draft_roof, DRAFT_ROOF_REFUSAL};
436// The Rust feature-history execution engine (migration-plan Stage 4/5 foundation).
437// Deserializes the serialized `{ type, inputParams, ... }` descriptor shape, runs
438// each feature against a live scene-map of resident handles, and returns per-feature
439// results (handles + face/edge names). See feature_pipeline/mod.rs for the contract.
440#[path = "feature_pipeline/mod.rs"]
441pub mod feature_pipeline;
442pub use feature_pipeline::execute_history_json;
443pub use feature_pipeline::{first_reference_name, imported_solid_names, is_gear_type, is_weld_type, reference_names};
444// Transform Face's default pivot (the selection's boundary centre) over the
445// results of a replayed prefix, so the gizmo and the stored `pivot` agree with
446// the feature by construction.
447pub use feature_pipeline::{face_transform_pivot, face_transform_reference_point};
448// Typed, in-process pipeline surface for native consumers (brep-render): run a
449// whole history and read the results without a JSON round trip.
450pub use feature_pipeline::{
451    clear_history_cache, execute_history, execute_history_observed, AddedSolid, Axis,
452    ComponentRecord, FeatureDescriptor, FeatureRefusal, FeatureResult, Frame, Fulfilment,
453    HistoryProgress, HistoryRequest, Rejected, RejectedKind,
454    HistoryResult, PortKind, PortRecord, ProfileLoop, ScenePoint, SketchProfile,
455};
456// Wire harness: the document's `wireHarness` block (connections), the tail's
457// routing report (per-connection status / length / route, per-segment bundle),
458// and the sided-port vocabulary the spline attachments share.
459pub use feature_pipeline::wire_harness::{
460    bundle_diameter, Attachment as SplineAttachment, BundleStatus, PortSide, RouteResult,
461    RouteStatus,
462    WireHarnessBundle, WireHarnessConnection,
463    WireHarnessEndpoint, WireHarnessReport, WireHarnessState, BUNDLE_SOLID_PREFIX,
464    WIRE_HARNESS_FEATURE_ID, WIRE_HARNESS_FEATURE_TYPE,
465};
466// A part's pins ARE its declared connection points, bound BY NAME within one
467// symbol unit and its port group: the report of what does not pair, following
468// an edit on one side to the other, the unit-to-group mapping, and a placed
469// part's pin resolved to a point ADDRESS (refused by name when it names none).
470pub use feature_pipeline::part_pins::{
471    declarations as declared_ports, declared_endpoints as declared_point_endpoints,
472    declared_points, endpoint_occurrence, follow_pin_edit, follow_point_edit, pin_labels,
473    pin_point_report, pins,
474    point_renames, port_group_for_unit, resolve_component_pin, resolve_part_pin,
475    unit_count as symbol_unit_count, unit_groups, DeclaredPin, DeclaredPoint, PinPoint,
476    PinPointChange, PinPointProblem, PinPointReport, PointRenames, DEFAULT_PORT_NAME,
477    DEFAULT_PORT_PURPOSE, PADS_BLOCK, SYMBOL_BLOCK,
478};
479// The declared-ports block itself: the schema a part document carries, the
480// address scheme, the unit map and the encapsulation-boundary rule — and the
481// SEAT, the frame a point's placement is an offset in, with the two mappings
482// an editor needs to put a gizmo on one and write the drag back.
483pub use feature_pipeline::ports::{
484    address as port_address, contact_body_axis, contact_body_end, contact_body_solid, document_is_boundary,
485    seat_of as port_seat_of, seat_point, ContactAxis as PortContactAxis, ContactRule as PortContactRule, PortContactRow,
486    seat_vector, seated_direction, split_address, unit_map, unseat_point, unseat_vector,
487    world_seat, PortDeclaration, PortPoint, PortPointRow, PortSeat, PortsReport, UnitProblem,
488    BOUNDARY_KEY, PORTS_BLOCK, PORTS_FEATURE_ID, PORTS_FEATURE_TYPE,
489};
490// PMI: the document's `pmi` block (views + annotations), the type table with
491// its schemas / selection predicates, the tail's resolved report, and the
492// presentation layout shared by the viewport and the AP242 export.
493pub use feature_pipeline::pmi::{
494    balloon_head as pmi_balloon_head, clamp_text_size, format_dimension, format_number,
495    nearest_point_on_edge, nearest_point_on_solid, pmi_schema_catalogue, pmi_type,
496    nearest_displayed_point, nearest_displayed_point_on_edge, pose_apply as pmi_pose_apply, pose_unapply as pmi_pose_unapply,
497    resolve_state as pmi_resolve_state, entry_names_solid, baseline_hide_id, BalloonAnchor, BalloonAnchorMode, CenterCircle, FcfFrame, HalfSpace as PmiHalfSpace, HeadScope as PmiHeadScope, PmiAnnotation,
498    PmiAnnotationReport, PmiCamera, PmiDisplay, PmiGeometry, PmiPlane, PmiPose, PmiProjection, PmiReport,
499    PmiState, PmiStatus, PmiTypeDef, PmiView, PmiViewReport, SolidPoses as PmiSolidPoses, ToleranceBlock, ToleranceMode, PMI_TYPES,
500};
501pub use feature_pipeline::pmi::layout::{present as pmi_present, LayoutStyle as PmiLayoutStyle, Presentation as PmiPresentation};
502pub use feature_pipeline::pmi::annotations::fcf::{characteristic as pmi_characteristic, Characteristic as PmiCharacteristic, CHARACTERISTICS as PMI_CHARACTERISTICS};
503// The sketch loop-id write-back: stamps each closed loop's stable id onto its
504// geometries so per-loop face names survive deleting the edge an id came from.
505// The editor calls it when a sketch is committed.
506pub use feature_pipeline::assign_sketch_loop_ids;
507// The 3D sketch feature's reference resolver and record shape, shared with the
508// engine-native 3D sketch editor so the editor materializes exactly what the
509// feature re-resolves on every run.
510pub use feature_pipeline::features::sketch3d::{
511    reference_record as sketch3d_reference_record, resolve_reference as resolve_sketch3d_reference,
512    ResolvedReference as Sketch3dResolvedReference, REFERENCE_TIP_LENGTH as SKETCH3D_REFERENCE_TIP_LENGTH,
513    common_edge_end as sketch3d_common_edge_end, curve_reference_controls as sketch3d_curve_reference_controls, REFERENCE_ANCHOR_EDGES_KEY as SKETCH3D_ANCHOR_EDGES_KEY,
514    SKETCH3D_DOC_KEY, SKETCH3D_EDIT_BUTTON, SKETCH3D_FEATURE_TYPE, SKETCH3D_REFERENCES_PARAM,
515    SKETCH3D_REFS_KEY,
516};
517// Sheet-metal flat-pattern (unfold) → 2D vector export, keyed by resident handle.
518pub use feature_pipeline::{flat_pattern_dxf, flat_pattern_svg, is_sheet_metal_handle};
519// The part Pattern's per-instance suppression list.
520pub use feature_pipeline::{pattern_component_instance, pattern_parse_suppressed};
521// Native IMPORT3D payload: finished solids → the `io/snapshot` container with
522// IMPORT3D's naming stamped on, i.e. the `inputParams.nativeBrep` an import lane
523// bakes into a part document (`features/import3d.rs` reads it back verbatim).
524pub use feature_pipeline::{native_import_payload, native_import_payload_with_appearance};
525// The scene-metadata isolation bracket a payload producer holds across the
526// encode, so ambient records of the LIVE document never leak into a new part.
527pub use feature_pipeline::IsolatedSceneMetadata;
528// The imported-colour read of the name-keyed scene-metadata store. Thread-local
529// like the rest of it, so an off-thread runner reads it and ships the result.
530pub use feature_pipeline::{scene_metadata_colors_json, scene_metadata_weld_colors_json};
531// Family tables (rows, the expression rewrite, the persisted fingerprints): one
532// copy for the CAD app and the PLM server.
533pub use feature_pipeline::family;
534// The assemblies parts library (unique part payloads for ACOMP instances):
535// insert / update-refresh mutations and the save-side serialization surface.
536pub use feature_pipeline::{
537    add_part_to_library, add_part_to_library_impl, install_parts_library, missing_library_parts,
538    parts_library_json, parts_library_map, parts_library_revision, refresh_library_entry,
539    refresh_library_entry_impl, same_build, follow_saved_rows, follow_saved_rows_known, kernel_source_stamp, stable_json_hash, PartsLibraryEntry, PartsLibraryMap,
540    part_pin_geometry, PartPinGeometry,
541};
542// Assembly constraint state + exported ABI (state/statuses/DOF/overlay reads,
543// constraint CRUD with auto-solve, the document pose/isFixed write-back fold).
544pub use feature_pipeline::assembly::{
545    assembly_add_constraint_json, assembly_apply_document_json,
546    assembly_apply_inferred_constraints_json, assembly_component_entities_json, assembly_dof_json,
547    assembly_infer_constraints_json, assembly_inferable_types_json,
548    assembly_move_constraint_json, assembly_overlay_json, assembly_pose_updates_json,
549    assembly_drag_solve_json, assembly_frame_solve_json, assembly_remove_constraint_json, assembly_resolve_refs_json,
550    assembly_run_solve_json,
551    assembly_set_constraint_enabled_json, assembly_set_constraint_open_json,
552    assembly_state_json, assembly_statuses_json, assembly_update_constraint_json,
553    constraint_hidden_params, constraint_schema_catalogue,
554    // The native doors: the same mutations with their errors as text. A native
555    // caller must use these — a `JsValue` error aborts a native build.
556    assembly_add_constraint_impl, assembly_apply_document_impl, assembly_move_constraint_impl,
557    assembly_drag_solve_impl, assembly_frame_solve_impl, assembly_flip_plan_json, assembly_rebase_mechanical_impl, assembly_remove_constraint_impl, assembly_run_solve_impl,
558    assembly_set_constraint_enabled_impl, assembly_set_constraint_open_impl,
559    assembly_update_constraint_impl,
560    assembly_session_export, assembly_session_import, assembly_session_serial, RetiredSession, SessionTransfer,
561};
562pub use feature_pipeline::{AssemblyState, ConstraintEntry};
563// The ONE matrix → `{translate, rotateEulerDeg}` (intrinsic XYZ, degrees) pose
564// encoder, shared by the solver write-back and any out-of-crate ACOMP author.
565pub use feature_pipeline::assembly::{pose_params_to_transform, transform_to_pose_params};
566// A part's mount frame (the `mount` block): read, written, and whether it is identity.
567pub use feature_pipeline::part_mount::{
568    is_identity as mount_is_identity, mount_aligned_to_footprint, mount_block_of, mount_from_block, mount_origin_to,
569    mount_seated_on, part_mount, reference_plane as mount_reference_plane, AlignPad, AlignReport, AlignSeat, MOUNT_BLOCK,
570};
571// The feature-schema catalogue (feature definitions: name + `inputParamsSchema`),
572// so a native UI can drive schema-driven feature dialogs without the JSON export.
573pub use feature_pipeline::feature_schema_catalogue;
574// The dialog field-visibility hook that pairs with the catalogue: given a feature
575// type + current param values, which params the schema dialog should hide.
576pub use feature_pipeline::feature_hidden_params;
577// Selection-context applicability: the context bar's per-feature/-constraint
578// show/no-show predicates, plus the constraint type table they pair with.
579pub use feature_pipeline::assembly::{constraint_type, ConstraintTypeDef, CONSTRAINT_TYPES, FIXED_IS_NOT_A_CONSTRAINT};
580pub use feature_pipeline::{feature_context_applicable, SelectionProbe};
581// The pipeline expression evaluator (the history's `expressions` + `configurator`
582// variable sheet), so a native UI (brep-render's engine-native sketcher) can
583// evaluate a LIVE dimension `valueExpr` against the same variables a committed
584// solve would (`features/sketch.rs` `pre_evaluate_expressions`). `Env::build`/
585// `eval` are pure arithmetic (no `std::time`), so this stays wasm-clean.
586pub use feature_pipeline::Env;
587// Expressions sources are kept one statement per line: the editor, the open
588// path and the automation setter normalise through this.
589pub use feature_pipeline::format_expressions;
590
591/// One-shot: build an [`Env`] from a history's `expressions` source + its
592/// `configurator` JSON, then evaluate `source` to a scalar. The small surface the
593/// engine-native sketcher's live dimension-value edit uses (deliverable S5.0) —
594/// equivalent to `Env::build(expressions, configurator_json)?.eval(source)`.
595pub fn eval_expression(
596    expressions: &str,
597    configurator_json: &serde_json::Value,
598    source: &str,
599) -> Result<f64, String> {
600    Env::build(expressions, configurator_json).and_then(|env| env.eval(source))
601}
602
603// In the shared-memory-threaded wasm build, re-export wasm-bindgen-rayon's
604// thread-pool initializer as `initThreadPool(numThreads)`. The JS side must
605// await it once after wasm init (needs a cross-origin-isolated page —
606// COOP/COEP — for SharedArrayBuffer). With the pool live, the ordinary
607// `tessellate_watertight_buffers` parallelizes its per-face loop across threads
608// (see `tessellate_faces_stride` under the `parallel` feature).
609#[cfg(feature = "wasm-threads")]
610pub use wasm_bindgen_rayon::init_thread_pool;
611#[path = "io/step_matrix.rs"]
612mod step_matrix;
613#[path = "io/step.rs"]
614mod step;
615pub use step::{
616    assembly_export_tree, audit_step_manifold, audit_step_pcurves, export_step,
617    export_step_assembly, export_step_assembly_report, export_step_report,
618    export_step_report_named, Mat4, StepAssemblyExport, StepColors, StepExportOccurrence,
619    StepExportProduct, StepExportReport, StepPmi, PART_ATTRIBUTES, PART_NUMBER,
620};
621// Imported appearance (colour) — the carrier between an importer that READ a
622// colour and the pipeline that stamps it as name-keyed scene metadata. Not a
623// storage layer: see the module doc for the `{"color": "#RRGGBB"}` convention.
624#[path = "io/appearance.rs"]
625mod appearance;
626pub use appearance::{BodyAppearance, ImportedColor, COLOR_METADATA_KEY};
627#[path = "solid_face_calls.rs"]
628mod solid_face_calls;
629pub use solid_face_calls::{offset_faces, solid_interference, thicken_faces, transform_faces, Interference};
630mod solid_display;
631pub use solid_display::{solid_display, DisplayEdge, DisplayFace, SolidDisplay};
632#[path = "plane_section.rs"]
633mod plane_section;
634pub use plane_section::{solid_section, solid_section_area};
635#[path = "io/step_import/mod.rs"]
636mod step_import;
637pub use step_import::{
638    import_step, import_step_bodies, import_step_report, sew_step, import_step_trim_readings, import_step_with_appearance,
639    occurrence_ref_parts, read_step_assembly, read_step_pmi, rewrite_occurrence_refs,
640    ImportedStep, StepAssembly, StepBodyError, StepBodyTrimReadings, StepEdgeReading, StepFaceReading, StepImportReport,
641    StepOccurrence, StepProduct, StepSuppliedTrim, StepTrimReadings, OCCURRENCE_REF_PREFIX,
642    STATED_PRECISION_INCONSISTENCY_RATIO,
643};
644/// Test seams for the Part 21 text codec of the PMI writer / reader.
645#[doc(hidden)]
646pub fn io_step_text_for_tests(value: &str) -> String {
647    step::pmi::step_text(value)
648}
649#[doc(hidden)]
650pub fn io_step_decode_text_for_tests(value: &str) -> String {
651    step_import::decode_step_text_for_tests(value)
652}
653#[path = "io/iges/mod.rs"]
654mod iges;
655pub use iges::{
656    export_iges, export_iges_assembly, export_iges_bodies, import_iges, import_iges_bodies, import_iges_report,
657    read_iges_assembly, IgesBody, IgesImportReport,
658};
659#[path = "io/parasolid/mod.rs"]
660pub mod parasolid;
661#[path = "io/solidworks/mod.rs"]
662pub mod solidworks;
663#[path = "io/mesh_io.rs"]
664mod mesh_io;
665pub use mesh_io::{
666    parse_stl_triangles, read_obj, read_stl, write_ascii_stl, write_binary_stl, write_obj,
667    ObjReadResult, StlError, StlFormat, StlReadResult, StlTriangles,
668};
669// 3MF (3D Manufacturing Format) import, core specification only: the OPC/ZIP
670// container, the model XML, and the build's instances flattened into one
671// millimetre triangle soup for the SAME mesh-to-solid chain STL and OBJ use.
672// The container, the deflate decoder and the XML reader are hand-rolled and
673// bounded — see the module doc for the dependency review behind that.
674#[path = "io/three_mf/mod.rs"]
675mod three_mf;
676pub use three_mf::{
677    read_3mf, write_3mf, write_3mf_meshes, ThreeMfBeam, ThreeMfBeamLattice, ThreeMfAppearance, ThreeMfTexture, ThreeMfError, ThreeMfInstance, ThreeMfMesh, ThreeMfReadResult,
678    ThreeMfSolid, ThreeMfUnit, ThreeMfWriteReport,
679};
680// Binary glTF 2.0 of the DISPLAY mesh — tessellated exchange for viewers, with
681// the axis convention and the unit carried by the root node's transform and the
682// colours converted from sRGB to glTF's linear `baseColorFactor`.
683#[path = "io/glb.rs"]
684mod glb;
685pub use glb::{write_glb, GlbReport, GlbSolid, GlbUpAxis, GLB_MAGIC};
686// Native serialized exact-BREP snapshot: the assemblies parts-library fast
687// lane (instant component insert from a cached payload; fails detectably so
688// the ACOMP self-heal lane can re-execute the embedded part document).
689#[path = "io/snapshot.rs"]
690mod snapshot;
691pub use snapshot::{
692    restore_solids, snapshot_resident_solids, snapshot_solids, RestoredSnapshot, RestoredSolid,
693    SNAPSHOT_FORMAT_VERSION,
694};
695
696
697mod abi;
698pub use abi::*;
699
700
701/// The source hashes of the kernel's crates (each crate's `build.rs`); together they are the stamp the
702/// parts library compares snapshots against, so a change in any kernel crate invalidates them.
703pub(crate) static KERNEL_SOURCE_HASHES: &[Option<&str>] = &[option_env!("BREP_KERNEL_SOURCE_HASH"), brep_geometry::SOURCE_HASH, brep_topology::SOURCE_HASH, brep_surface_offset::SOURCE_HASH, brep_boolean::SOURCE_HASH, brep_construction::SOURCE_HASH, brep_blend::SOURCE_HASH, brep_offset::SOURCE_HASH, brep_direct_edit::SOURCE_HASH, brep_solvers::SOURCE_HASH];
704
705/// One stamp over the crates' hashes; `None` when any crate could not compute its own.
706pub(crate) fn combined_source_stamp(parts: &[Option<&str>]) -> Option<String> {
707    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
708    for part in parts {
709        for byte in part.as_ref()?.bytes().chain([0]) {
710            hash ^= u64::from(byte);
711            hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
712        }
713    }
714    Some(format!("{hash:016x}"))
715}
716
717/// Drop every reading memo (the history cache's clear, a document switch): the
718/// topology memos and the boolean, heal and face-merge memos keyed on them.
719pub(crate) fn clear_reading_memos() {
720    brep_geometry::projection::clear_curve_seed_cache();
721    crate::reading_memo::clear();
722    crate::heal::clear_claim_memo();
723    crate::face_merge::clear_decline_memo();
724    crate::boolean::clear_candidate_memo();
725    crate::imprint::clear_window_memo();
726    crate::imprint::clear_touch_memo();
727}