﻿---
title: Tools
description: Tetrahedralize, triangulate, extrude, span layers, autocage and splinters from an image, with their parameters and results.
url: https://help.tangerina.io/deformable/v0.5.0/api-references/rust/tools/
---

# Tools – Rust API Reference – Deformable v0.5.0

The tools turn polygon meshes, triangle meshes and images into closed cages and tetrahedral meshes, the meshes a [`Scene`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/scene/#scene) takes. They keep no state between calls, so separate calls may run on different threads at the same time. Each runs on the calling thread, and the long ones take a [`CancelFlag`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#cancelflag) that another thread can set to stop them. Each tool comes right after the values it takes and returns.

## Anisotropy

**Struct** · `deformable::tools::Anisotropy`

```rust
pub struct Anisotropy {
    pub scale: f64,
    pub direction: Vector3,
}
```

A stretch of the mesher space by `scale` along `direction`, which [`triangulate`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/tools/#triangulate) and
[`tetrahedralize`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/tools/#tetrahedralize) take two of: the elements they make come out about `scale` times
longer along `direction`.

The stretch is `S = I + (scale - 1) n n^T`, with `n` the unit direction, after the clamps of
[`Anisotropy::clamped`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/tools/#anisotropy-clamped). `Anisotropy::default()` is scale 1 along (1, 1, 1): no stretch. Pass the same pair to
both tools. They differ on values out of range: `triangulate` refuses a NaN or infinite scale or component,
while `tetrahedralize` refuses only NaN and clamps an infinite one.

**Fields**

- `scale` (`f64`): The stretch factor along `direction`: above 1 makes longer elements, below 1 shorter ones. Default `1`,
  clamped to `[0.02, 50]`.
- `direction` ([`Vector3`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/math/#vector3)): The stretch direction, of any length; a zero direction makes the scale count as 1. Default `(1, 1, 1)`, each
  component clamped to `[-100, 100]`.

**Implements** `Clone` · `Copy` · `Debug` · `Default` · `PartialEq` · `Send` · `Sync`

**Example**

```rust
// Tetrahedrons about three times longer along y.
let grain = Anisotropy { scale: 3.0, direction: Vector3::Y };
let parameters = TetrahedralizeParameters {
    maximum_edge_length: 0.3,
    anisotropy: [grain, Anisotropy::default()],
    density_regions: Vec::new(),
};
let result = tetrahedralize(&cage, &parameters, None)?;
```

**See also** [Guide: Stretch the tetrahedrons](https://help.tangerina.io/deformable/v0.5.0/user-guides/rust/tools/#stretch-the-tetrahedrons) · [C `DeformableAnisotropy`](https://help.tangerina.io/deformable/v0.5.0/api-references/c/tools/#deformableanisotropy) · [Python `Anisotropy`](https://help.tangerina.io/deformable/v0.5.0/api-references/python/tools/#anisotropy)

### Anisotropy::clamped

**Method** · `deformable::tools::Anisotropy::clamped`

```rust
pub fn clamped(self) -> Self
```

The anisotropy as the tools use it: the scale clamped to `[0.02, 50]` and each direction component to
`[-100, 100]`. A NaN stays NaN.

### Anisotropy::is_finite

**Method** · `deformable::tools::Anisotropy::is_finite`

```rust
pub fn is_finite(&self) -> bool
```

True when the scale and every direction component are finite: neither NaN nor infinite.

## DensityRegion

**Struct** · `deformable::tools::DensityRegion`

```rust
pub struct DensityRegion {
    pub points: Vec<Vector3>,
    pub scale: f64,
}
```

A convex region of the cage meshed finer (scale above 1) or coarser (scale below 1) than the rest, one of the
density regions of [`TetrahedralizeParameters`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/tools/#tetrahedralizeparameters).

Regions whose hulls meet form one group, meshed at the size of its largest scale: the tetrahedrons that meet a
region of the group are carved out, and the hole is meshed again at that size. Where the hole reaches the cage, the
cage faces it reaches are triangulated again at that size too: the mesh boundary there gets new points and smaller
triangles, and the cage vertices keep their positions. A group whose largest scale is 1 changes nothing. A region
that cannot be used is skipped, not an error, and the [`Tetrahedralization`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/tools/#tetrahedralization) lists it.

**Fields**

- `points` ([`Vec<Vector3>`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/math/#vector3)): The region's points, in the cage's space; the region is their convex hull. Fewer than 4 points, or a NaN or
  infinite one, skip the region.
- `scale` (`f64`): The density factor: inside the region the tetrahedron size is the maximum edge length over the cube root of
  the scale, so 8 halves it. A scale of 0 or less counts as 1; a NaN scale skips the region.

**Implements** `Clone` · `Debug` · `PartialEq` · `Send` · `Sync`

**Example**

```rust
// Tetrahedrons half the size near one corner of the cube.
let points = vec![Vector3::ZERO, Vector3::X, Vector3::Y, Vector3::Z];
let parameters = TetrahedralizeParameters {
    maximum_edge_length: 0.3,
    anisotropy: [Anisotropy::default(); 2],
    density_regions: vec![DensityRegion { points, scale: 8.0 }],
};
let result = tetrahedralize(&cage, &parameters, None)?;
```

**See also** [Guide: Mesh some parts finer](https://help.tangerina.io/deformable/v0.5.0/user-guides/rust/tools/#mesh-some-parts-finer) · [C `DeformableDensityRegion`](https://help.tangerina.io/deformable/v0.5.0/api-references/c/tools/#deformabledensityregion) · [Python `DensityRegion`](https://help.tangerina.io/deformable/v0.5.0/api-references/python/tools/#densityregion)

## TetrahedralizeParameters

**Struct** · `deformable::tools::TetrahedralizeParameters`

```rust
pub struct TetrahedralizeParameters {
    pub maximum_edge_length: f64,
    pub anisotropy: [Anisotropy; 2],
    pub density_regions: Vec<DensityRegion>,
}
```

The inputs of [`tetrahedralize`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/tools/#tetrahedralize): the size limit, the two stretches of the mesher space and the density regions.
It has no default: the size limit is always the caller's choice.

**Fields**

- `maximum_edge_length` (`f64`): The cap on the tetrahedron size inside the volume, in the cage's unit, measured in the stretched mesher space;
  near the cage the size follows the cage triangles. 0 or less gives
  [`ErrorKind::MeshingFailed`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-meshingfailed); NaN or infinite meshes the cage with no size
  limit.
- `anisotropy` ([`[Anisotropy; 2]`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/tools/#anisotropy)): The two stretches of the mesher space, each clamped as [`Anisotropy::clamped`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/tools/#anisotropy-clamped) does;
  `[Anisotropy::default(); 2]` stretches nothing.
- `density_regions` ([`Vec<DensityRegion>`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/tools/#densityregion)): The regions meshed finer or coarser than the rest; empty for none.

**Implements** `Clone` · `Debug` · `PartialEq` · `Send` · `Sync`

**Example**

```rust
// Tetrahedrons of at most 0.25 inside the cube, with no stretch.
let parameters = TetrahedralizeParameters {
    maximum_edge_length: 0.25,
    anisotropy: [Anisotropy::default(); 2],
    density_regions: Vec::new(),
};
let fine = tetrahedralize(&cage, &parameters, None)?.mesh;
```

**See also** [Guide: Fill a cage with tetrahedrons](https://help.tangerina.io/deformable/v0.5.0/user-guides/rust/tools/#fill-a-cage-with-tetrahedrons) · [C `DeformableTetrahedralizeParameters`](https://help.tangerina.io/deformable/v0.5.0/api-references/c/tools/#deformabletetrahedralizeparameters) · [Python `TetrahedralizeParameters`](https://help.tangerina.io/deformable/v0.5.0/api-references/python/tools/#tetrahedralizeparameters)

## Tetrahedralization

**Struct** · `deformable::tools::Tetrahedralization`

```rust
pub struct Tetrahedralization {
    pub mesh: TetrahedralMesh,
    pub skipped_density_regions: Vec<usize>,
}
```

The result of [`tetrahedralize`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/tools/#tetrahedralize): the mesh, and the density regions the call skipped.

**Fields**

- `mesh` ([`TetrahedralMesh`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/meshes/#tetrahedralmesh)): The tetrahedral mesh: every tetrahedron positively oriented, the cage vertices at their input positions, and
  every node in a tetrahedron.
- `skipped_density_regions` (`Vec<usize>`): The indices of the density regions the call skipped, in ascending order: those with fewer than 4 points, a
  NaN or infinite point, or a NaN scale.

**Implements** `Clone` · `Debug` · `PartialEq` · `Send` · `Sync`

**See also** [Guide: Fill a cage with tetrahedrons](https://help.tangerina.io/deformable/v0.5.0/user-guides/rust/tools/#fill-a-cage-with-tetrahedrons) · [C `DeformableTetrahedralization`](https://help.tangerina.io/deformable/v0.5.0/api-references/c/tools/#deformabletetrahedralization) · [C `DeformableTetrahedralizationView`](https://help.tangerina.io/deformable/v0.5.0/api-references/c/tools/#deformabletetrahedralizationview) · [Python `Tetrahedralization`](https://help.tangerina.io/deformable/v0.5.0/api-references/python/tools/#tetrahedralization)

## tetrahedralize

**Function** · `deformable::tools::tetrahedralize`

```rust
pub fn tetrahedralize(
    cage: &TriangleMesh,
    parameters: &TetrahedralizeParameters,
    cancel: Option<&CancelFlag>,
) -> Result<Tetrahedralization, Error>
```

Fills a closed triangle cage with tetrahedrons, on the calling thread. The cage triangles become the boundary of
the mesh, except where a density region reaches the cage: there the cage faces are triangulated again at the
region's size, with new boundary points. The cage vertices keep their positions, and a vertex no triangle uses
is dropped. Every tetrahedron is
positively oriented, as [`Scene::add_object`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/scene/#scene-add_object) requires, and
every node belongs to a tetrahedron.

**Parameters**

- `cage` ([`&TriangleMesh`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/meshes/#trianglemesh)): A closed cage with outward normals and no self-intersections.
- `parameters` ([`&TetrahedralizeParameters`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/tools/#tetrahedralizeparameters)): The size limit, the two stretches and the density regions.
- `cancel` ([`Option<&CancelFlag>`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#cancelflag)): Stops the call when another thread sets it.

**Returns**

[`Tetrahedralization`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/tools/#tetrahedralization): The mesh, and the indices of the density regions the call skipped. A density region that cannot be used is
skipped, not an error.

**Errors**

- [`InvalidCage`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-invalidcage): The cage has no triangle, a NaN or infinite
  position, or a triangle with a corner past the positions or a repeated corner; or it is not closed and
  consistently outward, or it crosses itself.
- [`MeshingFailed`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-meshingfailed): `maximum_edge_length` is 0 or less, or the
  mesher stopped without a mesh.
- [`NoTetrahedrons`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-notetrahedrons): The mesh has no tetrahedron.
- [`BadScales`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-badscales): An anisotropy scale or direction component is NaN; an
  infinite one is clamped.
- [`OutputTooLarge`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-outputtoolarge): At `maximum_edge_length`, the cage would hold
  more regular tetrahedrons than 32-bit indices address, or so would the part a group of density regions carves
  out, at the group's size, or the cage faces that part reaches would hold more triangles. These are estimates,
  checked before the run they limit for a mesh that reaches the size everywhere, so a cage much coarser than the
  size is refused too. The nodes the groups add are counted as they are added, and may not pass that limit
  either.
- [`Cancelled`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-cancelled): Another thread set `cancel`.

**Example**

```rust
let parameters = TetrahedralizeParameters {
    maximum_edge_length: 0.3,
    anisotropy: [Anisotropy::default(); 2],
    density_regions: Vec::new(),
};
let result = tetrahedralize(&cage, &parameters, None)?;
println!("{} tetrahedrons", result.mesh.tetrahedrons.len());
```

**See also** [Guide: Fill a cage with tetrahedrons](https://help.tangerina.io/deformable/v0.5.0/user-guides/rust/tools/#fill-a-cage-with-tetrahedrons) · [C `deformable_tetrahedralize`](https://help.tangerina.io/deformable/v0.5.0/api-references/c/tools/#deformable_tetrahedralize) · [Python `tetrahedralize`](https://help.tangerina.io/deformable/v0.5.0/api-references/python/tools/#tetrahedralize)

## TriangulateParameters

**Struct** · `deformable::tools::TriangulateParameters`

```rust
pub struct TriangulateParameters {
    pub maximum_area: Option<f64>,
    pub quality: f64,
    pub anisotropy: [Anisotropy; 2],
    pub closed_boundary: bool,
}
```

The inputs of [`triangulate`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/tools/#triangulate): the area limit, the minimum angle, the two stretches of the mesher space and the
closed boundary check. `TriangulateParameters::default()` gives area 1, a minimum angle of 20 degrees, no stretch
and the closed boundary check on.

**Fields**

- `maximum_area` (`Option<f64>`): The largest triangle area, measured in the stretched mesher space; `None`, 0 or less sets no limit. Default
  `Some(1.0)`.
- `quality` (`f64`): The minimum triangle angle, in degrees: 0 or less runs as 2, and the rest is clamped to `[1, 20]`. Default
  `20`.
- `anisotropy` ([`[Anisotropy; 2]`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/tools/#anisotropy)): The two stretches of the mesher space, each clamped as [`Anisotropy::clamped`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/tools/#anisotropy-clamped) does. Default
  `[Anisotropy::default(); 2]`, no stretch.
- `closed_boundary` (`bool`): Refuses an edge that borders only one polygon, with
  [`ErrorKind::NonClosedBoundary`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-nonclosedboundary); turn it off for a non-closed mesh.
  Default `true`.

**Implements** `Clone` · `Copy` · `Debug` · `Default` · `PartialEq` · `Send` · `Sync`

**Example**

```rust
let parameters = TriangulateParameters {
    maximum_area: Some(0.05),
    quality: 15.0,
    ..TriangulateParameters::default()
};
let fine = triangulate(&polygons, &[], &parameters, None)?.mesh;
```

**See also** [Guide: Triangulate a polygon mesh](https://help.tangerina.io/deformable/v0.5.0/user-guides/rust/tools/#triangulate-a-polygon-mesh) · [C `DeformableTriangulateParameters`](https://help.tangerina.io/deformable/v0.5.0/api-references/c/tools/#deformabletriangulateparameters) · [Python `TriangulateParameters`](https://help.tangerina.io/deformable/v0.5.0/api-references/python/tools/#triangulateparameters)

## Triangulation

**Struct** · `deformable::tools::Triangulation`

```rust
pub struct Triangulation {
    pub mesh: TriangleMesh,
    pub source_polygons: Vec<u32>,
}
```

The result of [`triangulate`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/tools/#triangulate): the triangle mesh, and the input polygon of each triangle. Triangles come
grouped by polygon in input order, and each follows its polygon's winding.

**Fields**

- `mesh` ([`TriangleMesh`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/meshes/#trianglemesh)): The points, in order of first appearance with unused input vertices dropped, and the triangles.
- `source_polygons` (`Vec<u32>`): The input polygon each triangle was made from, one per triangle, so per-polygon data such as materials can
  carry over to the triangles.

**Implements** `Clone` · `Debug` · `Default` · `PartialEq` · `Send` · `Sync`

**See also** [Guide: Triangulate a polygon mesh](https://help.tangerina.io/deformable/v0.5.0/user-guides/rust/tools/#triangulate-a-polygon-mesh) · [C `DeformableTriangulation`](https://help.tangerina.io/deformable/v0.5.0/api-references/c/tools/#deformabletriangulation) · [C `DeformableTriangulationView`](https://help.tangerina.io/deformable/v0.5.0/api-references/c/tools/#deformabletriangulationview) · [Python `Triangulation`](https://help.tangerina.io/deformable/v0.5.0/api-references/python/tools/#triangulation)

## triangulate

**Function** · `deformable::tools::triangulate`

```rust
pub fn triangulate(
    cage: &PolygonMesh,
    holes: &[FaceHole],
    parameters: &TriangulateParameters,
    cancel: Option<&CancelFlag>,
) -> Result<Triangulation, Error>
```

Re-triangulates each polygon of a polygon mesh, holes included, under an area limit and a minimum angle, on the
calling thread.

Each polygon is triangulated in its own plane, in the stretched mesher space. Where two polygons share an edge,
the points added on it are shared too, so a closed mesh stays closed; the inner points of a non-planar polygon
get a height interpolated from its boundary. Triangles follow the winding of their polygon. When the polygons
cannot reach the minimum angle, the call retries at 0.9 times the angle while it stays at least 1 degree.

**Parameters**

- `cage` ([`&PolygonMesh`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/meshes/#polygonmesh)): The polygons: their positions, and the corners of each one, its hole runs included.
- `holes` ([`&[FaceHole]`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/meshes/#facehole)): The runs of polygon corners that form hole loops; empty when no polygon has a hole.
- `parameters` ([`&TriangulateParameters`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/tools/#triangulateparameters)): The area limit, the minimum angle, the two stretches and the closed boundary check.
- `cancel` ([`Option<&CancelFlag>`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#cancelflag)): Stops the call when another thread sets it.

**Returns**

[`Triangulation`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/tools/#triangulation): The triangle mesh, and the input polygon of each triangle.

**Errors**

- [`NonFiniteValue`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-nonfinitevalue): A position of `cage`, the area limit, the
  minimum angle, or an anisotropy scale or direction component is NaN or infinite.
- [`EmptyMesh`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-emptymesh): `cage` has no vertices or no polygons.
- [`IndexOutOfRange`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-indexoutofrange): A corner names a vertex past the positions,
  a polygon's corners or a hole run go past the end of their list, a hole names a polygon past the last, or
  corners are left over after the last polygon. The error's first index names the polygon, or the polygon count
  for corners left over.
- [`DegeneratePolygon`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-degeneratepolygon): A polygon has a loop of fewer than 3
  vertices or a zero normal, no outer loop, or an edge it uses twice, or the triangulator cannot mesh its loops,
  as when they cross in its plane. The error's first index names the polygon.
- [`NonManifoldEdge`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-nonmanifoldedge): An edge borders three or more polygons.
  The error's two indices name its vertices.
- [`NonClosedBoundary`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-nonclosedboundary): `closed_boundary` is on and an edge borders
  only one polygon. The error's two indices name its vertices.
- [`OutputTooLarge`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-outputtoolarge): The polygons' area, in the stretched mesher
  space, would hold more triangles of the area limit than 32-bit indices address. It is checked before
  triangulating.
- [`CouldNotConverge`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-couldnotconverge): The polygons did not settle at any
  minimum angle down to 1 degree.
- [`Cancelled`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-cancelled): Another thread set `cancel`.

**Example**

```rust
let parameters = TriangulateParameters {
    maximum_area: Some(0.1),
    ..TriangulateParameters::default()
};
let result = triangulate(&polygons, &[], &parameters, None)?;
// Each triangle names the face of the cube it came from.
assert!(result.source_polygons.iter().all(|&face| face < 6));
```

**See also** [Guide: Triangulate a polygon mesh](https://help.tangerina.io/deformable/v0.5.0/user-guides/rust/tools/#triangulate-a-polygon-mesh) · [C `deformable_triangulate`](https://help.tangerina.io/deformable/v0.5.0/api-references/c/tools/#deformable_triangulate) · [Python `triangulate`](https://help.tangerina.io/deformable/v0.5.0/api-references/python/tools/#triangulate)

## ExtrudeDirection

**Enum** · `deformable::tools::ExtrudeDirection`

```rust
pub enum ExtrudeDirection {
    Up,
    Down,
    Both,
}
```

Where [`extrude`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/tools/#extrude) puts the two layers of its shell, along each vertex's unit normal. The normal points to the side
from which the faces' corners run counter-clockwise. `ExtrudeDirection::default()` is [`Both`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/tools/#extrudedirection-both).

**Values**

- `Up`: The mesh, and a copy `thickness` along the normal.
- `Down`: The mesh, and a copy `thickness` against the normal.
- `Both`: Two copies, half of `thickness` on each side of the mesh. The default.

**Implements** `Clone` · `Copy` · `Debug` · `Default` · `Eq` · `PartialEq` · `Send` · `Sync`

**See also** [Guide: Extrude a triangle mesh into a shell](https://help.tangerina.io/deformable/v0.5.0/user-guides/rust/tools/#extrude-a-triangle-mesh-into-a-shell) · [C `DeformableExtrudeDirection`](https://help.tangerina.io/deformable/v0.5.0/api-references/c/tools/#deformableextrudedirection) · [Python `ExtrudeDirection`](https://help.tangerina.io/deformable/v0.5.0/api-references/python/tools/#extrudedirection)

## extrude

**Function** · `deformable::tools::extrude`

```rust
pub fn extrude(
    mesh: &TriangleMesh,
    thickness: f64,
    direction: ExtrudeDirection,
) -> Result<TetrahedralMesh, Error>
```

Turns a triangle mesh into a shell `thickness` thick, on the calling thread: each vertex moves along its unit
angle-weighted normal, which gives 2 points per vertex and 3 tetrahedrons per triangle, with no added points.

The mesh can be non-closed, for sheets, plates and other thin objects. A face wound against its neighbours counts
with its normal flipped. A vertex on no face keeps both of its points at its position and is in no tetrahedron.
A mesh with no vertices or no triangles gives an empty tetrahedral mesh.

Nothing checks the tetrahedrons: they come out positively oriented, but on sharp curvature a thick shell can
invert some, and [`Scene::add_object`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/scene/#scene-add_object) then refuses the mesh. Use
a thinner shell or a smoother mesh there. Nor are the positions checked: a NaN or infinite position, or an
infinite `thickness`, gives NaN or infinite points.

**Parameters**

- `mesh` ([`&TriangleMesh`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/meshes/#trianglemesh)): The triangle mesh to thicken, open or closed.
- `thickness` (`f64`): The shell's thickness, in the mesh's unit; it must be above 0.
- `direction` ([`ExtrudeDirection`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/tools/#extrudedirection)): Where the two layers go: on the normal side, on the other side, or half on each.

**Returns**

[`TetrahedralMesh`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/meshes/#tetrahedralmesh): The shell: the points of the layer on the normal side, one per vertex, then those of the other layer, and 3
tetrahedrons per triangle, in triangle order.

**Errors**

- [`NonPositiveThickness`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-nonpositivethickness): `thickness` is 0 or less, or NaN,
  even for an empty mesh.
- [`UnknownVertex`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-unknownvertex): A triangle names a vertex past the end of the
  positions. The error's first index names the triangle.
- [`DuplicateVertex`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-duplicatevertex): A triangle uses one vertex at two corners.
  The error's first index names the triangle.
- [`DegenerateFace`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-degenerateface): A triangle has a zero normal: its corners lie
  on one line. The error's first index names the triangle.
- [`MultipleBoundaries`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-multipleboundaries): The triangles around a vertex form
  more than one fan, as where two parts of the mesh touch at that vertex only. The error's first index names
  the vertex.
- [`NullNormal`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-nullnormal): The angle-weighted normals of the triangles around a
  vertex cancel out. The error's first index names the vertex.

**Example**

```rust
// A hollow cube: walls 0.1 thick, centred on the cage's faces.
let shell = extrude(&cage, 0.1, ExtrudeDirection::Both)?;
assert_eq!(shell.positions.len(), 2 * cage.positions.len());
assert_eq!(shell.tetrahedrons.len(), 3 * cage.triangles.len());
```

**See also** [Guide: Extrude a triangle mesh into a shell](https://help.tangerina.io/deformable/v0.5.0/user-guides/rust/tools/#extrude-a-triangle-mesh-into-a-shell) · [C `deformable_extrude`](https://help.tangerina.io/deformable/v0.5.0/api-references/c/tools/#deformable_extrude) · [Python `extrude`](https://help.tangerina.io/deformable/v0.5.0/api-references/python/tools/#extrude)

## span_layers

**Function** · `deformable::tools::span_layers`

```rust
pub fn span_layers(
    first_layer: &TriangleMesh,
    second_layer: &TriangleMesh,
) -> Result<TetrahedralMesh, Error>
```

Fills the space between two triangle meshes with the same vertices and faces, such as a mesh and a moved
copy of it, on the calling thread: each triangle and its partner make a prism of 3 tetrahedrons.

Only the first layer's triangles are used; each must match exactly one triangle of the second layer, with the
same vertices and winding, up to a rotation of its corners. The tetrahedrons come out positively oriented
whichever layer is on top. Layers that touch give flat tetrahedrons, which are kept, and which
[`Scene::add_object`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/scene/#scene-add_object) then refuses. Layers with no vertices or no
triangles give an empty mesh. The positions are not checked: a NaN or infinite one passes into the mesh.

**Parameters**

- `first_layer` ([`&TriangleMesh`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/meshes/#trianglemesh)): One side of the space, whose triangles the tetrahedrons follow.
- `second_layer` ([`&TriangleMesh`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/meshes/#trianglemesh)): The other side: the same number of vertices, and the same triangles up to a rotation of each
  one's corners.

**Returns**

[`TetrahedralMesh`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/meshes/#tetrahedralmesh): The mesh: the first layer's positions, then the second layer's, and 3 tetrahedrons per triangle, in triangle
order.

**Errors**

- [`NotIsomorphic`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-notisomorphic): The layers differ in vertex or triangle count,
  or a triangle of the first layer does not match exactly one triangle of the second.
- [`UnknownVertex`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-unknownvertex): A triangle names a vertex past the end of the
  positions. The error's first index names the triangle.
- [`DuplicateVertex`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-duplicatevertex): A triangle uses one vertex at two corners.
  The error's first index names the triangle.
- [`MultipleBoundaries`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-multipleboundaries): The triangles around a vertex form
  more than one fan, as where two parts of the mesh touch at that vertex only. The error's first index names
  the vertex.

**Example**

```rust
// A hollow box: the cage, and a copy three times its size around it.
let grow = |point: Vector3| point * 3.0 - Vector3::new(1.0, 1.0, 1.0);
let outer = TriangleMesh {
    positions: cage.positions.iter().copied().map(grow).collect(),
    triangles: cage.triangles.clone(),
};
let walls = span_layers(&cage, &outer)?;
assert_eq!(walls.tetrahedrons.len(), 3 * cage.triangles.len());
```

**See also** [Guide: Fill the space between two layers](https://help.tangerina.io/deformable/v0.5.0/user-guides/rust/tools/#fill-the-space-between-two-layers) · [C `deformable_span_layers`](https://help.tangerina.io/deformable/v0.5.0/api-references/c/tools/#deformable_span_layers) · [Python `span_layers`](https://help.tangerina.io/deformable/v0.5.0/api-references/python/tools/#span_layers)

## AutocageParameters

**Struct** · `deformable::tools::AutocageParameters`

```rust
pub struct AutocageParameters {
    pub scale_gap: f64,
    pub target_face_count: i32,
    pub target_tetrahedron_count: i32,
}
```

The inputs of [`autocage`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/tools/#autocage): the gap between the cage and the mesh, and the size of the cage's triangles, set by a
face target or else a tetrahedron target. `AutocageParameters::default()` gives scale gap 1, a target of 300
faces and no tetrahedron target.

The counts are targets, not exact results. With neither target, the triangles are sized from the mesh's bounding
box alone.

**Fields**

- `scale_gap` (`f64`): Multiplies the gap the cage keeps from the mesh, which follows the size of the cage's triangles; NaN or
  infinite gives [`ErrorKind::NonFiniteValue`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-nonfinitevalue). Default `1.0`, clamped to
  `[0.1, 10]`.
- `target_face_count` (`i32`): The number of triangles the cage aims for; 0 or less leaves the size to `target_tetrahedron_count`. Default
  `300`.
- `target_tetrahedron_count` (`i32`): When there is no face target, the number of tetrahedrons the cage's volume aims for, which sizes its
  triangles; 0 or less sets none. Default `0`.

**Implements** `Clone` · `Copy` · `Debug` · `Default` · `PartialEq` · `Send` · `Sync`

**Example**

```rust
// A coarser cage than the default, kept twice as far out.
let parameters = AutocageParameters {
    scale_gap: 2.0,
    target_face_count: 100,
    ..AutocageParameters::default()
};
let wrapped = autocage(&polygons, &parameters, None)?;
```

**See also** [Guide: Wrap any mesh in a cage](https://help.tangerina.io/deformable/v0.5.0/user-guides/rust/tools/#wrap-any-mesh-in-a-cage) · [C `DeformableAutocageParameters`](https://help.tangerina.io/deformable/v0.5.0/api-references/c/tools/#deformableautocageparameters) · [Python `AutocageParameters`](https://help.tangerina.io/deformable/v0.5.0/api-references/python/tools/#autocageparameters)

## autocage

**Function** · `deformable::tools::autocage`

```rust
pub fn autocage(
    mesh: &PolygonMesh,
    parameters: &AutocageParameters,
    cancel: Option<&CancelFlag>,
) -> Result<TriangleMesh, Error>
```

Wraps any polygon mesh, open or closed, in a closed, outward cage of near-equilateral triangles at a small gap
outside it, on the calling thread, for [`tetrahedralize`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/tools/#tetrahedralize) to fill. It makes no
tetrahedrons itself.

The cage grows as a front of triangles around the mesh. A front that fails starts again with a target triangle
area one percent larger each time, up to 7 times. The face and tetrahedron counts of `parameters` are targets,
not exact results.

**Parameters**

- `mesh` ([`&PolygonMesh`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/meshes/#polygonmesh)): The polygon mesh to wrap, open or closed.
- `parameters` ([`&AutocageParameters`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/tools/#autocageparameters)): The gap, and the face or tetrahedron target that sizes the cage's triangles.
- `cancel` ([`Option<&CancelFlag>`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#cancelflag)): Stops the call when another thread sets it.

**Returns**

[`TriangleMesh`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/meshes/#trianglemesh): The cage: a closed triangle mesh with outward normals around `mesh`, ready for
[`tetrahedralize`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/tools/#tetrahedralize).

**Errors**

- [`NonFiniteValue`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-nonfinitevalue): `scale_gap` or a position of `mesh` is NaN or
  infinite, or the mesh is so large that its size overflows.
- [`IndexOutOfRange`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-indexoutofrange): A polygon's corners run past the end of the
  corner list or name a vertex past the positions, or corners are left over after the last polygon. The error's
  first index names the polygon, or the polygon count for corners left over.
- [`EmptyInput`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-emptyinput): No polygon has 3 or more corners, or all the vertices
  the polygons use coincide.
- [`OutputTooLarge`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-outputtoolarge): The targets ask for triangles with an edge
  under `4.28e-3` times half the largest side of the mesh's bounding box, finer than the tool resolves. It is
  checked before the cage grows.
- [`StepLimitReached`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-steplimitreached): The cage did not close within its step
  limit, 1,000 steps per expected triangle and at least 100,000, restarts included.
- [`Cancelled`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-cancelled): Another thread set `cancel`.

**Example**

```rust
let parameters = AutocageParameters::default();
let wrapped = autocage(&polygons, &parameters, None)?;
let parameters = TetrahedralizeParameters {
    maximum_edge_length: 0.5,
    anisotropy: [Anisotropy::default(); 2],
    density_regions: Vec::new(),
};
let filled = tetrahedralize(&wrapped, &parameters, None)?.mesh;
```

**See also** [Guide: Wrap any mesh in a cage](https://help.tangerina.io/deformable/v0.5.0/user-guides/rust/tools/#wrap-any-mesh-in-a-cage) · [C `deformable_autocage`](https://help.tangerina.io/deformable/v0.5.0/api-references/c/tools/#deformable_autocage) · [Python `autocage`](https://help.tangerina.io/deformable/v0.5.0/api-references/python/tools/#autocage)

## PixelGrid

**Struct** · `deformable::tools::PixelGrid`

```rust
pub struct PixelGrid {
    pub width: u32,
    pub height: u32,
    pub pixels: Vec<[u8; 3]>,
}
```

An image decoded by the host, for [`splinters_from_image`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/tools/#splinters_from_image): 8-bit red, green and blue pixels, row 0 at the bottom
(y up, as a BMP stores it). The library never reads image files.

**Fields**

- `width` (`u32`): Pixels per row; 0 gives [`ErrorKind::EmptyImage`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-emptyimage).
- `height` (`u32`): Number of rows; 0 gives [`ErrorKind::EmptyImage`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-emptyimage).
- `pixels` (`Vec<[u8; 3]>`): The pixels as `[red, green, blue]`, row after row, bottom row first: `width` times `height` of them, or the
  call gives [`ErrorKind::LengthMismatch`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-lengthmismatch).

**Implements** `Clone` · `Debug` · `Default` · `Eq` · `PartialEq` · `Send` · `Sync`

**Example**

```rust
// A 9 by 9 square outline: black sides, red corners, white inside.
let edge = |at: u32| usize::from(at == 0 || at == 8);
let colours = [[255, 255, 255], [0, 0, 0], [255, 0, 0]];
let pixels = (0..81)
    .map(|pixel| colours[edge(pixel % 9) + edge(pixel / 9)])
    .collect();
let image = PixelGrid { width: 9, height: 9, pixels };
```

**See also** [Guide: Make a splinter cage from a drawing](https://help.tangerina.io/deformable/v0.5.0/user-guides/rust/tools/#make-a-splinter-cage-from-a-drawing) · [C `DeformablePixelGrid`](https://help.tangerina.io/deformable/v0.5.0/api-references/c/tools/#deformablepixelgrid) · [Python `PixelGrid`](https://help.tangerina.io/deformable/v0.5.0/api-references/python/tools/#pixelgrid)

## SplinterImageParameters

**Struct** · `deformable::tools::SplinterImageParameters`

```rust
pub struct SplinterImageParameters {
    pub size: Vector3,
    pub origin: Vector3,
    pub allow_nonconvex: bool,
}
```

The inputs of [`splinters_from_image`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/tools/#splinters_from_image): where the cage lies, how deep it is, and whether the traced cell outlines
are kept. `SplinterImageParameters::default()` gives size (1, 1, 1), origin (0, 0, 0) and non-convex cells
allowed.

**Fields**

- `size` ([`Vector3`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/math/#vector3)): The size the image covers in x and y, and the cage's depth; a NaN or infinite component gives
  [`ErrorKind::NonFiniteValue`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-nonfinitevalue). Default `Vector3::new(1.0, 1.0, 1.0)`.
- `origin` ([`Vector3`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/math/#vector3)): The image's lower-left corner in x and y, and the z of the cage's top face; the bottom face sits one depth
  lower. A NaN or infinite component gives [`ErrorKind::NonFiniteValue`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-nonfinitevalue).
  Default `Vector3::ZERO`.
- `allow_nonconvex` (`bool`): Keeps the traced cell outlines; off, the bends in each wall between two cells are dissolved, so that it runs
  straight between junctions. Default `true`.

**Implements** `Clone` · `Copy` · `Debug` · `Default` · `PartialEq` · `Send` · `Sync`

**Example**

```rust
// The image over 2 by 2 units around the origin, a cage 0.1 deep
// with its top face at z = 0.5 and straight cell sides.
let parameters = SplinterImageParameters {
    size: Vector3::new(2.0, 2.0, 0.1),
    origin: Vector3::new(-1.0, -1.0, 0.5),
    allow_nonconvex: false,
};
```

**See also** [Guide: Make a splinter cage from a drawing](https://help.tangerina.io/deformable/v0.5.0/user-guides/rust/tools/#make-a-splinter-cage-from-a-drawing) · [C `DeformableSplinterImageParameters`](https://help.tangerina.io/deformable/v0.5.0/api-references/c/tools/#deformablesplinterimageparameters) · [Python `SplinterImageParameters`](https://help.tangerina.io/deformable/v0.5.0/api-references/python/tools/#splinterimageparameters)

## splinters_from_image

**Function** · `deformable::tools::splinters_from_image`

```rust
pub fn splinters_from_image(
    image: &PixelGrid,
    parameters: &SplinterImageParameters,
) -> Result<PolygonMesh, Error>
```

Turns a line drawing into a splinter cage, one closed prism per cell, on the calling thread. Pass the cage to
[`embed_surface`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/render-surfaces/#embed_surface), and the render surface breaks into those splinters.

The drawing is black lines on white. A pixel is black when its red is below 128 and its green plus blue is 15 or
less. The lines must close every cell and join into one connected drawing. A red pixel, whose red is 128 or more and
at least 8 times its green plus blue, marks a corner where a line bends without meeting another line. Every other
pixel is background. Neighbouring prisms share their corner points. The tracing warnings, such as a line that ends
nowhere, do not stop the call and are not returned.

**Parameters**

- `image` ([`&PixelGrid`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/tools/#pixelgrid)): The drawing: black lines between the cells, red marks at the corners where a line bends.
- `parameters` ([`&SplinterImageParameters`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/tools/#splinterimageparameters)): Where the cage lies, how deep it is, and whether the traced cell outlines are kept.

**Returns**

[`PolygonMesh`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/meshes/#polygonmesh): The cage: the top points, then the bottom points; the top faces, then the bottom faces, then a side quad for each
side of a wall that borders a cell.

**Errors**

- [`EmptyImage`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-emptyimage): `width` or `height` is 0.
- [`LengthMismatch`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-lengthmismatch): The pixel count is not `width` times `height`.
- [`NonFiniteValue`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-nonfinitevalue): A component of `size` or `origin` is NaN or
  infinite.
- [`NoVertices`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-novertices): The drawing has no red mark and no place where lines
  meet, or none is left once the loose line ends are cleaned up: it is blank, or holds only an open line or a
  closed line without a red mark.
- [`NoCells`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-nocells): The drawing has vertices, but its lines close no cell.
- [`EndlessCycle`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-endlesscycle): Tracing a cell took more steps than there are
  vertices.
- [`FaceAlreadySet`](https://help.tangerina.io/deformable/v0.5.0/api-references/rust/errors/#errorkind-facealreadyset): Tracing a cell met a wall side that another
  cell already holds. Loose line ends with red marks can cause it, such as a T on its own with red marks at its
  three ends.

**Example**

```rust
let edge = |at: u32| usize::from(at == 0 || at == 8);
let colours = [[255, 255, 255], [0, 0, 0], [255, 0, 0]];
let pixels = (0..81)
    .map(|pixel| colours[edge(pixel % 9) + edge(pixel / 9)])
    .collect();
let image = PixelGrid { width: 9, height: 9, pixels };
let cage = splinters_from_image(&image, &Default::default())?;
assert_eq!(cage.polygon_sizes, [4; 6]); // A top, a bottom, 4 sides.
```

**See also** [Guide: Make a splinter cage from a drawing](https://help.tangerina.io/deformable/v0.5.0/user-guides/rust/tools/#make-a-splinter-cage-from-a-drawing) · [C `deformable_splinters_from_image`](https://help.tangerina.io/deformable/v0.5.0/api-references/c/tools/#deformable_splinters_from_image) · [Python `splinters_from_image`](https://help.tangerina.io/deformable/v0.5.0/api-references/python/tools/#splinters_from_image)
