fix crash when entity is added and removed same frame

pull/5/head
thatcosmonaut 2019-08-20 15:44:01 -07:00
parent 524548ea0e
commit b8d3d706ad
3 changed files with 52 additions and 3 deletions

View File

@ -20,6 +20,7 @@ namespace Encompass
private readonly Dictionary<Type, HashSet<Guid>> typeToComponentIDs = new Dictionary<Type, HashSet<Guid>>();
private readonly List<(Entity, Type, Guid, IComponent)> componentAddData = new List<(Entity, Type, Guid, IComponent)>();
private readonly HashSet<Guid> componentIDsMarkedForAdd = new HashSet<Guid>();
private readonly HashSet<Guid> componentsMarkedForRemoval = new HashSet<Guid>();
private readonly Dictionary<Guid, IComponent> pendingUpdates = new Dictionary<Guid, IComponent>();
@ -43,7 +44,7 @@ namespace Encompass
{
var id = NextID();
componentAddData.Add((entity, typeof(TComponent), id, component));
// add these here so entity and component lookups dont break on pending components
componentIDsMarkedForAdd.Add(id);
return id;
}
@ -85,6 +86,7 @@ namespace Encompass
}
componentAddData.Clear();
componentIDsMarkedForAdd.Clear();
}
internal IEnumerable<Guid> GetComponentIDsByEntityID(Guid entityID)
@ -181,9 +183,16 @@ namespace Encompass
internal void RemoveMarkedComponents()
{
foreach (var componentID in componentsMarkedForRemoval)
{
if (componentIDsMarkedForAdd.Contains(componentID))
{
componentIDsMarkedForAdd.Remove(componentID);
}
else
{
Remove(componentID);
}
}
componentsMarkedForRemoval.Clear();
}

View File

@ -348,7 +348,7 @@ namespace Encompass
protected TMessage ReadMessage<TMessage>() where TMessage : struct, IMessage
{
return ReadMessages<TMessage>().Single();
return ReadMessages<TMessage>().First();
}
protected bool SomeMessage<TMessage>() where TMessage : struct, IMessage

View File

@ -804,5 +804,45 @@ namespace Tests
resultMessages.Should().NotBeEmpty();
resultMessages.First().Should().BeOfType<MockMessage>();
}
[Receives(typeof(MockMessage))]
[Activates(typeof(MockComponent))]
class ActivateComponentEngine : Engine
{
public override void Update(double dt)
{
foreach (var message in ReadMessages<MockMessage>())
{
var entity = CreateEntity();
AddComponent(entity, new MockComponent {});
}
}
}
[ReadsPending(typeof(MockComponent))]
class RemoveComponentEngine : Engine
{
public override void Update(double dt)
{
foreach (var (componentID, component) in ReadComponents<MockComponent>())
{
RemoveComponent(componentID);
}
}
}
[Test]
public void EngineAddAndRemoveComponentSameFrame()
{
var worldBuilder = new WorldBuilder();
worldBuilder.AddEngine(new ActivateComponentEngine());
worldBuilder.AddEngine(new RemoveComponentEngine());
worldBuilder.SendMessage(new MockMessage {});
var world = worldBuilder.Build();
Assert.DoesNotThrow(() => world.Update(0.01));
}
}
}