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

Rust SDK

Errors and threads

The error type of the Rust SDK, the kinds of failure each call returns, how to handle them, and how to use the library from several threads and cancel long calls.

On this page

Every call that can fail returns a Result whose error is deformable::Error. The library checks your input and returns an error instead of panicking. This page explains the error type, lists the kinds of failure each call returns, shows how to handle them, and explains the thread rules. Every item, with its documentation, is in the errors reference.

The error type

One type, Error, serves every call. It carries:

  • kind(): an ErrorKind, what went wrong. Match on it to react to one case.
  • message(): the library’s description of the failure, in English. Display prints it too.
  • first_index() and second_index(): the elements the failure names, such as a tetrahedron, a polygon, a vertex or the two vertices of an edge. They are 0 when the kind names no element. Each ErrorKind variant says what its indices mean.

Error implements std::error::Error, so the ? operator turns it into a Box<dyn std::error::Error>. It is also Clone, Eq and Debug.

ErrorKind is a small Copy enum with one variant per failure. DegenerateTetrahedron carries a mesh::DegenerateKind: an Inverted tetrahedron has its corners in the wrong order, so swap two of them; a Flat or TooSmall one must be remeshed. A tetrahedron is degenerate when its orientation determinant is not above 1e-9, in simulation units.

ErrorKind is #[non_exhaustive]: a newer library can add kinds, so a match on it needs a _ arm. A status this crate does not know comes as ErrorKind::Unrecognized(code).

On this guide’s pages, “gives NonFiniteValue” is short for “returns an Error whose kind is ErrorKind::NonFiniteValue”.

Error kinds

Each call returns only some kinds. This table lists them, with the meaning of the indices where a kind has them.

Call Kinds
Scene methods UnknownObject, UnknownMaterial, IndexOutOfRange, LengthMismatch, NonFiniteValue, ScaleOutOfRange, InvalidWorkerCount, TimeWentBackwards. add_object also checks the mesh: EmptyMesh, NonManifoldFace and DegenerateTetrahedron, whose first index is the tetrahedron.
material_region_indices The mesh kinds, and DegenerateRegion: the first index is the region, the second the polygon.
verify_surface, PolygonMesh::validate, SurfaceMesh::validate IndexOutOfRange, LengthMismatch, NonFiniteValue.
meshes_intersect, TetrahedralMesh::validate EmptyMesh, IndexOutOfRange, NonFiniteValue.
boundary_faces EmptyMesh, IndexOutOfRange, NonFiniteValue, NonManifoldFace.
triangulate EmptyMesh, IndexOutOfRange and DegeneratePolygon (first index: the polygon), NonManifoldEdge and NonClosedBoundary (first and second index: the edge’s vertices), NonFiniteValue, CouldNotConverge, Cancelled, OutputTooLarge.
tetrahedralize BadScales, MeshingFailed, NoTetrahedrons, InvalidCage, Cancelled, OutputTooLarge.
autocage EmptyInput, IndexOutOfRange (first index: the polygon), NonFiniteValue, StepLimitReached, Cancelled, OutputTooLarge.
extrude, span_layers NonPositiveThickness, NotIsomorphic, UnknownVertex, DuplicateVertex and DegenerateFace (first index: the face), MultipleBoundaries and NullNormal (first index: the vertex).
splinters_from_image EmptyImage, LengthMismatch, NonFiniteValue, NoVertices, NoCells, EndlessCycle, FaceAlreadySet.
embed_surface, SurfaceEmbedding::deform IndexOutOfRange, LengthMismatch, NonFiniteValue, EmptyMesh, NonManifoldFace, InvalidSplinterCage, SingularTransform.
deformable::license functions InvalidArgument (not a license key, or another key is active), LicenseServiceUnavailable, LicenseKeyRejected, LicenseStorageFailed, and the license kinds below.

Three kinds can come from any call. InvalidArgument means the library could not read an argument, and Panicked means it failed inside: drop the objects the call used. NullPointer never comes from this crate’s safe API; if you see it, report a bug.

The ErrorKind reference gives the cause of every kind.

License errors

Engine calls check the license first: the Developer license key the program activated, or else the Standard trial or license of this computer. When it does not allow the call, the call returns one of these kinds, and nothing is created. The message is the status line, such as Standard trial ended — Buy license.

Kind When
LicenseRequired The Standard trial ended, the computer has no Standard trial, the Standard license was removed, or the Developer trial key ended.
TrialLimitExceeded More than 2,500 tetrahedrons would take part in the simulation during the Standard trial; a disabled object does not count. The first index is that count, the second the limit. add_object adds nothing then, and the scene goes on with the objects it holds.
LicenseNeedsOnline The Standard trial has not started, the Standard license needs its renewal, or the clock is behind.
LicenseServiceUnavailable activate, deactivate or refresh could not reach our licensing service, the service refused this copy of the library, its answer did not verify, or set_online_access(false) turned contacts off.
LicenseKeyRejected Our licensing service refused the Standard key: unknown, revoked or expired, of another product, or its seat is in use on another device; or the service takes no more devices. Or the Developer key was refused: it was revoked, its trial ended, or the program is Blender or Maya, where Developer licenses do not work.
LicenseStorageFailed The license state could not be saved in your user folder.

These 15 calls check the license: the tools triangulate, tetrahedralize, extrude, span_layers, autocage, splinters_from_image, verify_surface and meshes_intersect, then boundary_faces, material_region_indices, embed_surface, SurfaceEmbedding::deform, Scene::add_object, Scene::step and Scene::skip_to. Creating a scene, setting its values, reading its outputs and dropping it never do, so your program can always clean up. deformable::license reads and changes the license state: see License.

Handle an error

Match on the kind to react to one case, and pass the rest on:

rust
use deformable::ErrorKind;
use deformable::math::Vector3;
use deformable::mesh::{DegenerateKind, TetrahedralMesh};
use deformable::scene::{MaterialParameters, ObjectOptions, Scene, TetrahedronMaterials};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let positions = vec![Vector3::ZERO, Vector3::X, Vector3::Y, Vector3::Z];
    let mut mesh = TetrahedralMesh { positions, tetrahedrons: vec![[0, 1, 2, 3]] };

    let mut scene = Scene::new();
    let material = scene.add_material(&MaterialParameters::default())?;
    let materials = TetrahedronMaterials::Uniform(material);

    let object = match scene.add_object(&mesh, materials, ObjectOptions::default()) {
        Err(error) if error.kind() == ErrorKind::DegenerateTetrahedron(DegenerateKind::Inverted) => {
            let tetrahedron = error.first_index();
            println!("tetrahedron {tetrahedron} is inverted: swapping two corners");
            mesh.tetrahedrons[tetrahedron as usize].swap(1, 2);
            scene.add_object(&mesh, materials, ObjectOptions::default())?
        }
        result => result?,
    };
    println!("added {object:?}");

    scene.remove_object(object)?;
    let error = scene.node_positions(object, &mut Vec::new()).unwrap_err();
    println!("{:?}: {error}", error.kind());
    println!("{}", scene.set_scale(5000.0).unwrap_err());
    Ok(())
}
text
tetrahedron 0 is inverted: swapping two corners
added ObjectHandle(0)
UnknownObject: unknown object
scale outside [0.001, 1000]

A tool error is handled the same way. Here a size that is far too fine for the cage is refused before any work, and the program tries a coarser one:

rust
mod shapes;

use deformable::ErrorKind;
use deformable::math::Vector3;
use deformable::tools::{Anisotropy, TetrahedralizeParameters, TriangulateParameters, tetrahedralize, triangulate};
use shapes::cuboid;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let cube = cuboid(Vector3::ZERO, Vector3::new(1.0, 1.0, 1.0));
    let refined = TriangulateParameters { maximum_area: Some(0.05), ..TriangulateParameters::default() };
    let cage = triangulate(&cube, &[], &refined, None)?.mesh;

    for maximum_edge_length in [0.0001, 0.3] {
        let parameters = TetrahedralizeParameters {
            maximum_edge_length,
            anisotropy: [Anisotropy::default(); 2],
            density_regions: Vec::new(),
        };
        match tetrahedralize(&cage, &parameters, None) {
            Ok(result) => println!("{maximum_edge_length}: {} tetrahedrons", result.mesh.tetrahedrons.len()),
            Err(error) if error.kind() == ErrorKind::OutputTooLarge => {
                println!("{maximum_edge_length}: too fine for this cage")
            }
            Err(error) => return Err(error.into()),
        }
    }
    Ok(())
}
text
0.0001: too fine for this cage
0.3: 471 tetrahedrons

What the library checks

Every public call checks its input. add_object checks the whole mesh before it creates anything, so a refused mesh leaves no half-built object behind.

  • Positions and parameters must be finite. NaN and infinity give NonFiniteValue, or the tool’s matching kind. tetrahedralize has two exceptions: it treats a NaN or infinite maximum_edge_length as no size limit, and it clamps an infinite anisotropy scale or direction instead of refusing it.
  • Indices must be in range, and list lengths must match.
  • add_object also runs the quality check on every tetrahedron.
  • Tools whose output grows with a size parameter estimate the output first, and return OutputTooLarge instead of running out of memory.

To check a mesh early, before a call that would refuse it, use the validate methods of TetrahedralMesh, PolygonMesh and SurfaceMesh. They check that every index is in range and that every position is finite. TetrahedralMesh::validate also refuses a mesh with no tetrahedron; the other two accept a mesh with no polygon, and check that the polygon sizes add up to the corner count. They run in the crate, without calling the library, and do not run the tetrahedron quality check.

Numerical trouble inside a step is not an error. When the positions of a part of an object become NaN, that part stops moving, and the NaN never reaches another object through a contact.

Threads

The library is thread-safe in the Rust way: the types say what you can share.

  • Scene is Send but not Sync. You can move it to another thread, and you call it from one thread at a time. Wrap it in a Mutex to reach it from several threads.
  • step runs its own worker threads. set_worker_count sets how many, and the results do not depend on it.
  • The tools keep no global state. Call them from as many threads as you like.
  • The mesh types, the parameter types, SurfaceEmbedding and CancelFlag are Send and Sync. Several threads can skin one embedding at once.
  • The error of a failed call is read on the thread that made the call, so errors never mix between threads.

This example fills one cage at three sizes on three threads, then steps a scene on another thread and takes it back:

rust
mod shapes;

use std::thread;

use deformable::math::Vector3;
use deformable::scene::{MaterialParameters, ObjectOptions, Scene, TetrahedronMaterials};
use deformable::tools::{Anisotropy, TetrahedralizeParameters, TriangulateParameters, tetrahedralize, triangulate};
use shapes::cuboid;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let cube = cuboid(Vector3::ZERO, Vector3::new(1.0, 1.0, 1.0));
    let refined = TriangulateParameters { maximum_area: Some(0.05), ..TriangulateParameters::default() };
    let cage = triangulate(&cube, &[], &refined, None)?.mesh;

    // One tool call per thread, all reading the same cage.
    let results = thread::scope(|scope| {
        let workers: Vec<_> = [0.3, 0.2, 0.1]
            .map(|maximum_edge_length| {
                let cage = &cage;
                scope.spawn(move || {
                    let parameters = TetrahedralizeParameters {
                        maximum_edge_length,
                        anisotropy: [Anisotropy::default(); 2],
                        density_regions: Vec::new(),
                    };
                    tetrahedralize(cage, &parameters, None)
                })
            })
            .into_iter()
            .collect();
        workers.into_iter().map(|worker| worker.join().expect("the tool does not panic")).collect::<Vec<_>>()
    });
    let mut meshes = Vec::new();
    for result in results {
        meshes.push(result?.mesh);
    }
    println!("{:?}", meshes.iter().map(|mesh| mesh.tetrahedrons.len()).collect::<Vec<_>>());

    // Move the scene to a worker thread, step it there, and take it back.
    let mut scene = Scene::new();
    let material = scene.add_material(&MaterialParameters::default())?;
    let object = scene.add_object(&meshes[0], TetrahedronMaterials::Uniform(material), ObjectOptions::default())?;
    let worker = thread::spawn(move || {
        for frame in 0..=24 {
            scene.step(f64::from(frame) / 24.0, 10, None).expect("a valid step");
        }
        scene
    });
    let scene = worker.join().expect("the step does not panic");
    let mut positions = Vec::new();
    scene.node_positions(object, &mut positions)?;
    println!("{} nodes after one second on another thread", positions.len());
    Ok(())
}
text
[471, 727, 2602]
146 nodes after one second on another thread

At 0.3 the size follows the cage triangles, so a coarser size would give the same 471 tetrahedrons.

Cancel a long call

The calls that can run long take a cancel: Option<&CancelFlag>: Scene::step, triangulate, tetrahedralize and autocage. Pass None for no flag. They read the flag often while they run.

  • CancelFlag::new() makes a flag that is not set. set(true) sets it from any thread, and is_set() reads it.
  • A tool returns an error of kind Cancelled once the flag is set.
  • A step stops between two substeps, after at least one, and returns Ok with StepOutcome::Cancelled. The time stands at the last substep run, so the next step goes on from there.
  • A flag that is already set stops a tool at once, and a step after its first substep. Clear it with set(false) before you reuse it.
  • One flag can serve several calls at once, for example every tool of one job.

Scene and Tools each show a flag set from another thread.

Next steps