WorldManagerTests.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System;
  2. using System.Collections.Generic;
  3. using Microsoft.Xna.Framework;
  4. using MonoGame.Extended.ECS.Systems;
  5. namespace MonoGame.Extended.ECS.Tests;
  6. public class WorldManagerTests
  7. {
  8. private GameTime _gameTime = new GameTime(TimeSpan.Zero, TimeSpan.FromMilliseconds(16));
  9. [Fact]
  10. public void CrudEntity()
  11. {
  12. var dummySystem = new DummySystem();
  13. var worldBuilder = new WorldBuilder();
  14. worldBuilder.AddSystem(dummySystem);
  15. var world = worldBuilder.Build();
  16. var addedEntities = new List<int>();
  17. var removedEntities = new List<int>();
  18. var changedEntities = new List<int>();
  19. world.Initialize();
  20. world.EntityAdded += entityId => addedEntities.Add(entityId);
  21. var entity = world.CreateEntity();
  22. entity.Attach(new Transform2());
  23. world.Update(_gameTime);
  24. world.Draw(_gameTime);
  25. var otherEntity = world.GetEntity(entity.Id);
  26. Assert.Equal(entity, otherEntity);
  27. Assert.True(otherEntity.Has<Transform2>());
  28. Assert.Contains(entity.Id, dummySystem.AddedEntitiesId);
  29. Assert.Single(addedEntities);
  30. Assert.Equal(entity.Id, addedEntities[0]);
  31. world.EntityChanged += entityId => changedEntities.Add(entityId);
  32. entity.Attach(new TestComponent());
  33. world.Update(_gameTime);
  34. Assert.Single(changedEntities);
  35. Assert.Equal(entity.Id, changedEntities[0]);
  36. world.EntityRemoved += entityId => removedEntities.Add(entityId);
  37. entity.Destroy();
  38. world.Update(_gameTime);
  39. world.Draw(_gameTime);
  40. otherEntity = world.GetEntity(entity.Id);
  41. Assert.Null(otherEntity);
  42. Assert.Contains(entity.Id, dummySystem.RemovedEntitiesId);
  43. Assert.Single(removedEntities);
  44. Assert.Equal(entity.Id, removedEntities[0]);
  45. }
  46. private class TestComponent { }
  47. private class DummyComponent { }
  48. private class DummySystem : EntitySystem, IUpdateSystem, IDrawSystem
  49. {
  50. public List<int> AddedEntitiesId { get; } = new();
  51. public List<int> RemovedEntitiesId { get; } = new();
  52. public DummySystem() : base(Aspect.All(typeof(DummyComponent))) { }
  53. public override void Initialize(IComponentMapperService mapperService)
  54. {
  55. // Do NOT initialize mapper in order to test: https://github.com/craftworkgames/MonoGame.Extended/issues/707
  56. }
  57. public void Draw(GameTime gameTime) { }
  58. public void Update(GameTime gameTime) { }
  59. protected override void OnEntityAdded(int entityId)
  60. {
  61. base.OnEntityAdded(entityId);
  62. AddedEntitiesId.Add(entityId);
  63. }
  64. protected override void OnEntityRemoved(int entityId)
  65. {
  66. base.OnEntityRemoved(entityId);
  67. RemovedEntitiesId.Add(entityId);
  68. }
  69. }
  70. }