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, 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_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    sweep_solid_within, OutlinePiece, ScrewStep, SolidMotion, SweepClip, SweptTool, SOLID_SWEEP_REFUSAL,
151};
152pub use brep_construction::gears;
153pub 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};
154pub use brep_construction::mill_program::{flat_mill_region_prisms, MillMove, MILL_REGION_REFUSAL};
155pub 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};
156pub use brep_construction::closed_curves::{make_ellipse, make_ellipse_arc, make_ellipsoid_brep, make_periodic_bspline};
157pub use brep_construction::planar_region::{cut_planar_sweep_from_prism, region_cut_on, swept_region_holds, target_outline_holds};
158pub use brep_construction::surface_faces::{face_from_surface, face_from_surface_trimmed, sheet_from_sheets, solid_from_sheets, SURFACE_FACE_REFUSAL};
159pub use brep_construction::polygon_solids::{make_pyramid_on_polygon, solid_from_polygons};
160pub use brep_construction::loft_guide_chain::loft_profile_brep_guided_chain;
161pub 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};
162pub use brep_construction::extrude_up_to::{extrude_profile_up_to_face, solid_pieces, EXTRUDE_UP_TO_REFUSAL};
163pub use brep_construction::sweep_round_corners::{sweep_profile_round_corners, SWEEP_ROUND_CORNERS_REFUSAL};
164pub use brep_construction::sweep_ellipsoid::sweep_ellipsoid_along_line;
165pub use brep_construction::sweep_topology::{
166    extrude_profile_brep, extrude_profile_brep_draft, fit_helix_curve, helix_sample_points,
167    profile_anchor, rib_from_profile, sweep_bend_profile, sweep_closure, BendStation,
168    JointContinuity, PathJoint, SweepClosure,
169    RibExtrusion, RibNames, SweepPath, MAX_JOINT_TANGENT_BREAK, SWEEP_TIGHT_BEND_REFUSAL,
170    SWEEP_TWIST_CLOSURE_REFUSAL,
171    build_swept_envelope, recognize_swept_envelope, swept_envelope_volume, SweptEnvelope,
172    SWEEP_ENVELOPE_REFUSAL, sweep_envelope_bodies,
173    sweep_profile_along_chain, sweep_profile_along_chain_reported,
174    sweep_profile_along_chain_with_stations, sweep_profile_along_chain_with_stations_reported,
175    sweep_profile_along_path,
176    sweep_profile_along_path_anchored,
177    sweep_profile_helix,
178    sweep_profile_twisted, sweep_profile_twisted_anchored, sweep_profile_twisted_scaled,
179    ProfileAnchor, SectionPlacement,
180    StationBudget, SweepStationReport, SweptChain, SWEEP_DEFAULT_TOLERANCE, SWEEP_MAX_STATIONS,
181    SWEEP_REFINEMENT_ROUNDS,
182};
183pub use brep_construction::revolve_topology::{revolve_profile_brep, revolve_profile_brep_named};
184pub use brep_construction::loft_topology::{
185    loft_profile_brep, loft_profile_brep_closed, loft_profile_brep_guided,
186    loft_profile_brep_guided_frame, loft_profile_brep_tangent,
187};
188pub use brep_blend::blend::{
189    take_blend_approximations, take_blend_notes,
190    blend_timing_capture, take_blend_timings, BlendTiming,
191    blend_closed_edge, blend_edge_variable, blend_open_edge, blend_smooth_chain,
192    round_convex_corner,
193};
194pub use brep_blend::fillet::{
195    chamfer_edge, chamfer_edge_angle, chamfer_edge_asymmetric, chamfer_edges_angle,
196    chamfer_edges_asymmetric, fillet_edge, fillet_edge_conic, fillet_edges, fillet_edges_conic, fillet_edges_reported, fillet_edges_reported_at_offset,
197    fillet_edges_variable, fillet_edges_variable_law, fillet_edges_variable_vertex_radii,
198    BlendSelection,
199};
200pub use brep_blend::law::{LawSegment, RadiusLaw};
201pub use brep_offset::thicken_faces::{extrude_curves_to_sheet, thicken_sheet_faces, THICKEN_FACES_REFUSAL};
202pub use brep_offset::shell_rounded::{offset_shell_rounded, SHELL_ROUNDED_REFUSAL};
203pub use brep_offset::thicken::{thicken_face_sheet, thicken_trimmed_sheet};
204pub use brep_offset::offset_shell::{
205    offset_shell, offset_shell_by_boolean, offset_shell_closed, offset_shell_with_diagnostics, offset_solid, OffsetCorners,
206    OffsetFaceRole, OffsetShellFaceImageRecord, OffsetShellResultRecord,
207};
208pub use brep_direct_edit::direct_edit::{
209    delete_face_and_heal, delete_faces_and_heal, draft_faces, draft_faces_parted, draft_faces_unchecked, move_faces, move_faces_unchecked,
210    offset_freeform_face, offset_freeform_face_unchecked,
211    offset_revolution_face, offset_revolution_face_unchecked, offset_ruled_face, offset_ruled_face_unchecked, offset_sphere_face,
212    offset_sphere_face_unchecked, offset_torus_face, offset_torus_face_unchecked,
213    rebuild_displaced_blends, with_blend_rebuild_decline,
214    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,
215    route_reading, RouteReading,
216};
217pub use brep_direct_edit::direct_edit::{face_refusal_slugs, face_transform_reason, FaceTransformReason};
218pub use brep_direct_edit::direct_edit::{deform_shell, ShellDeformPick, ShellDeformReport, ShellDeformSpec};
219pub use brep_direct_edit::direct_edit::{deform_face, face_deform_default_anchor, FaceDeformPick, FaceDeformReport, FaceDeformSpec};
220pub use brep_direct_edit::direct_edit::{
221    refit_faces_as_one, refit_refusal_phrases, RefitCarrier, RefitReport, RefitSurfaceKind,
222};
223
224
225#[macro_use]
226extern crate brep_geometry;
227#[allow(unused_imports)]
228use brep_geometry::*;
229#[macro_use]
230extern crate brep_topology;
231#[allow(unused_imports)]
232use brep_topology::*;
233
234// The public root API of the kernel, from the crates below.
235pub use brep_topology::{display_chord_tolerance, solid_model_scale, solid_scale};
236pub use brep_geometry::switch;
237pub use brep_geometry::debug_flag;
238pub use brep_geometry::mode_switch;
239pub use brep_geometry::env_read;
240pub use brep_geometry::panic_hook;
241pub use brep_geometry::text;
242pub use brep_geometry::tolerance::{
243    curve_model_scale, model_scale, report_scale_migration, SolidScale,
244    offset_construction_band, vertex_tolerance_from_edges, KernelTolerances,
245    MeasuredTolerance, OFFSET_CONSTRUCTION_FLOOR, OFFSET_CONSTRUCTION_REL,
246    VERTEX_MATCH_FLOOR, VOLUME_DRIFT_ABS, VOLUME_DRIFT_REL,
247};
248pub use brep_geometry::diagnostics::{
249    Approximation, ApproximationBudget, Backing, BudgetMechanism, BudgetReason, MeasuredComponent, DiagnosticEvent, DiagnosticSeverity, EdgeOrigin, KernelDiagnostics,
250    KernelOutcome, KernelRefusal, OffCarrierEdge,
251    KernelStage, OrRefuse, RefusalClass, SoundnessDefect, UndecidedCause,
252};
253pub use brep_geometry::polygon;
254pub use brep_geometry::curve::{
255    make_arc, make_circle, make_hyperbola, make_line, make_parabola, uniform_clamped_knots,
256    KnotVector, NurbsCurve, Vec4, KNOT_DEDUP_EPS, KNOT_IDENTITY_TOL,
257};
258pub use brep_geometry::fit::{
259    fit_polyline, fit_polyline_at, fit_polyline_of_degree, interpolate_curve, interpolate_curve_closed,
260    interpolate_curve_local, interpolate_curve_thinned, interpolate_curve_with_end_tangents,
261    simplify_polyline, simplify_polyline_indices, solve_banded, solve_dense, PolylineFit,
262    PolylineFitExit, PolylineFitLedger, PolylineFitReport, PolylineFitScope, MAX_FIT_STATIONS,
263};
264pub use brep_geometry::image_curve::{affine_image_curve, image_curve, image_curve_pair, ImageCurve, ImageCurveTier};
265pub use brep_geometry::surface::{
266    carrier_preview_patch, make_cone_surface, make_cylinder_surface, make_extrusion, make_plane,
267    make_revolution, make_sphere_surface, make_sphere_surface_framed, make_torus_surface,
268    ExtendRefusal, KnotDirection, KnotRefinementRefusal, NurbsSurface, SurfaceSide, WeightSite,
269    MAXIMUM_FOLD_ANGLE, MAXIMUM_GROWTH_RATIO,
270};
271pub use brep_geometry::deform::{
272    deform_surface, deform_surface_where, deform_surfaces_tied, DeformPick, PoleSupport, SurfaceTie, TieContinuity,
273    TiedResult, TiedSurface, DeformRefusal, DeformResult, DeformSide, DeformSpec,
274    EdgeHold,
275};
276pub use brep_geometry::coons::{
277    coons_bilinear, coons_bilinear_reported, coons_with_ribbons, CompatWork, CoonsRefusal,
278    CoonsReport, RibbonReport,
279};
280pub use brep_geometry::gordon::{gordon_surface, gordon_surface_reported, GordonRefusal, GordonReport};
281pub use brep_geometry::n_sided::{n_sided_fill, reentrant_corners as n_sided_reentrant_corners, NSidedRefusal, NSidedReport};
282pub use brep_geometry::regularity::{certify_regular, Irregularity, RegularityReport};
283pub use brep_geometry::analytic_surface::{
284    circle_angle_to_parameter, intersect_analytic_pair, plane_ruled_section_arc,
285    revolution_structure, AnalyticSurface, RevolutionFrame, RevolutionStructure,
286};
287pub use brep_geometry::sphere_chart::{
288    canonicalize_points, chart_grid_divisions, chart_grid_parameters, corner_index,
289    cube_edge_corner, cube_edge_divisions, cube_edge_index, cube_edge_parameters,
290    cube_edge_parts, Chart, ChartSegment, ChartSide, SphereAtlas,
291    SphericalRegion, CHART_COUNT, CUBE_CORNER_COUNT, CUBE_EDGE_COUNT,
292};
293#[doc(hidden)]
294pub use brep_geometry::projection_profile::report as projection_profile_report;
295pub use brep_geometry::projection::{
296    project_point_to_curve, project_point_to_surface, project_point_to_surface_seeded,
297    CurveProjection, SurfaceProjection,
298};
299#[doc(hidden)]
300pub use brep_geometry::projection::{
301    project_point_to_surface_basin_census, project_point_to_surface_general_lanes, BasinCensus,
302    GlobalStats,
303};
304pub use brep_geometry::curve_surface_intersection::{intersect_curve_surface, CurveSurfaceIntersection};
305pub use brep_geometry::curve_curve_intersection::{intersect_curves, CurveCurveIntersection};
306pub use brep_geometry::surface_surface_intersection::{
307    intersect_surfaces, intersect_surfaces_supplemental, SurfaceIntersectionCurve,
308    SurfaceIntersectionOptions,
309};
310pub use brep_geometry::crossing_node::{crossing_node_split_enabled, split_at_crossing_nodes};
311pub use brep_geometry::tangent_curve::{
312    classify_tangent_contact_at, find_tangent_contact, trace_tangent_curve, TangentContact,
313    EXTENDED_RANK_FLOOR,
314};
315pub use brep_geometry::spatial::{Aabb, Bvh};
316pub use brep_geometry::arrangement::{
317    arrange_segments, point_in_polygon, segment_intersection, ArrangementPiece, ArrangementRegion,
318    CycleUse, Segment2, Vec2,
319};
320pub use brep_geometry::pcurve::{
321    build_pcurve_on_surface, build_pcurve_on_surface_marched, build_pcurve_on_surface_range,
322    build_pcurve_on_surface_range_dense, build_pcurve_on_surface_stations, fit_pcurve_on_surface,
323    fit_pcurve_on_surface_marched, fit_pcurve_on_surface_range, fit_pcurve_on_surface_range_dense,
324    fit_pcurve_on_surface_stations, PcurveFit, PcurveFitExit, PcurveFitLedger, PcurveFitReport,
325    PcurveFitScope, PCURVE_OFF_BAR, PCURVE_REFINEMENT_TOLERANCE,
326};
327pub use brep_geometry::offset_point::{OffsetEvaluator, OffsetNormal, OffsetSample};
328pub use brep_geometry::Vec3;
329pub use brep_geometry::Mesh;
330pub use brep_geometry::make_box;
331pub use brep_geometry::make_cylinder;
332pub use brep_geometry::union_find;
333pub use brep_geometry::union_find::UnionFind;
334pub use brep_geometry::poly;
335pub use brep_geometry::analytic_surface::{circumcenter, circumcenter_2d, recognize_circle, RecognizedCircle};
336pub use brep_geometry::triangle::closest_point_on_triangle;
337pub use brep_geometry::tolerance::RIGID_TOL;
338pub use brep_topology::entity_tolerance::{EntityTolerances, EDGE_CAP_FRACTION, VERTEX_CAP_FRACTION};
339pub use brep_topology::control_cage::{
340    CagePoint, CagePrimitive, ControlCage, CAGE_DEGREE, MAX_RINGS, MAX_SEGMENTS, MIN_RINGS,
341    MIN_SEGMENTS,
342};
343pub use brep_topology::solid_codec::{decode_solid, encode_solid, SolidNames, SOLID_CODEC_VERSION, SOLID_CODEC_VERSION_KIND};
344pub use brep_topology::topology::{
345    make_box_brep, make_cylinder_brep, make_pyramid_brep, topology_kind, BodyKind, BrepSolid, CellRecord, CoedgeRecord,
346    FaceRecord, IssueKind, KindReport, LoopRecord, TopologyKind, ValidationReport,
347};
348pub use brep_topology::soundness::{
349    face_self_intersections, loop_self_crossings, shell_vector_areas, solid_connectivity,
350    solid_euler, solid_self_intersections, ConnectivityReport, CrossingConfirmation, EulerReport,
351    CertificateScope, CertifiedFacePair, FaceCrossing, FaceFold, FaceVectorArea,
352    LoopCrossing, LoopCrossingReport, SelfIntersectionOptions, SelfIntersectionReport,
353    ClosureReading, ShellConnectivity, ShellVectorArea, VectorAreaReport, CrossingUndecidedCause, UndecidedCrossing,
354    MAX_LISTED_UNDECIDED,
355};
356pub use brep_topology::topology_arena::{
357    ArenaCoedge, ArenaEdge, ArenaFace, ArenaLoop, ArenaShell, ArenaVertex, CoedgeId, EdgeId,
358    FaceId, LoopId, ShellId, TopologyArena, VertexId,
359};
360pub use brep_topology::analytic_topology::{
361    make_cone_brep, make_sphere_brep, make_sphere_brep_framed, make_torus_brep,
362};
363pub use brep_topology::curve_chain::{join_curve_chain, split_surface};
364pub use brep_topology::transform_topology::{mirror_brep, transform_brep, AffineTransform};
365pub use brep_topology::mass_properties::{
366    curve_arc_length, edge_arc_length, face_area, face_boundary_length, face_volume_contribution,
367    face_set_identity, mass_caller, parameter_space_area, solid_edge_length_total,
368    solid_mass_properties,
369    solid_mass_properties_full, signed_volume_against, solid_signed_volume, solid_signed_volume_for_sign, trim_polygons,
370    DensityMassProperties,
371    FaceSetIdentity, FullMassProperties, MassCaller, MassProperties, MassPropertiesCache,
372};
373pub use brep_topology::carrier_dimensions::{curve_carrier_dimensions, surface_carrier_dimensions, CarrierDimensions};
374pub use brep_topology::tessellation::{tessellate_brep, tessellate_face, TessellationOptions};
375pub use brep_topology::watertight_tessellation::{
376    sample_edge_polyline_checked, EdgeChordError, EdgeChordFailure, TessellationError,
377    tessellate_brep_watertight_checked,
378    sample_edge_polylines, sample_edges_encoded, tessellate_brep_watertight,
379    tessellate_brep_watertight_face_stride, tessellate_brep_watertight_face_stride_with_samples,
380};
381pub use brep_topology::classification::{
382    classify_point, containment_lane, horizon_cross_frame, parameter_point_in_face,
383    trim_sample_count, trim_station, ContainmentLane, PointClass, PointClassification,
384    PolygonClass, SolidClassifier, COVERING_RIM_STRIP_SWITCH, HORIZON_CONTAINMENT_SWITCH,
385    HORIZON_CROSS_FRAME_SWITCH, HORIZON_SINGLE_LOOP_SWITCH, NO_SPHERE_CHART_TRIM_SWITCH,
386    SEAM_BAND_MERGED_SWITCH,
387};
388#[doc(hidden)]
389pub use brep_topology::classification::parameter_point_in_face_scan;
390pub use brep_topology::pair_classification::{
391    classify_surface_pair, classify_surface_pair_cached, SurfaceClassifyData,
392    SurfacePairClassification, SurfacePairRelation,
393};
394pub use brep_topology::offset_measure::{
395    measure_edge_against_pcurve_image, measure_surface_fit_against_pointwise_offset,
396    span_midpoint_error, vertex_endpoint_gap,
397};
398pub use brep_topology::mesh_weld::{canonical_bits, VertexWeld};
399
400
401use serde::{Deserialize, Serialize};
402use wasm_bindgen::prelude::*;
403
404// The wasm global allocator, when the `wasm-talc` feature asks for it.
405#[cfg(all(feature = "wasm-talc", target_family = "wasm", not(target_feature = "atomics")))]
406#[global_allocator]
407static TALC: talc::wasm::WasmDynamicTalc = talc::wasm::new_wasm_dynamic_allocator();
408
409// The native global allocator, when the `native-rusty-alloc` feature asks for it.
410#[cfg(all(feature = "native-rusty-alloc", not(target_family = "wasm")))]
411#[cfg(not(feature = "profile-wall"))]
412#[global_allocator]
413static RUSTY_ALLOC: rusty_alloc_api::RustyAlloc = rusty_alloc_api::RustyAlloc;
414
415#[cfg(all(feature = "native-rusty-alloc", not(target_family = "wasm"), feature = "profile-wall"))]
416#[global_allocator]
417static RUSTY_ALLOC: wall_profile::Allocator<rusty_alloc_api::RustyAlloc> = wall_profile::Allocator(rusty_alloc_api::RustyAlloc);
418#[path = "construction/draft_roof.rs"]
419mod draft_roof;
420pub use draft_roof::{extrude_profile_brep_draft_roof, DRAFT_ROOF_REFUSAL};
421// The Rust feature-history execution engine (migration-plan Stage 4/5 foundation).
422// Deserializes the serialized `{ type, inputParams, ... }` descriptor shape, runs
423// each feature against a live scene-map of resident handles, and returns per-feature
424// results (handles + face/edge names). See feature_pipeline/mod.rs for the contract.
425#[path = "feature_pipeline/mod.rs"]
426pub mod feature_pipeline;
427pub use feature_pipeline::execute_history_json;
428pub use feature_pipeline::{first_reference_name, imported_solid_names, is_gear_type, is_weld_type, reference_names};
429// Transform Face's default pivot (the selection's boundary centre) over the
430// results of a replayed prefix, so the gizmo and the stored `pivot` agree with
431// the feature by construction.
432pub use feature_pipeline::{face_transform_pivot, face_transform_reference_point};
433// Typed, in-process pipeline surface for native consumers (brep-render): run a
434// whole history and read the results without a JSON round trip.
435pub use feature_pipeline::{
436    clear_history_cache, execute_history, execute_history_observed, AddedSolid, Axis,
437    ComponentRecord, FeatureDescriptor, FeatureRefusal, FeatureResult, Frame, Fulfilment,
438    HistoryProgress, HistoryRequest, Rejected, RejectedKind,
439    HistoryResult, PortKind, PortRecord, ProfileLoop, ScenePoint, SketchProfile,
440};
441// Wire harness: the document's `wireHarness` block (connections), the tail's
442// routing report (per-connection status / length / route, per-segment bundle),
443// and the sided-port vocabulary the spline attachments share.
444pub use feature_pipeline::wire_harness::{
445    bundle_diameter, Attachment as SplineAttachment, BundleStatus, PortSide, RouteResult,
446    RouteStatus,
447    WireHarnessBundle, WireHarnessConnection,
448    WireHarnessEndpoint, WireHarnessReport, WireHarnessState, BUNDLE_SOLID_PREFIX,
449    WIRE_HARNESS_FEATURE_ID, WIRE_HARNESS_FEATURE_TYPE,
450};
451// A part's pins ARE its declared connection points, bound BY NAME within one
452// symbol unit and its port group: the report of what does not pair, following
453// an edit on one side to the other, the unit-to-group mapping, and a placed
454// part's pin resolved to a point ADDRESS (refused by name when it names none).
455pub use feature_pipeline::part_pins::{
456    declarations as declared_ports, declared_endpoints as declared_point_endpoints,
457    declared_points, endpoint_occurrence, follow_pin_edit, follow_point_edit, pin_labels,
458    pin_point_report, pins,
459    point_renames, port_group_for_unit, resolve_component_pin, resolve_part_pin,
460    unit_count as symbol_unit_count, unit_groups, DeclaredPin, DeclaredPoint, PinPoint,
461    PinPointChange, PinPointProblem, PinPointReport, PointRenames, DEFAULT_PORT_NAME,
462    DEFAULT_PORT_PURPOSE, PADS_BLOCK, SYMBOL_BLOCK,
463};
464// The declared-ports block itself: the schema a part document carries, the
465// address scheme, the unit map and the encapsulation-boundary rule — and the
466// SEAT, the frame a point's placement is an offset in, with the two mappings
467// an editor needs to put a gizmo on one and write the drag back.
468pub use feature_pipeline::ports::{
469    address as port_address, document_is_boundary, seat_of as port_seat_of, seat_point,
470    seat_vector, seated_direction, split_address, unit_map, unseat_point, unseat_vector,
471    world_seat, PortDeclaration, PortPoint, PortPointRow, PortSeat, PortsReport, UnitProblem,
472    BOUNDARY_KEY, PORTS_BLOCK, PORTS_FEATURE_ID, PORTS_FEATURE_TYPE,
473};
474// PMI: the document's `pmi` block (views + annotations), the type table with
475// its schemas / selection predicates, the tail's resolved report, and the
476// presentation layout shared by the viewport and the AP242 export.
477pub use feature_pipeline::pmi::{
478    balloon_head as pmi_balloon_head, clamp_text_size, format_dimension, format_number,
479    nearest_point_on_edge, nearest_point_on_solid, pmi_schema_catalogue, pmi_type,
480    nearest_displayed_point, nearest_displayed_point_on_edge, pose_apply as pmi_pose_apply, pose_unapply as pmi_pose_unapply,
481    resolve_state as pmi_resolve_state, entry_names_solid, baseline_hide_id, BalloonAnchor, BalloonAnchorMode, CenterCircle, FcfFrame, HalfSpace as PmiHalfSpace, HeadScope as PmiHeadScope, PmiAnnotation,
482    PmiAnnotationReport, PmiCamera, PmiDisplay, PmiGeometry, PmiPlane, PmiPose, PmiProjection, PmiReport,
483    PmiState, PmiStatus, PmiTypeDef, PmiView, PmiViewReport, SolidPoses as PmiSolidPoses, ToleranceBlock, ToleranceMode, PMI_TYPES,
484};
485pub use feature_pipeline::pmi::layout::{present as pmi_present, LayoutStyle as PmiLayoutStyle, Presentation as PmiPresentation};
486pub use feature_pipeline::pmi::annotations::fcf::{characteristic as pmi_characteristic, Characteristic as PmiCharacteristic, CHARACTERISTICS as PMI_CHARACTERISTICS};
487// The sketch loop-id write-back: stamps each closed loop's stable id onto its
488// geometries so per-loop face names survive deleting the edge an id came from.
489// The editor calls it when a sketch is committed.
490pub use feature_pipeline::assign_sketch_loop_ids;
491// The 3D sketch feature's reference resolver and record shape, shared with the
492// engine-native 3D sketch editor so the editor materializes exactly what the
493// feature re-resolves on every run.
494pub use feature_pipeline::features::sketch3d::{
495    reference_record as sketch3d_reference_record, resolve_reference as resolve_sketch3d_reference,
496    ResolvedReference as Sketch3dResolvedReference, REFERENCE_TIP_LENGTH as SKETCH3D_REFERENCE_TIP_LENGTH,
497    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,
498    SKETCH3D_DOC_KEY, SKETCH3D_EDIT_BUTTON, SKETCH3D_FEATURE_TYPE, SKETCH3D_REFERENCES_PARAM,
499    SKETCH3D_REFS_KEY,
500};
501// Sheet-metal flat-pattern (unfold) → 2D vector export, keyed by resident handle.
502pub use feature_pipeline::{flat_pattern_dxf, flat_pattern_svg, is_sheet_metal_handle};
503// The part Pattern's per-instance suppression list.
504pub use feature_pipeline::{pattern_component_instance, pattern_parse_suppressed};
505// Native IMPORT3D payload: finished solids → the `io/snapshot` container with
506// IMPORT3D's naming stamped on, i.e. the `inputParams.nativeBrep` an import lane
507// bakes into a part document (`features/import3d.rs` reads it back verbatim).
508pub use feature_pipeline::{native_import_payload, native_import_payload_with_appearance};
509// The scene-metadata isolation bracket a payload producer holds across the
510// encode, so ambient records of the LIVE document never leak into a new part.
511pub use feature_pipeline::IsolatedSceneMetadata;
512// The imported-colour read of the name-keyed scene-metadata store. Thread-local
513// like the rest of it, so an off-thread runner reads it and ships the result.
514pub use feature_pipeline::{scene_metadata_colors_json, scene_metadata_weld_colors_json};
515// Family tables (rows, the expression rewrite, the persisted fingerprints): one
516// copy for the CAD app and the PLM server.
517pub use feature_pipeline::family;
518// The assemblies parts library (unique part payloads for ACOMP instances):
519// insert / update-refresh mutations and the save-side serialization surface.
520pub use feature_pipeline::{
521    add_part_to_library, add_part_to_library_impl, install_parts_library, missing_library_parts,
522    parts_library_json, parts_library_map, parts_library_revision, refresh_library_entry,
523    refresh_library_entry_impl, same_build, follow_saved_rows, follow_saved_rows_known, kernel_source_stamp, stable_json_hash, PartsLibraryEntry, PartsLibraryMap,
524};
525// Assembly constraint state + exported ABI (state/statuses/DOF/overlay reads,
526// constraint CRUD with auto-solve, the document pose/isFixed write-back fold).
527pub use feature_pipeline::assembly::{
528    assembly_add_constraint_json, assembly_apply_document_json,
529    assembly_apply_inferred_constraints_json, assembly_component_entities_json, assembly_dof_json,
530    assembly_infer_constraints_json, assembly_inferable_types_json,
531    assembly_move_constraint_json, assembly_overlay_json, assembly_pose_updates_json,
532    assembly_drag_solve_json, assembly_frame_solve_json, assembly_remove_constraint_json, assembly_resolve_refs_json,
533    assembly_run_solve_json,
534    assembly_set_constraint_enabled_json, assembly_set_constraint_open_json,
535    assembly_state_json, assembly_statuses_json, assembly_update_constraint_json,
536    constraint_hidden_params, constraint_schema_catalogue,
537    // The native doors: the same mutations with their errors as text. A native
538    // caller must use these — a `JsValue` error aborts a native build.
539    assembly_add_constraint_impl, assembly_apply_document_impl, assembly_move_constraint_impl,
540    assembly_drag_solve_impl, assembly_frame_solve_impl, assembly_flip_plan_json, assembly_rebase_mechanical_impl, assembly_remove_constraint_impl, assembly_run_solve_impl,
541    assembly_set_constraint_enabled_impl, assembly_set_constraint_open_impl,
542    assembly_update_constraint_impl,
543    assembly_session_export, assembly_session_import, assembly_session_serial, RetiredSession, SessionTransfer,
544};
545pub use feature_pipeline::{AssemblyState, ConstraintEntry};
546// The ONE matrix → `{translate, rotateEulerDeg}` (intrinsic XYZ, degrees) pose
547// encoder, shared by the solver write-back and any out-of-crate ACOMP author.
548pub use feature_pipeline::assembly::transform_to_pose_params;
549// The feature-schema catalogue (feature definitions: name + `inputParamsSchema`),
550// so a native UI can drive schema-driven feature dialogs without the JSON export.
551pub use feature_pipeline::feature_schema_catalogue;
552// The dialog field-visibility hook that pairs with the catalogue: given a feature
553// type + current param values, which params the schema dialog should hide.
554pub use feature_pipeline::feature_hidden_params;
555// Selection-context applicability: the context bar's per-feature/-constraint
556// show/no-show predicates, plus the constraint type table they pair with.
557pub use feature_pipeline::assembly::{constraint_type, ConstraintTypeDef, CONSTRAINT_TYPES, FIXED_IS_NOT_A_CONSTRAINT};
558pub use feature_pipeline::{feature_context_applicable, SelectionProbe};
559// The pipeline expression evaluator (the history's `expressions` + `configurator`
560// variable sheet), so a native UI (brep-render's engine-native sketcher) can
561// evaluate a LIVE dimension `valueExpr` against the same variables a committed
562// solve would (`features/sketch.rs` `pre_evaluate_expressions`). `Env::build`/
563// `eval` are pure arithmetic (no `std::time`), so this stays wasm-clean.
564pub use feature_pipeline::Env;
565// Expressions sources are kept one statement per line: the editor, the open
566// path and the automation setter normalise through this.
567pub use feature_pipeline::format_expressions;
568
569/// One-shot: build an [`Env`] from a history's `expressions` source + its
570/// `configurator` JSON, then evaluate `source` to a scalar. The small surface the
571/// engine-native sketcher's live dimension-value edit uses (deliverable S5.0) —
572/// equivalent to `Env::build(expressions, configurator_json)?.eval(source)`.
573pub fn eval_expression(
574    expressions: &str,
575    configurator_json: &serde_json::Value,
576    source: &str,
577) -> Result<f64, String> {
578    Env::build(expressions, configurator_json).and_then(|env| env.eval(source))
579}
580
581// In the shared-memory-threaded wasm build, re-export wasm-bindgen-rayon's
582// thread-pool initializer as `initThreadPool(numThreads)`. The JS side must
583// await it once after wasm init (needs a cross-origin-isolated page —
584// COOP/COEP — for SharedArrayBuffer). With the pool live, the ordinary
585// `tessellate_watertight_buffers` parallelizes its per-face loop across threads
586// (see `tessellate_faces_stride` under the `parallel` feature).
587#[cfg(feature = "wasm-threads")]
588pub use wasm_bindgen_rayon::init_thread_pool;
589#[path = "io/step_matrix.rs"]
590mod step_matrix;
591#[path = "io/step.rs"]
592mod step;
593pub use step::{
594    assembly_export_tree, audit_step_manifold, audit_step_pcurves, export_step,
595    export_step_assembly, export_step_assembly_report, export_step_report,
596    export_step_report_named, Mat4, StepAssemblyExport, StepColors, StepExportOccurrence,
597    StepExportProduct, StepExportReport, StepPmi, PART_ATTRIBUTES, PART_NUMBER,
598};
599// Imported appearance (colour) — the carrier between an importer that READ a
600// colour and the pipeline that stamps it as name-keyed scene metadata. Not a
601// storage layer: see the module doc for the `{"color": "#RRGGBB"}` convention.
602#[path = "io/appearance.rs"]
603mod appearance;
604pub use appearance::{BodyAppearance, ImportedColor, COLOR_METADATA_KEY};
605#[path = "io/step_import/mod.rs"]
606mod step_import;
607pub use step_import::{
608    import_step, import_step_bodies, import_step_report, import_step_trim_readings, import_step_with_appearance,
609    occurrence_ref_parts, read_step_assembly, read_step_pmi, rewrite_occurrence_refs,
610    ImportedStep, StepAssembly, StepBodyError, StepBodyTrimReadings, StepEdgeReading, StepFaceReading, StepImportReport,
611    StepOccurrence, StepProduct, StepSuppliedTrim, StepTrimReadings, OCCURRENCE_REF_PREFIX,
612    STATED_PRECISION_INCONSISTENCY_RATIO,
613};
614/// Test seams for the Part 21 text codec of the PMI writer / reader.
615#[doc(hidden)]
616pub fn io_step_text_for_tests(value: &str) -> String {
617    step::pmi::step_text(value)
618}
619#[doc(hidden)]
620pub fn io_step_decode_text_for_tests(value: &str) -> String {
621    step_import::decode_step_text_for_tests(value)
622}
623#[path = "io/iges/mod.rs"]
624mod iges;
625pub use iges::{
626    export_iges, export_iges_assembly, export_iges_bodies, import_iges, import_iges_bodies, import_iges_report,
627    read_iges_assembly, IgesBody, IgesImportReport,
628};
629#[path = "io/parasolid/mod.rs"]
630pub mod parasolid;
631#[path = "io/solidworks/mod.rs"]
632pub mod solidworks;
633#[path = "io/mesh_io.rs"]
634mod mesh_io;
635pub use mesh_io::{
636    parse_stl_triangles, read_obj, read_stl, write_ascii_stl, write_binary_stl, write_obj,
637    ObjReadResult, StlError, StlFormat, StlReadResult, StlTriangles,
638};
639// 3MF (3D Manufacturing Format) import, core specification only: the OPC/ZIP
640// container, the model XML, and the build's instances flattened into one
641// millimetre triangle soup for the SAME mesh-to-solid chain STL and OBJ use.
642// The container, the deflate decoder and the XML reader are hand-rolled and
643// bounded — see the module doc for the dependency review behind that.
644#[path = "io/three_mf/mod.rs"]
645mod three_mf;
646pub use three_mf::{
647    read_3mf, write_3mf, write_3mf_meshes, ThreeMfBeam, ThreeMfBeamLattice, ThreeMfAppearance, ThreeMfTexture, ThreeMfError, ThreeMfInstance, ThreeMfMesh, ThreeMfReadResult,
648    ThreeMfSolid, ThreeMfUnit, ThreeMfWriteReport,
649};
650// Binary glTF 2.0 of the DISPLAY mesh — tessellated exchange for viewers, with
651// the axis convention and the unit carried by the root node's transform and the
652// colours converted from sRGB to glTF's linear `baseColorFactor`.
653#[path = "io/glb.rs"]
654mod glb;
655pub use glb::{write_glb, GlbReport, GlbSolid, GlbUpAxis, GLB_MAGIC};
656// Native serialized exact-BREP snapshot: the assemblies parts-library fast
657// lane (instant component insert from a cached payload; fails detectably so
658// the ACOMP self-heal lane can re-execute the embedded part document).
659#[path = "io/snapshot.rs"]
660mod snapshot;
661pub use snapshot::{
662    restore_solids, snapshot_resident_solids, snapshot_solids, RestoredSnapshot, RestoredSolid,
663    SNAPSHOT_FORMAT_VERSION,
664};
665
666
667mod abi;
668pub use abi::*;
669
670
671/// The source hashes of the kernel's crates (each crate's `build.rs`); together they are the stamp the
672/// parts library compares snapshots against, so a change in any kernel crate invalidates them.
673pub(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];
674
675/// One stamp over the crates' hashes; `None` when any crate could not compute its own.
676pub(crate) fn combined_source_stamp(parts: &[Option<&str>]) -> Option<String> {
677    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
678    for part in parts {
679        for byte in part.as_ref()?.bytes().chain([0]) {
680            hash ^= u64::from(byte);
681            hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
682        }
683    }
684    Some(format!("{hash:016x}"))
685}
686
687/// Drop every reading memo (the history cache's clear, a document switch): the
688/// topology memos and the boolean, heal and face-merge memos keyed on them.
689pub(crate) fn clear_reading_memos() {
690    brep_geometry::projection::clear_curve_seed_cache();
691    crate::reading_memo::clear();
692    crate::heal::clear_claim_memo();
693    crate::face_merge::clear_decline_memo();
694    crate::boolean::clear_candidate_memo();
695    crate::imprint::clear_window_memo();
696    crate::imprint::clear_touch_memo();
697}
698
699