csgrs

repository·main·Indexed 42 days ago

https://github.com/timschmidt/csgrs

A benchmark suite and library for Constructive Solid Geometry (CSG) on meshes composed from hyper geometry crates. Version 0.23.0 provides tools to evaluate geometric kernel performance and correctness by comparing csgrs against industry standards such as CGAL and OpenCascade (OCCT), as well as other Rust implementations like boolmesh and Manifold.

Tokens
32.2K
Snippets
89
Records
132
Agent score
54%

What's inside csgrs

  1. Overview of the csgrs benchmark suite

    main

    The csgrs benchmark suite provides four distinct optimization anchors to evaluate performance and correctness across different geometry engines:

    • kernel_comparison: Runs identical CAD scenarios in csgrs, CGAL, and OpenCascade (OCCT).
    • feature_pipeline: Covers end-to-end paths specific to csgrs, including the Hyper geometry stack, solid/curve-region features, adapters, and I/O.
    • competitive: Compares the csgrs mesh path against boolmesh and pure-Rust Manifold versions. It includes a large workload for union, intersection, and difference operations on 3,072-triangle closed meshes.
    • solidean_comparison: Replays published Solidean ordered Boolean requests. This is an opt-in mode that downloads datasets and executes expensive requests.

    Results are managed via run.sh (orchestration) and summarize.py (validation and comparison).

  2. Understand the kernel_comparison coverage and parity requirements

    main

    The kernel_comparison benchmark measures the portable solid-kernel surface shared by CSGRS, CGAL EPECK, and OpenCascade.

    To ensure valid comparison results, every combination of kernel, precision, and corpus workload must be executed across all three runners. The summary script benchmarks/summarize.py --require-engine-parity enforces this by rejecting any results that contain missing or extra engine rows.

    Note that while stress and dangerous rows are available, they are considered diagnostic ceilings and fall outside the standard portable parity set.

  3. Understand CSGRS correctness boundaries

    main

    When using CSGRS, be aware of the following mathematical and topological constraints:

    • Topology: Decisions are topology-sensitive and use Real and the Hyper predicate stack. Boolean inputs must meet Hypermesh's finite, closed, and oriented solid preconditions. Use try_* methods to handle errors.
    • Approximations: Sampled circles, text, raster contours, implicit fields, and graphics buffers are explicit approximations at the resolution chosen by the caller.
    • 2D Representations: CurveRegion2, CurveString2, and CurvePath2 have distinct meanings and are not unified behind a single 2D facade.
    • Authoritative Geometry: TriangleMesh is the authoritative geometry. AttributedMesh is only for storing aligned boundary attributes.
    • Application Boundaries: Projections in Bevy, WebAssembly, scalar adapters, FFI, and serialization are application-level boundaries and do not represent the underlying topological truth.
  4. Understand GeometryContext policies for SolidExt API

    main

    When using the context-aware SolidExt API, you can choose between different GeometryContext policies that affect how Boolean operations are completed:

    • STRICT: The standard policy. For complex workloads like sampled-cylinder subtraction, it may fail to resolve the operation and return PredicateUndecided.
    • APPROXIMATE_512: A policy that completes the operation by using approximation. It is slower than STRICT but ensures completion. Operations using this policy will report Approximate512Consumed.

    In the benchmarked workload (subtracting a cylinder from a body), APPROXIMATE_512 successfully completes the operation, while STRICT does not.

  5. Understand csgrs binding compatibility and constraints

    main

    When using language bindings, adhere to these safety and compatibility rules:

    • ABI Versioning: Opaque handles are only valid within the ABI version that created them. Do not mix handles across different ABI versions.
    • Memory Management: You must use the specific free function that matches the object's creation.
    • Scalar Families: Do not mix different scalar families in operations.
    • Error Handling: If an operation returns a borrowed error string, you must copy that text before making any subsequent ABI calls to prevent use-after-free or data corruption.
    • Versioning Note: Wrappers are developed alongside the repository and do not currently promise independent semantic versioning.
  6. Understand the CSGRS Comparison Protocol

    main

    The comparison protocol ensures fair benchmarking by fixing dimensions, tessellation counts, transforms, and operation names in the source.

    Key Timing Boundaries:

    • Setup: Objects that can be reused without changing semantics are built outside the timed region.
    • Input/Output: OBJ parsing and request decoding occur outside the timed window. For the Solidean runner, timed work begins with converting indexed f64 triangles into the native Hypermesh carrier and ends once the final mesh is materialized.
    • Validation: Failed Booleans, invalid mass properties, or failed serialization abort the run to prevent deceptively fast results. The runner checks area/volume oracles outside the recorded interval.

    Engine Representations:

    • csgrs: Uses native Hypermesh triangle meshes and Hypercurve regions.
    • cgal-epeck: Uses Exact_predicates_exact_constructions_kernel (EPECK) and triangulated Surface_mesh inputs.
    • opencascade-double-tight: Uses analytic B-reps with no added Boolean fuzzy tolerance. Construction and transforms include OCCT result meshing for comparable output-size reporting.
  7. Identify non-portable CSGRS surfaces

    main

    Certain CSGRS features are excluded from the kernel_comparison three-kernel matrix because they lack equivalent abstractions in CGAL or OpenCascade. These features are still exercised by feature_pipeline, tests, or dependency benchmarks but are not part of the parity set:

    • Metadata & Propagation: Metadata filtering, mapping, and source-face propagation.
    • Hyperreal/Exactness: Hyperreal expression evaluation and finite-boundary conversion.
    • Advanced Geometry: Convex hull, Minkowski sum, Laplacian/Taubin smoothing, Loft, twist, revolve, and path sweep.
    • Domain Constructors: Gear, egg, teardrop, arrow, text, and raster-derived constructors.
    • Planar/Profile Topology: CurveRegion2 Boolean, offset, skeleton, flatten, and slice APIs.
    • Sampling/Meshing: SDF, TPMS, and metaball meshing.
    • Adapters/Formats: AMF, DXF, Gerber, glTF, PLY, SVG, Bevy, WASM, and JavaScript adapters.
  8. Understand Lazy Cuboid and Octahedra topology

    main

    CSGRS uses a lazy topology pattern for cuboids and octahedra to minimize memory allocation and computation.

    • Lazy Cuboids: The constructor reserves exact position and coordinate identities immediately but defers the materialization of the 24 face-corner vertices until geometry is actually read. This allows translation and centering to construct the final carrier directly from shifted exact bounds without rebuilding the entire vertex set.
    • Lazy Octahedra: Similar to cuboids, octahedra reserve six exact position identities but defer the 24 face vertices and eight sampled unit normals until needed.
    • Distributions: Linear and grid distributions of cuboids/cubes also retain lazy translated copies, preserving exact translation and plane identities without constructing every output coordinate upfront.
  9. Understand the Boolean operation performance characteristics

    main

    CSGRS provides Boolean operations (union, intersection, difference) with performance that scales based on whether plane evidence is retained.

    Performance Benchmarks (Corrected/Current):

    operationfresh first callrepeated CSGRSnative Hypermesh
    union21.20 ms13.79 ms10.30--10.70 ms
    intersection11.43 ms--
    difference12.84 ms--

    Key Performance Notes:

    • Plane Evidence Handoff: CSGRS forwards transform-derived exact support planes only when they are already retained. If exactly one operand has retained plane evidence, the missing aligned side is derived to maintain the Hypermesh contract. If neither has it, the system falls back to the ordinary certified-convex Hypermesh entry point.
    • Scale Crossover: CSGRS is highly competitive on subdivided-box Booleans (e.g., 3,072-triangle cases), often outperforming other libraries. However, for larger specific workloads (like the 4,512-triangle YeahRight Booleans), other specialized libraries like boolmesh or manifold-rust may be faster.
  10. Understand CSGRS primary geometry types

    main

    CSGRS acts as a modeling language that composes native types from the Hyper geometry workspace. Use CSGRS for describing models, converting between curve and solid representations, or exchanging geometry with other formats. Use Hypercurve or Hypermesh directly for kernel-level work.

    Core Types

    • csgrs::Real: A re-export of the exact-aware hyperreal::Real scalar used for all core coordinates.
    • csgrs::TriangleMesh: Re-exported from hypermesh::TriangleMesh. This is the primary input/output type for solid modeling and represents indexed triangle geometry.
    • csgrs::AttributedMesh<M>: An optional, feature-gated sidecar for TriangleMesh that stores one metadata value per triangle and optional authored normals. Modeling operations still consume the underlying TriangleMesh geometry.

    Curve Types (via Hypercurve)

    • hypercurve::CurveRegion2: Filled planar material, including holes.
    • hypercurve::CurveString2: An open or closed curve string without implied fill.
    • hypercurve::CurvePath2: A curve that preserves higher-order path topology.
  11. Understand the High-Precision Policy for OCCT and CGAL

    main

    The benchmark suite uses different precision strategies depending on the engine to ensure representative end-to-end CAD comparisons.

    CGAL EPECK: Uses exact predicates and exact constructions via a lazy exact field type. While sampled round primitives start with fixed binary floating-point trigonometric samples, EPECK promotes these values exactly for subsequent topology and construction decisions.

    OCCT (opencascade-double-tight): Since OCCT uses IEEE double (Standard_Real), the opencascade-double-tight profile manages accuracy through:

    • Setting Boolean fuzzy tolerance to zero.
    • Using deterministic, non-parallel Boolean execution for repeatability.
    • Exercising a 1e-6 thin overlap (10x OCCT's Precision::Confusion() of 1e-7).
    • Using a high-resolution sphere mesh (linear deflection 0.005, angular deflection 0.07 radians).

    Note on Serialization: OCCT's stl_write includes temporary-file I/O, whereas csgrs and CGAL use in-memory serialization. Conclusions regarding serialization speed should account for this difference.

  12. Understand `CertifiedSdfMeshOutcome` results

    main

    A successful certified meshing operation returns a CertifiedSdfMeshOutcome. This object provides more than just geometry; it provides the evidence required for certification:

    • TriangleMesh: The actual geometric output.
    • Hypermesh predicate certainty: Confirmation of mesh validity.
    • Field-topology certification status: A status distinct from mesh certainty, proving the mesh relates correctly to the continuous field.
    • Exact Metadata: Includes the exact domain, iso value, and exact geometric-error bound.
    • Provenance: Counts and lineage for cells, roots, topology decisions, and refinement.
    • Certificate: A retained certificate or a stable certificate digest suitable for replay.
    • Optional Proposal: A sampled proposal report, kept explicitly separate from the certified data.