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