World.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. using System;
  2. using Microsoft.Xna.Framework;
  3. using MonoGame.Extended.Collections;
  4. using MonoGame.Extended.ECS.Systems;
  5. namespace MonoGame.Extended.ECS
  6. {
  7. /// <summary>
  8. /// Represents an Entity Component System (ECS) world that manages entities, components, and system.s
  9. /// </summary>
  10. /// <remarks>
  11. /// The World is the central container for all ECS operations. It manages the lifecycle of entities, coordinates
  12. /// component storage, and executes registered systems during update and draw cycles.
  13. /// </remarks>
  14. public class World : SimpleDrawableGameComponent
  15. {
  16. private readonly Bag<IUpdateSystem> _updateSystems;
  17. private readonly Bag<IDrawSystem> _drawSystems;
  18. internal EntityManager EntityManager { get; }
  19. internal ComponentManager ComponentManager { get; }
  20. /// <summary>
  21. /// Occurs when an entity is added to the world during the update cycle.
  22. /// </summary>
  23. /// <remarks>
  24. /// This event is raised after the entity has been fully initialized with it initial components.
  25. /// The entity ID is valid and can be used to retrieve the entity or query its components.
  26. /// Subscribers can use this even to perform initialization logic such as adding the entity to external
  27. /// collections, registering it with other systems, or creating associated resources.
  28. /// </remarks>
  29. public event Action<int> EntityAdded;
  30. /// <summary>
  31. /// Occurs when an entity is removed from the world during the update cycle.
  32. /// </summary>
  33. /// <remarks>
  34. /// This event is raised before the entity is returned to the pool and before its components are destroyed,
  35. /// allowing subscribers to perform cleanup operations such as removing the entity from external collections,
  36. /// unregistering it from other systems, or releasing associated resources.
  37. /// After this event completes, the entity ID becomes invalid and should not be used.
  38. /// </remarks>
  39. public event Action<int> EntityRemoved;
  40. /// <summary>
  41. /// Occurs when an entity's component composition changes during the update cycle.
  42. /// </summary>
  43. /// <remarks>
  44. /// This event is raised whenever components are attached to or detached from an entity.
  45. /// Subscribers can use this event to respond to composition changes, such as updating cached component
  46. /// references, recalculating entity classifications, or refreshing system queries.
  47. /// The event is not raised for component value modifications, only structural changes to which components are
  48. /// present on the entity.
  49. /// </remarks>
  50. public event Action<int> EntityChanged;
  51. /// <summary>
  52. /// Gets the number of active entities in the world.
  53. /// </summary>
  54. /// <remarks>
  55. /// This count reflects entities that have been created and not yet destroyed.
  56. /// Entities queued for destruction are still counted until the next update cycle completes.
  57. /// </remarks>
  58. public int EntityCount => EntityManager.ActiveCount;
  59. internal World()
  60. {
  61. _updateSystems = new Bag<IUpdateSystem>();
  62. _drawSystems = new Bag<IDrawSystem>();
  63. RegisterSystem(ComponentManager = new ComponentManager());
  64. RegisterSystem(EntityManager = new EntityManager(ComponentManager));
  65. EntityManager.EntityAdded += OnEntityAdded;
  66. EntityManager.EntityRemoved += OnEntityRemoved;
  67. EntityManager.EntityChanged += OnEntityChanged;
  68. }
  69. private void OnEntityAdded(int entityId)
  70. {
  71. if (EntityAdded != null)
  72. {
  73. EntityAdded.Invoke(entityId);
  74. }
  75. }
  76. private void OnEntityRemoved(int entityId)
  77. {
  78. if (EntityRemoved != null)
  79. {
  80. EntityRemoved.Invoke(entityId);
  81. }
  82. }
  83. private void OnEntityChanged(int entityId)
  84. {
  85. if (EntityChanged != null)
  86. {
  87. EntityChanged.Invoke(entityId);
  88. }
  89. }
  90. internal void RegisterSystem(ISystem system)
  91. {
  92. // ReSharper disable once ConvertIfStatementToSwitchStatement
  93. if (system is IUpdateSystem updateSystem)
  94. {
  95. _updateSystems.Add(updateSystem);
  96. }
  97. if (system is IDrawSystem drawSystem)
  98. {
  99. _drawSystems.Add(drawSystem);
  100. }
  101. system.Initialize(this);
  102. }
  103. /// <summary>
  104. /// Retrieves an entity by its unique identifier.
  105. /// </summary>
  106. /// <param name="entityId">The unique identifier of the entity to retrieve.</param>
  107. /// <returns>
  108. /// The entity with the specified identifier, or <c>null</c> if the entity has been destroyed or the ID is
  109. /// invalid.
  110. /// </returns>
  111. public Entity GetEntity(int entityId)
  112. {
  113. return EntityManager.Get(entityId);
  114. }
  115. /// <summary>
  116. /// Creates a new entity in the world.
  117. /// </summary>
  118. /// <remarks>
  119. /// The entity is created immediately, but the <see cref="EntityAdded"/> event is not raised until
  120. /// the next <see cref="Update(GameTime)"/> cycle. The returned entity can be used immediately to
  121. /// attach components.
  122. /// Entity IDs are reused from a pool after entities are destroyed.
  123. /// </remarks>
  124. /// <returns>A new entity with a unique identifier.</returns>
  125. public Entity CreateEntity()
  126. {
  127. return EntityManager.Create();
  128. }
  129. /// <summary>
  130. /// Destroys an entity in the world.
  131. /// </summary>
  132. /// <remarks>
  133. /// The entity is queued for destruction and the <see cref="EntityRemoved"/> event is raised during
  134. /// the next <see cref="Update(GameTime)"/> cycle, before the entity and its components are removed from
  135. /// memory.
  136. /// Calling this method multiple times with the same entity ID has no additional effect.
  137. /// After destruction completes, the entity ID may be reused for new entities.
  138. /// </remarks>
  139. /// <param name="entityId">The unique identifier of the entity to destroy.</param>
  140. public void DestroyEntity(int entityId)
  141. {
  142. EntityManager.Destroy(entityId);
  143. }
  144. /// <summary>
  145. /// Destroys an entity in the world.
  146. /// </summary>
  147. /// <remarks>
  148. /// The entity is queued for destruction and the <see cref="EntityRemoved"/> event is raised during
  149. /// the next <see cref="Update(GameTime)"/> cycle, before the entity and its components are removed from
  150. /// memory.
  151. /// Calling this method multiple times with the same entity ID has no additional effect.
  152. /// After destruction completes, the entity ID may be reused for new entities.
  153. /// </remarks>
  154. /// <param name="entity">The entity to destroy.</param>
  155. public void DestroyEntity(Entity entity)
  156. {
  157. EntityManager.Destroy(entity);
  158. }
  159. /// <summary>
  160. /// Updates all registered systems in the world.
  161. /// </summary>
  162. /// <remarks>
  163. /// This method invokes <see cref="IUpdateSystem.Update(GameTime)"/> on all registered update systems in
  164. /// registration order.
  165. /// Entity lifecycle events (<see cref="EntityAdded"/>, <see cref="EntityRemoved"/>,
  166. /// <see cref="EntityChanged"/>) are raised during this update cycle as entities are processed by the
  167. /// <see cref="EntityManager"/>.
  168. /// </remarks>
  169. /// <param name="gameTime">A snapshot of the timing values for the current cycle.</param>
  170. public override void Update(GameTime gameTime)
  171. {
  172. foreach (var system in _updateSystems)
  173. {
  174. system.Update(gameTime);
  175. }
  176. }
  177. /// <summary>
  178. /// Draws all registered systems in the world.
  179. /// </summary>
  180. /// <remarks>
  181. /// This method invokes <see cref="IDrawSystem.Draw(GameTime)"/> on all registered draw systems in
  182. /// registration order.
  183. /// </remarks>
  184. /// <param name="gameTime">A snapshot of the timing values for the current cycle.</param>
  185. public override void Draw(GameTime gameTime)
  186. {
  187. foreach (var system in _drawSystems)
  188. {
  189. system.Draw(gameTime);
  190. }
  191. }
  192. /// <summary>
  193. /// Releases all resources used by the <see cref="World"/>
  194. /// </summary>
  195. public override void Dispose()
  196. {
  197. EntityManager.EntityAdded -= OnEntityAdded;
  198. EntityManager.EntityRemoved -= OnEntityRemoved;
  199. EntityManager.EntityChanged -= OnEntityChanged;
  200. foreach (var updateSystem in _updateSystems)
  201. {
  202. updateSystem.Dispose();
  203. }
  204. foreach (var drawSystem in _drawSystems)
  205. {
  206. drawSystem.Dispose();
  207. }
  208. _updateSystems.Clear();
  209. _drawSystems.Clear();
  210. base.Dispose();
  211. }
  212. }
  213. }