Avatar state, network sync and replays¶
Three things built on one description of an avatar's state (C reference: state, sync and replays):
- Save and restore: an avatar's whole state as one small versioned blob. Put back on an avatar of the same look, in this process or another, it goes on exactly as the original would have, update for update.
- Network sync: a stream that carries one avatar from a sender to a receiver in a few bytes a tick, over any transport, losses and reordering included. Receivers show the avatar on a puppet, and every receiver fed the same packets shows the same pose bits on any CPU.
- Replays: a recorder writes avatars' states into one compact file; a replay shows any track at any time, so seeking, slow motion, fast forward, reverse, kill-cams and bug reports are just a matter of which time the host asks for.
The sample is samples/c/net_session.c.
What a state holds¶
| Part | In the blob | On the network and in replays |
|---|---|---|
| Look | the manifest, packed, unless SONA_STATE_NO_LOOK |
sent once, until acknowledged: the manifest, or an id of the host's (sona_net_sender_look) |
| Placement | position, turn, scale and an eased move in progress | position (1/1024 m), turn (1/64 degree), scale |
| The clip | clip, time, speed, loop, the idle playlist, held or not, a play still loading | clip, time (to a fixed resolution of a 4096th of a second), speed, loop |
| Crossfade | the old clip, its time and speed, the fade's progress and length | the same |
| Queue and marks | every queued clip with its options; every mark | left out |
| Root motion | mode and the travel collected so far | mode |
| Overrides | every joint's rotation, weight and mode | rotation (1/32767), weight (1/4096), mode |
| Expression | the shapes the game set | the shapes the last pose showed |
| Layers | everything: kind, mode, mask, weight and its fade, both motions (clip or blend space, time, speed, blend point), a crossfade's still pose, the state machine and its state, the parameters | kind, mode, mask (1/255), effective weight, fade progress, both motions; not the still pose of an interrupted crossfade, nor the machine |
| IK | targets, feet, ground points, look-at, limits, and the smoothing (weights, look direction, hips, feet, eyes) | the same, quantised |
| IK additions | foot locking (and where each locked foot is held), spine assist, finger curl and its fade, eye turns and the eyes' own turn | left out |
| Props | each attached prop: a stock prop by its item id, a host mesh by a hash of its triangles; the joint, offset, flags, second hand and the prop's own clock | left out |
| Procedural idle | its options; it runs on the avatar's own clock | the same |
| The avatar's clock | yes: the idle and IK smoothing run on it | yes |
Clips are named so any machine can find them: a stock clip by its stable id (SONA_STOCK_*), any other clip by its
asset id, an imported clip by its key, the held prop's clip as "prop". Blend spaces and state machines are named by a
hash of their definition (clips, points, parameter names, transitions), so the loading ctx must create the same ones
first; sona_avatar_state_status reports SONA_STATE_MISSING_BLEND or _MACHINE when it has not. A ground callback
(SONA_IK_GROUND_CALLBACK) is code, not state: the loading avatar keeps its own, and without one the feet are not
planted (SONA_STATE_MISSING_GROUND).
Props: a stock prop is made again in the loading ctx from its item id (the same mesh is reused when the ctx already has
it); a host mesh is found among the loading ctx's own meshes by a hash of its triangles, so make the same mesh first, as
with blend spaces. A prop that finds no mesh is left off and missing gets SONA_STATE_MISSING_PROP (1 << 6);
sona_state_info's parts gets SONA_STATE_PART_PROPS (1 << 6). The avatar's props are replaced by the state's when
it is loaded. The blob carries both as sections after the snap ("PRPS", then "IKX1"); a blob without them loads as
before. A state with a host box in a hand and a stock pet playing its clip is 551 bytes; loaded into a second ctx the
props' frames and palettes match the saved avatar's exactly after 20 updates in step.
Not state: clip and layer events (they are about what happened, not what is), the face sheet's pixels (made again from the shapes) and anything the host keeps.
Save and restore¶
uint8_t *blob; size_t n;
/* 0.4 to 2 KB with the manifest; sona_free */
sona_avatar_save_state(a, 0, &blob, &n);
sona_avatar *b;
/* a new avatar with the blob's look and state */
sona_avatar_add_state(other_ctx, blob, n, NULL, &b);
/* or, into an avatar that already has the look:
sona_avatar_load_state(b, blob, n); */
uint8_t *blob = nullptr;
size_t n = 0;
// 0.4 to 2 KB with the manifest; sona_free
sona_avatar_save_state(avatar.raw(), 0, &blob, &n);
sona_avatar *copy = nullptr;
// a new avatar with the blob's look and state
sona_avatar_add_state(other_ctx.raw(), blob, n, nullptr, ©);
// or, into an avatar that already has the look:
// sona_avatar_load_state(copy, blob, n);
// 0.4 to 2 KB with the manifest
byte[] blob = avatar.SaveState();
// a new avatar with the blob's look and state
var copy = otherCtx.AddState(blob);
// or, into an avatar that already has the look: copy.LoadState(blob);
// the crate has no state wrapper: the C calls through sona_sys
let mut blob: *mut u8 = std::ptr::null_mut();
let mut n = 0usize;
let mut b: *mut sona_sys::sona_avatar = std::ptr::null_mut();
unsafe {
// 0.4 to 2 KB with the manifest
sona_sys::sona_avatar_save_state(avatar.raw(), 0, &mut blob, &mut n);
// a new avatar with its look and state
sona_sys::sona_avatar_add_state(ctx.raw(), blob as *const _, n,
std::ptr::null(), &mut b);
sona_sys::sona_free(ctx.raw(), blob as *mut _);
}
# 0.4 to 2 KB with the manifest
blob = avatar.save_state()
# a new avatar with the blob's look and state
copy = other_ctx.add_state(blob)
# or, into an avatar that already has the look: copy.load_state(blob)
The state goes on at the next sona_update once the avatar is READY and the clips it needs are loaded; until then the
avatar holds still and sona_avatar_state_status says SONA_STATE_WAITING. From then on the same updates give the
same pose bits as the avatar it was saved from, whatever it was doing: a crossfade, a masked one-shot, a blend
space, an override, an expression, a look-at, a hand target, the idle or an eased move. sona_state_info_get reads a
blob without a ctx.
Network sync¶
One stream per avatar per receiver. The sender writes a packet each tick; the receiver reads what arrives, sends back
the tick sona_net_read gives it, and drives a puppet a little behind the newest tick so there is something on both
sides to blend between.
/* sender, each tick */
uint8_t pkt[1500]; size_t n;
sona_net_write(tx, my_avatar, tick, pkt, sizeof pkt, &n);
send_unreliable(peer, pkt, n);
/* when an ack arrives */
sona_net_ack(tx, acked_tick);
/* receiver, for each packet */
uint32_t ack;
if (sona_net_read(rx, pkt, n, &ack) == SONA_OK) send_unreliable(sender,
&ack, 4);
/* once: the look */
sona_net_look look; look.size = sizeof look;
if (sona_net_receiver_look(rx, &look) == SONA_OK &&
look.kind == SONA_NET_LOOK_MANIFEST && !puppet)
sona_avatar_add(ctx, look.manifest, NULL, &puppet);
/* each frame: three ticks behind the newest, at the frame's own fraction
of a tick */
sona_net_drive(rx, puppet, render_tick - 3.0);
// the sender and the receiver made above; sona.hpp has no wrapper for them:
// the C calls on the handles
sona_net_sender *tx = nullptr;
sona_net_receiver *rx = nullptr;
uint32_t tick = 0, acked_tick = 0;
double render_tick = 0;
sona_avatar *puppet = nullptr;
auto send_unreliable = [](const void *, size_t) {}; // your network
// sender, each tick
uint8_t pkt[1500]; size_t n = 0;
sona_net_write(tx, avatar.raw(), tick, pkt, sizeof pkt, &n);
send_unreliable(pkt, n);
// when an ack arrives
sona_net_ack(tx, acked_tick);
// receiver, for each packet
uint32_t ack;
if (sona_net_read(rx, pkt, n, &ack) == SONA_OK) send_unreliable(&ack, 4);
// once: the look
sona_net_look look; look.size = sizeof look;
if (sona_net_receiver_look(rx, &look) == SONA_OK &&
look.kind == SONA_NET_LOOK_MANIFEST && !puppet)
sona_avatar_add(ctx.raw(), look.manifest, nullptr, &puppet);
// each frame: three ticks behind the newest, at the frame's own fraction of
// a tick
sona_net_drive(rx, puppet, render_tick - 3.0);
// the sender and the receiver made above; the binding has no wrapper for
// them: the calls of its raw Native layer
IntPtr tx = IntPtr.Zero, rx = IntPtr.Zero;
uint tick = 0, ackedTick = 0;
double renderTick = 0;
SonaAvatar puppet = null;
void SendUnreliable(byte[] data, int length) { } // your network
// sender, each tick
var pkt = new byte[1500];
UIntPtr n;
fixed (byte* p = pkt) Native.sona_net_write(tx, avatar.Handle, tick, p,
(UIntPtr)pkt.Length, &n);
SendUnreliable(pkt, (int)n);
// when an ack arrives
Native.sona_net_ack(tx, ackedTick);
// receiver, for each packet
uint ack;
fixed (byte* p = pkt)
if (Native.sona_net_read(rx, p, n,
&ack) == SonaResult.Ok) SendUnreliable(BitConverter.GetBytes(ack), 4);
// once: the look
var look = new Native.sona_net_look { size = (uint)sizeof(Native.sona_net_look) };
if (Native.sona_net_receiver_look(rx, &look) == SonaResult.Ok &&
look.kind == Native.SONA_NET_LOOK_MANIFEST && puppet == null)
{
var bytes = new byte[1000];
for (var i = 0; i < 1000; i++) bytes[i] = look.manifest[i];
puppet = ctx.Add(bytes);
}
// each frame: three ticks behind the newest, at the frame's own fraction of
// a tick
if (puppet != null) Native.sona_net_drive(rx, puppet.Handle,
renderTick - 3.0);
// the sender and the receiver made above; the crate has no wrapper for
// them: the C calls through sona_sys
let tx: *mut sona_sys::sona_net_sender = std::ptr::null_mut();
let rx: *mut sona_sys::sona_net_receiver = std::ptr::null_mut();
let (tick, acked_tick, render_tick) = (0u32, 0u32, 0.0f64);
let mut puppet: *mut sona_sys::sona_avatar = std::ptr::null_mut();
let send_unreliable = |_data: &[u8]| {}; // your network
// sender, each tick
let mut pkt = [0u8; 1500];
let mut n = 0usize;
unsafe { sona_sys::sona_net_write(tx, avatar.raw(), tick, pkt.as_mut_ptr(),
pkt.len(), &mut n) };
send_unreliable(&pkt[..n]);
// when an ack arrives
unsafe { sona_sys::sona_net_ack(tx, acked_tick) };
// receiver, for each packet
let mut ack = 0u32;
if unsafe { sona_sys::sona_net_read(rx, pkt.as_ptr() as *const _, n,
&mut ack) } == sona_sys::SONA_OK {
send_unreliable(&ack.to_le_bytes());
}
// once: the look
let mut look: sona_sys::sona_net_look = unsafe { std::mem::zeroed() };
look.size = std::mem::size_of::<sona_sys::sona_net_look>() as u32;
if unsafe { sona_sys::sona_net_receiver_look(rx,
&mut look) } == sona_sys::SONA_OK
&& look.kind == sona_sys::SONA_NET_LOOK_MANIFEST && puppet.is_null() {
unsafe { sona_sys::sona_avatar_add(ctx.raw(), look.manifest.as_ptr(),
std::ptr::null(), &mut puppet) };
}
// each frame: three ticks behind the newest, at the frame's own fraction of
// a tick
unsafe { sona_sys::sona_net_drive(rx, puppet, render_tick - 3.0) };
tx = sona.NetSender(ctx)
rx = sona.NetReceiver(ctx)
puppet = None
# sender, each tick
pkt = tx.write(avatar, tick)
send(peer, pkt)
# when an ack arrives
tx.ack(tick)
# receiver, for each packet
send(peer, rx.read(packet).to_bytes(4, "little"))
# once: the look
look = rx.look()
if look and look[0] == "manifest" and puppet is None:
puppet = ctx.add(look[1])
# each frame: three ticks behind the newest, at the frame's own fraction of
# a tick
rx.drive(puppet, render_tick - 3.0)
A packet is the format's version, the tick, how far back its baseline is (0 for a full state), a flags byte, the look
while it is not acknowledged, then the state coded against the baseline: per section (the clip, the crossfade, each
override, each layer and its mask, IK, the idle) how many instances changed and which, then each changed value as its
difference from the baseline's (exp-Golomb, as a bitmap or a list of the changed values, whichever is shorter). The
baseline is the newest state the receiver acknowledged; with no acknowledgement for full_after ticks (default one
second) a full state goes out. Times are not sent as times but as their phase against the tick: a clip that plays
on at its speed, and the avatar's clock, keep the same integer from tick to tick, so they cost nothing.
Sizes from the sample (net_session): thirty ticks a second, a link that loses a quarter of its packets each way and a delay of up to
three ticks. It ran on an RTX 4090 machine. Its
sender runs on the wall clock, so the sizes move by a byte or two from run to run:
| The sample's six-second session | Bytes |
|---|---|
| The first packet (with the manifest) | 316 |
| Every later packet, on average | 31.5 |
| A saved state of the sender | 1,764 |
Determinism. The receiver rebuilds every value from integers by IEEE divisions and multiplications in a fixed order, so every CPU gets the same doubles. A puppet's clocks stand still between drives (its clip, layers, fades, IK smoothing and idle move only when a state is put on it), and its face is set from the shapes the sender showed, so nothing an earlier frame left behind can change a later pose. The pose code is the same as everywhere else in the core (fdlibm trigonometry, no fused multiply-add), so the same state gives the same pose bits. So:
- two receivers fed the same packets in the same order show the same palette bits at every frame, through loss, reordering and repeats;
- a state decodes to the same integers whatever baseline it was coded against, so two receivers on different links show the same bits at every tick both hold;
- packets, decoded values and poses are the same bits on x86-64, arm64 and 32- and 64-bit big-endian PowerPC.
What it does not promise: poses before a puppet's clips are loaded (pending in sona_avatar_state_status); poses at
a tick that blends between two received ticks on receivers that hold different ticks; and, inside one ctx, the frame
cache shares a clip's sample between avatars whose clip times are the same at a fixed resolution of 0.1 ms, so a puppet sharing a ctx with
other avatars of the same clip can take their sample. Both peers must run SDK versions with the same packet format
(the first byte); a newer one is refused with SONA_E_UNSUPPORTED.
What the host chooses. tick_hz (both ends the same) and how far behind to drive (three ticks, a delay set to cover 100 ms of
jitter at a tick rate of 30 Hz); history (ticks kept, default 64) must cover the round trip, or packets coded against a dropped
baseline are refused until the next full state. A puppet let go (sona_avatar_puppet(a, 0)) plays on from its last
state like any avatar, for prediction when packets stop.
Replays¶
sona_recorder *rec;
sona_record_options ro;
sona_record_defaults(&ro);
/* a kill-cam: about the last ten seconds only; 0 keeps everything */
ro.keep_seconds = 10;
sona_recorder_create(ctx, &ro, &rec);
sona_recorder_track(rec, player, "player", NULL);
/* each tick */
sona_recorder_capture(rec, tick);
/* the file */
uint8_t *file; size_t n;
sona_recorder_save(rec, &file, &n);
/* playback: any time, any order */
sona_replay *rp;
sona_replay_open(ctx, file, n, &rp);
sona_replay_track(rp, 0, manifest, name, &from, &to);
/* speed 0.25 for slow motion, -1 for reverse */
t += dt * speed;
sona_replay_drive(rp, 0, puppet, t);
// sona.hpp has no wrapper for recordings: the C calls on the handles
sona_avatar *puppet = nullptr;
uint32_t tick = 0;
char name[64];
float from = 0, to = 0;
double t = 0, speed = 1;
sona_recorder *rec = nullptr;
sona_record_options ro;
sona_record_defaults(&ro);
// a kill-cam: about the last ten seconds only; 0 keeps everything
ro.keep_seconds = 10;
sona_recorder_create(ctx.raw(), &ro, &rec);
sona_recorder_track(rec, avatar.raw(), "player", nullptr);
// each tick
sona_recorder_capture(rec, tick);
// the file
uint8_t *file = nullptr; size_t n = 0;
sona_recorder_save(rec, &file, &n);
// playback: any time, any order
sona_replay *rp = nullptr;
uint8_t look[SONA_MANIFEST_BYTES];
sona_replay_open(ctx.raw(), file, n, &rp);
sona_replay_track(rp, 0, look, name, &from, &to);
// speed 0.25 for slow motion, -1 for reverse
t += dt * speed;
sona_replay_drive(rp, 0, puppet, t);
// the binding has no wrapper for recordings: the calls of its raw Native
// layer
IntPtr rec, rp;
SonaAvatar puppet = other;
uint tick = 0;
double t = 0, speed = 1;
var ro = new Native.sona_record_options();
Native.sona_record_defaults(&ro);
// a kill-cam: about the last ten seconds only; 0 keeps everything
ro.keep_seconds = 10;
Native.sona_recorder_create(ctx.Handle, &ro, &rec);
fixed (byte* name = System.Text.Encoding.UTF8.GetBytes("player\0")) Native.sona_recorder_track(rec, avatar.Handle, name, null);
// each tick
Native.sona_recorder_capture(rec, tick);
// the file
IntPtr file; UIntPtr n;
Native.sona_recorder_save(rec, &file, &n);
// playback: any time, any order
Native.sona_replay_open(ctx.Handle, (byte*)file, n, &rp);
// speed 0.25 for slow motion, -1 for reverse
t += dt * speed;
Native.sona_replay_drive(rp, 0, puppet.Handle, t);
// the crate has no wrapper for recordings: the C calls through sona_sys
let (tick, speed) = (0u32, 1.0f64);
let mut t = 0.0f64;
let mut rec: *mut sona_sys::sona_recorder = std::ptr::null_mut();
let mut rp: *mut sona_sys::sona_replay = std::ptr::null_mut();
let mut file: *mut u8 = std::ptr::null_mut();
let mut n = 0usize;
unsafe {
let mut ro: sona_sys::sona_record_options = std::mem::zeroed();
sona_sys::sona_record_defaults(&mut ro);
// a kill-cam: about the last ten seconds only; 0 keeps everything
ro.keep_seconds = 10.0;
sona_sys::sona_recorder_create(ctx.raw(), &ro, &mut rec);
sona_sys::sona_recorder_track(rec, avatar.raw(), c"player".as_ptr(),
std::ptr::null_mut());
// each tick
sona_sys::sona_recorder_capture(rec, tick);
// the file
sona_sys::sona_recorder_save(rec, &mut file, &mut n);
// playback: any time, any order
sona_sys::sona_replay_open(ctx.raw(), file as *const _, n, &mut rp);
// speed 0.25 for slow motion, -1 for reverse
t += dt * speed;
sona_sys::sona_replay_drive(rp, 0, other.raw(), t);
}
# a kill-cam: about the last ten seconds only; 0 keeps everything
rec = sona.Recorder(ctx, keep_seconds=10)
rec.track(avatar, "player")
# each tick
rec.capture(tick)
# the file
data = rec.save()
# playback: any time, any order
rp = sona.Replay(ctx, data)
look, name, start, end = rp.track(0)
seconds = 0.0
# 0.25 for slow motion, -1 for reverse
seconds += dt * 0.25
rp.drive(0, other, seconds)
The file holds each track's name, look and frames, each frame coded against the one before with a full state every
keyframe_ticks (default one second), so any moment is at most a second of decoding away; driving forwards decodes one
frame on from the last. The sample's recording of its six-second session is 5,420 bytes for
180 frames (the same run as above). Forwards, backwards or after any seek, half
ticks included, the same time gives the same pose bits, and at every tick they are the network puppet's bits at that
tick.
Untrusted input¶
Packets, blobs and replay files come from other machines, so every state read from one is checked before it goes on an
avatar. The codec refuses a value outside the range any encoder writes (2^52) with SONA_E_CORRUPT; then every real is
made finite and kept within 10^12, and each part is put into what its public setter accepts or dropped where the setter
would refuse it: an IK target relative to a joint that does not exist, a wrist flag on a foot or unknown flags lose the
target; feet on an unknown ground or a plane with no normal are turned off; look and limit angles, weights, masks and
fades are clamped to their ranges; a layer of an unknown kind or mode is emptied, a clip layer whose motion is a blend
space (or the other way round) takes the motion's kind, a still pose on the new side of a crossfade is dropped, and a
state machine state is kept only when the machine has it; overrides on the root or with no rotation, unknown root motion
modes and look shapes are dropped. A state this SDK wrote passes through unchanged, bit for bit.
Damaged or hostile input (a joint index far out of range, random values in a real state's fields, flipped bits in a blob or a replay file) is refused or posed with finite palette values; it never crashes the receiver.
The sample¶
samples/c/net_session.c runs three peers, each its own ctx as on its own machine: a sender playing a six-second
script, and two receivers fed the same packets over a link that loses a quarter of them and delivers the rest up to
three ticks late. It draws, headless, the sender and the receiver's puppet side by side at six moments, a strip of the
packets (grey: lost), and the recording played back in reverse; it also puts a state saved halfway on a fresh avatar.
It exits 1 when the receivers ever disagree, the restored pose differs, or a cell is empty.
net_session --cast devs-cast.json --pick 53 --out net-session.png --replay \
net-session.snrp
Formats¶
- Blob:
SNST, the format version (varint, 1), a flags byte (1: a look follows), the packed manifest, then sections: id, instance, byte length, field count, fields (doubles tagged: 0, 1, a float that holds them exactly, or all 8 bytes), and0xFF. Readers skip sections and trailing fields they do not know, so later versions can add both. - Packet: version byte (1), tick, baseline distance, flags, the look (version, kind, packed manifest or id), the coded state.
- Replay:
SNRP, version (1), ticks a second, keyframe spacing, tracks; per track its name, look and frames (tick step, keyframe flag, length, coded state).
Every multi-byte value is written byte by byte, little-endian; nothing depends on the host's byte order.
This page as Markdown · All the docs as one file (llms-full.txt)