Game Saves
A save is a snapshot of the state your game owns: the campaign progress, the player's inventory, the position of the hero when the player pressed Save. Turian does not capture your scene for you. The save brick takes a plain data object you define, encodes it with a stable header, and writes it to a slot through storage that checks revisions before it overwrites anything. Saves never change your authored assets, prefabs or scenes.
The brick lives in the Turian.Engine.Save namespace. It has no dependency on the renderer, the network or a
third-party serializer, so it also works in dedicated servers and headless tests.
Installing the brick
Add it to the project with the command line or from Studio's Project → Bricks… dialog. Bricks are described in Bricks.
turian-cli brick add org.mass4.turian.save
The brick registers no engine services. Your code creates a SaveService itself, as the examples below do. The save
example adds global using Turian.Engine.Save; to a Globals.cs file in Assets, so the save types are available in
every script.
What a save contains
Every save has three parts:
- State, your own type. Use a
recordor another plain type with only values and collections, never live nodes, components or assets. - Metadata, a
SaveMetadataobject: the time it was saved (SavedAt), the elapsed play time (PlayTime), your game's release identifier (GameVersion), the simulation tick and RNG state, and content or mod fingerprints (ContentVersions). A deterministic game needs the tick, RNG state and content versions to resume at the same point. - A slot, a name such as
campaign-1that identifies the save within a storage location.
Slot names are 1 to 64 ASCII letters, digits, hyphens or underscores. SaveSlot stores them in lowercase.
Capturing, saving and loading
The example below saves a small state record and loads it back. FileSaveStorage.ForGame stores files under the
user's local data folder, in a folder for the game and the account, so your game never builds paths by hand.
namespace Usercode;
public sealed record CampaignState(Guid PlayerId, float X, int Gold);
public sealed class CampaignSaves
{
readonly SaveService saves = new(
FileSaveStorage.ForGame(new SaveSlot("my-game"), new SaveSlot("player-1")),
"my-game:campaign", schemaVersion: 1);
readonly SaveSlot slot = new("campaign-1");
string? revision;
public async Task SaveAsync(CampaignState state, long tick, ulong rngState)
{
var metadata = new SaveMetadata { GameVersion = "1.0.0", Tick = tick, RngState = rngState };
revision = await saves.SaveAsync(slot, state, metadata, revision);
}
public async Task<CampaignState?> LoadAsync()
{
var loaded = await saves.LoadAsync<CampaignState>(slot);
revision = loaded?.Revision;
return loaded?.State;
}
}
The second argument of SaveService is the schema ID, a name for this kind of save. The third argument is the
schema version, a positive number you raise when the state changes shape. Both are written into every file.
Keep the revision that SaveAsync and LoadAsync return and pass it back on your next save. A save without a revision
is accepted only when the slot is empty; if another writer changed the slot in the meantime, the save fails with
SaveConflictException and leaves the stored save unchanged. Reload and decide how to merge, as the example does.
LoadAsync returns null for an empty slot. Otherwise it returns a LoadedSave<T> with the detached State, the
Metadata and the Revision.
Capture and restore on the simulation thread
Saving and loading run on worker threads. Your game state does not. The rules are:
- Capture a copy of the state on the simulation thread. Copy any collections; do not pass the live ones.
- Call
SaveAsyncwith that copy. Encoding, checksums and storage run on a worker. - Return to the simulation thread before you apply a loaded state. Look up every node, component and asset from its stable identifier at that point, not before.
The save example starts storage work with Async.Run, keeps the component's Async context before awaiting, and calls
MainThread(token) on it before writing the loaded state into the scene.
Large worlds may need incremental snapshots to fit a frame budget. Running the work on a worker does not make the capture itself free.
Making components saveable
ISaveable<T> is an optional contract for an entity or a component. It gives the component a stable identity and two
methods, CaptureSave and RestoreSave. The brick does not call them for you; your game decides when to capture and
restore.
public sealed class SaveShowcase : Component, ISaveable<CampaignState>
{
[JsonIgnore]
public Guid SaveId => player.Id;
[JsonIgnore]
public int Gold { get; private set; }
public CampaignState CaptureSave() => new(SaveId, player.Position.X, Gold);
public void RestoreSave(CampaignState state)
{
if (state.PlayerId != SaveId || !float.IsFinite(state.X) || state.X is < -4 or > 4 || state.Gold < 0)
{
throw new InvalidDataException("The saved player identity or state is invalid.");
}
player.Position = player.Position with { X = state.X };
Gold = state.Gold;
}
}
This is a reduction of the component in the save example, which also declares player as a node it finds on awake.
Three rules come from it:
- The game assigns the identity. Use a
Guidthat you store with the entity, not an array index, a CLR type name or a hierarchy path. - Store references to other entities as their identities, and resolve them after every entity exists.
- Validate the state before you change anything. A save with invalid data should fail without a partial restore.
Mark any injected or live property with [JsonIgnore], as shown, so a serializer never tries to write it.
Schema versions and migrations
A save records the schema version it was written with. When you change the shape of your state, raise the version you
pass to SaveService and register one migration per step. Each ISaveMigration upgrades exactly one version:
using System.Text.Json;
using System.Text.Json.Nodes;
sealed class GoldMigration : ISaveMigration
{
public int FromVersion => 1;
public string SerializerId => "json";
public byte[] Upgrade(ReadOnlyMemory<byte> data)
{
var state = JsonNode.Parse(data.Span)!.AsObject();
state["Gold"] = state["Score"]!.DeepClone();
state.Remove("Score");
return JsonSerializer.SerializeToUtf8Bytes(state);
}
}
var saves = new SaveService(storage, "my-game:campaign", schemaVersion: 2, migrations: [new GoldMigration()]);
The rules that apply:
- Loading a version 1 save with a version 2 service runs
GoldMigrationonce, then decodes the result. The stored file is not rewritten. - A save with a version newer than the service's
schemaVersionis refused as an unsupported schema. - If a step for a version is missing, the load fails and reports the missing step. The save and the session are left unchanged.
- Migrations work on the payload bytes, not on live objects.
Slots, revisions and backups
FileSaveStorage writes each commit to a temporary file in the slot's folder, then moves it into place. The previous
generation is kept in a .bak file, so LoadBackupAsync can offer the player a recovery. The brick also provides these
calls:
| Call | Use |
|---|---|
LoadBackupAsync<T>(slot) |
Read the previous generation. Its revision identifies the backup, not the current save. |
InspectAsync(slot) |
Read the metadata for a menu without decoding the state. |
DeleteAsync(slot, revision) |
Delete a save, but only the revision you observed. |
ListAsync() |
List the slots in the storage. |
FileSaveStorage limits each file to 128 MB by default, and SaveService limits a save to 64 MB. Both limits accept a
different value in the constructor. Corrupt files are reported as an error; the brick does not silently replace them.
Encoding, serializers and encryption
The payload is encoded with an ISaveSerializer. The default is JsonSaveSerializer, which takes optional
JsonSerializerOptions. Each serializer has an Id stored in the file, so you can change the writer later and still
read old saves by registering the old serializer as a reader:
var saves = new SaveService(storage, "my-game:campaign",
writer: newSerializer,
readers: [oldSerializer]);
AesGcmSaveSerializer wraps another serializer and encrypts its payload with a key you supply. The save example passes
a 32-byte key:
using var encrypted = new AesGcmSaveSerializer(new JsonSaveSerializer(), key);
var saves = new SaveService(storage, "my-game:campaign", writer: encrypted);
Store the key outside the save files. The metadata of an encrypted save stays readable, and the checksum detects corruption, not tampering. Treat saves as untrusted input on a server.
Storage and transfers
Storage is an ISaveStorage with the operations ReadAsync, WriteAsync, DeleteAsync and ListAsync. The brick ships
two implementations: FileSaveStorage for local files and MemorySaveStorage for tests and demonstrations.
SaveTransfer.CopyAsync moves the exact bytes of a slot from one storage to another, for example to a cloud adapter. It
checks the revision on both sides, so a conflicting change is reported instead of overwritten.
The brick does not include cloud or platform adapters. A cloud adapter must support a conditional write against the service's own version tag; a plain upload that ignores the revision does not meet the contract. The brick has no Studio panel for save slots, and it does not include typed settings or preferences. Use the project's settings for those, not a save file.
Engine checkpoints
The engine also has a checkpoint format for simulations, RuntimeSave in the Turian.Engine.Core namespace. It holds
the tick, the RNG state, extensions for game-owned data and a content fingerprint. To keep it alongside your DTOs, store
the JSON string that RuntimeSave.Write returns as a string field of a DTO through a SaveService. Before you restore
it, read it back with RuntimeSave.ReadAsync using the receiving session's asset loader, then apply it with
SimulationSession.RestoreSave.
Next steps
- Components explains the lifecycle that capture and restore run in.
- Assets covers the assets that a save refers to by identifier.
- Bricks explains how the save brick is installed and versioned.
- Tags and Layers shows the identifiers that a save can record for nodes.