C SDK

Tools

Turn polygon meshes, layers and line drawings into simulation input from C, and check meshes for problems before you simulate them.

On this page

The mesh tools prepare the inputs of a scene. They are plain functions with no global state, so separate calls can run on different threads at the same time. Each tool works in the unit of its input. For the full signature and documentation of every tool and its parameter struct, see the C API Reference. What each tool is for, and how many tetrahedrons to aim for, is on Preparing meshes in the Engine guide.

Function Input Result
deformable_triangulate Polygon mesh DeformableTriangulation: a triangle cage
deformable_tetrahedralize Closed triangle cage DeformableTetrahedralization: a tetrahedral mesh
deformable_extrude Triangle mesh DeformableTetrahedralMesh: a thin shell
deformable_span_layers Two triangle meshes DeformableTetrahedralMesh: the space between them
deformable_autocage Polygon mesh DeformableTriangleMesh: a closed cage around it
deformable_splinters_from_image Line drawing DeformablePolygonMesh: a splinter cage
deformable_verify_surface Polygon mesh with normals and UVs DeformableMeshIssueList: the problems found
deformable_meshes_intersect Two tetrahedral meshes 1 when they overlap, 0 otherwise

Each tool that makes a result writes a new handle. Read the handle with its _view function, and free it with its _destroy function.

From polygons to tetrahedrons

A typical path to a simulated object has three steps:

  1. deformable_triangulate the polygon mesh to the triangle size you want.
  2. deformable_tetrahedralize the triangle cage.
  3. deformable_scene_add_object the tetrahedral mesh; see Scene.
triangulate tetrahedralize polygons triangle cage tetrahedrons
Triangulate the polygons into a fine triangle cage, then tetrahedralize the cage to fill it with tetrahedrons.

For a mesh that is open, messy or too detailed, deformable_autocage first builds a clean cage around it.

The snippets on this page build on each other. Paste them in order into main of a program that has the CHECK macro from Scene and includes <stdlib.h>.

Mesh views

The tools take meshes as views: structs of borrowed pointers and counts. A DeformablePolygonMeshView lists the positions, the corner count of each polygon, and the vertex of every corner, polygon after polygon. A closed mesh lists the corners of each face counter-clockwise as seen from outside, so its normals point outward. A DeformableTriangleMeshView lists the positions and three vertex indices per triangle.

This is the unit cube as six outward quads. The snippets below use it as box:

c
DeformableVector3 positions[8];
for (int corner = 0; corner < 8; ++corner) {
    positions[corner] = (DeformableVector3){corner & 1, (corner >> 1) & 1, corner >> 2};
}
const uint32_t sizes[6] = {4, 4, 4, 4, 4, 4};
const uint32_t corners[24] = {0, 2, 3, 1, 4, 5, 7, 6, 0, 1, 5, 4, 2, 6, 7, 3, 0, 4, 6, 2, 1, 3, 7, 5};
DeformablePolygonMeshView box = {positions, 8, sizes, 6, corners, 24};

Triangulate a polygon mesh

deformable_triangulate splits each polygon into well-shaped triangles under an area limit and a minimum angle (Triangulate). Neighbouring polygons get matching points on their shared edges, so a closed mesh stays closed. deformable_triangulate_parameters_default writes the defaults:

Field Default Meaning
maximum_area 1 The largest triangle area. 0 or less sets no limit.
quality 20 The smallest triangle angle, in degrees, clamped to [1, 20]. 0 or less means 2.
anisotropy no stretch Two stretches of the space the triangles are made in; see Stretch the elements.
closed_boundary 1 When not 0, an edge with only one polygon gives DEFORMABLE_STATUS_NON_CLOSED_BOUNDARY.
c
DeformableTriangulateParameters triangulate_parameters;
CHECK(deformable_triangulate_parameters_default(&triangulate_parameters));
triangulate_parameters.maximum_area = 0.02;
DeformableTriangulation *triangulation = NULL;
CHECK(deformable_triangulate(&box, NULL, 0, &triangulate_parameters, NULL, &triangulation));
DeformableTriangulationView cage;
CHECK(deformable_triangulation_view(triangulation, &cage));
printf("%zu triangles\n", cage.mesh.triangle_count);
text
440 triangles

The view lends the triangle cage as mesh, and for each triangle the input polygon it came from as source_polygons. Use it to carry per-face data, such as materials, over to the triangles.

When a polygon cannot reach the quality, the tool retries with a smaller angle. When no angle works, it returns DEFORMABLE_STATUS_COULD_NOT_CONVERGE.

A polygon with a hole

A DeformableFaceHole names a run of a polygon’s corners that forms one hole loop: the polygon, the run’s first corner within the polygon, and the run’s corner count. The corners before the polygon’s first hole form its outer loop. This snippet triangulates a flat square with a square hole. One polygon is not closed, so it turns closed_boundary off:

c
const DeformableVector3 frame_positions[8] = {
    {0, 0, 0}, {3, 0, 0}, {3, 3, 0}, {0, 3, 0}, /* the outer square, counter-clockwise */
    {1, 1, 0}, {1, 2, 0}, {2, 2, 0}, {2, 1, 0}, /* the hole, clockwise */
};
const uint32_t frame_sizes[1] = {8};
const uint32_t frame_corners[8] = {0, 1, 2, 3, 4, 5, 6, 7};
DeformablePolygonMeshView frame_mesh = {frame_positions, 8, frame_sizes, 1, frame_corners, 8};
const DeformableFaceHole hole = {0, 4, 4}; /* polygon 0, corners 4 to 7 */

DeformableTriangulateParameters flat_parameters;
CHECK(deformable_triangulate_parameters_default(&flat_parameters));
flat_parameters.closed_boundary = 0;
DeformableTriangulation *flat = NULL;
CHECK(deformable_triangulate(&frame_mesh, &hole, 1, &flat_parameters, NULL, &flat));
DeformableTriangulationView flat_view;
CHECK(deformable_triangulation_view(flat, &flat_view));
printf("frame: %zu triangles\n", flat_view.mesh.triangle_count);
deformable_triangulation_destroy(flat);
text
frame: 12 triangles

The triangles cover an area of 8: the 3 by 3 square without the 1 by 1 hole.

Fill a cage with tetrahedrons

deformable_tetrahedralize fills a closed triangle cage with tetrahedrons (Tetrahedralize). The cage must be closed, with outward normals and no self-intersections, or the call returns DEFORMABLE_STATUS_INVALID_CAGE. The cage triangles become the boundary of the mesh, except where a density region reaches the cage and meshes the cage faces there again at its size, and the cage vertices keep their positions. So the size of the cage triangles sets the size of the tetrahedrons at the surface: triangulate the cage first to the size you want.

DeformableTetrahedralizeParameters has three settings, and no _default function:

  • maximum_edge_length caps the size of the tetrahedrons inside the volume. A size of 0 or less makes the call return DEFORMABLE_STATUS_MESHING_FAILED; a NaN or infinite size meshes the cage with no size limit.
  • anisotropy stretches the tetrahedrons; see Stretch the elements. Set both entries with deformable_anisotropy_default when you want no stretch. A zeroed DeformableAnisotropy stretches nothing too, since a zero direction makes its scale count as 1.
  • density_regions makes the tetrahedrons smaller, or larger, inside convex regions.

A DeformableDensityRegion is the convex hull of its points, with a scale; see Density regions. Inside it, the tetrahedron size is maximum_edge_length divided by the cube root of the scale, so a scale of 8 halves the size. A region with fewer than 4 points, a non-finite point or a NaN scale is skipped, and the view lists it in skipped_density_regions.

This snippet fills the triangulated cube, once plainly and once with a finer corner:

c
DeformableTetrahedralizeParameters tetrahedralize_parameters = {0};
tetrahedralize_parameters.maximum_edge_length = 0.2;
CHECK(deformable_anisotropy_default(&tetrahedralize_parameters.anisotropy[0]));
CHECK(deformable_anisotropy_default(&tetrahedralize_parameters.anisotropy[1]));

DeformableTetrahedralization *plain = NULL;
CHECK(deformable_tetrahedralize(&cage.mesh, &tetrahedralize_parameters, NULL, &plain));
DeformableTetrahedralizationView plain_view;
CHECK(deformable_tetrahedralization_view(plain, &plain_view));
printf("%zu tetrahedrons\n", plain_view.mesh.tetrahedron_count);

/* Eight times the density in the corner at the origin. */
const DeformableVector3 corner_points[4] = {{0, 0, 0}, {0.5, 0, 0}, {0, 0.5, 0}, {0, 0, 0.5}};
DeformableDensityRegion region = {corner_points, 4, 8.0};
tetrahedralize_parameters.density_regions = &region;
tetrahedralize_parameters.density_region_count = 1;
DeformableTetrahedralization *dense = NULL;
CHECK(deformable_tetrahedralize(&cage.mesh, &tetrahedralize_parameters, NULL, &dense));
DeformableTetrahedralizationView dense_view;
CHECK(deformable_tetrahedralization_view(dense, &dense_view));
printf("with the region: %zu tetrahedrons, %zu regions skipped\n", dense_view.mesh.tetrahedron_count,
       dense_view.skipped_density_region_count);
deformable_tetrahedralization_destroy(dense);
text
1247 tetrahedrons
with the region: 1601 tetrahedrons, 0 regions skipped

plain_view.mesh is ready for deformable_scene_add_object. When the cage would hold more tetrahedrons than 32-bit indices can address at the edge length you ask for, the call returns DEFORMABLE_STATUS_OUTPUT_TOO_LARGE before it starts. The density regions have bounds of their own, checked during the run before each group of regions is meshed again, so the call can also return it after the first mesh. A long run can be stopped with a cancel flag; see Memory and errors.

Stretch the elements

deformable_triangulate and deformable_tetrahedralize can stretch their elements, for example to make long tetrahedrons along the grain of wood (Anisotropy). A DeformableAnisotropy stretches the elements by scale along direction. The scale is clamped to [0.02, 50]. The direction can have any length; each component is clamped to [-100, 100]. deformable_anisotropy_default writes scale 1 along (1, 1, 1): no stretch. A NaN scale or direction gives DEFORMABLE_STATUS_BAD_SCALES from deformable_tetrahedralize and DEFORMABLE_STATUS_NON_FINITE_VALUE from deformable_triangulate.

c
DeformableTetrahedralizeParameters grain_parameters = {0};
grain_parameters.maximum_edge_length = 0.2;
CHECK(deformable_anisotropy_default(&grain_parameters.anisotropy[0]));
CHECK(deformable_anisotropy_default(&grain_parameters.anisotropy[1]));
grain_parameters.anisotropy[0].scale = 3.0;
grain_parameters.anisotropy[0].direction = (DeformableVector3){0, 1, 0};
DeformableTetrahedralization *grain = NULL;
CHECK(deformable_tetrahedralize(&cage.mesh, &grain_parameters, NULL, &grain));
DeformableTetrahedralizationView grain_view;
CHECK(deformable_tetrahedralization_view(grain, &grain_view));
printf("stretched along y: %zu tetrahedrons\n", grain_view.mesh.tetrahedron_count);
deformable_tetrahedralization_destroy(grain);
deformable_triangulation_destroy(triangulation); /* The cage is no longer needed. */
text
stretched along y: 964 tetrahedrons

Make a thin shell

deformable_extrude makes a thin shell from a triangle mesh, for sheets and panels (Extrude). It offsets each vertex along its normal, so the shell has 2 nodes per vertex and 3 tetrahedrons per triangle. The direction says where the two layers go:

Direction Layers
DEFORMABLE_EXTRUDE_DIRECTION_UP The mesh and the mesh moved out along its normals by the thickness.
DEFORMABLE_EXTRUDE_DIRECTION_DOWN The mesh and the mesh moved in by the thickness.
DEFORMABLE_EXTRUDE_DIRECTION_BOTH Half the thickness on each side of the mesh.
thickness extrude triangle mesh 3 tetrahedrons per triangle
Extrude makes a thin shell with 2 nodes per vertex and 3 tetrahedrons per triangle.

A thickness of 0 or less, or NaN, gives DEFORMABLE_STATUS_NON_POSITIVE_THICKNESS. Where the mesh curves sharply, a thick shell can make inverted tetrahedrons, which deformable_scene_add_object then refuses: use a thinner shell or a smoother mesh there.

c
const DeformableVector3 sheet_positions[4] = {{0, 0, 0}, {1, 0, 0}, {1, 0, 1}, {0, 0, 1}};
const uint32_t sheet_triangles[2][3] = {{0, 2, 1}, {0, 3, 2}};
DeformableTriangleMeshView sheet = {sheet_positions, 4, sheet_triangles, 2};

DeformableTetrahedralMesh *shell = NULL;
CHECK(deformable_extrude(&sheet, 0.1, DEFORMABLE_EXTRUDE_DIRECTION_BOTH, &shell));
DeformableTetrahedralMeshView shell_view;
CHECK(deformable_tetrahedral_mesh_view(shell, &shell_view));
printf("%zu nodes, %zu tetrahedrons\n", shell_view.position_count, shell_view.tetrahedron_count);
deformable_tetrahedral_mesh_destroy(shell);
text
8 nodes, 6 tetrahedrons

Fill the space between two layers

deformable_span_layers 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 gives 3 tetrahedrons. Each face of the first layer must match one face of the second, with the same winding, or the call returns DEFORMABLE_STATUS_NOT_ISOMORPHIC. This snippet spans the sheet from Make a thin shell and a wavy copy above it:

c
const DeformableVector3 top_positions[4] = {{0, 0.2, 0}, {1, 0.3, 0}, {1, 0.2, 1}, {0, 0.3, 1}};
DeformableTriangleMeshView top = {top_positions, 4, sheet_triangles, 2};

DeformableTetrahedralMesh *layers = NULL;
CHECK(deformable_span_layers(&top, &sheet, &layers));
DeformableTetrahedralMeshView layers_view;
CHECK(deformable_tetrahedral_mesh_view(layers, &layers_view));
printf("%zu nodes, %zu tetrahedrons\n", layers_view.position_count, layers_view.tetrahedron_count);
deformable_tetrahedral_mesh_destroy(layers);
text
8 nodes, 6 tetrahedrons

Build a cage around any mesh

deformable_autocage builds a closed, outward triangle cage around any polygon mesh, at a small gap from it (Autocage). The input can be non-closed. The cage is ready for deformable_tetrahedralize. deformable_autocage_parameters_default writes the defaults:

Field Default Meaning
scale_gap 1 Multiplies the gap between the cage and the mesh. Clamped to [0.1, 10].
target_face_count 300 The number of cage faces to aim for. 0 or less uses the tetrahedron target.
target_tetrahedron_count 0 The number of tetrahedrons to aim for when there is no face target. 0 or less sets none.
c
DeformableAutocageParameters autocage_parameters;
CHECK(deformable_autocage_parameters_default(&autocage_parameters));
autocage_parameters.target_face_count = 200;
DeformableTriangleMesh *autocage = NULL;
CHECK(deformable_autocage(&box, &autocage_parameters, NULL, &autocage));
DeformableTriangleMeshView autocage_view;
CHECK(deformable_triangle_mesh_view(autocage, &autocage_view));
printf("%zu triangles\n", autocage_view.triangle_count);
deformable_triangle_mesh_destroy(autocage);
text
294 triangles

The face target is a guide, not an exact count. A front that fails starts again, up to 7 times; when the cage has not closed within the step limit (1,000 steps per expected triangle and at least 100,000, restarts included), the call returns DEFORMABLE_STATUS_STEP_LIMIT_REACHED. A target finer than the tool can resolve gives DEFORMABLE_STATUS_OUTPUT_TOO_LARGE.

Make splinters from a drawing

deformable_splinters_from_image turns a line drawing into a splinter cage: a closed prism for each cell of the drawing. Render surfaces uses the cage to break an object into those shapes. You decode the image yourself; the library never reads files.

line drawing splinter cage: one prism per cell
Each cell of the line drawing becomes one closed prism of the splinter cage.

A DeformablePixelGrid holds 8-bit red, green and blue pixels, one row after the other, with the bottom row first, as a BMP file stores them. pixel_count must equal width times height. The drawing follows the rules of Draw your own pattern, with these colour limits:

  • Black lines separate the cells. A pixel is black when red is below 128 and green plus blue is 15 or less.
  • Red pixels mark the corners where a line bends without meeting another line. A pixel is red when red is 128 or more and at least 8 times green plus blue.

deformable_splinter_image_parameters_default writes the defaults: size (1, 1, 1), origin (0, 0, 0) and allow_nonconvex 1. The cage covers size.x by size.y, with the image’s lower-left corner at origin.x, origin.y. Its top face is at origin.z and its bottom at origin.z - size.z. With allow_nonconvex 1, the tool keeps the traced cell outlines; with 0, it straightens cell sides between junctions.

This snippet draws a square with a cross in it, which gives four cells:

c
enum { SIDE = 32 };
static uint8_t pixels[SIDE * SIDE][3];
for (int y = 0; y < SIDE; ++y) {
    for (int x = 0; x < SIDE; ++x) {
        int line = x == 0 || y == 0 || x == SIDE - 1 || y == SIDE - 1 || x == SIDE / 2 || y == SIDE / 2;
        int outline_corner = (x == 0 || x == SIDE - 1) && (y == 0 || y == SIDE - 1);
        uint8_t *pixel = pixels[y * SIDE + x];
        pixel[0] = line && !outline_corner ? 0 : 255; /* black lines, red outline corners, white cells */
        pixel[1] = pixel[2] = line ? 0 : 255;
    }
}
DeformablePixelGrid image = {SIDE, SIDE, (const uint8_t (*)[3])pixels, SIDE * SIDE};

DeformableSplinterImageParameters image_parameters;
CHECK(deformable_splinter_image_parameters_default(&image_parameters));
DeformablePolygonMesh *splinters = NULL;
CHECK(deformable_splinters_from_image(&image, &image_parameters, &splinters));
DeformablePolygonMeshView splinter_cage;
CHECK(deformable_polygon_mesh_view(splinters, &splinter_cage));
printf("%zu points, %zu polygons\n", splinter_cage.position_count, splinter_cage.polygon_count);
deformable_polygon_mesh_destroy(splinters);
text
18 points, 24 polygons

Four prisms share 9 corners on top and 9 below. Their polygons are 4 tops, 4 bottoms, and a side quad for each outer wall and each side of an inner wall.

Status Cause
DEFORMABLE_STATUS_EMPTY_IMAGE The width or height is 0.
DEFORMABLE_STATUS_NO_VERTICES The image is blank, or holds only an open line, a closed line without a red mark or a T without red marks.
DEFORMABLE_STATUS_NO_CELLS The lines close no cell.
DEFORMABLE_STATUS_FACE_ALREADY_SET Tracing a cell met a line 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 plugin zips carry ready-made drawings as 24-bit BMP files and ready-made splinter 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. Unzip a copy of one of the zips to use them from your own program.

Check a mesh for problems

deformable_verify_surface checks a mesh before you simulate it: a non-closed boundary, degenerate faces, self-intersections, inward normals and more. What each problem means, and how to fix it, is on Verify Mesh. It takes a DeformableSurfaceMeshView, the render surface type of Render surfaces, so it can check UVs too. deformable_mesh_checks_default writes the default checks:

Field Default Meaning
angle_threshold_degrees 2 A face with a corner angle of its outer loop below this has a small angle.
gap_threshold 0.001 Two corners of a face closer than this fraction of the mesh radius are near vertices.
planar_threshold 0.05 A face further than this fraction of its radius from its plane is not planar.
check_uv_consistency 0 When not 0, check that the UVs follow the face, within uv_threshold.
uv_threshold 0 The UV tolerance, as a fraction of the face radius.
same_uv 0 When not 0, report corners at different places with the same UVs.
convex 0 When not 0, report reflex corners.
closed_boundary 0 When not 0, report edges with one face and check for inward normals and nesting.
self_intersection DEFORMABLE_SELF_INTERSECTION_CHECK_PER_ISLAND _SKIP turns the self-intersection, island, inward-normal and nesting checks off; _PER_ISLAND checks within each connected piece; _FULL checks across pieces too.

The result is a list of DeformableMeshIssue records, in check order. An empty list means the mesh passes. Each record’s kind, a DEFORMABLE_MESH_ISSUE_KIND_ constant, says which fields it fills; the others are 0 or NULL. For example, DEFORMABLE_MESH_ISSUE_KIND_NON_CLOSED_BOUNDARY fills edge, two vertex indices with the smaller first, and DEFORMABLE_MESH_ISSUE_KIND_SMALL_ANGLE fills face and degrees. The C API Reference lists all 22 kinds and their fields. Some issues are reported twice; remove duplicates before you show them to a user.

This snippet checks the unit cube cage with one triangle missing:

c
const uint32_t cube_triangles[12][3] = {
    {0, 2, 3}, {0, 3, 1}, {4, 5, 7}, {4, 7, 6}, {0, 1, 5}, {0, 5, 4},
    {2, 6, 7}, {2, 7, 3}, {0, 4, 6}, {0, 6, 2}, {1, 3, 7}, {1, 7, 5},
};
const uint32_t triangle_sizes[11] = {3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3};
DeformableSurfaceMeshView surface = {
    {positions, 8, triangle_sizes, 11, &cube_triangles[0][0], 33}, NULL, 0, NULL, 0, NULL, 0,
};

DeformableMeshChecks checks;
CHECK(deformable_mesh_checks_default(&checks));
checks.closed_boundary = 1;
DeformableMeshIssueList *issues = NULL;
CHECK(deformable_verify_surface(&surface, NULL, 0, &checks, &issues));
const DeformableMeshIssue *records = NULL;
size_t record_count = 0;
CHECK(deformable_mesh_issue_list_issues(issues, &records, &record_count));
for (size_t index = 0; index < record_count; ++index) {
    if (records[index].kind == DEFORMABLE_MESH_ISSUE_KIND_NON_CLOSED_BOUNDARY) {
        printf("non-closed boundary %u-%u\n", (unsigned)records[index].edge[0], (unsigned)records[index].edge[1]);
    }
}
deformable_mesh_issue_list_destroy(issues);
text
non-closed boundary 5-7
non-closed boundary 1-5
non-closed boundary 1-7
non-closed boundary 5-7
non-closed boundary 1-5
non-closed boundary 1-7

A malformed mesh, such as one with an index out of range, gives an error status, not an issue.

Find overlapping objects

deformable_meshes_intersect tells whether two tetrahedral meshes in world space overlap, for example to find objects that start inside each other (Overlapping objects): a tetrahedron of each must overlap by a volume above 1e-10 with a nonzero normal, so a pair where one tetrahedron lies wholly inside the other, or the two coincide, does not count. This snippet moves a copy of the plain cube from Fill a cage with tetrahedrons along x, then frees the cube:

c
DeformableTetrahedralMeshView moved = plain_view.mesh;
DeformableVector3 *moved_positions = malloc(moved.position_count * sizeof *moved_positions);
for (size_t node = 0; node < moved.position_count; ++node) {
    moved_positions[node] = plain_view.mesh.positions[node];
    moved_positions[node].x += 0.9;
}
moved.positions = moved_positions;

uint8_t intersect = 0;
CHECK(deformable_meshes_intersect(&plain_view.mesh, &moved, &intersect));
printf("moved by 0.9: %u\n", (unsigned)intersect);
free(moved_positions);
deformable_tetrahedralization_destroy(plain);
text
moved by 0.9: 1

Moved by 1.1 instead, the two cubes no longer overlap, and the call writes 0. Cubes that only touch along a face do not count as overlapping.

Tetrahedron faces

Face k of a tetrahedron is the face opposite corner k. The face bits of the scene outputs use this numbering. deformable_face_corners writes the three local corners of a face:

Face Corners
0 1, 2, 3
1 0, 3, 2
2 0, 1, 3
3 0, 2, 1

deformable_boundary_faces gives, for each tetrahedron of a mesh, the mask of its faces on the surface at rest.

c
uint32_t face_corners[3];
CHECK(deformable_face_corners(1, &face_corners));
printf("face 1: %u, %u, %u\n", (unsigned)face_corners[0], (unsigned)face_corners[1], (unsigned)face_corners[2]);
text
face 1: 0, 3, 2

Next steps

  • Render surfaces: skin a render mesh on the simulated object, and break it along splinters.
  • Memory and errors: ownership, status codes, threads and cancel flags.
  • C API Reference: every tool, parameter struct and result of deformable.h.