You are viewing the documentation for Deformable v0.1.1, an older version. Read the latest, v0.9.0

Rust API Reference

Tools

Tetrahedralize, triangulate, extrude, span layers, autocage and splinters from an image, with their parameters and results.

On this page

The tools turn polygon meshes, triangle meshes and images into closed cages and tetrahedral meshes, the meshes a 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 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 and 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. 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)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 · C DeformableAnisotropy · Python 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.

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 lists it.

Fields

  • points (Vec<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 · C DeformableDensityRegion · Python 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: 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; NaN or infinite meshes the cage with no size limit.
  • anisotropy ([Anisotropy; 2])The two stretches of the mesher space, each clamped as Anisotropy::clamped does; [Anisotropy::default(); 2] stretches nothing.
  • density_regions (Vec<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 · C DeformableTetrahedralizeParameters · Python TetrahedralizeParameters

Tetrahedralization

Struct · deformable::tools::Tetrahedralization

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

The result of tetrahedralize: the mesh, and the density regions the call skipped.

Fields

  • mesh (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 · C DeformableTetrahedralization · C DeformableTetrahedralizationView · Python 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 requires, and every node belongs to a tetrahedron.

Parameters

Returns

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

  • InvalidCageThe 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.
  • MeshingFailedmaximum_edge_length is 0 or less, or the mesher stopped without a mesh.
  • NoTetrahedronsThe mesh has no tetrahedron.
  • BadScalesAn anisotropy scale or direction component is NaN; an infinite one is clamped.
  • OutputTooLargeAt 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.
  • CancelledAnother thread set cancel.
  • The license kinds every engine call can return.

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 · C deformable_tetrahedralize · Python 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: 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])The two stretches of the mesher space, each clamped as Anisotropy::clamped does. Default [Anisotropy::default(); 2], no stretch.
  • closed_boundary (bool)Refuses an edge that borders only one polygon, with 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 · C DeformableTriangulateParameters · Python TriangulateParameters

Triangulation

Struct · deformable::tools::Triangulation

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

The result of 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)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 · C DeformableTriangulation · C DeformableTriangulationView · Python 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)The polygons: their positions, and the corners of each one, its hole runs included.
  • holes (&[FaceHole])The runs of polygon corners that form hole loops; empty when no polygon has a hole.
  • parameters (&TriangulateParameters)The area limit, the minimum angle, the two stretches and the closed boundary check.
  • cancel (Option<&CancelFlag>)Stops the call when another thread sets it.

Returns

Triangulation: The triangle mesh, and the input polygon of each triangle.

Errors

  • NonFiniteValueA position of cage, the area limit, the minimum angle, or an anisotropy scale or direction component is NaN or infinite.
  • EmptyMeshcage has no vertices or no polygons.
  • IndexOutOfRangeA 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.
  • DegeneratePolygonA 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.
  • NonManifoldEdgeAn edge borders three or more polygons. The error’s two indices name its vertices.
  • NonClosedBoundaryclosed_boundary is on and an edge borders only one polygon. The error’s two indices name its vertices.
  • OutputTooLargeThe 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.
  • CouldNotConvergeThe polygons did not settle at any minimum angle down to 1 degree.
  • CancelledAnother thread set cancel.
  • The license kinds every engine call can return.

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 · C deformable_triangulate · Python triangulate

ExtrudeDirection

Enum · deformable::tools::ExtrudeDirection

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

Where 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.

Values

  • UpThe mesh, and a copy thickness along the normal.
  • DownThe mesh, and a copy thickness against the normal.
  • BothTwo 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 · C DeformableExtrudeDirection · Python 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 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)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)Where the two layers go: on the normal side, on the other side, or half on each.

Returns

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

  • NonPositiveThicknessthickness is 0 or less, or NaN, even for an empty mesh.
  • UnknownVertexA triangle names a vertex past the end of the positions. The error’s first index names the triangle.
  • DuplicateVertexA triangle uses one vertex at two corners. The error’s first index names the triangle.
  • DegenerateFaceA triangle has a zero normal: its corners lie on one line. The error’s first index names the triangle.
  • MultipleBoundariesThe 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.
  • NullNormalThe angle-weighted normals of the triangles around a vertex cancel out. The error’s first index names the vertex.
  • The license kinds every engine call can return.

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 · C deformable_extrude · Python 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 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)One side of the space, whose triangles the tetrahedrons follow.
  • second_layer (&TriangleMesh)The other side: the same number of vertices, and the same triangles up to a rotation of each one’s corners.

Returns

TetrahedralMesh: The mesh: the first layer’s positions, then the second layer’s, and 3 tetrahedrons per triangle, in triangle order.

Errors

  • NotIsomorphicThe layers differ in vertex or triangle count, or a triangle of the first layer does not match exactly one triangle of the second.
  • UnknownVertexA triangle names a vertex past the end of the positions. The error’s first index names the triangle.
  • DuplicateVertexA triangle uses one vertex at two corners. The error’s first index names the triangle.
  • MultipleBoundariesThe 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.
  • The license kinds every engine call can return.

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 · C deformable_span_layers · Python 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: 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. 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 · C DeformableAutocageParameters · Python 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 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

Returns

TriangleMesh: The cage: a closed triangle mesh with outward normals around mesh, ready for tetrahedralize.

Errors

  • NonFiniteValuescale_gap or a position of mesh is NaN or infinite, or the mesh is so large that its size overflows.
  • IndexOutOfRangeA 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.
  • EmptyInputNo polygon has 3 or more corners, or all the vertices the polygons use coincide.
  • OutputTooLargeThe 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.
  • StepLimitReachedThe cage did not close within its step limit, 1,000 steps per expected triangle and at least 100,000, restarts included.
  • CancelledAnother thread set cancel.
  • The license kinds every engine call can return.

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 · C deformable_autocage · Python 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: 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

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 · C DeformablePixelGrid · Python 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: 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)The size the image covers in x and y, and the cage’s depth; a NaN or infinite component gives ErrorKind::NonFiniteValue. Default Vector3::new(1.0, 1.0, 1.0).
  • origin (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. 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 · C DeformableSplinterImageParameters · Python 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, 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)The drawing: black lines between the cells, red marks at the corners where a line bends.
  • parameters (&SplinterImageParameters)Where the cage lies, how deep it is, and whether the traced cell outlines are kept.

Returns

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

  • EmptyImagewidth or height is 0.
  • LengthMismatchThe pixel count is not width times height.
  • NonFiniteValueA component of size or origin is NaN or infinite.
  • NoVerticesThe 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.
  • NoCellsThe drawing has vertices, but its lines close no cell.
  • EndlessCycleTracing a cell took more steps than there are vertices.
  • FaceAlreadySetTracing 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.
  • The license kinds every engine call can return.

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 · C deformable_splinters_from_image · Python splinters_from_image