Recursive AI

Bake a physics simulation to an animation cache in C#

OnePhysics is a free, open-source physics library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

Use BeginBake to record motion and BakeClip to read it without running physics again.

Terminal
dotnet add package RecursiveAI.OnePhysics

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using RecursiveAI.OnePhysics.Bake;
using RecursiveAI.OnePhysics.Physics3D;
var world = new PhysicsWorld3D();
world.AddBox(new(1, 1, 1), at: new(0, 4, 0));
using var bake = world.BeginBake(new());
for (int i = 0; i < 60; i++)
    world.Step(1f / 60);
var clip = BakeClip.Parse(bake.Finish());
var box = clip.Rigid.Single();
if (!box.TrySampleRigid(0.5, out var pose))
    throw new InvalidOperationException("No pose.");
Console.WriteLine(FormattableString.Invariant(
    $"Box Y: {pose.Position.Y:F2} m"));

Unzip the example, then dotnet run.

The snippet bakes one falling box to an in-memory cache and prints its height half a second in:

Text
Box Y: 2.75 m

The full program

This version bakes a crate starting 4 meters up and a static floor whose top is at Y = 0. It writes crate.bake and reopens it after WriteCache returns. The reader uses the crate’s saved handle index and generation to choose its track, instead of assuming the crate is the only body in the cache.

C#
using RecursiveAI.OnePhysics;
using RecursiveAI.OnePhysics.Bake;
using RecursiveAI.OnePhysics.Physics3D;
 
const string path = "crate.bake";
var (crateSlot, crateGeneration) = WriteCache(path);
 
using var file = File.OpenRead(path);
var clip = BakeClip.Read(file);
var crate = clip.FindRigid(crateSlot, crateGeneration);
foreach (double time in new[] { 0.0, 0.5, 1.75 })
{
    if (crate is null || !crate.TrySampleRigid(time, out var pose))
        throw new InvalidOperationException("No crate pose at that time.");
 
    Console.WriteLine(FormattableString.Invariant(
        $"At {time:F2} s: crate Y = {pose.Position.Y:F2} m"));
}
 
static (int Slot, int Generation) WriteCache(string destination)
{
    var world = new PhysicsWorld3D();
    world.AddBox(new(10, 1, 10), at: new(0, -0.5, 0),
        type: BodyType.Static);
    var crate = world.AddBox(new(1, 1, 1), at: new(0, 4, 0));
 
    const float dt = 1f / 60;
    using var bake = world.BeginBake(new BakeOptions
    {
        Dt = dt, FrameStride = 2, Tracks = BakeTracks.Rigid
    });
    for (int i = 0; i < 120; i++)
        world.Step(dt);
    File.WriteAllBytes(destination, bake.Finish());
    return (crate.RawHandle.Index, crate.RawHandle.Generation);
}
Text
At 0.00 s: crate Y = 4.00 m
At 0.50 s: crate Y = 2.75 m
At 1.75 s: crate Y = 0.50 m

The last pose is the center of the one-meter crate resting on the floor. If a sample returns false, check that the requested time is inside that body’s recorded lifetime. Keep the step length equal to BakeOptions.Dt; a mismatch faults the recording and Finish() throws.

Variations

Store every physics step. Replace the options initializer in WriteCache with:

C#
new BakeOptions { Dt = dt, FrameStride = 1, Tracks = BakeTracks.Rigid }

A stride of 1 stores 121 frames instead of 61 for the same 120 steps, counting the initial pose in both cases.

The short answer

Build your scene, call BeginBake, and step it at a fixed interval. Save the bytes from Finish() or pass them straight to BakeClip.Parse. During playback, sample the track for each animated object at the current time. The baking guide says, “BakeClip opens the cache and samples it by time.” Your renderer applies the returned position and rotation to its own object.

What does baking physics do?

It stores the result of the simulation rather than the inputs needed to run it again. Use it for a cutscene whose crate drop starts the same way on every playback, not for a crate the player can knock sideways. The cache is a OnePhysics file read by BakeClip, not a set of editor keyframes. If the floor moves or the crate starts somewhere else, bake a new cache to see the new motion.

BakeOptions.Tracks controls what’s saved. The full example keeps only rigid-body tracks: body origin and rotation. The track list also includes soft bodies and cloth, rods and ropes, particles, fractures, and events. A body created midway through recording starts its track later than frame zero, so a player should show it only when the sample succeeds.

Can you play a physics cache between recorded frames?

Yes. Frame zero holds the state when you call BeginBake. At 60 steps per second and FrameStride = 2, poses are stored about every 1/30 second. The sample at 1.75 seconds falls between stored frames. According to the sampling rules, positions interpolate linearly and rotations use normalized linear interpolation along the shorter arc. The sampler reads those two poses; it doesn’t calculate what the solver would have done on a missing tick.

A lower stride stores more poses when you want to capture quick changes in motion. It does not change the physics step itself. A cache stores quantized poses by default, so use a snapshot or replay if you need to restore simulation state rather than draw an animation.

All onephysics recipes