You are viewing the documentation for Deformable v0.6.0, an older version. Read the latest, v0.9.0
Rust SDK
Getting started with Rust
Add the deformable crate to a Cargo project, build it with the library it downloads, and run your first simulation from Rust.
On this page
The Rust SDK brings the Tangerina Deformable engine into your own Rust tools. It is the crate deformable: a safe
Rust API over libdeformable, the shared library of the C SDK. The crate holds no engine code. It calls the library,
so the C, Rust and Python SDKs all run the same engine and give the same results. The crate itself uses only the Rust
standard library, so it adds no other crate to your build.
The crate holds the scene, the mesh tools that prepare its inputs, and the render surfaces that show the result. What they do, and why, is in the Engine guide, starting with How the engine works; this guide shows how to use them from Rust.
Requirements
- Rust 1.85 or later. Your own project may use any edition.
- macOS on Apple silicon, Linux x64 or Windows x64 (MSVC).
curl, which macOS, Windows 10 and later and most Linux distributions ship. The first build uses it to download the library.
Install
Create a project and add the crate:
cargo new falling-cube
cd falling-cube
cargo add deformableThat is all. The first cargo build downloads libdeformable, the shared library the crate links, for your platform
and the crate’s version from https://assets.tangerina.io/releases. The build checks the file against the SHA-256
checksums the crate carries, and keeps it in your project’s target folder, so later builds reuse it and download
nothing. When the download fails or the file does not match, the build stops with a message that says why.
Build without a download
On a machine that cannot reach the internet, or where builds must not download anything, use the C SDK instead.
Download the C SDK zip for your platform from the download page, for
example deformable-c-v0.1.0-macos-arm64.zip, and unzip it. Its lib/ folder holds the shared library. Use the C SDK
of the same version as the crate.
On macOS, clear the download mark from the unzipped folder once. A browser marks a downloaded zip, unzipping copies the mark onto each file, and macOS will not load a marked library that is not notarized, so without this step your program never starts:
xattr -dr com.apple.quarantine /path/to/deformable-c-v0.1.0-macos-arm64Set DEFORMABLE_LIB_DIR to the absolute path of the lib/ folder before you build:
export DEFORMABLE_LIB_DIR=/path/to/deformable-c-v0.1.0-macos-arm64/libOn Windows, in PowerShell:
$env:DEFORMABLE_LIB_DIR = "C:\path\to\deformable-c-v0.1.0-windows-x64\lib"With the variable set, the crate links the library in that folder and downloads nothing. Cargo runs the crate’s
build script from the crate’s own folder, not from your project, so a relative path would point at the wrong place:
the build refuses one. To keep the path in your project instead, put it in .cargo/config.toml with
relative = true, which Cargo turns into an absolute path:
[env]
DEFORMABLE_LIB_DIR = { value = "deformable-c-v0.1.0-macos-arm64/lib", relative = true }On Windows the crate links deformable.dll through its import library, deformable.dll.lib, which the C SDK ships
next to it. Cargo does not put that folder on the loader’s search path, so tell the loader yourself when you run
the program, as Build and run shows.
Your first simulation
This program builds a closed unit cube, fills it with tetrahedrons, and lets it fall under gravity for one second.
Save it as src/main.rs.
use deformable::math::Vector3;
use deformable::scene::{MaterialParameters, ObjectOptions, Scene, TetrahedronMaterials};
use deformable::tools::{Anisotropy, TetrahedralizeParameters, TriangleMesh, tetrahedralize};
fn main() -> Result<(), Box<dyn std::error::Error>> {
// A closed unit cube: 8 corners and 12 outward triangles.
let positions: Vec<Vector3> = (0..8)
.map(|corner| Vector3::new(f64::from(corner & 1), f64::from(corner >> 1 & 1), f64::from(corner >> 2)))
.collect();
let triangles = vec![
[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],
];
let cage = TriangleMesh { positions, triangles };
// Fill the cage with tetrahedrons. None means no cancel flag.
let parameters = TetrahedralizeParameters {
maximum_edge_length: 0.5,
anisotropy: [Anisotropy::default(); 2],
density_regions: Vec::new(),
};
let mesh = tetrahedralize(&cage, ¶meters, None)?.mesh;
let mut scene = Scene::new();
let material = scene.add_material(&MaterialParameters::default())?;
let cube = scene.add_object(&mesh, TetrahedronMaterials::Uniform(material), ObjectOptions::default())?;
// 24 frames per second, 10 substeps per frame. The first call only records the time.
for frame in 0..=24 {
scene.step(f64::from(frame) / 24.0, 10, None)?;
}
let mut node_positions = Vec::new();
scene.node_positions(cube, &mut node_positions)?;
println!("{} nodes, first node at y = {:.3}", node_positions.len(), node_positions[0].y);
println!("libdeformable {}", deformable::version());
Ok(())
}Build and run
cargo run --release9 nodes, first node at y = -4.925
libdeformable 0.1.0The crate links libdeformable dynamically, so your program loads the shared library when it starts. cargo run
and cargo test tell the loader where the downloaded library is, so nothing else is needed while you develop.
Cargo does that only for folders inside your project’s target folder, so with DEFORMABLE_LIB_DIR set, tell the
loader yourself. On macOS:
DYLD_LIBRARY_PATH="$DEFORMABLE_LIB_DIR" cargo run --releaseOn Linux, set LD_LIBRARY_PATH instead. On Windows, nothing is needed: the build copies deformable.dll next to the programs it builds. The engine is already an
optimized build, so a debug build of your program runs the simulation at full speed too.
To read the documentation of every public item in your browser, run:
cargo doc -p deformable --openShip your program
A program you give to others needs the shared library next to it. Copy the library next to your executable, and tell the program to look there:
| Platform | File | How the program finds it |
|---|---|---|
| Windows | deformable.dll |
Windows looks in the executable’s folder first. |
| Linux | libdeformable.so |
Give the program the run path $ORIGIN. |
| macOS | libdeformable.dylib |
Give the program the run path @executable_. The library’s install name is @rpath/libdeformable.dylib. |
To set the run path, add a build.rs next to your Cargo.toml:
fn main() {
match std::env::var("CARGO_CFG_TARGET_OS").as_deref() {
Ok("linux") => println!("cargo:rustc-link-arg-bins=-Wl,-rpath,$ORIGIN"),
Ok("macos") => println!("cargo:rustc-link-arg-bins=-Wl,-rpath,@executable_path"),
_ => {}
}
}Then build, and copy the library next to the program. The build keeps the downloaded library in
target/release/build/deformable-*/out/library/; the C SDK zip of the same version holds the same file in its
lib/ folder. On macOS:
cargo build --release
cp target/release/build/deformable-*/out/library/libdeformable.dylib target/release/
./target/release/falling-cubeOn Windows, copy deformable.dll the same way.
The program now runs with no loader variable set, from any folder, as long as the library stays next to it.
A Standalone subscription or license belongs to each device that runs the program. On a colleague’s device, a server or a render farm node, the program runs as Free, up to 2,500 tetrahedrons per scene, unless that device has its own seat. To ship the engine inside an app you give to others, you need an Application license: your app then activates its key at every start, offline, and its users need no activation, network or seat. See Application license.
What the program does
tetrahedralizefills the closed triangle cage with tetrahedrons. It returns aTetrahedralization, whosemeshfield is aTetrahedralMesh.Scene::newcreates an empty scene with gravity (0, -9.81, 0).add_materialreturns aMaterialHandle, andadd_objectreturns anObjectHandle. Both count up from 0.add_objectcopies the mesh, so you can drop or reuse it afterwards.stepadvances the scene to a time in seconds. The first call only records the start time.node_positionsfills a vector you own with the current node positions.deformable::versionreturns the version of the library the program loaded.
The cube falls about 4.9 units in one second. Nothing stops it, because the scene has no floor. Scene adds one.
The cage has only 12 triangles, and tetrahedralize keeps the cage triangles as the boundary of the mesh, so the
cube gets only 12 tetrahedrons. Tools shows how to triangulate the cage first for a
finer mesh.
License
The crate works with Free, the Standalone subscription, and the Standalone and Application licenses. Without a sign-in or a key, it runs as Free, forever: every feature, up to 2,500 tetrahedrons per scene, with no account and no internet, and nothing is sent. A Standalone subscription or a Standalone license lifts the limit on your device. Sign in to the subscription once, in the browser, and the library checks it in by itself while the program runs online, at least once a day. Or activate a Standalone license key once, online, and the library renews it by itself, at least once every 7 days. Either one is shared with the plugins and the other SDKs on the same device. An app you ship to others uses an Application license instead: it activates the Application key at every start, offline, as its first Deformable call, before any engine call. Licensing has the whole story.
deformable::license reads and changes the license state. This program renews the Standalone subscription or license
when that is due, and prints the status line:
use deformable::license;
fn main() -> Result<(), deformable::Error> {
let status = license::refresh(license::DEFAULT_TIMEOUT)?;
println!("{}", status.message);
Ok(())
}Free: up to 2,500 tetrahedrons per scene| Function | What it does |
|---|---|
status() |
Returns a License in a Result: the state, days_ (of an Application trial), tetrahedron_ (Some(2500) on Free, None without a limit), has_, signed_ (true while a Standalone subscription is signed in on this device), the signed-in account’s email and the status line message. It never goes online. |
refresh(timeout) |
Renews the Standalone license, or checks in the Standalone subscription, when that is due. Call it when your program starts. On Free, and under an Application license, it contacts nothing. |
start_ |
Starts a sign-in with a Standalone subscription. Returns a Sign: the user_ to approve, the verification_ of the page that approves it, and expires_, how long the code lasts. Show both to the user, or open the address in the browser. |
wait_ |
Waits for the approval, for at most the timeout. Returns Some status once the account approved the sign-in: the state after it tries to take a seat, Standalone when a seat was free, otherwise the state that says why there is none (for example Subscription, where take_ can be offered). Or None while not yet: call it again. It can return up to 25 seconds after its timeout, so call it off your interface thread. |
take_ |
Moves the subscription’s seat to this device from the device that uses it. |
sign_ |
Forgets the sign-in on this device at once, even offline, and frees its seat when the device is online. |
activate(license_ |
Turns a license key on. A Standalone key, such as "tgdfp-xxxxx-xxxxx-xxxxx-xxxxx", is activated on this device and needs internet. An Application key, "tgdfp-<payload hex>-<signature hex>", is checked offline and holds for this run of the program, so call it at every start. |
deactivate(timeout) |
Forgets the Standalone license on this device at once, even offline, and frees its seat when the device is online. |
set_ |
With false, keeps the program off the network: nothing is sent, and a subscription or a Standalone license runs only as long as it runs offline. |
The state is a LicenseState, such as LicenseState::Free, StandaloneSubscription, StandaloneLicense or
ApplicationLicense. SubscriptionNeedsOnline, SubscriptionNoSeat (another device uses the seat, or this one was
removed), NoSubscription, SignInEnded, LicenseNeedsOnline (a Standalone license that needs a renewal) and
ApplicationTrialEnded run as Free, with its limit.
A sign-in shows a code and waits until the user approves it in the browser:
use std::time::Duration;
use deformable::license;
fn main() -> Result<(), deformable::Error> {
let sign_in = license::start_sign_in(license::DEFAULT_TIMEOUT)?;
println!("Open {} and approve the code {}", sign_in.verification_url, sign_in.user_code);
let status = loop {
if let Some(status) = license::wait_for_sign_in(Duration::from_secs(5))? {
break status;
}
};
println!("{}", status.message);
Ok(())
}Open https://platform.tangerina.io/device?user_code=ABCDEFGH and approve the code ABCD-EFGH
Standalone subscriptionWhen the code ends or the user denies it, the wait returns ErrorKind::LicenseSignInFailed, and the loop ends with
its message.
The timeouts are Durations; license::DEFAULT_TIMEOUT is 15 seconds. On Free, Scene::add_object returns
ErrorKind::TetrahedronLimitExceeded for an object that would take the scene past the limit, with a message such as
Free: this would simulate 3,120 tetrahedrons; the limit is 2,500 per scene. See
Errors and threads.
The crate
The crate has five public modules, and a few items at its root.
| Path | What it holds |
|---|---|
deformable |
Scene, its materials, objects, driven vertices, forces, glue and outputs, and the render surfaces: embed_ and Surface. |
deformable |
The mesh tools: triangulate, tetrahedralize, autocage, extrude, span_, splinters_, verify_, meshes_, and their parameter types. |
deformable |
The mesh types: Polygon, Tetrahedral, the face table FACES, and boundary_. |
deformable |
The value types: Vector3, Vector2, Matrix3 and Affine. |
deformable |
The license of this program and device: status, refresh, start_, wait_, take_, sign_, activate, deactivate, set_, Sign, License and License. |
deformable and deformable |
The error of every call that can fail, and the kind of failure. |
deformable |
A flag that stops a long call from another thread. |
deformable |
The version of the loaded library. |
The mesh types are plain structs with public fields, so you build them from your own data:
| Type | Fields |
|---|---|
Vector3 |
x, y, z, all f64. Vector3 builds one. It supports +, -, * and / by a scalar, dot and cross. |
Polygon |
positions: Vec<Vector3>, polygon_ (the corner count of each polygon) and polygon_ (the corners of every polygon, one polygon after another). |
Triangle |
positions: Vec<Vector3> and triangles: Vec<[u32; 3]>. In deformable. |
Tetrahedral |
positions: Vec<Vector3> and tetrahedrons: Vec<[u32; 4]>. Every tetrahedron must be positively oriented, as the tools make them, though a thick extrude shell can invert some where the mesh curves sharply. |
Affine |
linear: Matrix3 and translation: Vector3. Affine is the identity. |
The full list of items is in the Rust API Reference.
Conventions
These rules hold for the whole crate.
- Errors. Every call that can fail returns
Result<_, deformable::Error>. The library never panics on your input: it returns an error instead. See Errors and threads. - Handles. Materials and objects are
MaterialHandleandObjectHandlevalues, small copyable numbers that count up from 0 in creation order. ASceneand aSurfaceEmbeddingown memory inside the library, and free it when you drop them. - Outputs. The scene’s output methods fill a
Vecyou pass in. Reuse the same vectors every frame to avoid new allocations. - Units. Lengths are in your units. Time, forces, gravity, masses and material values are in simulation units. The scene’s scale converts your lengths to simulation lengths; it is 1 by default, so one unit reads as a metre. The tools work in the unit of their input. See Units and axes.
- License. On Free, a scene simulates up to 2,500 tetrahedrons, and
Scene::add_objectreturns a license error for an object past the limit.deformable::licensereads and changes the license. - Cancel flags. The calls that can run long take an
Option<&CancelFlag>. PassNonefor no flag, or set a flag from another thread to stop the call. - Threads.
SceneisSendbut notSync: move it to any thread, and call it from one thread at a time. The tools are safe to call from many threads at once. - Determinism. The same inputs and calls give bitwise identical results, run to run and for any worker count.
Helpers for the other pages
The examples on the other pages of this guide use two small helpers. Save them as src/shapes.rs, next to
src/main.rs. Each example starts with mod shapes; to use them.
// Each example uses only some of the helpers.
#![allow(dead_code)]
use deformable::Error;
use deformable::math::Vector3;
use deformable::mesh::{PolygonMesh, TetrahedralMesh};
use deformable::tools::{Anisotropy, TetrahedralizeParameters, TriangulateParameters, tetrahedralize, triangulate};
/// A closed box from `minimum` to `maximum`, as six outward quads.
pub fn cuboid(minimum: Vector3, maximum: Vector3) -> PolygonMesh {
let positions = (0..8)
.map(|corner| {
let pick = |bit: u32, low: f64, high: f64| if corner >> bit & 1 == 1 { high } else { low };
Vector3::new(pick(0, minimum.x, maximum.x), pick(1, minimum.y, maximum.y), pick(2, minimum.z, maximum.z))
})
.collect();
PolygonMesh {
positions,
polygon_sizes: vec![4; 6],
polygon_vertices: vec![0, 2, 3, 1, 4, 5, 7, 6, 0, 1, 5, 4, 2, 6, 7, 3, 0, 4, 6, 2, 1, 3, 7, 5],
}
}
/// Triangulates a closed polygon mesh, then fills it with tetrahedrons.
pub fn solid(polygons: &PolygonMesh, maximum_area: f64, maximum_edge_length: f64) -> Result<TetrahedralMesh, Error> {
let triangulate_parameters = TriangulateParameters { maximum_area: Some(maximum_area), ..TriangulateParameters::default() };
let cage = triangulate(polygons, &[], &triangulate_parameters, None)?.mesh;
let tetrahedralize_parameters = TetrahedralizeParameters {
maximum_edge_length,
anisotropy: [Anisotropy::default(); 2],
density_regions: Vec::new(),
};
Ok(tetrahedralize(&cage, &tetrahedralize_parameters, None)?.mesh)
}cuboid makes the artist’s polygons. solid turns them into a tetrahedral mesh in two steps: triangulate makes a
fine triangle cage, and tetrahedralize fills it. Tools explains both.
Next steps
- How the engine works: the ideas the plugins and every SDK share, explained once in the Engine guide.
- Scene: materials, objects, driven vertices, forces, stepping and outputs.
- Tools: the mesh tools that prepare a scene’s inputs.
- Render surfaces: skin a render mesh on a simulated object.
- Errors and threads: the error type, cancel flags and threads.