Skip to main content

brep_kernel/
lib.rs

1use serde::{Deserialize, Serialize};
2use wasm_bindgen::prelude::*;
3
4#[path = "geometry/tolerance.rs"]
5mod tolerance;
6pub use tolerance::{
7    curve_model_scale, model_scale, report_scale_migration, solid_model_scale, solid_scale,
8    offset_construction_band, vertex_tolerance_from_edges, KernelTolerances,
9    MeasuredTolerance, OFFSET_CONSTRUCTION_FLOOR, OFFSET_CONSTRUCTION_REL,
10    VERTEX_MATCH_FLOOR,
11};
12#[path = "props/diagnostics.rs"]
13mod diagnostics;
14pub use diagnostics::{
15    DiagnosticEvent, DiagnosticSeverity, KernelDiagnostics, KernelOutcome, KernelStage,
16};
17#[path = "geometry/curve.rs"]
18mod curve;
19pub use curve::{
20    make_arc, make_circle, make_hyperbola, make_line, make_parabola, uniform_clamped_knots,
21    KnotVector, NurbsCurve, Vec4,
22};
23#[path = "blending/blend/mod.rs"]
24mod blend;
25pub use blend::{
26    blend_closed_edge, blend_edge_variable, blend_open_edge, blend_smooth_chain,
27    round_convex_corner,
28};
29#[path = "blending/fillet.rs"]
30mod fillet;
31pub use fillet::{
32    chamfer_edge, chamfer_edge_angle, chamfer_edge_asymmetric, chamfer_edges_angle,
33    chamfer_edges_asymmetric, fillet_edge, fillet_edges, fillet_edges_variable,
34    fillet_edges_variable_law, fillet_edges_variable_vertex_radii,
35};
36#[path = "blending/law.rs"]
37mod law;
38pub use law::{LawSegment, RadiusLaw};
39#[path = "geometry/fit.rs"]
40mod fit;
41pub use fit::{
42    fit_polyline, interpolate_curve, interpolate_curve_closed, interpolate_curve_local,
43    interpolate_curve_thinned, interpolate_curve_with_end_tangents, simplify_polyline,
44    solve_banded, solve_dense, PolylineFit,
45};
46#[path = "geometry/image_curve.rs"]
47mod image_curve;
48pub use image_curve::{affine_image_curve, image_curve, image_curve_pair, ImageCurve, ImageCurveTier};
49#[path = "geometry/surface.rs"]
50mod surface;
51pub use surface::{
52    carrier_preview_patch, make_cone_surface, make_cylinder_surface, make_extrusion, make_plane,
53    make_revolution, make_sphere_surface, make_torus_surface, NurbsSurface,
54};
55#[path = "geometry/analytic_surface.rs"]
56mod analytic_surface;
57pub use analytic_surface::{
58    circle_angle_to_parameter, intersect_analytic_pair, revolution_structure, AnalyticSurface,
59    RevolutionFrame, RevolutionStructure,
60};
61#[path = "brep/solid_codec.rs"]
62mod solid_codec;
63pub use solid_codec::{decode_solid, encode_solid, SolidNames, SOLID_CODEC_VERSION};
64#[path = "brep/topology.rs"]
65mod topology;
66pub use topology::{
67    make_box_brep, make_cylinder_brep, make_pyramid_brep, BrepSolid, FaceRecord, ValidationReport,
68};
69#[path = "brep/topology_arena.rs"]
70mod topology_arena;
71pub use topology_arena::{
72    ArenaCoedge, ArenaEdge, ArenaFace, ArenaLoop, ArenaShell, ArenaVertex, CoedgeId, EdgeId,
73    FaceId, LoopId, ShellId, TopologyArena, VertexId,
74};
75#[path = "brep/analytic_topology.rs"]
76mod analytic_topology;
77pub use analytic_topology::{make_cone_brep, make_sphere_brep, make_torus_brep};
78#[path = "construction/sweep_topology.rs"]
79mod sweep_topology;
80pub use sweep_topology::{
81    extrude_profile_brep, extrude_profile_brep_draft, profile_anchor, rib_from_profile,
82    RibExtrusion,
83    sweep_profile_along_chain, sweep_profile_along_path, sweep_profile_along_path_anchored,
84    sweep_profile_helix,
85    sweep_profile_twisted, sweep_profile_twisted_anchored, ProfileAnchor, SectionPlacement,
86};
87#[path = "construction/revolve_topology.rs"]
88mod revolve_topology;
89pub use revolve_topology::{revolve_profile_brep, revolve_profile_brep_named};
90#[path = "construction/loft_topology.rs"]
91mod loft_topology;
92pub use loft_topology::{
93    loft_profile_brep, loft_profile_brep_closed, loft_profile_brep_guided,
94    loft_profile_brep_guided_frame, loft_profile_brep_tangent,
95};
96#[path = "brep/transform_topology.rs"]
97mod transform_topology;
98pub use transform_topology::{mirror_brep, transform_brep, AffineTransform};
99#[path = "edit/split.rs"]
100mod split;
101pub use split::{
102    split_solid_by_face_surface, split_solid_by_plane, split_solid_by_surface, SplitSurface,
103};
104#[path = "props/mass_properties.rs"]
105mod mass_properties;
106pub use mass_properties::{
107    curve_arc_length, edge_arc_length, face_area, face_boundary_length, face_volume_contribution,
108    parameter_space_area, solid_edge_length_total, solid_mass_properties,
109    solid_mass_properties_full, solid_signed_volume, trim_polygons, DensityMassProperties,
110    FullMassProperties, MassProperties,
111};
112#[path = "meshing/tessellation.rs"]
113mod tessellation;
114pub use tessellation::{tessellate_brep, tessellate_face, TessellationOptions};
115#[path = "meshing/watertight_tessellation/mod.rs"]
116mod watertight_tessellation;
117pub use watertight_tessellation::{
118    sample_edge_polylines, sample_edges_encoded, tessellate_brep_watertight,
119    tessellate_brep_watertight_face_stride, tessellate_brep_watertight_face_stride_with_samples,
120};
121// The Rust feature-history execution engine (migration-plan Stage 4/5 foundation).
122// Deserializes the serialized `{ type, inputParams, ... }` descriptor shape, runs
123// each feature against a live scene-map of resident handles, and returns per-feature
124// results (handles + face/edge names). See feature_pipeline/mod.rs for the contract.
125#[path = "feature_pipeline/mod.rs"]
126mod feature_pipeline;
127pub use feature_pipeline::execute_history_json;
128// Typed, in-process pipeline surface for native consumers (brep-render): run a
129// whole history and read the results without a JSON round trip.
130pub use feature_pipeline::{
131    clear_history_cache, execute_history, AddedSolid, Axis, ComponentRecord, FeatureDescriptor,
132    FeatureResult, Frame, HistoryRequest, HistoryResult, ProfileLoop, SketchProfile,
133};
134// The sketch loop-id write-back: stamps each closed loop's stable id onto its
135// geometries so per-loop face names survive deleting the edge an id came from.
136// The editor calls it when a sketch is committed.
137pub use feature_pipeline::assign_sketch_loop_ids;
138// Sheet-metal flat-pattern (unfold) → 2D vector export, keyed by resident handle.
139pub use feature_pipeline::{flat_pattern_dxf, flat_pattern_svg, is_sheet_metal_handle};
140// Native IMPORT3D payload: finished solids → the `io/snapshot` container with
141// IMPORT3D's naming stamped on, i.e. the `inputParams.nativeBrep` an import lane
142// bakes into a part document (`features/import3d.rs` reads it back verbatim).
143pub use feature_pipeline::{native_import_payload, native_import_payload_with_appearance};
144// The scene-metadata isolation bracket a payload producer holds across the
145// encode, so ambient records of the LIVE document never leak into a new part.
146pub use feature_pipeline::IsolatedSceneMetadata;
147// The imported-colour read of the name-keyed scene-metadata store. Thread-local
148// like the rest of it, so an off-thread runner reads it and ships the result.
149pub use feature_pipeline::scene_metadata_colors_json;
150// The assemblies parts library (unique part payloads for ACOMP instances):
151// insert / update-refresh mutations and the save-side serialization surface.
152pub use feature_pipeline::{
153    add_part_to_library, install_parts_library, missing_library_parts, parts_library_json,
154    parts_library_map, parts_library_revision, refresh_library_entry, PartsLibraryEntry,
155    PartsLibraryMap,
156};
157// Assembly constraint state + exported ABI (state/statuses/DOF/overlay reads,
158// constraint CRUD with auto-solve, the document pose/isFixed write-back fold).
159pub use feature_pipeline::assembly::{
160    assembly_add_constraint_json, assembly_apply_document_json, assembly_dof_json,
161    assembly_move_constraint_json, assembly_overlay_json, assembly_pose_updates_json,
162    assembly_remove_constraint_json, assembly_run_solve_json,
163    assembly_set_constraint_enabled_json, assembly_set_constraint_open_json,
164    assembly_state_json, assembly_statuses_json, assembly_update_constraint_json,
165    constraint_schema_catalogue,
166};
167pub use feature_pipeline::{AssemblyState, ConstraintEntry};
168// The ONE matrix → `{translate, rotateEulerDeg}` (intrinsic XYZ, degrees) pose
169// encoder, shared by the solver write-back and any out-of-crate ACOMP author.
170pub use feature_pipeline::assembly::transform_to_pose_params;
171// The feature-schema catalogue (feature definitions: name + `inputParamsSchema`),
172// so a native UI can drive schema-driven feature dialogs without the JSON export.
173pub use feature_pipeline::feature_schema_catalogue;
174// Selection-context applicability: the context bar's per-feature/-constraint
175// show/no-show predicates, plus the constraint type table they pair with.
176pub use feature_pipeline::assembly::{constraint_type, ConstraintTypeDef, CONSTRAINT_TYPES};
177pub use feature_pipeline::{feature_context_applicable, SelectionProbe};
178// The pipeline expression evaluator (the history's `expressions` + `configurator`
179// variable sheet), so a native UI (brep-render's engine-native sketcher) can
180// evaluate a LIVE dimension `valueExpr` against the same variables a committed
181// solve would (`features/sketch.rs` `pre_evaluate_expressions`). `Env::build`/
182// `eval` are pure arithmetic (no `std::time`), so this stays wasm-clean.
183pub use feature_pipeline::Env;
184
185/// One-shot: build an [`Env`] from a history's `expressions` source + its
186/// `configurator` JSON, then evaluate `source` to a scalar. The small surface the
187/// engine-native sketcher's live dimension-value edit uses (deliverable S5.0) —
188/// equivalent to `Env::build(expressions, configurator_json)?.eval(source)`.
189pub fn eval_expression(
190    expressions: &str,
191    configurator_json: &serde_json::Value,
192    source: &str,
193) -> Result<f64, String> {
194    Env::build(expressions, configurator_json).and_then(|env| env.eval(source))
195}
196
197// In the shared-memory-threaded wasm build, re-export wasm-bindgen-rayon's
198// thread-pool initializer as `initThreadPool(numThreads)`. The JS side must
199// await it once after wasm init (needs a cross-origin-isolated page —
200// COOP/COEP — for SharedArrayBuffer). With the pool live, the ordinary
201// `tessellate_watertight_buffers` parallelizes its per-face loop across threads
202// (see `tessellate_faces_stride` under the `parallel` feature).
203#[cfg(feature = "wasm-threads")]
204pub use wasm_bindgen_rayon::init_thread_pool;
205#[path = "geometry/projection.rs"]
206mod projection;
207pub use projection::{
208    project_point_to_curve, project_point_to_surface, project_point_to_surface_seeded,
209    CurveProjection, SurfaceProjection,
210};
211#[path = "intersect/curve_surface_intersection.rs"]
212mod curve_surface_intersection;
213pub use curve_surface_intersection::{intersect_curve_surface, CurveSurfaceIntersection};
214#[path = "intersect/curve_curve_intersection.rs"]
215mod curve_curve_intersection;
216pub use curve_curve_intersection::{intersect_curves, CurveCurveIntersection};
217#[path = "intersect/surface_surface_intersection.rs"]
218mod surface_surface_intersection;
219pub use surface_surface_intersection::{
220    intersect_surfaces, intersect_surfaces_supplemental, SurfaceIntersectionCurve,
221    SurfaceIntersectionOptions,
222};
223#[path = "brep/classification.rs"]
224mod classification;
225pub use classification::{
226    classify_point, parameter_point_in_face, PointClass, PointClassification, PolygonClass,
227    SolidClassifier,
228};
229#[path = "geometry/spatial.rs"]
230mod spatial;
231pub use spatial::{Aabb, Bvh};
232#[path = "brep/pair_classification.rs"]
233mod pair_classification;
234pub use pair_classification::{
235    classify_surface_pair, classify_surface_pair_cached, SurfaceClassifyData,
236    SurfacePairClassification, SurfacePairRelation,
237};
238#[path = "intersect/arrangement.rs"]
239mod arrangement;
240pub use arrangement::{
241    arrange_segments, point_in_polygon, segment_intersection, ArrangementPiece, ArrangementRegion,
242    CycleUse, Segment2, Vec2,
243};
244#[path = "geometry/pcurve.rs"]
245mod pcurve;
246pub use pcurve::{
247    build_pcurve_on_surface, build_pcurve_on_surface_marched, build_pcurve_on_surface_range,
248    build_pcurve_on_surface_range_dense,
249};
250#[path = "csg/imprint.rs"]
251mod imprint;
252pub use imprint::{
253    build_imprints, EdgeSplitRecord, FaceImprints, FaceKey, FacePcurve, ImprintOptions,
254    ImprintPieceRecord, ImprintResultRecord, ImprintVertex,
255};
256#[path = "csg/edge_split.rs"]
257mod edge_split;
258pub use edge_split::{apply_edge_splits, apply_edge_splits_with_map};
259#[path = "csg/fragment.rs"]
260mod fragment;
261pub use fragment::{
262    fragment_face, fragment_solid, FaceFragmentRecord, FragmentCoedge, FragmentEdgeSource,
263    FragmentLoop,
264};
265#[path = "csg/boolean/mod.rs"]
266mod boolean;
267pub use boolean::{
268    boolean_operation, boolean_operation_nary, boolean_operation_with_diagnostics,
269    BooleanOperation, BooleanOptions,
270};
271#[path = "csg/oracle.rs"]
272mod oracle;
273pub use oracle::{
274    boolean_residual_fusables, boolean_semantic_disagreement, boolean_semantic_disagreement_nary,
275    OracleReport, ResidualFusable, ResidualKind, SemanticDisagreement, DISAGREEMENT_THRESHOLD,
276};
277#[path = "healing/heal.rs"]
278mod heal;
279// The pointwise offset evaluator — ONE definition of "the offset of a surface
280// at a parameter", shared by `offset_surface`'s Greville sampling, the blend
281// march's tangency residual, and the push-face offset residual gates. Declared
282// before `offset` because that module is its first consumer.
283#[path = "offset/point.rs"]
284mod offset_point;
285pub use offset_point::{OffsetEvaluator, OffsetNormal, OffsetSample};
286// The LOCUS-level offset seam — ONE definition of "intersect two offset
287// analytic carriers in closed form", shared by the blend's corner closures.
288// The pointwise evaluator above answers "where is the offset at this (u, v)";
289// this answers "where do two offsets MEET", which is what the corner solves
290// need and what no pointwise evaluator can produce (audit §9.4, §11).
291// Crate-internal: no consumer outside the kernel names these.
292#[path = "offset/analytic_pair.rs"]
293mod offset_analytic_pair;
294// The shared re-trim helpers — ONE definition of "rebuild a face's carrier and
295// pcurves around a boundary that has already moved", shared by push-face,
296// face-move and the direct-edit heals. This is the RE-INTERSECTION sense of
297// trimming; offset-shell's parametric-image trimming is a different operation
298// and deliberately not here (see the module doc). Crate-internal: no consumer
299// outside the kernel names these.
300#[path = "offset/retrim.rs"]
301mod offset_retrim;
302// The RE-INTERSECTION seam — ONE definition of "intersect two carriers to
303// remake a trim boundary", with the exact analytic lane first and the general
304// marched lane behind it. `offset_retrim` above re-trims a face around a
305// boundary that has ALREADY moved; this is the step that moves it, and it is
306// what makes a neighbour re-intersection surface-type-blind the way
307// offset-shell's imprint driver already is. Crate-internal: no consumer outside
308// the kernel names these.
309#[path = "offset/reintersect.rs"]
310mod offset_reintersect;
311// The MEASURED half of the tolerance model: the deviation actually observed
312// between an offset construction and the geometry it was built to reproduce.
313// Everything in `geometry/tolerance.rs` above `MeasuredTolerance` DERIVES a
314// band from a size before the geometry exists; this measures what the
315// construction then did. Declared before `offset` because that module is its
316// first consumer (occt-offset-algorithms.md §6.1, ADOPT #2).
317#[path = "offset/measure.rs"]
318mod offset_measure;
319pub use offset_measure::{
320    measure_edge_against_pcurve_image, measure_surface_fit_against_pointwise_offset,
321    span_midpoint_error, vertex_endpoint_gap,
322};
323#[path = "offset/offset.rs"]
324mod offset;
325pub use offset::{
326    offset_face_carrier, offset_face_carrier_measured, offset_surface, offset_surface_measured,
327    CarrierDeviation, MeasuredOffsetSurface, OffsetFaceCarrier, OffsetSurfaceLane,
328};
329#[path = "offset/thicken.rs"]
330mod thicken;
331pub use thicken::{thicken_face_sheet, thicken_trimmed_sheet};
332#[path = "healing/coalesce.rs"]
333mod coalesce;
334pub use coalesce::{concatenate_exact_curve_pieces, merge_curve_continuation_edges};
335#[path = "healing/face_merge.rs"]
336mod face_merge;
337// Retained for potential mesh-import repair; no exact operation may fall
338// back to it (offset shell must produce real surfaces or fail loudly).
339#[allow(dead_code)]
340#[path = "healing/faceted_repair.rs"]
341mod faceted_repair;
342pub use face_merge::{merge_same_surface_faces, merge_same_surface_faces_excluding};
343pub use faceted_repair::mesh_to_faceted_brep;
344#[path = "offset/offset_shell.rs"]
345mod offset_shell;
346pub use offset_shell::{
347    offset_shell, offset_shell_with_diagnostics, OffsetFaceRole, OffsetShellFaceImageRecord,
348    OffsetShellResultRecord,
349};
350#[path = "io/step.rs"]
351mod step;
352pub use step::{
353    audit_step_manifold, audit_step_pcurves, export_step, export_step_report, StepExportReport,
354};
355// Imported appearance (colour) — the carrier between an importer that READ a
356// colour and the pipeline that stamps it as name-keyed scene metadata. Not a
357// storage layer: see the module doc for the `{"color": "#RRGGBB"}` convention.
358#[path = "io/appearance.rs"]
359mod appearance;
360pub use appearance::{BodyAppearance, ImportedColor, COLOR_METADATA_KEY};
361#[path = "io/step_import/mod.rs"]
362mod step_import;
363pub use step_import::{
364    import_step, import_step_report, import_step_with_appearance, read_step_assembly, StepAssembly,
365    StepOccurrence, StepProduct,
366};
367#[path = "io/iges/mod.rs"]
368mod iges;
369pub use iges::{export_iges, import_iges};
370#[path = "io/mesh_io.rs"]
371mod mesh_io;
372pub use mesh_io::{
373    read_binary_stl, read_obj, write_binary_stl, write_obj, ObjReadResult, StlReadResult,
374};
375// Native serialized exact-BREP snapshot: the assemblies parts-library fast
376// lane (instant component insert from a cached payload; fails detectably so
377// the ACOMP self-heal lane can re-execute the embedded part document).
378#[path = "io/snapshot.rs"]
379mod snapshot;
380pub use snapshot::{
381    restore_solids, snapshot_resident_solids, snapshot_solids, RestoredSnapshot, RestoredSolid,
382    SNAPSHOT_FORMAT_VERSION,
383};
384#[path = "solvers/sketch_solver.rs"]
385mod sketch_solver;
386pub use sketch_solver::{
387    solve_sketch, solve_sketch_from_json, SketchSolverSettings, SolveSketchRequest,
388};
389#[path = "solvers/assembly_solver.rs"]
390mod assembly_solver;
391pub use assembly_solver::{
392    solve_assembly, AssemblyBody, AssemblyMate, AssemblySolution, AssemblySolveOptions, BodyPose,
393    MateAlign, MateAxis, MateKind, MatePlane, MateResidualReport, SolveStrategy,
394};
395// Assembly selection resolution (build-spec §5): a namespaced selection ref
396// resolved to an analytic frame (plane/axis/sphere/circle/line/point) read from
397// the exact BREP, feeding `MateKind` inputs in component-local coordinates.
398#[path = "solvers/assembly_resolve.rs"]
399mod assembly_resolve;
400pub use assembly_resolve::{
401    is_component_reference, resolve_component_point, resolve_edge_selection,
402    resolve_face_selection, resolve_named_selection, resolve_vertex_selection,
403    split_component_namespace, ResolveError, SelectionGeometry,
404};
405#[path = "edit/direct_edit.rs"]
406mod direct_edit;
407pub use direct_edit::{
408    delete_face_and_heal, move_faces, offset_freeform_face, offset_revolution_face,
409    offset_ruled_face, offset_sphere_face, offset_torus_face, resolve_face_by_point,
410};
411#[path = "healing/sew.rs"]
412mod sew;
413pub use sew::{sew_solid, split_pinched_vertices, SewReport};
414#[path = "meshing/mesh_segment.rs"]
415mod mesh_segment;
416pub use mesh_segment::{
417    mesh_regions_to_brep, segment_mesh_faces, MeshRegion, MeshSegmentation, RegionCarrier,
418    SegmentOptions, UNASSIGNED_REGION,
419};
420
421#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize)]
422pub struct Vec3 {
423    pub x: f64,
424    pub y: f64,
425    pub z: f64,
426}
427
428impl Vec3 {
429    pub fn new(x: f64, y: f64, z: f64) -> Self {
430        Self { x, y, z }
431    }
432    pub fn sub(self, rhs: Self) -> Self {
433        Self::new(self.x - rhs.x, self.y - rhs.y, self.z - rhs.z)
434    }
435    pub fn add(self, rhs: Self) -> Self {
436        Self::new(self.x + rhs.x, self.y + rhs.y, self.z + rhs.z)
437    }
438    pub fn scale(self, factor: f64) -> Self {
439        Self::new(self.x * factor, self.y * factor, self.z * factor)
440    }
441    pub fn cross(self, rhs: Self) -> Self {
442        Self::new(
443            self.y * rhs.z - self.z * rhs.y,
444            self.z * rhs.x - self.x * rhs.z,
445            self.x * rhs.y - self.y * rhs.x,
446        )
447    }
448    pub fn dot(self, rhs: Self) -> f64 {
449        self.x * rhs.x + self.y * rhs.y + self.z * rhs.z
450    }
451    pub fn length(self) -> f64 {
452        self.dot(self).sqrt()
453    }
454    pub fn length_squared(self) -> f64 {
455        self.dot(self)
456    }
457    pub fn normalized(self) -> Result<Self, String> {
458        let length = self.length();
459        if length <= 1e-12 {
460            return Err("Vec3.normalized: zero-length vector".into());
461        }
462        Ok(self.scale(1.0 / length))
463    }
464    pub fn perpendicular(self) -> Result<Self, String> {
465        let x = self.x.abs();
466        let y = self.y.abs();
467        let z = self.z.abs();
468        let axis = if x <= y && x <= z {
469            Self::new(1.0, 0.0, 0.0)
470        } else if y <= z {
471            Self::new(0.0, 1.0, 0.0)
472        } else {
473            Self::new(0.0, 0.0, 1.0)
474        };
475        self.cross(axis).normalized()
476    }
477}
478
479#[derive(Clone, Debug, Default, Deserialize, Serialize)]
480pub struct Mesh {
481    pub positions: Vec<f64>,
482    pub normals: Vec<f64>,
483    pub indices: Vec<u32>,
484    pub face_ids: Vec<u32>,
485}
486
487impl Mesh {
488    fn push_vertex(&mut self, point: Vec3, normal: Vec3) -> u32 {
489        self.positions.extend([point.x, point.y, point.z]);
490        self.normals.extend([normal.x, normal.y, normal.z]);
491        (self.positions.len() / 3 - 1) as u32
492    }
493
494    fn quad(&mut self, points: [Vec3; 4], normal: Vec3, face_id: u32) {
495        let base = self.push_vertex(points[0], normal);
496        for point in points.iter().skip(1) {
497            self.push_vertex(*point, normal);
498        }
499        self.indices
500            .extend([base, base + 1, base + 2, base, base + 2, base + 3]);
501        self.face_ids.extend([face_id, face_id]);
502    }
503
504    pub fn signed_volume(&self) -> f64 {
505        self.indices
506            .chunks_exact(3)
507            .map(|tri| {
508                let point = |index: u32| {
509                    let i = index as usize * 3;
510                    Vec3::new(
511                        self.positions[i],
512                        self.positions[i + 1],
513                        self.positions[i + 2],
514                    )
515                };
516                point(tri[0]).dot(point(tri[1]).cross(point(tri[2]))) / 6.0
517            })
518            .sum()
519    }
520
521    pub fn validate(&self) -> Result<(), String> {
522        if self.positions.len() % 3 != 0 || self.normals.len() != self.positions.len() {
523            return Err("invalid vertex or normal buffer".into());
524        }
525        self.validate_geometry()
526    }
527
528    /// Geometry-only validation for consumers that use positions + indices but
529    /// NOT normals (e.g. `signed_volume`, whose tetrahedron sum never reads a
530    /// normal). Mesh-only solids such as sheet-metal bodies supply metrics
531    /// meshes with an empty normal buffer, which is legitimate for volume.
532    pub fn validate_geometry(&self) -> Result<(), String> {
533        if self.positions.len() % 3 != 0 {
534            return Err("invalid vertex buffer".into());
535        }
536        if self.indices.len() % 3 != 0 {
537            return Err("index buffer is not triangular".into());
538        }
539        let count = self.positions.len() / 3;
540        if self.indices.iter().any(|index| *index as usize >= count) {
541            return Err("index outside vertex buffer".into());
542        }
543        if !self.positions.iter().all(|value| value.is_finite()) {
544            return Err("non-finite vertex".into());
545        }
546        Ok(())
547    }
548}
549
550pub fn make_box(size_x: f64, size_y: f64, size_z: f64) -> Mesh {
551    let x = size_x.abs();
552    let y = size_y.abs();
553    let z = size_z.abs();
554    let p = [
555        Vec3::new(0.0, 0.0, 0.0),
556        Vec3::new(x, 0.0, 0.0),
557        Vec3::new(x, y, 0.0),
558        Vec3::new(0.0, y, 0.0),
559        Vec3::new(0.0, 0.0, z),
560        Vec3::new(x, 0.0, z),
561        Vec3::new(x, y, z),
562        Vec3::new(0.0, y, z),
563    ];
564    let mut mesh = Mesh::default();
565    mesh.quad([p[0], p[3], p[2], p[1]], Vec3::new(0.0, 0.0, -1.0), 0);
566    mesh.quad([p[4], p[5], p[6], p[7]], Vec3::new(0.0, 0.0, 1.0), 1);
567    mesh.quad([p[0], p[1], p[5], p[4]], Vec3::new(0.0, -1.0, 0.0), 2);
568    mesh.quad([p[3], p[7], p[6], p[2]], Vec3::new(0.0, 1.0, 0.0), 3);
569    mesh.quad([p[0], p[4], p[7], p[3]], Vec3::new(-1.0, 0.0, 0.0), 4);
570    mesh.quad([p[1], p[2], p[6], p[5]], Vec3::new(1.0, 0.0, 0.0), 5);
571    mesh
572}
573
574pub fn make_cylinder(radius: f64, height: f64, segments: usize) -> Mesh {
575    let radius = radius.abs();
576    let height = height.abs();
577    let segments = segments.max(3);
578    let mut mesh = Mesh::default();
579    for i in 0..segments {
580        let a = std::f64::consts::TAU * i as f64 / segments as f64;
581        let b = std::f64::consts::TAU * (i + 1) as f64 / segments as f64;
582        let (sa, ca) = a.sin_cos();
583        let (sb, cb) = b.sin_cos();
584        let pa = Vec3::new(radius * ca, 0.0, -radius * sa);
585        let pb = Vec3::new(radius * cb, 0.0, -radius * sb);
586        let ta = Vec3::new(pa.x, height, pa.z);
587        let tb = Vec3::new(pb.x, height, pb.z);
588        mesh.quad(
589            [pa, pb, tb, ta],
590            Vec3::new((ca + cb) * 0.5, 0.0, -(sa + sb) * 0.5),
591            0,
592        );
593        let bottom = mesh.push_vertex(Vec3::default(), Vec3::new(0.0, -1.0, 0.0));
594        let bi = mesh.push_vertex(pb, Vec3::new(0.0, -1.0, 0.0));
595        let bj = mesh.push_vertex(pa, Vec3::new(0.0, -1.0, 0.0));
596        mesh.indices.extend([bottom, bi, bj]);
597        mesh.face_ids.push(1);
598        let top = mesh.push_vertex(Vec3::new(0.0, height, 0.0), Vec3::new(0.0, 1.0, 0.0));
599        let ti = mesh.push_vertex(ta, Vec3::new(0.0, 1.0, 0.0));
600        let tj = mesh.push_vertex(tb, Vec3::new(0.0, 1.0, 0.0));
601        mesh.indices.extend([top, ti, tj]);
602        mesh.face_ids.push(2);
603    }
604    mesh
605}
606
607
608mod abi;
609pub use abi::*;
610
611#[cfg(test)]
612mod tests;