Skip to content

Snapshots ​

WorldSerializer writes every live entity that has components, and those components, to a stream and restores them into an empty world. Entities keep their index and generation, so Entity fields inside components remain valid; component types are identified by name, not by runtime index.

csharp
var serializer = new WorldSerializer();
serializer.Register(new InventoryFormatter());   // only for components with reference fields

using (var file = File.Create(path)) {
    serializer.Save(world, file);
}

world.Clear();
using (var file = File.OpenRead(path)) {
    serializer.Load(world, file);                 // fires no world events; filters and groups fill normally
}

Save leaves the stream open. Load requires an empty world (EntityCount == 0, e.g. after world.Clear()) and throws otherwise. It also refuses (InvalidOperationException) a world whose pools still hold components that a DestroyEntity interrupted by a throwing listener or AutoReset left without an entity; world.Clear() removes them. It also throws when the stream is not a snapshot, has an unsupported version, or names a component type that is not loaded in the process. The world tick is saved and restored.

Component types are stored by assembly-qualified name. If that name no longer resolves (for example after an assembly version bump), Load falls back to the namespace-qualified name.

Dead handles stay dead ​

A snapshot also stores the generations of the slots that hold no entity. A handle to an entity that was destroyed before Save is still dead after Load: IsAlive is false for it, also after a new entity takes its slot, which gets the generation it would have got in the saved world. Handles issued before a world.Clear() of the saved world stay dead the same way.

The free slots are saved in the order the saved world would reuse them, so the entities created after Load get the same slots and handles as they would have got in the saved world: a world restored from a snapshot goes on creating entities as the saved one would. A world loaded into that has free slots of its own above the saved world's highest slot (its entities were destroyed, not cleared) hands those out after the saved ones, lowest first.

Slots and entities left out ​

Save writes only the live entities that have components. Called by a listener of DestroyEntity, it saves the world without the entity being destroyed; called by a listener of the removal of an entity's last component, without that entity, which the auto-destroy that follows takes. Their slots are free in the loaded world, next in line, as they will be in the saved one.

A DestroyEntity interrupted by a throwing listener or AutoReset leaves the components it had not removed yet orphaned in their pools, and keeps the slot off the free list until Clear. Save leaves the orphans out and stores the slot as kept: the loaded world keeps it off its free list too, until its own Clear.

Rollback ​

Loaded into a world with a past of its own (a rollback: world.Clear(), then Load into the same world), a free slot keeps the later of the two generations: the one the saved world would give its next entity, or the one this world would. A handle of an entity that lived and died in the slot after the snapshot was taken, still kept by a view or a system, stays dead; the next entity created in such a slot then gets a later handle than it would have got in the saved world.

Changed in 2.5.0

The snapshot format is version 2: after the live entities it stores the saved world's highest slot, its free slots with their generations in the order of its free-slot list, the slots it keeps off that list until Clear, and the slots above the highest one whose generation a Clear raised. Snapshots written by 2.4.0 and earlier (version 1) still load, but they hold no generations of free slots: in a world restored from one, a handle that was dead at Save can name the next entity created in its slot. 2.4.0 cannot read a version 2 snapshot. Up to 2.4.0 Save called by a DestroyEntity listener wrote the entity being destroyed, a stream Load rejected, and Save wrote the orphans of an interrupted destroy, which Load then put on a free slot. Up to 2.4.0 Load did not check for components left by an interrupted DestroyEntity: a stored component that met one in its pool made it throw "already has component" halfway through the restore.

Components with references ​

Unmanaged components are written bit-for-bit. A component that holds references (a List, a string, an object) needs an IComponentFormatter<T>, otherwise Save throws.

csharp
struct Inventory : IComponent {
    public List<int> Items;                  // reference field: needs a formatter
}

sealed class InventoryFormatter : IComponentFormatter<Inventory> {
    public void Write(BinaryWriter writer, ref Inventory c) {
        int count = c.Items?.Count ?? 0;
        writer.Write(count);
        for (int i = 0; i < count; i++) {
            writer.Write(c.Items[i]);
        }
    }

    public void Read(BinaryReader reader, out Inventory c) {
        int count = reader.ReadInt32();
        c = new Inventory { Items = new List<int>(count) };
        for (int i = 0; i < count; i++) {
            c.Items.Add(reader.ReadInt32());
        }
    }
}

Write receives the component by ref; Read must assign it through out. The formatter owns the binary layout, so keep Write and Read symmetric.

Registering types ​

Register<T>() without a formatter lets Load reach the pool through a direct Pool<T>() call instead of reflection, which matters under IL2CPP for types that no code touches before loading.

csharp
serializer.Register<Position>();   // no formatter: Load reaches Pool<Position>() without reflection

Register(formatter) does the same for the formatted type.

Events during Load ​

Load (like Warmup) fires no IWorldEventListener events and records nothing in the profiler; filter listeners and pool listeners do fire, since the components go through the normal Add path. Filters and groups fill normally. Called by a listener in the middle of a CreateEntity, a CopyEntity or a change world listeners are being told of (a rollback inside a callback), Load, like Clear, ends them for the entities it removes: the restored entities, whose handles may be the same, get no event of them (see World Events).

Listeners that are subscribed before Load therefore see a world that is still being restored, and may change it:

  • A listener that adds a component the snapshot also holds (one component derived from another, in a world wired like the saved one): when the stored value arrives, it overwrites the listener's value, which is reset as a Remove would reset it. No listener gets a second OnAdded for it; on a tracking pool it counts as changed.
  • A listener that destroys an entity being restored (a rule that destroys entities without health): the components of that entity that are not restored yet are skipped. They do not land on the freed slot, nor on an entity the listener created in it.
  • A listener that saves the world, or loads another world, with the same WorldSerializer (a checkpoint on some event): the Load goes on with what it read, and both worlds are the saved ones. The serializer can be shared by such nested calls; it keeps no state of one call that another one could change.

Changed in 2.5.0

Up to 2.4.0 a component a listener had already added made Load throw "already has component", and the components of an entity a listener destroyed went to the freed slot (the next entity created there inherited them) or to the listener's entity in it; under KENSEI_DEBUG Load threw.