Skip to content

API Reference

Capabilities and limits

STEP preparation and JAX evaluation

STEP reading and OCCT extraction run on the host, outside jit, vmap, and differentiation. The numerical kernels operate on the resulting arrays and geometric models; JAX transformation support follows each API's contract.

Face conversion and mesh extraction support planes, cylinders, spheres, cones, tori, and B-spline surfaces (including rational weights). Other OCCT surface types are unsupported. face_to_primitive warns and returns None for them; mesh extraction raises NotImplementedError rather than returning an incomplete mesh. CSG reconstruction also rejects unsupported faces. Successful conversion alone does not establish an accurate solid SDF.

extract_mesh_topology and evaluate_mesh separate OCCT preparation from JAX vertex evaluation. Connectivity and the extracted UV samples form a fixed discretization; uv_scale_param can scale plane UV coordinates so that caps follow a linked parameter. Parameter changes must preserve closure and shared boundaries; a derivative of this discretization is not a derivative through OCCT reconstruction or remeshing. Topology-changing edits require separate validation.

Mesh mass properties

For a watertight, consistently oriented mesh, the divergence theorem gives the mesh's signed volume. Accuracy against the original curved CAD depends on tessellation. The integration report records fixture measurements, not an error bound for every supported surface or input.

triangulate_shape evaluates each triangle corner from its own face's parameters independently, so a vertex on an edge shared by two faces gets two numerically close but generally distinct copies; the mesh is not literally watertight at the index level. triangulate_shape_watertight is an opt-in mode that instead welds shared vertices identified from OCCT's own per-edge mesh discretization (not a distance tolerance) and returns a WatertightMesh (vertices, faces, max_gap) whose vertices[faces] is a true index-level watertight mesh. WatertightMesh is a registered JAX pytree (an equinox.Module of arrays only), so jit and vmap can return it directly; host metadata such as surface_type and per-face triangle counts is not array data and lives instead on WatertightTopology, from extract_watertight_topology. A shared vertex's position is a two-level mean -- each incident face's own nodes there, then those per-face means across the vertex's distinct incident faces -- so jax.grad distributes symmetrically per incident face even when one face (e.g. at a periodic face's own seam) contributes more than one of its own nodes to that vertex. extract_watertight_topology and evaluate_watertight_mesh split the host-side OCCT extraction and validation from this averaging, a pure JAX function of explicit per-face parameters (B-spline degrees excluded -- they are shape-determining dispatch keys, not differentiable data, and stay on WatertightTopology so a traced call never needs to hash one), so a caller can differentiate, jit, or vmap with respect to specific per-face surface parameters without repeating the OCCT work. WatertightMesh.max_gap reports an upper bound on the largest disagreement between any two of a shared vertex's incident nodes -- computed from their raw evaluations, not the per-face means used for vertices, so it still catches two nodes of the same face disagreeing (e.g. across a periodic face's own seam) -- and an optional tolerance argument rejects a mesh whose evaluations disagree by more than that bound instead of silently welding through the disagreement.

Function Numerical contract
divergence_volume Cubic polynomial in triangle vertices; signed volume in length cubed.
mesh_surface_area Sum of triangle areas, in length squared; uses a norm, not a polynomial. Collapsed triangles use a chosen zero subgradient.
mesh_center_of_mass First moments divided by volume, in length units; undefined for nonempty zero-volume inputs.
mesh_inertia_tensor Tensor about the center of mass at unit density, in length to the fifth power; requires nonzero volume and outward orientation.

Nearly degenerate solids can make the normalized moments ill-conditioned. See the function contracts below for empty-input behavior and other assumptions.

Boolean measures and trimmed surfaces

Union, intersection, and subtraction have stratum-dispatched measure implementations. Where finite primitive volume formulas apply, disjoint and contained configurations use analytical gradients. Intersecting configurations and other fallbacks differentiate a smoothed indicator on a frozen grid as a surrogate for the hard sampled forward measure. These estimators have discretization error and do not establish exact derivatives through arbitrary CAD topology changes. See Boolean operations for the APIs.

Standalone trimmed-face distances and CSG half-space composition have different contracts. TrimmedCSGStump uses raw primitive SDFs in its DNF composition, including B-splines; trim frames are retained as metadata. ADR-0020 explains why the trim-aware blend is excluded from that composition. See NURBS differentiation scope for the remaining distinction between surface, face, and solid derivatives.

Primitives

  • Primitives -- Geometric primitives with SDF interface

Boolean Operations

  • Boolean -- Differentiable Boolean operations with stratum-dispatched gradients

Analytical

  • Analytical -- Closed-form ground-truth solutions

Experimental

  • Applications -- Bounded STEP hole editing and application demonstrators

STEP and mesh APIs

brepax.io.step.read_step(path)

Read a STEP file and return the top-level shape.

Parameters:

Name Type Description Default
path str | Path

Path to the STEP file (.step or .stp).

required

Returns:

Type Description
TopoDS_Shape

The parsed OCCT shape.

Raises:

Type Description
FileNotFoundError

If the file does not exist.

ValueError

If the STEP file cannot be parsed.

Source code in src/brepax/io/step.py
def read_step(path: str | Path) -> TopoDS_Shape:
    """Read a STEP file and return the top-level shape.

    Args:
        path: Path to the STEP file (.step or .stp).

    Returns:
        The parsed OCCT shape.

    Raises:
        FileNotFoundError: If the file does not exist.
        ValueError: If the STEP file cannot be parsed.
    """
    resolved = Path(path).resolve()
    if not resolved.is_file():
        msg = f"STEP file not found: {resolved}"
        raise FileNotFoundError(msg)

    reader = STEPControl_Reader()
    status = reader.ReadFile(str(resolved))
    if status != IFSelect_RetDone:
        msg = f"Failed to read STEP file (status={status}): {resolved}"
        raise ValueError(msg)

    reader.TransferRoots()
    shape = reader.OneShape()
    if shape.IsNull():
        msg = f"STEP file produced a null shape: {resolved}"
        raise ValueError(msg)

    return shape

brepax.brep.convert.face_to_primitive(face)

Convert a single OCP face to a BRepAX Primitive.

Maps planes, cylinders, spheres, cones, tori, and B-spline surfaces (including rational weights) to BRepAX primitives, extracting geometric parameters via OCCT adaptor classes. This is host-side preparation.

Returns None with a warning for other surface types.

Parameters:

Name Type Description Default
face TopoDS_Face

An OCCT topological face.

required

Returns:

Name Type Description
A Primitive | None

class:Primitive instance, or None if the surface type

Primitive | None

is not supported.

Source code in src/brepax/brep/convert.py
def face_to_primitive(face: TopoDS_Face) -> Primitive | None:
    """Convert a single OCP face to a BRepAX Primitive.

    Maps planes, cylinders, spheres, cones, tori, and B-spline surfaces
    (including rational weights) to BRepAX primitives, extracting geometric
    parameters via OCCT adaptor classes. This is host-side preparation.

    Returns None with a warning for other surface types.

    Args:
        face: An OCCT topological face.

    Returns:
        A :class:`Primitive` instance, or ``None`` if the surface type
        is not supported.
    """
    adaptor = BRepAdaptor_Surface(face)
    stype = adaptor.GetType()

    if stype == GeomAbs_Plane:
        gp_plane = adaptor.Plane()
        point = _gp_pnt_to_array(gp_plane.Location())
        normal = _gp_dir_to_array(gp_plane.Axis().Direction())
        offset = jnp.dot(normal, point)
        return PlanePrim(normal=normal, offset=offset)

    if stype == GeomAbs_Cylinder:
        gp_cyl = adaptor.Cylinder()
        point = _gp_pnt_to_array(gp_cyl.Location())
        axis = _gp_dir_to_array(gp_cyl.Axis().Direction())
        radius = jnp.array(gp_cyl.Radius())
        return CylinderPrim(point=point, axis=axis, radius=radius)

    if stype == GeomAbs_Sphere:
        gp_sph = adaptor.Sphere()
        center = _gp_pnt_to_array(gp_sph.Location())
        radius = jnp.array(gp_sph.Radius())
        return SpherePrim(center=center, radius=radius)

    if stype == GeomAbs_Cone:
        gp_cone = adaptor.Cone()
        apex = _gp_pnt_to_array(gp_cone.Apex())
        axis = _gp_dir_to_array(gp_cone.Axis().Direction())
        angle = jnp.array(abs(gp_cone.SemiAngle()))
        return ConePrim(apex=apex, axis=axis, angle=angle)

    if stype == GeomAbs_Torus:
        gp_torus = adaptor.Torus()
        center = _gp_pnt_to_array(gp_torus.Location())
        axis = _gp_dir_to_array(gp_torus.Axis().Direction())
        major_radius = jnp.array(gp_torus.MajorRadius())
        minor_radius = jnp.array(gp_torus.MinorRadius())
        return TorusPrim(
            center=center,
            axis=axis,
            major_radius=major_radius,
            minor_radius=minor_radius,
        )

    if stype == GeomAbs_BSplineSurface:
        return _convert_bspline_face(adaptor, face)

    type_name = _SURFACE_TYPE_NAMES.get(stype, "unknown")
    warnings.warn(
        f"Unsupported surface type: {type_name}, skipping face",
        stacklevel=2,
    )
    return None

brepax.brep.triangulate

Triangulation of B-Rep faces for divergence theorem volume.

Uses OCCT BRepMesh for watertight mesh topology, then re-evaluates vertex positions inside the JAX computation graph using parametric surface functions. This gives jax.grad flow from volume through triangle vertices to primitive parameters (control points, radius, etc.) while preserving mesh watertightness.

triangulate_shape evaluates each triangle corner from its own face's parameters independently, so a vertex on a shared edge gets two numerically close but distinct copies: watertight as a surface covering, but not at the index level. triangulate_shape_watertight additionally welds those copies into one vertex per physical point, identified from OCCT edge topology rather than a distance tolerance; extract_watertight_topology and evaluate_watertight_mesh split that into frozen host-side topology and a pure JAX re-evaluation function, for differentiating with respect to specific per-face surface parameters without repeating the OCCT work. See their docstrings and ADR-0024 for the design rationale.

WatertightMesh

Bases: Module

Welded, consistently oriented mesh from :func:evaluate_watertight_mesh.

A registered JAX pytree (an :class:equinox.Module) of arrays only, so it can be returned from -- not just passed through -- jax.jit and jax.vmap. Host metadata (surface_type, per-face triangle counts) lives on :class:WatertightTopology instead, since it is not itself array data; correlate it with faces via WatertightTopology.n_triangles_per_face.

vertices[faces] reproduces the (n, 3, 3) triangle-corner layout :func:triangulate_shape returns, so it can be passed directly to :func:divergence_volume, :func:mesh_surface_area, and the other mesh metrics in this module.

faces instance-attribute

Triangle connectivity into vertices.

max_gap instance-attribute

An upper bound on the largest disagreement between any two of a shared vertex's incident nodes (not the per-face means used for vertices): twice the largest distance from any individual node's own independent evaluation to that vertex's final welded position. By the triangle inequality this bounds the true largest pairwise gap between any two incident nodes' evaluations, including a disagreement between two nodes on the same face (e.g. both sides of a periodic face's own seam), which the face-weighted mean used for vertices does not by itself expose. A large value indicates surface reconstructions that disagree at a shared boundary; see the tolerance argument of :func:triangulate_shape_watertight.

vertices instance-attribute

Welded vertex positions. Each row is the mean, over every incident face, of that face's own mean of its (one or more) nodes at this vertex -- see :func:evaluate_watertight_mesh -- so jax.grad distributes symmetrically across incident faces, weighted by face, not by node.

WatertightTopology dataclass

Frozen host-side topology feeding :func:evaluate_watertight_mesh.

Produced once per shape by :func:extract_watertight_topology (OCCT meshing, edge-topology welding, and manifold validation -- all outside jit/vmap/differentiation), then reused for repeated differentiable re-evaluation with different per-face surface parameters, analogous to :func:extract_mesh_topology and :func:evaluate_mesh for the non-welded mesh. Not itself a registered pytree: it is meant to be closed over or passed as a static argument, never returned from or traced by jit/vmap.

face_records instance-attribute

Per-face host data: surface_type, us, vs, n_points, and -- for a "bspline" face -- the B-spline degrees deg_u, deg_v. Degrees are shape-determining metadata (they select which batched evaluator to dispatch to and are used as dict/cache keys), so they live here, not in params_list, and stay concrete Python ints even when evaluate_watertight_mesh is called under jax.jit.

faces instance-attribute

Triangle connectivity into the welded vertices, (n_triangles, 3), int32; already filtered to drop zero-area triangles (a full-revolution pole or apex can leave OCCT's own mesh with one spanning two now-welded copies of that point, which contributed exactly zero area and volume before welding).

n_triangles_per_face instance-attribute

Post-filtering triangle count for each face, in face_records order. Can differ from :func:triangulate_shape's count for the same face because of the zero-area triangles faces drops.

node_vertex instance-attribute

Flattened (face, local node) index -> welded vertex index directly (pair_vertex[pair_of]), used for the raw per-node gap in WatertightMesh.max_gap.

pair_of instance-attribute

Flattened (face, local node) index -> (welded vertex, face) pair index.

pair_vertex instance-attribute

(welded vertex, face) pair index -> welded vertex index.

params_list instance-attribute

Default per-face surface parameters extracted from OCCT, in face_records order, with B-spline degrees excluded (see face_records). Pass to :func:evaluate_watertight_mesh, or a modified copy of it to differentiate with respect to specific per-face parameters.

triangulate_shape(shape, *, deflection=_DEFAULT_DEFLECTION)

Triangulate all faces of a shape with JAX-native vertices.

Uses OCCT BRepMesh for watertight mesh topology, then re-evaluates each vertex position using JAX-native parametric surface functions. Faces are grouped by surface type (and BSpline signature) so each group is evaluated with a single batched jax.vmap, eliminating per-face Python dispatch overhead.

Each triangle corner is evaluated independently from its own face's parameters: a vertex shared by two faces gets two numerically close but generally distinct copies (see :func:triangulate_shape_watertight for a mode that welds them to a single, shared vertex). This is the original, unchanged contract depended on by existing callers.

Parameters:

Name Type Description Default
shape TopoDS_Shape

An OCCT topological shape.

required
deflection float

Mesh deflection tolerance for OCCT tessellation.

_DEFAULT_DEFLECTION

Returns:

Type Description
ndarray

Tuple of (triangles, params_list) where triangles has

list[dict[str, Any]]

shape (n_total, 3, 3) and params_list contains one

tuple[ndarray, list[dict[str, Any]]]

parameter dict per face, in traversal order.

Raises:

Type Description
NotImplementedError

An evaluated face has an unsupported surface type.

ValueError

An evaluated face has no triangulation or no triangles.

If solids are present, only their faces are evaluated. Otherwise all faces are evaluated. A shape with no faces returns empty arrays and metadata.

triangulate_shape_watertight(shape, *, deflection=_DEFAULT_DEFLECTION, tolerance=None)

Triangulate a shape into a single welded, watertight mesh.

Unlike :func:triangulate_shape, which gives each triangle corner an independent evaluation from its own face (so a shared edge gets two numerically close but distinct copies), this welds shared vertices identified from OCCT's own per-edge mesh discretization (topology and the edge's own curve parameter, not a vertex distance tolerance) and averages every incident face's own evaluation there, producing one vertex per physical point with gradients that flow symmetrically to every incident face's parameters. Degenerate edges (poles, apices) and a periodic face's seam are handled explicitly (see :func:_weld_shared_vertices).

A convenience composition of :func:extract_watertight_topology (host extraction and validation) and :func:evaluate_watertight_mesh (differentiable re-evaluation). Call those directly to re-evaluate the same topology under jax.jit, jax.vmap, or jax.grad against specific per-face parameters without repeating the OCCT work.

Parameters:

Name Type Description Default
shape TopoDS_Shape

An OCCT topological shape.

required
deflection float

Mesh deflection tolerance for OCCT tessellation.

_DEFAULT_DEFLECTION
tolerance float | None

If given, raise when WatertightMesh.max_gap (an upper bound on the largest gap between any two nodes' independent evaluations at a shared vertex) exceeds it. Pass the shape's own CAD tolerance (e.g. :func:brepax.experimental.applications. _hole_geometry.shape_tolerance) to reject faces whose reconstructions disagree by more than the model already tolerates. None (default) never raises on the gap; the value is still returned in max_gap for the caller to inspect.

None

Returns:

Name Type Description
A WatertightMesh

class:WatertightMesh.

Raises:

Type Description
NotImplementedError

An evaluated face has an unsupported surface type.

ValueError

A face has no triangulation; a shared edge cannot be identified from OCCT topology (see :func:_weld_shared_vertices); the welded result is not a closed, manifold, consistently oriented mesh; or tolerance is given and exceeded.

Examples:

>>> shape = read_step("model.step")
>>> mesh = triangulate_shape_watertight(shape, tolerance=1e-4)
>>> vol = divergence_volume(mesh.vertices[mesh.faces])
>>> grad = jax.grad(
...     lambda v: divergence_volume(v[mesh.faces])
... )(mesh.vertices)

extract_watertight_topology(shape, *, deflection=_DEFAULT_DEFLECTION)

Host-side extraction and validation for a welded watertight mesh.

Meshes shape, identifies shared vertices from OCCT edge topology (see :func:_weld_shared_vertices), and validates that the welded result is a closed, manifold, consistently oriented mesh whose every vertex's incident triangles form a single fan (see :func:_check_manifold_closed and :func:_check_vertex_links_manifold). All of this runs once, on the host, outside any JAX transformation; :func:evaluate_watertight_mesh does the repeated, differentiable part.

Parameters:

Name Type Description Default
shape TopoDS_Shape

An OCCT topological shape.

required
deflection float

Mesh deflection tolerance for OCCT tessellation.

_DEFAULT_DEFLECTION

Returns:

Name Type Description
A WatertightTopology

class:WatertightTopology.

Raises:

Type Description
NotImplementedError

An evaluated face has an unsupported surface type.

ValueError

A face has no triangulation, or the welded result is not a closed, manifold, consistently oriented mesh.

Examples:

>>> topology = extract_watertight_topology(shape)
>>> mesh = evaluate_watertight_mesh(topology, topology.params_list)
>>> vol = divergence_volume(mesh.vertices[mesh.faces])

evaluate_watertight_mesh(topology, params_list)

Re-evaluate a welded mesh's vertices from explicit per-face parameters.

For each face, evaluates its own surface function at its stored UV coordinates using params_list (JAX-native, so jax.grad flows from the result through these parameters). A shared vertex's position is a two-level mean: first the mean of each incident face's own node evaluations at that vertex (collapsing, for example, both sides of a periodic face's own seam to one value per face), then the mean of those per-face means across the vertex's distinct incident faces. The second level is what keeps the result -- and its gradient -- weighted equally per incident face regardless of how many of that face's own nodes happen to coincide there. WatertightMesh.max_gap is computed separately, directly from the raw per-node evaluations (before either level of averaging), so it still exposes a disagreement the position averaging would otherwise hide, including between two nodes of the same face.

params_list entries hold only differentiable arrays (for a B-spline face, no deg_u/deg_v: see WatertightTopology. face_records), so this is a pure function of params_list with topology held static, and it supports jax.jit, jax.vmap, and differentiation the same way :func:evaluate_mesh does for the non-welded mesh -- including returning its WatertightMesh result directly from a jitted or vmapped function.

Parameters:

Name Type Description Default
topology WatertightTopology

Frozen topology from :func:extract_watertight_topology.

required
params_list list[dict[str, Any]]

One parameter dict per face, in topology.face_records order; typically topology.params_list or a modified copy of it (e.g. with one face's control points perturbed).

required

Returns:

Name Type Description
A WatertightMesh

class:WatertightMesh.

Examples:

>>> topology = extract_watertight_topology(shape)
>>> def volume_of(radius, face_index):
...     params = [dict(p) for p in topology.params_list]
...     params[face_index] = {**params[face_index], "radius": radius}
...     mesh = evaluate_watertight_mesh(topology, params)
...     return divergence_volume(mesh.vertices[mesh.faces])
>>> grad = jax.grad(volume_of)(jnp.array(5.0), 0)

extract_mesh_topology(shape, *, deflection=_DEFAULT_DEFLECTION)

Extract watertight mesh topology from an OCCT shape.

Tessellates the shape via OCCT BRepMesh, then extracts per-face UV coordinates, triangle connectivity, and surface parameters. The returned data is static (not in the JAX graph) and serves as input to :func:evaluate_mesh for differentiable vertex re-evaluation.

Parameters:

Name Type Description Default
shape TopoDS_Shape

An OCCT topological shape.

required
deflection float

Mesh deflection tolerance for OCCT tessellation.

_DEFAULT_DEFLECTION

Returns:

Type Description
list[dict[str, Any]]

List of face dicts, each containing us, vs (numpy),

list[dict[str, Any]]

conn (numpy int32), reverse (bool), and surface

list[dict[str, Any]]

parameters (JAX arrays).

Raises:

Type Description
NotImplementedError

An evaluated face has an unsupported surface type.

ValueError

An evaluated face has no triangulation or no triangles.

Face selection and empty-shape behavior follow :func:triangulate_shape.

Examples:

>>> topology = extract_mesh_topology(shape)
>>> triangles = evaluate_mesh(topology)
>>> vol = divergence_volume(triangles)

evaluate_mesh(topology, overrides=None, *, uv_scale_param=None)

Re-evaluate mesh vertices from topology with parameter overrides.

For each face, evaluates the surface function at the stored UV coordinates using surface parameters. Any parameter in overrides replaces the corresponding stored value, allowing jax.grad to flow from volume through vertices to the overridden design parameter.

When uv_scale_param is set, plane faces scale their UV coordinates by overrides[uv_scale_param] / uv_scale_ref so that flat caps follow curved-surface parameter changes (e.g. disk caps scale with cylinder radius).

Parameters:

Name Type Description Default
topology list[dict[str, Any]]

Face list from :func:extract_mesh_topology.

required
overrides dict[str, ndarray] | None

Parameter name-value pairs to override.

None
uv_scale_param str | None

Override key used to scale plane UV coordinates. Required for multi-face optimization where flat caps must track a curved-surface parameter.

None

Returns:

Type Description
ndarray

Triangle vertices, shape (n_total, 3, 3).

Examples:

>>> topology = extract_mesh_topology(cylinder_shape)
>>> def volume_fn(radius):
...     return divergence_volume(
...         evaluate_mesh(topology, {"radius": radius},
...                       uv_scale_param="radius")
...     )
>>> grad = jax.grad(volume_fn)(jnp.array(5.0))

divergence_volume(triangles)

Compute volume of a closed triangle mesh via the divergence theorem.

Uses the signed-tetrahedra formula in a local frame near the mesh: each triangle and the local origin form a tetrahedron whose signed volume is v0 . (v1 x v2) / 6. The sum over all triangles gives the enclosed volume for a watertight mesh with outward-facing normals.

Local coordinates reduce cancellation for solids far from the world origin. Units are length cubed. Empty meshes return zero.

jax.grad differentiates the frozen mesh. Geometric shape derivatives require shared boundaries to move consistently and preserve closure; independently moving duplicated triangle corners can open the mesh.

Parameters:

Name Type Description Default
triangles ndarray

Triangle vertices, shape (n, 3, 3).

required

Returns:

Type Description
ndarray

Enclosed volume (scalar).

Examples:

>>> shape = read_step("model.step")
>>> tris, params = triangulate_shape(shape)
>>> vol = divergence_volume(tris)
>>> grad = jax.grad(divergence_volume)(tris)

mesh_surface_area(triangles)

Compute surface area of a triangle mesh.

Sums the area of each triangle: (1/2) ||cross(e1, e2)||. Units are length squared. No absolute area floor is applied. Collapsed or collinear triangles have zero area with a chosen zero subgradient at the nondifferentiable point. Empty meshes return zero.

Parameters:

Name Type Description Default
triangles ndarray

Triangle vertices, shape (n, 3, 3).

required

Returns:

Type Description
ndarray

Total surface area (scalar).

Examples:

>>> tris, _ = triangulate_shape(shape)
>>> area = mesh_surface_area(tris)

mesh_center_of_mass(triangles)

Compute center of mass of a closed triangle mesh.

Integrates signed tetrahedron first moments in a local frame, then divides by signed volume. This avoids cancelling world-origin moments and introducing a dimensionful epsilon into the denominator.

Assumes a watertight mesh with nonzero volume. Units are length. Empty meshes return zero. For nonempty zero-volume inputs the center is undefined; nearly degenerate solids are ill-conditioned. Shape derivatives require closure-preserving shared-boundary motion.

Parameters:

Name Type Description Default
triangles ndarray

Triangle vertices, shape (n, 3, 3).

required

Returns:

Type Description
ndarray

Center of mass, shape (3,).

Examples:

>>> tris, _ = triangulate_shape(shape)
>>> com = mesh_center_of_mass(tris)

mesh_inertia_tensor(triangles)

Compute the inertia tensor of a closed triangle mesh about its center of mass.

Integrates signed tetrahedron moments (Tonon 2005), then applies the parallel axis theorem in a local frame near the center of mass. See https://doi.org/10.3844/jmssp.2005.8.11 for tetrahedron moments.

Assumes a watertight, outward-oriented mesh with nonzero volume and uniform density rho = 1. Empty meshes return zero. Length units L give inertia units L**5; uniform scaling by s multiplies the tensor by s**5. Nearly degenerate solids are ill-conditioned.

Parameters:

Name Type Description Default
triangles ndarray

Triangle vertices, shape (n, 3, 3).

required

Returns:

Type Description
ndarray

Symmetric 3x3 inertia tensor about center of mass.

Examples:

>>> tris, _ = triangulate_shape(shape)
>>> I = mesh_inertia_tensor(tris)