﻿---
title: Getting started with Rust
description: Add the deformable crate to a Cargo project, build it with the library it downloads, and run your first simulation from Rust.
url: https://help.tangerina.io/deformable/v0.3.0/user-guides/rust/getting-started/
---

# Getting started with Rust – Rust SDK – Deformable v0.3.0

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](https://help.tangerina.io/deformable/v0.3.0/user-guides/engine/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:

```sh
cargo new falling-cube
cd falling-cube
cargo add deformable
```

That is all. The first `cargo build` downloads `libdeformable`, the shared library the crate links, for your platform
and the crate's version from `https://downloads.tangerina.io`. 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](https://tangerina.io/deformable#download-c), 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:

```sh
xattr -dr com.apple.quarantine /path/to/deformable-c-v0.1.0-macos-arm64
```

Set `DEFORMABLE_LIB_DIR` to the absolute path of the `lib/` folder before you build:

```sh
export DEFORMABLE_LIB_DIR=/path/to/deformable-c-v0.1.0-macos-arm64/lib
```

On Windows, in PowerShell:

```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:

```toml
[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](#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`.

```rust
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, &parameters, 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

```sh
cargo run --release
```

```text
9 nodes, first node at y = -4.925
libdeformable 0.1.0
```

The 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:

```sh
DYLD_LIBRARY_PATH="$DEFORMABLE_LIB_DIR" cargo run --release
```

On 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:

```sh
cargo doc -p deformable --open
```

## Ship 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_path`. The library's install name is `@rpath/libdeformable.dylib`. |

To set the run path, add a `build.rs` next to your `Cargo.toml`:

```rust
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:

```sh
cargo build --release
cp target/release/build/deformable-*/out/library/libdeformable.dylib target/release/
./target/release/falling-cube
```

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

The Standard license belongs to each device that runs the program. On a colleague's device, a server or a render
farm node, the program runs under the Free license, 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 a Developer license: your app then activates its
key at every start, offline, and its users need no activation, network or seat. See
[Developer license](https://help.tangerina.io/deformable/v0.3.0/licensing/#developer-license).

## What the program does

1. `tetrahedralize` fills the closed triangle cage with tetrahedrons. It returns a `Tetrahedralization`, whose
   `mesh` field is a `TetrahedralMesh`.
2. `Scene::new` creates an empty scene with gravity (0, -9.81, 0).
3. `add_material` returns a `MaterialHandle`, and `add_object` returns an `ObjectHandle`. Both count up from 0.
4. `add_object` copies the mesh, so you can drop or reuse it afterwards.
5. `step` advances the scene to a time in seconds. The first call only records the start time.
6. `node_positions` fills a vector you own with the current node positions.
7. `deformable::version` returns the version of the library the program loaded.

![A tetrahedral cube is added as an object, then falls further each frame, and its node positions are read after every step.](https://help.tangerina.io/deformable/v0.3.0/images/sdk-first-simulation-loop.svg)

The cube falls about 4.9 units in one second. Nothing stops it, because the scene has no floor.
[Scene](https://help.tangerina.io/deformable/v0.3.0/user-guides/rust/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](https://help.tangerina.io/deformable/v0.3.0/user-guides/rust/tools/) shows how to triangulate the cage first for a
finer mesh.

## License

The crate works with all three licenses. Without a key, it runs under the Free license, forever: every feature, up to
2,500 tetrahedrons per scene, with no account and no internet, and nothing is sent. A Standard license lifts the limit
on your device: activate its key once, online, and the library renews it by itself while the program runs online, at
least once every 14 days. It is shared with the plugins and the other SDKs on the same device. An app you ship to others
uses a Developer license instead: it activates the Developer key at every start, offline, as its first Deformable call,
before any engine call. [Licensing](https://help.tangerina.io/deformable/v0.3.0/licensing/) has the whole story.

`deformable::license` reads and changes the license state. This program renews the Standard license when that is due,
and prints the status line:

```rust
use deformable::license;

fn main() -> Result<(), deformable::Error> {
    let status = license::refresh(license::DEFAULT_TIMEOUT)?;
    println!("{}", status.message);
    Ok(())
}
```

```text
Free license: up to 2,500 tetrahedrons per scene — Buy license
```

| Function | What it does |
|---|---|
| `status()` | Returns a `LicenseStatus` in a `Result`: the `state`, `days_left` (of a Developer trial), `tetrahedron_limit` (`Some(2500)` under the Free license, `None` without a limit), `has_license_key` and the status line `message`. It never goes online. |
| `refresh(timeout)` | Renews the Standard license when that is due. On a Standard license, call it when your program starts. Without a key, and under a Developer license, it contacts nothing. |
| `activate(license_key, timeout)` | Turns a license key on. A Standard key, such as `"tgdfp-xxxxx-xxxxx-xxxxx-xxxxx"`, is activated on this device and needs internet. A Developer 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 Standard license on this device at once, even offline, and frees its seat when the device is online. |
| `set_online_access(allowed)` | With `false`, keeps the program off the network: nothing is sent, and the Standard license runs only as long as it runs offline. |

The state is a `LicenseState`, such as `LicenseState::FreeLicense`, `StandardLicense` or `DeveloperLicense`.
`NeedsOnline` (a Standard license that needs a renewal) and `DeveloperTrialEnded` run under the Free license, with its
limit.

The timeouts are `Duration`s; `license::DEFAULT_TIMEOUT` is 15 seconds. Under the Free license, `Scene::add_object`
returns `ErrorKind::TetrahedronLimitExceeded` for an object that would take the scene past the limit, with a message
such as **Free license: this would simulate 3,120 tetrahedrons; the limit is 2,500 per scene**. See
[Errors and threads](https://help.tangerina.io/deformable/v0.3.0/user-guides/rust/errors/#license-errors).

## The crate

The crate has five public modules, and a few items at its root.

| Path | What it holds |
|---|---|
| `deformable::scene` | `Scene`, its materials, objects, driven vertices, forces, glue and outputs, and the render surfaces: `embed_surface` and `SurfaceEmbedding`. |
| `deformable::tools` | The mesh tools: `triangulate`, `tetrahedralize`, `autocage`, `extrude`, `span_layers`, `splinters_from_image`, `verify_surface`, `meshes_intersect`, and their parameter types. |
| `deformable::mesh` | The mesh types: `PolygonMesh`, `TetrahedralMesh`, the face table `FACES`, and `boundary_faces`. |
| `deformable::math` | The value types: `Vector3`, `Vector2`, `Matrix3` and `AffineTransform`. |
| `deformable::license` | The license of this program and device: `status`, `refresh`, `activate`, `deactivate`, `set_online_access`, `LicenseStatus` and `LicenseState`. |
| `deformable::Error` and `deformable::ErrorKind` | The error of every call that can fail, and the kind of failure. |
| `deformable::CancelFlag` | A flag that stops a long call from another thread. |
| `deformable::version` | 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::new(x, y, z)` builds one. It supports `+`, `-`, `*` and `/` by a scalar, `dot` and `cross`. |
| `PolygonMesh` | `positions: Vec<Vector3>`, `polygon_sizes: Vec<u32>` (the corner count of each polygon) and `polygon_vertices: Vec<u32>` (the corners of every polygon, one polygon after another). |
| `TriangleMesh` | `positions: Vec<Vector3>` and `triangles: Vec<[u32; 3]>`. In `deformable::tools`. |
| `TetrahedralMesh` | `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. |
| `AffineTransform` | `linear: Matrix3` and `translation: Vector3`. `AffineTransform::IDENTITY` is the identity. |

The full list of items is in the [Rust API Reference](https://help.tangerina.io/deformable/v0.3.0/api-references/rust/overview/).

## 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](https://help.tangerina.io/deformable/v0.3.0/user-guides/rust/errors/).
- **Handles.** Materials and objects are `MaterialHandle` and `ObjectHandle` values, small copyable numbers that
  count up from 0 in creation order. A `Scene` and a `SurfaceEmbedding` own memory inside the library, and free
  it when you drop them.
- **Outputs.** The scene's output methods fill a `Vec` you 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](https://help.tangerina.io/deformable/v0.3.0/user-guides/engine/how-the-engine-works/#units-and-axes).
- **License.** Under the Free license, a scene simulates up to 2,500 tetrahedrons, and `Scene::add_object` returns a
  license error for an object past the limit. `deformable::license` reads and changes the license.
- **Cancel flags.** The calls that can run long take an `Option<&CancelFlag>`. Pass `None` for no flag, or set a
  flag from another thread to stop the call.
- **Threads.** `Scene` is `Send` but not `Sync`: 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.

```rust
// 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](https://help.tangerina.io/deformable/v0.3.0/user-guides/rust/tools/) explains both.

## Next steps

- [How the engine works](https://help.tangerina.io/deformable/v0.3.0/user-guides/engine/how-the-engine-works/): the ideas the plugins and every SDK
  share, explained once in the Engine guide.
- [Scene](https://help.tangerina.io/deformable/v0.3.0/user-guides/rust/scene/): materials, objects, driven vertices, forces, stepping and
  outputs.
- [Tools](https://help.tangerina.io/deformable/v0.3.0/user-guides/rust/tools/): the mesh tools that prepare a scene's inputs.
- [Render surfaces](https://help.tangerina.io/deformable/v0.3.0/user-guides/rust/render-surfaces/): skin a render mesh on a simulated object.
- [Errors and threads](https://help.tangerina.io/deformable/v0.3.0/user-guides/rust/errors/): the error type, cancel flags and threads.
