fast snapshot restore

rev2
cosmonaut 2023-10-26 11:02:45 -07:00
parent 5419fbd72d
commit 344a0082b4
2 changed files with 19 additions and 13 deletions

View File

@ -87,23 +87,30 @@ public class Snapshot
public void Restore(Archetype archetype) public void Restore(Archetype archetype)
{ {
// Clear out existing entities
archetype.ClearAll();
// Copy all component data // Copy all component data
for (int i = 0; i < ComponentColumns.Count; i += 1) for (int i = 0; i < ComponentColumns.Count; i += 1)
{ {
ComponentColumns[i].CopyAllTo(archetype.ComponentColumns[i]); ComponentColumns[i].CopyAllTo(archetype.ComponentColumns[i]);
} }
// Clear the row to entity list var archetypeCount = archetype.Count;
archetype.RowToEntity.Clear();
// Create new entities and repopulate the row to entity list if (Count < archetypeCount)
for (int i = 0; i < Count; i += 1)
{ {
var entityId = archetype.World.CreateEntityOnArchetype(archetype); // if snapshot has fewer entities than archetype, remove extra entities
archetype.RowToEntity.Add(entityId); for (int i = archetypeCount - 1; i >= Count; i -= 1)
{
archetype.World.FreeEntity(archetype.RowToEntity[i]);
archetype.RowToEntity.RemoveAt(i);
}
}
else if (Count > archetypeCount)
{
// if snapshot has more entities than archetype, add entities
for (int i = archetypeCount; i < Count; i += 1)
{
archetype.World.CreateEntityOnArchetype(archetype);
}
} }
} }
} }

View File

@ -67,16 +67,15 @@ namespace MoonTools.ECS.Rev2
return entityId; return entityId;
} }
// used as a fast path by Archetype.Transfer // used as a fast path by snapshot restore
internal EntityId CreateEntityOnArchetype(Archetype archetype) internal void CreateEntityOnArchetype(Archetype archetype)
{ {
var entityId = EntityIdAssigner.Assign(); var entityId = EntityIdAssigner.Assign();
EntityIndex.Add(entityId, new Record(archetype, archetype.Count)); EntityIndex.Add(entityId, new Record(archetype, archetype.Count));
archetype.RowToEntity.Add(entityId); archetype.RowToEntity.Add(entityId);
return entityId;
} }
// used as a fast path by Archetype.ClearAll // used as a fast path by Archetype.ClearAll and snapshot restore
internal void FreeEntity(EntityId entityId) internal void FreeEntity(EntityId entityId)
{ {
EntityIndex.Remove(entityId); EntityIndex.Remove(entityId);