You are viewing the documentation for Deformable v0.7.0, an older version. Read the latest, v0.9.0
Python SDK
Tools
Turn polygon meshes, layers and line images into simulation input with the mesh tools, and check meshes before you use them.
On this page
The tools prepare what a scene needs: a closed triangle cage, then a tetrahedral mesh. They also make splinter
cages and check meshes. Every name on this page is in the deformable module. For every parameter and field of
each tool, see the tools reference; the mesh checks are on the
mesh checks reference, and the mesh classes and face helpers on the
meshes reference.
A tool that fails raises DeformableError. Each section below names the statuses its tool raises, and the
status list says what each one means.
The examples on this page build on each other. Run them in order in one Python session, starting with the first.
All tools are plain functions with no global state. They work in the unit of their input, so you can call them before you create a scene. Separate calls can run on several threads at the same time.
| Function | Takes | Returns |
|---|---|---|
triangulate |
A Polygon, with optional holes |
A triangle cage, and the source polygon of each triangle |
tetrahedralize |
A closed, outward Triangle |
A Tetrahedral, and the skipped density regions |
autocage |
Any Polygon |
A closed, outward Triangle around it |
extrude |
A Triangle and a thickness |
A Tetrahedral shell |
span_ |
Two Triangle layers with the same topology |
A Tetrahedral between them |
splinters_ |
A Pixel line image |
A Polygon splinter cage |
verify_ |
A Surface, with optional holes |
A list of Mesh |
meshes_ |
Two Tetrahedral values |
bool |
boundary_ |
A Tetrahedral |
One face mask per tetrahedron |
embed_surface is on Render surfaces, and material_region_indices is
on Scene.
From polygons to tetrahedrons
The usual path has two steps. triangulate turns the artist’s polygons into a fine triangle cage, and
tetrahedralize fills the cage with tetrahedrons. What each tool is for, and how many tetrahedrons to aim for, is on
Preparing meshes in the Engine guide.
import deformable
positions = [(x, y, z) for z in (0.0, 1.0) for y in (0.0, 1.0) for x in (0.0, 1.0)]
quads = [0, 2, 3, 1, 4, 5, 7, 6, 0, 1, 5, 4, 2, 6, 7, 3, 0, 4, 6, 2, 1, 3, 7, 5]
cube = deformable.PolygonMesh(positions, [4] * 6, quads)
refined = deformable.TriangulateParameters.default(maximum_area=0.05)
cage = deformable.triangulate(cube, parameters=refined).mesh
result = deformable.tetrahedralize(cage, deformable.TetrahedralizeParameters(maximum_edge_length=0.3))
print(len(cage.triangles), "triangles,", len(result.mesh.tetrahedrons), "tetrahedrons")214 triangles, 471 tetrahedronsThe cage triangles stay the boundary of the tetrahedral mesh, except where a density region reaches the cage and meshes
the cage faces there again at its size, and cage points never move. So a finer cage gives a finer boundary. When the
input is not closed, or is too detailed to use as a cage, wrap it with autocage instead.
Triangulate a polygon mesh
triangulate(cage, holes=(), parameters=None, cancel=None) triangulates each polygon in its own plane
(Triangulate). Where two
polygons share an edge, the points added on that edge are shared too, so the result stays closed. Triangles follow
the winding of their polygon.
Build the parameters with TriangulateParameters.default(**changes). The values you change most:
maximum_area: the largest triangle area. Smaller gives a finer cage. 0 or less sets no limit.quality: the minimum angle, in degrees, up to 20.closed_boundary: on by default. Every edge must border two polygons, or the call raisesNON_CLOSED_BOUNDARY. Turn it off to triangulate a non-closed mesh.
The result is a Triangulation. Its mesh is the cage, and source_polygons gives the input polygon of each
triangle, so you can carry per-polygon data, such as materials, to the triangles.
A polygon can have holes. Each FaceHole(face, first_corner, corner_count) marks a run of a polygon’s corners as a
hole loop. The corners before the polygon’s first hole form its outer loop.
outline = [(0.0, 0.0, 0.0), (2.0, 0.0, 0.0), (2.0, 1.0, 0.0), (0.0, 1.0, 0.0)]
hole = [(0.75, 0.25, 0.0), (0.75, 0.75, 0.0), (1.25, 0.75, 0.0), (1.25, 0.25, 0.0)]
plate = deformable.PolygonMesh(outline + hole, [8], list(range(8)))
flat_parameters = deformable.TriangulateParameters.default(maximum_area=0.05, closed_boundary=False)
triangulation = deformable.triangulate(plate, [deformable.FaceHole(0, 4, 4)], flat_parameters)
print(len(triangulation.mesh.triangles), set(triangulation.source_polygons))59 {0}The plate is a single open polygon, so closed_boundary must be False. With the default True, the call raises
NON_CLOSED_BOUNDARY, and first_index and second_index name the edge’s two vertices.
Errors: EMPTY_MESH, INDEX_OUT_OF_RANGE (the polygon), NON_FINITE_VALUE, DEGENERATE_POLYGON (the polygon),
NON_MANIFOLD_EDGE and NON_CLOSED_BOUNDARY (the edge’s two vertices), COULD_NOT_CONVERGE, OUTPUT_TOO_LARGE and
CANCELLED.
Fill a cage with tetrahedrons
tetrahedralize(cage, parameters, cancel=None) fills a closed triangle cage with tetrahedrons
(Tetrahedralize). The cage must be
closed, face outward, and not cross itself; otherwise the call raises INVALID_CAGE. Every tetrahedron of the result
is positively oriented, as Scene.add_object requires.
TetrahedralizeParameters(maximum_edge_length, anisotropy=None, density_regions=()) has no default size: you always
choose it. maximum_edge_length caps the tetrahedron size inside the volume, in the cage’s unit. Near the surface,
the size follows the cage triangles.
Errors: INVALID_CAGE, MESHING_FAILED (also for a maximum_edge_length of 0 or less), NO_TETRAHEDRONS,
BAD_SCALES (a NaN anisotropy), OUTPUT_TOO_LARGE and CANCELLED.
Stretch the tetrahedrons
An Anisotropy(scale, direction) stretches the mesher’s space: with a scale s along a direction n, the tetrahedrons
come out about s times longer along n. Use it for long objects, such as planks and beams, to spend fewer tetrahedrons
along their length (Anisotropy). Both triangulate and
tetrahedralize take two of them; pass the same pair to both. Anisotropy.default() is no stretch.
beam = deformable.PolygonMesh([(4.0 * x, y, z) for x, y, z in positions], [4] * 6, quads)
def beam_mesh(stretch):
"""The beam meshed with its tetrahedrons stretched along x."""
anisotropy = (deformable.Anisotropy(stretch, (1.0, 0.0, 0.0)), deformable.Anisotropy.default())
triangulate_parameters = deformable.TriangulateParameters.default(maximum_area=0.05, anisotropy=anisotropy)
beam_cage = deformable.triangulate(beam, parameters=triangulate_parameters).mesh
return deformable.tetrahedralize(beam_cage, deformable.TetrahedralizeParameters(0.3, anisotropy=anisotropy)).mesh
def mean_extent(mesh, axis):
"""The mean size of the tetrahedrons along one axis."""
extents = [
max(mesh.positions[node][axis] for node in tetrahedron) - min(mesh.positions[node][axis] for node in tetrahedron)
for tetrahedron in mesh.tetrahedrons
]
return sum(extents) / len(extents)
for stretch in (1.0, 4.0):
stretched = beam_mesh(stretch)
ratio = mean_extent(stretched, 0) / mean_extent(stretched, 1)
print(f"stretch {stretch}: {len(stretched.tetrahedrons)} tetrahedrons, {ratio:.1f} times longer along x")stretch 1.0: 1329 tetrahedrons, 1.0 times longer along x
stretch 4.0: 471 tetrahedrons, 3.9 times longer along xThe beam is 4 units long. Stretched by 4 along its length, it takes as many tetrahedrons as the unit cube.
Mesh some parts finer
A DensityRegion(points, scale) meshes the convex hull of points finer or coarser than the rest
(Density regions). Its tetrahedron
size is maximum_edge_length divided by the cube root of scale, so a scale above 1 is finer. A region with fewer
than 4 points, a NaN or infinite point, or a NaN scale, is skipped, not refused. The result lists the skipped regions.
corner = [(x, y, z) for x in (0.0, 0.5) for y in (0.0, 0.5) for z in (0.0, 0.5)]
flat = [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)]
regions = [deformable.DensityRegion(corner, 8.0), deformable.DensityRegion(flat, 8.0)]
parameters = deformable.TetrahedralizeParameters(0.3, density_regions=regions)
result = deformable.tetrahedralize(cage, parameters)
print(len(result.mesh.tetrahedrons), result.skipped_density_regions)693 [1]The finer corner region adds tetrahedrons, from 471 to 693. The second region has only three points, so it is skipped.
Cancel a tool
triangulate, tetrahedralize and autocage can run long on a fine size, so they take a CancelFlag. Library
calls release the global interpreter lock, so another thread can set the flag while the tool runs. The tool then
raises CANCELLED.
import threading
fine_cage = deformable.triangulate(cube, parameters=deformable.TriangulateParameters.default(maximum_area=0.002)).mesh
with deformable.CancelFlag() as cancel:
threading.Timer(0.02, cancel.set).start()
try:
deformable.tetrahedralize(fine_cage, deformable.TetrahedralizeParameters(0.05), cancel)
except deformable.DeformableError as error:
print(error.status.name)CANCELLEDA size so small that the result could not be indexed raises OUTPUT_TOO_LARGE at once, before any work. The density
regions have bounds of their own, checked during the run before each group of regions is meshed again, so a region
can raise it after the first mesh.
Wrap any mesh in a cage
autocage(mesh, parameters=None, cancel=None) wraps any polygon mesh, open or closed, in a closed, outward cage of
near-equilateral triangles, at a small gap outside it
(Autocage). Fill the cage with tetrahedralize, then skin
the input mesh on the object as Render surfaces shows.
Build the parameters with AutocageParameters.default(**changes). target_face_count sets how many triangles the
cage aims for, and scale_gap multiplies the gap. The counts are targets, not exact results.
wrapped = deformable.autocage(cube, deformable.AutocageParameters.default(target_face_count=100))
mesh = deformable.tetrahedralize(wrapped, deformable.TetrahedralizeParameters(0.5)).mesh
print(len(wrapped.triangles), "cage triangles,", len(mesh.tetrahedrons), "tetrahedrons")154 cage triangles, 301 tetrahedronsErrors: EMPTY_INPUT (no polygon with three corners), INDEX_OUT_OF_RANGE (the polygon), NON_FINITE_VALUE,
STEP_LIMIT_REACHED (the cage did not close), OUTPUT_TOO_LARGE (a target finer than the tool resolves) and
CANCELLED.
Make thin objects
Extrude a triangle mesh into a shell
extrude(mesh, thickness, direction=ExtrudeDirection.BOTH) turns a triangle mesh into a shell thickness thick, with 2
nodes per vertex and 3 tetrahedrons per triangle (Extrude).
Use it for sheets, plates and other thin objects; the mesh can be non-closed. Each vertex moves along its normal.
ExtrudeDirection says where the second layer goes: UP along the normal, DOWN against it, or BOTH, half on each
side.
sheet = deformable.TriangleMesh(
[(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 0.0, 1.0), (0.0, 0.0, 1.0)],
[(0, 2, 1), (0, 3, 2)],
)
shell = deformable.extrude(sheet, 0.1, deformable.ExtrudeDirection.UP)
print(len(shell.positions), len(shell.tetrahedrons), sorted({position.y for position in shell.positions}))8 6 [0.0, 0.1]The sheet’s triangles face +y, so UP puts the second layer at y = 0.1. On sharp curvature some tetrahedrons can
come out inverted; Scene.add_object then refuses the mesh. Use a smaller thickness or a smoother mesh.
Errors: NON_POSITIVE_THICKNESS, UNKNOWN_VERTEX and DUPLICATE_VERTEX (the face), DEGENERATE_FACE (the face,
for zero area), MULTIPLE_BOUNDARIES and NULL_NORMAL (the vertex).
Fill the space between two layers
span_layers(first_layer, second_layer) fills the space between two triangle meshes with the same vertices and faces,
such as a mesh and a moved copy of it (Span Layers).
Each triangle and its partner make a prism of 3 tetrahedrons, and the tetrahedrons come out positive whichever layer is
on top. Layers that touch give flat tetrahedrons, which add_object refuses.
lifted = deformable.TriangleMesh([(x, 0.5, z) for x, _, z in sheet.positions], sheet.triangles)
slab = deformable.span_layers(sheet, lifted)
print(len(slab.positions), len(slab.tetrahedrons))8 6Errors: NOT_ISOMORPHIC (the layers do not have the same faces), UNKNOWN_VERTEX and DUPLICATE_VERTEX (the
face), MULTIPLE_BOUNDARIES (the vertex whose triangles form more than one fan).
Make a splinter cage from a drawing
splinters_from_image(image, parameters=None) turns a line drawing into a splinter cage: one closed prism per cell.
You pass the cage to embed_surface, and the render surface breaks into those splinters. See
Render surfaces, and for how to draw one,
Draw your own pattern.
The plugin zips carry a library of drawings and ready cages as
OBJ files: the Blender plugin zip in splinters/images and splinters/meshes, the Maya plugin zip in
deformable/assets/splinters/images and deformable/assets/splinters/meshes. The Python package does not hold them.
To use them from your own program, download one of the plugin zips from the
download page, the one of any platform, and unzip it. This example unzips
the Blender plugin zip into a folder named deformable-blender in the folder where you run Python:
unzip deformable-blender-v0.1.0-macos-arm64.zip -d deformable-blenderOn Windows, in PowerShell:
Expand-Archive deformable-blender-v0.1.0-windows-x64.zip deformable-blenderThe call never reads files: you decode the image into a PixelGrid(width, height, pixels). The pixels run row after
row, bottom row first, as (red, green, blue) triples or flat bytes. SplinterImageParameters.default(**changes)
places the cage: size is its width and height in x and y and its depth, and origin is the image’s lower-left
corner in x and y and the z of the top face.
The bundled drawings are 24-bit BMP files, stored bottom row first with blue, green, red bytes. This reader is enough for them:
import struct
def read_bmp(path):
"""A 24-bit, bottom-up BMP file as a PixelGrid."""
with open(path, "rb") as file:
data = file.read()
(offset,) = struct.unpack_from("<I", data, 10)
width, height, _, bits = struct.unpack_from("<iiHH", data, 18)
if data[:2] != b"BM" or bits != 24 or height <= 0:
raise ValueError(f"{path} is not a bottom-up 24-bit BMP")
stride = (3 * width + 3) // 4 * 4
pixels = bytearray()
for row in range(height):
start = offset + row * stride
for column in range(width):
blue, green, red = data[start + 3 * column : start + 3 * column + 3]
pixels += bytes((red, green, blue))
return deformable.PixelGrid(width, height, bytes(pixels))
image = read_bmp("deformable-blender/splinters/images/bricks.bmp")
parameters = deformable.SplinterImageParameters.default(size=(2.0, 1.0, 0.25), origin=(-1.0, 0.0, 0.125))
splinter_cage = deformable.splinters_from_image(image, parameters)
print(image.width, image.height, len(splinter_cage.positions), len(splinter_cage.polygon_sizes))656 450 268 502Errors: EMPTY_IMAGE, LENGTH_MISMATCH (the pixel count is not width * height), NON_FINITE_VALUE,
NO_VERTICES (a blank image, or one that holds only an open line, a closed line without a red mark or a T without
red marks), NO_CELLS, ENDLESS_CYCLE and FACE_ALREADY_SET (loose line ends with red marks, such as a T on its
own with red marks at its three ends).
Check a mesh before you use it
verify_surface(mesh, holes=(), checks=None) checks the polygon mesh of a surface mesh and returns what it finds. An
empty list means the mesh passes; what each problem means, and how to fix it, is on
Verify Mesh. Run it before triangulate to find the
problems that would make the cage fail: a non-closed boundary, inverted normals, tiny angles, faces that cross each
other, and more.
MeshChecks.default(**changes) sets which checks run and their thresholds. Turn on closed_boundary for a simulation
cage: it reports a non-closed boundary, and checks for inward normals and nested parts.
checks = deformable.MeshChecks.default(closed_boundary=True)
print(deformable.verify_surface(deformable.SurfaceMesh(cube), checks=checks))
open_box = deformable.PolygonMesh(positions, [4] * 5, quads[:20])
for issue in deformable.verify_surface(deformable.SurfaceMesh(open_box), checks=checks)[:4]:
print(issue.kind.name, issue.edge)[]
NON_CLOSED_BOUNDARY (1, 3)
NON_CLOSED_BOUNDARY (5, 7)
NON_CLOSED_BOUNDARY (1, 5)
NON_CLOSED_BOUNDARY (3, 7)Each MeshIssue has a kind, a MeshIssueKind, which says which of its fields it fills: a vertex, an edge, a face,
an island, a distance. Some issues are reported twice, once per way the check walks the edges, so remove duplicates
before you show them. The 22 kinds are listed under
MeshIssueKind, and the fields under
MeshIssue.
Errors: malformed input is an error, not an issue. INDEX_OUT_OF_RANGE for an index past the positions or a hole run
outside its face, LENGTH_MISMATCH when the polygon sizes do not add up to the corner count, and NON_FINITE_VALUE
for a NaN or infinite position, UV or threshold.
Find objects that start inside each other
meshes_intersect(first, second) returns True when a tetrahedron of first overlaps a tetrahedron of second by a
volume above 1e-10 with a nonzero normal: a pair where one tetrahedron lies wholly inside the other, or the two
coincide, does not count (Overlapping objects).
Both are TetrahedralMesh values in world space. Use it to find objects that start inside each other before you
simulate the scene.
moved = deformable.TetrahedralMesh([(x + 0.5, y, z) for x, y, z in mesh.positions], mesh.tetrahedrons)
far = deformable.TetrahedralMesh([(x + 3.0, y, z) for x, y, z in mesh.positions], mesh.tetrahedrons)
print(deformable.meshes_intersect(mesh, moved), deformable.meshes_intersect(mesh, far))True FalseTwo identical meshes give False, because their overlaps have no direction.
Errors: EMPTY_MESH, INDEX_OUT_OF_RANGE and NON_FINITE_VALUE.
Tetrahedron faces
boundary_faces(mesh) returns one mask per tetrahedron: bit k is set when face k has no neighbour, so it lies on
the outer surface. Subtract it from a FaceEvent’s exposed_faces to keep only the faces a crack opened.
face_corners(face) returns the three corners of face face of a tetrahedron. Face k is the face opposite corner k.
masks = deformable.boundary_faces(mesh)
print(sum(bin(mask).count("1") for mask in masks), "boundary faces")
print([deformable.face_corners(face) for face in range(4)])154 boundary faces
[(1, 2, 3), (0, 3, 2), (0, 1, 3), (0, 2, 1)]Seen from outside a positive tetrahedron, the corners of each face run clockwise, so (b - a) × (c - a) points into the tetrahedron.
boundary_faces raises EMPTY_MESH, INDEX_OUT_OF_RANGE, NON_MANIFOLD_FACE (a face on three tetrahedrons) and
NON_FINITE_VALUE. Both functions are on the meshes reference.
Next steps
- Scene: turn the meshes into objects.
- Render surfaces: skin the artist’s mesh on the result, and break it along splinters.
- Tools reference: every tool, parameter class and result, with its signature.