Serialization And Replay
To resume a Gravitas simulation from a record, create the context and physics objects in your host first. Chronicler writes saved physics values into those existing objects, including their bodies and concrete collider shapes. Use the resulting state for save-state testing, replay, or rollback-style validation.
Quick Read
Advance a 3D crate through four fixed steps. Queue a torque for its next step, then save its body record. To replay from that point, prepare another crate with the same collider shape in a world on the matching frame and timeline. Populating the body record restores values such as mass and the queued torque into that existing crate. Step both worlds with the same subsequent commands.
flowchart TB
accTitle: Restore a crate at a replay checkpoint
accDescr: Save a body record and prepare a matching host world and crate. Populate the prepared body, then continue stepping with the same commands.
Save["Saved record"] --> Load["Populate the body"]
Shell["Prepared crate"] --> Load
Load --> Replay["Continue stepping"]
The host supplies the timeline and object bindings. Compare replay hashes only once the worlds have equivalent continuation state, including any live contact caches that affect the next step. See the restore order and hash comparison rules.
Ownership Contract
| Host-created shell | Serialized state |
|---|---|
GravitasWorldContext and GridWorld |
Settings that affect deterministic execution. |
IMatterAgent, FixedTransform, engine wrappers |
Body position, rotation, motion type, velocities, force/torque stores, gravity scale, sleep, CCD, freeze axes. |
SolidBody, SolidBody2D |
3D grounding state and 2D planar support state. |
Concrete LSCollider and LSCollider2D types |
Active/trigger state for bodyless trigger volumes, layer, local ignored physical layers, material, local offset, shape inputs, mixed half-thickness override. |
| Compound runtime shells and private part colliders | Authored shape/part values needed to rebuild deterministic geometry. |
Existing registered Joint3D, Joint2D, ragdoll runtimes |
Joint enabled state, type, frames, limits, motors, linked collision policy, ragdoll activation state. |
Existing StaticSurface, StaticSurface2D handles |
Declared membership through typed links to registered collider lifetimes. |
| Renderer, ECS, networking, pooling, editor state | Nothing. These remain host-owned. |
Derived State And Host Bindings
The following values stay outside the record. The runtime rebuilds derived state as needed, and the host supplies bindings and callbacks.
- context-local collider IDs and service indices.
- GridForge partition coordinate lists and active partition payloads.
- collision pairs, pair holder references, warm runtime pair caches, query buffers, diagnostic buffers, and pooled collections.
- derived collider bounds and transformed mesh caches. Absolute endpoints, corners, and contact/query witnesses are materialized on demand from canonical rigid-frame and local geometry rather than stored as runtime authority.
- context-local joint IDs, ragdoll IDs, articulation suppression tables, and service-owned joint/ragdoll arrays.
- lifecycle hooks, delegates, renderer callbacks, and event subscribers.
- host transform object identity.
- 3D visual interpolation buffers and presentation-only rotation speed state.
Validation And Publication
On load, bodies publish restored authoritative position and rotation into their existing host transform. A restored 3D quaternion is scale-safely normalized before any runtime shape or host state observes it; a zero quaternion resolves to identity. 3D visual interpolation buffers reset from that authoritative state instead of being treated as replay truth.
Continuous-collision modes are validated at the settings and body publication
boundaries. Inherit, Discrete, Continuous, and Auto load normally;
undefined byte-cast values throw ArgumentOutOfRangeException. A rejected body
value does not replace its previously valid mode, and a rejected
PhysicsSettingsSaver does not replace the context's existing settings.
The MotionType field records the body's PhysicsMobilityType and defaults to
Dynamic when the field is absent. The runtime validates motion type and freeze
masks before publishing loaded body state. Loading a different role into an already
registered shell reconciles simulated-body membership, partitions, CCD state,
and solver caches through the same atomic lifecycle invariants as a public role
transition. Undefined roles or freeze bits fail without partially publishing the
new state.
Mass retains its existing "Mass" record key. Loading writes backing state and
refreshes derived inertia and awake membership at the final load commit; it
preserves recorded sleep and motion rather than invoking the public mass
setter's wake policy. Restoring an active body clears contact and
connected-joint impulse caches and prepared CCD state while retaining pair and
joint identity.
Loaded geometry passes the same effective-size admission as initialization, including host-scale compensation and complete body/compound attachment reach. An unsupported candidate cannot publish new runtime geometry or partitions. Optional mixed thickness must remain positive; its mixed-size budget applies when the slab is used. Successful loads retain saved sleep rather than invoking the waking geometry setters.
This protects geometry publication, not arbitrary payload application as a whole. Chronicler can write authored or body fields before a nested geometry load fails. After a rejected record, restore a known valid payload or discard the affected shell before resuming simulation; do not assume the entire record rolled back.
Recordable Types
The 3D body record starts with BodySchemaVersion = 1 and a signed 64-bit
LastGroundCheckFrame. A nonnegative value is an absolute simulation frame;
-1 means no cached probe. Missing or unsupported schema versions and invalid
negative stamps reject before any body fields are changed, consistently in JSON
and MemoryPack. Unversioned narrow-frame body snapshots are not accepted.
The 2D body does not persist its ground-check frame: its support lookup cache is invalidated on population and rebuilt by simulation. Its record shape is unchanged. Neither body record restores the containing world's clock. Hosts must coordinate matching timeline and runtime-shell state before continuation; there is no live-world rewind API.
| Type | What it records | What it does not own |
|---|---|---|
SolidBody |
3D position/height, rotation, motion type, freeze axes, motion stores, mass, COM, gravity scale, sleep, CCD, grounding/probe state, owned collider state. | FixedTransform identity, service IDs, partitions, pairs. |
SolidBody2D |
X/Z position, scalar rotation, motion type, freeze axes, planar motion stores, scalar angular state, mass, COM, scalar moment policy, gravity, grounding/probe state, sleep, CCD, owned collider state. | Host transform identity, runtime service IDs, query buffers. |
LSCollider |
3D active state, bodyless trigger state, layer/filter state, local ignored physical mask, material, shape state. | Context-owned collider ID, partition identity, pairs/events. |
LSCollider2D |
2D active state, bodyless trigger state, layer/filter state, material, shape-local values, mixed half-thickness override. | Context-owned collider ID, private runtime pair/partition state. |
ColliderShapeDefinition |
Data-only 3D authoring/import values for primitive, mesh, and compound part inputs. | Runtime body, context, collider ID, pairs, hierarchy, events. |
ColliderShapeDefinition2D |
Data-only 2D authoring/import values for circle, capsule, AABB, convex polygon, triangle convenience, and compound parts. | Runtime body, context, collider ID, pairs, hierarchy, events. |
PhysicsSettingsSaver |
Frame rate, collision matrix, ground mask, CCD settings, restitution threshold, retained partition cleanup, runtime mode, mixed 2D thickness. | Runtime service state. |
Joint3D / Joint2D |
Mutable joint continuation state: enabled flag, type, frames/anchors, limits, motors, linked-collider policy. | Body link construction, service joint IDs, solver caches. |
RagdollRuntime3D / RagdollRuntime2D |
Runtime activation state for existing handles. | Definitions, link bodies, colliders, joint ownership. |
StaticSurface / StaticSurface2D |
Versioned membership and typed member links through IRecordable. |
Collider construction, derived joins, contacts, spatial indexes. |
PhysicsLayer / PhysicsLayerMask |
JSON/MemoryPack-friendly value fields. | Chronicler graph identity. |
Collider geometry can derive default COM/mass properties for new shells, but populated snapshots restore body-owned COM state directly where that state is authoritative.
A successful SolidBody.TryReconfigureCollider(...) becomes ordinary
authoritative body/collider state: the published body root, local offset, and
primitive geometry are recorded by the existing serialization paths. The
operation itself, detached fit candidate, returned blocker, invalidated pairs,
and refreshed partition coordinates are not serialized. A blocked or invalid
attempt publishes nothing, so its serialized payload and authoritative replay
hash remain unchanged.
Retained contacts and pair-local warm-start impulses affect the next response
and contribute to the authoritative replay hash. They belong to the live
context. Populating body records clears the affected warm starts and joint
impulses, as described above. The extended
GravitasReplayHashMode.AuthoritativeWithSolverCaches adds diagnostic state
such as joint solve metrics and additional solver bookkeeping.
Retained manifold witnesses and witnesses in diagnostic cache sections are
hashed as the canonical Origin, Rotation, LocalPoint, and
LocalDisplacement components of their ContactAnchor or ContactAnchor2D
frame. A clipped or
unavailable rotated offset or absolute world point is not replay truth. Derived
bounds and other rebuildable shape caches remain outside the authoritative shape
hash and are covered only by their dedicated cache section.
Joint and ragdoll handles are valid serialization targets only while registered with their owning constraint service. Endpoint teardown removes dependent joints and any owning ragdoll before collider identity release; removed handles reject save and load operations instead of applying state to a later pooled body or collider lifetime. Context reset and disposal invalidate those handles by the same rule.
Static Surface Membership
The host creates
surface handles through the
owning dimensional physics service and supplies Chronicler's typed links to
existing registered collider lifetimes. RecordData(...) records
SurfaceSchemaVersion = 1, the member count, and those links. Restore body and
collider state first, then populate the existing surface handle between fixed
steps. An empty handle can serve as the reconstruction target.
Loading resolves and validates the complete candidate membership before publishing it. Missing, foreign, stale, duplicate, ineligible, or already-owned members reject without replacing the previous declaration. Context reset, disposal, and disposed handles cannot be restored into a new lifetime; create a new handle and resolve links to the reconstructed colliders. Reactivation alone does not restore lost membership.
Membership affects authoritative replay hashes through canonical live registration identity, independently of input member order or recycled collider IDs. Derived adjacency, surface geometry caches, and contact ownership caches are rebuilt rather than recorded. A recorded declaration does not reconstruct its collider geometry or host objects.
Replay Workflow
For a scene with more objects than the single crate, restore dependencies in this order.
- Create or attach a
GravitasWorldContextwith matching settings and GridForge world setup. - Create host agents, transforms, bodies, and concrete collider shapes in the same stable order the host expects.
- Materialize authored 3D and 2D compound assets from
ColliderShapeDefinition,ColliderShapeDefinition2D, and compound part data before binding. - Populate settings first when the snapshot includes
PhysicsSettingsSaver. - Populate body/collider/joint/ragdoll state into existing shells, then restore static-surface membership links when used.
- Continue fixed-step simulation from the restored frame using the same ordered input commands.
For dynamic replay tests, compare authoritative body/collider values and observable collision/query behavior at the checkpoint. Advance the matching host-created shell and timeline with the same subsequent inputs. When loading clears a cache that affects response, compare exact replay against a control with equivalent live continuation state. Measure the recovery against the uninterrupted warm run separately.
Replay Hashes
GravitasWorldContext.ComputeReplayHash() is the preferred compact conformance
signal for checking replay and rollback continuation.
Apply ordered host commands before each fixed step, call Simulate() and then
LateSimulate() exactly once, and compute the frame hash after both phases
complete. Simulate() advances the clock, coroutines and simulate hooks;
LateSimulate() completes physics and late hooks. A late-only trace omits part
of the authoritative host lifecycle. Presentation phases may run between fixed
steps and must leave the authoritative hash unchanged.
Compare relevant host events and coroutine effects separately: a physics-state hash does not include arbitrary host state.
Compare peers using identical initial state, settings, ordered commands and replay-hash schema versions. Record OS/CPU architecture, runtime and dependency versions separately from authoritative state so differences can be diagnosed without changing the equality contract. Native execution provides evidence for the workloads and platforms exercised; repeated agreement on one machine does not establish agreement across all platforms.
Contexts with equivalent continuation state and ordered inputs should produce
the same per-frame ChronicleHash sequence after population. Equivalence
includes replay-relevant live state such as retained contacts and warm-start
impulses.
What The Hash Covers
The authoritative hash covers context state that can affect continuation:
- serialized continuation state is included.
- host-owned bindings are excluded.
- derived shape caches are excluded from the authoritative shape hash.
- live pair identity, retained contact state, and pair warm starts are included.
- active cross-frame CCD handoff state is included because it can affect the next fixed step.
- runtime collider IDs are context-local lookup and pair keys; replay hashes use canonical live registration order with dense replay ordinals for collider, hierarchy, and pair identity, so deleted collider ID history and allocator holes are excluded.
- additional solver cache state and diagnostic counters are included in
AuthoritativeWithSolverCachesmode for RCA.
Hash Schema
Replay hashes use Chronicler.Hashing.ChronicleHash and Chronicler's
hash-writer mechanics. Gravitas owns the physics-specific inclusion policy and
deterministic ordering. The root gravitas.replay section is version 3. The
hash mode, 3D shape definition kind, mesh inertia policy, and material combine
policies each contribute one byte. Frame and late-phase stamps are signed 64-bit
values, and elapsed time is ordered whole seconds (long) then fractional
seconds (uint). Affected body, pair, manifold, and cache sections are
versioned independently for their widened stamps. The body.3d section is
version 7 and includes the automatic support-normal threshold; body.2d remains
version 4. The pair.mixed section is version 9 and records retained
contact-geometry freshness without hashing historical publication counters or
poses. Hashes from older schema versions are not comparable.
Sparse transports that omit a default-valued MotionType deterministically
resolve it to Dynamic. Both body recorders validate GroundMinNormalDot in
[0, 1] before publishing loaded state and default missing values to one half.
2D restores gravity and support policy through backing state to preserve saved
sleep, then rebuilds its transient support ownership and probe timing. Its
recorded fields and replay hash layout remain unchanged.
Transport Notes
Import Chronicler.Serialization for JsonRecordSerializer,
MemoryPackRecordSerializer, converters, and SerializationPayloadEditor.
Recording contracts and helpers remain in Chronicler; replay hash values and
writers use Chronicler.Hashing. Rebuild consuming assemblies together when
updating these imports. See the
migration guide
for the payload-editor replacements and hash compatibility notes.
Standard Release builds include MemoryPack support through the standard
dependency chain. ReleaseLean defines GRAVITAS_DISABLE_MEMORYPACK, excludes
the direct MemoryPack package, and relies on shim attributes needed for the same
core API to compile without built-in MemoryPack support.
When changing serialized fields, defaults, or load behavior:
- add or update save/populate tests under
tests/Gravitas.Tests/Serialization. - cover JSON and MemoryPack in standard builds.
- keep the same source compiling under
ReleaseLean. - run focused replay tests that serialize, restore into a fresh shell, and continue simulation.
- document whether the field is authoritative simulation state, host-owned binding, or runtime cache.
Rules That Matter
- Do not turn Chronicler loading into a construct-from-data object factory.
- Do not serialize host bindings such as engine objects, renderers, or external transform object identity.
- Do not serialize context-local IDs as portable identity.
- Keep JSON and MemoryPack behavior aligned when both are supported.
- Treat presentation-only data and runtime caches as rebuildable.
- Add replay-continuation tests when state affects deterministic continuation.