This repository has been archived by the owner on Jan 18, 2022. It is now read-only.
/
EntityQuerySnapshot.cs
64 lines (56 loc) · 2.4 KB
/
EntityQuerySnapshot.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using System.Collections.Generic;
using Unity.Entities;
using Entity = Improbable.Worker.CInterop.Entity;
namespace Improbable.Gdk.Core
{
/// <summary>
/// A snapshot of a SpatialOS entity, containing the result of a entity query.
/// </summary>
/// <remarks>
/// This copies entity components from <see cref="Improbable.Worker.CInterop.Entity" /> for long term storage.
/// This may only be a partial snapshot of an entity.
/// The components present depend on the component filter used when making the entity query.
/// </remarks>
public struct EntityQuerySnapshot
{
private struct ComponentDataHandler : DynamicSnapshot.ISnapshotHandler
{
public Entity EntitySnapshot;
public Dictionary<uint, ISpatialComponentSnapshot> Components;
public void Accept<T>(uint componentId, DynamicSnapshot.SnapshotDeserializer<T> deserializeSnapshot,
DynamicSnapshot.SnapshotSerializer<T> serializeSnapshot) where T : struct, ISpatialComponentSnapshot
{
var schemaObject = EntitySnapshot.Get(componentId).Value;
Components.Add(componentId, deserializeSnapshot(schemaObject));
}
}
private readonly Dictionary<uint, ISpatialComponentSnapshot> components;
internal EntityQuerySnapshot(Entity entitySnapshot)
{
components = new Dictionary<uint, ISpatialComponentSnapshot>();
var componentDataHandler = new ComponentDataHandler
{
EntitySnapshot = entitySnapshot,
Components = components,
};
foreach (var componentId in entitySnapshot.GetComponentIds())
{
DynamicSnapshot.ForSnapshotComponent(componentId, componentDataHandler);
}
}
/// <summary>
/// Get the SpatialOS component snapshot if present.
/// </summary>
/// <returns> The component snapshot, if it exists, or null otherwise.</returns>
/// <typeparam name="T">The component type.</typeparam>
public T? GetComponentSnapshot<T>() where T : struct, ISpatialComponentSnapshot
{
var id = DynamicSnapshot.GetSnapshotComponentId<T>();
if (components.TryGetValue(id, out var data))
{
return (T) data;
}
return null;
}
}
}