Mirror of Svelto.ECS because we're a fan of it
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

439 lines
19KB

  1. #if PROFILE_SVELTO && DEBUG
  2. #warning the global define PROFILE_SVELTO should be used only when it's necessary to profile in order to reduce the overhead of debug code. While debugging remove this define to get insights when errors happen
  3. #endif
  4. using System;
  5. using System.Collections.Generic;
  6. using DBC.ECS;
  7. using Svelto.Common;
  8. using Svelto.DataStructures;
  9. using Svelto.ECS.Internal;
  10. using Svelto.ECS.Schedulers;
  11. namespace Svelto.ECS
  12. {
  13. public partial class EnginesRoot
  14. {
  15. static EnginesRoot()
  16. {
  17. EntityDescriptorsWarmup.WarmUp();
  18. GroupHashMap.WarmUp();
  19. SerializationDescriptorMap.Init();
  20. _swapEntities = SwapEntities;
  21. _removeEntities = RemoveEntities;
  22. _removeGroup = RemoveGroup;
  23. _swapGroup = SwapGroup;
  24. }
  25. /// <summary>
  26. /// Engines root contextualize your engines and entities. You don't need to limit yourself to one EngineRoot
  27. /// as multiple engines root could promote separation of scopes. The EntitySubmissionScheduler checks
  28. /// periodically if new entity must be submitted to the database and the engines. It's an external
  29. /// dependencies to be independent by the running platform as the user can define it.
  30. /// The EntitySubmissionScheduler cannot hold an EnginesRoot reference, that's why
  31. /// it must receive a weak reference of the EnginesRoot callback.
  32. /// </summary>
  33. public EnginesRoot(EntitiesSubmissionScheduler entitiesComponentScheduler)
  34. {
  35. _entitiesOperations = new EntitiesOperations();
  36. _cachedRangeOfSubmittedIndices = new FasterList<(uint, uint)>();
  37. _transientEntityIDsAffectedByRemoveAtSwapBack = new FasterDictionary<uint, uint>();
  38. InitDebugChecks();
  39. #if UNITY_NATIVE //because of the thread count, ATM this is only for unity
  40. _nativeSwapOperationQueue = new AtomicNativeBags(Allocator.Persistent);
  41. _nativeRemoveOperationQueue = new AtomicNativeBags(Allocator.Persistent);
  42. _nativeAddOperationQueue = new AtomicNativeBags(Allocator.Persistent);
  43. #endif
  44. _serializationDescriptorMap = new SerializationDescriptorMap();
  45. _reactiveEnginesAdd = new FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnAdd>>>();
  46. _reactiveEnginesAddEx =
  47. new FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnAddEx>>>();
  48. _reactiveEnginesRemove =
  49. new FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnRemove>>>();
  50. _reactiveEnginesRemoveEx =
  51. new FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnRemoveEx>>>();
  52. _reactiveEnginesSwap =
  53. new FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnSwap>>>();
  54. _reactiveEnginesSwapEx =
  55. new FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnSwapEx>>>();
  56. _reactiveEnginesDispose =
  57. new FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnDispose>>>();
  58. _reactiveEnginesDisposeEx =
  59. new FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnDisposeEx>>>();
  60. _reactiveEnginesSubmission = new FasterList<IReactOnSubmission>();
  61. _reactiveEnginesSubmissionStarted = new FasterList<IReactOnSubmissionStarted>();
  62. _enginesSet = new FasterList<IEngine>();
  63. _enginesTypeSet = new HashSet<Type>();
  64. _disposableEngines = new FasterList<IDisposable>();
  65. _groupEntityComponentsDB =
  66. new FasterDictionary<ExclusiveGroupStruct, FasterDictionary<ComponentID, ITypeSafeDictionary>>();
  67. _groupsPerEntity =
  68. new FasterDictionary<ComponentID, FasterDictionary<ExclusiveGroupStruct, ITypeSafeDictionary>>();
  69. _groupedEntityToAdd = new DoubleBufferedEntitiesToAdd();
  70. _entityStreams = EntitiesStreams.Create();
  71. _entityLocator.InitEntityReferenceMap();
  72. _entitiesDB = new EntitiesDB(this, _entityLocator);
  73. InitFilters();
  74. scheduler = entitiesComponentScheduler;
  75. scheduler.onTick = new EntitiesSubmitter(this);
  76. #if UNITY_NATIVE
  77. AllocateNativeOperations();
  78. #endif
  79. }
  80. /// <summary>
  81. ///Ready is a callback that can be used to signal that an engine is ready to be used because the entitiesDB is now available
  82. ///usually engines are ready to be used when they are added to the enginesRoot, but in some special cases, it is possible to
  83. ///wait for the user input to signal that engines are ready to be used
  84. /// </summary>
  85. protected EnginesRoot(EntitiesSubmissionScheduler entitiesComponentScheduler,
  86. EnginesReadyOption enginesWaitForReady): this(entitiesComponentScheduler)
  87. {
  88. _enginesWaitForReady = enginesWaitForReady;
  89. }
  90. public EntitiesSubmissionScheduler scheduler { get; }
  91. /// <summary>
  92. /// Dispose an EngineRoot once not used anymore, so that all the
  93. /// engines are notified with the entities removed.
  94. /// It's a clean up process.
  95. /// </summary>
  96. public void Dispose()
  97. {
  98. Dispose(true);
  99. GC.SuppressFinalize(this);
  100. }
  101. public bool IsValid()
  102. {
  103. return _isDisposed == false;
  104. }
  105. public void AddEngine(IEngine engine, bool addSubEngines = true)
  106. {
  107. var type = engine.GetType();
  108. var refWrapper = new RefWrapperType(type);
  109. Check.Require(engine != null, "Engine to add is invalid or null");
  110. Check.Require(
  111. _enginesTypeSet.Contains(refWrapper) == false ||
  112. type.ContainsCustomAttribute(typeof(AllowMultipleAttribute)),
  113. "The same engine has been added more than once, if intentional, use [AllowMultiple] class attribute "
  114. .FastConcat(engine.ToString()));
  115. try
  116. {
  117. if (engine is IReactOnAdd viewEngineAdd)
  118. #pragma warning disable CS0612
  119. CheckReactEngineComponents(typeof(IReactOnAdd<>), viewEngineAdd, _reactiveEnginesAdd, type.Name);
  120. #pragma warning restore CS0612
  121. if (engine is IReactOnAddEx viewEngineAddEx)
  122. CheckReactEngineComponents(
  123. typeof(IReactOnAddEx<>), viewEngineAddEx, _reactiveEnginesAddEx, type.Name);
  124. if (engine is IReactOnRemove viewEngineRemove)
  125. CheckReactEngineComponents(
  126. #pragma warning disable CS0612
  127. typeof(IReactOnRemove<>), viewEngineRemove, _reactiveEnginesRemove, type.Name);
  128. #pragma warning restore CS0612
  129. if (engine is IReactOnRemoveEx viewEngineRemoveEx)
  130. CheckReactEngineComponents(
  131. typeof(IReactOnRemoveEx<>), viewEngineRemoveEx, _reactiveEnginesRemoveEx, type.Name);
  132. if (engine is IReactOnDispose viewEngineDispose)
  133. CheckReactEngineComponents(
  134. #pragma warning disable CS0618
  135. typeof(IReactOnDispose<>), viewEngineDispose, _reactiveEnginesDispose, type.Name);
  136. #pragma warning restore CS0618
  137. if (engine is IReactOnDisposeEx viewEngineDisposeEx)
  138. CheckReactEngineComponents(
  139. typeof(IReactOnDisposeEx<>), viewEngineDisposeEx, _reactiveEnginesDisposeEx, type.Name);
  140. if (engine is IReactOnSwap viewEngineSwap)
  141. #pragma warning disable CS0612
  142. #pragma warning disable CS0618
  143. CheckReactEngineComponents(typeof(IReactOnSwap<>), viewEngineSwap, _reactiveEnginesSwap, type.Name);
  144. #pragma warning restore CS0618
  145. #pragma warning restore CS0612
  146. if (engine is IReactOnSwapEx viewEngineSwapEx)
  147. CheckReactEngineComponents(
  148. typeof(IReactOnSwapEx<>), viewEngineSwapEx, _reactiveEnginesSwapEx, type.Name);
  149. if (engine is IReactOnSubmission submissionEngine)
  150. _reactiveEnginesSubmission.Add(submissionEngine);
  151. if (engine is IReactOnSubmissionStarted submissionEngineStarted)
  152. _reactiveEnginesSubmissionStarted.Add(submissionEngineStarted);
  153. if (addSubEngines)
  154. if (engine is IGroupEngine stepGroupEngine)
  155. foreach (var stepEngine in stepGroupEngine.engines)
  156. AddEngine(stepEngine);
  157. _enginesTypeSet.Add(refWrapper);
  158. _enginesSet.Add(engine);
  159. if (engine is IDisposable)
  160. _disposableEngines.Add(engine as IDisposable);
  161. if (engine is IQueryingEntitiesEngine queryableEntityComponentEngine)
  162. queryableEntityComponentEngine.entitiesDB = _entitiesDB;
  163. //Ready is a callback that can be used to signal that the engine is ready to be used because the entitiesDB is now available
  164. if (_enginesWaitForReady == EnginesReadyOption.ReadyAsAdded && engine is IGetReadyEngine getReadyEngine)
  165. getReadyEngine.Ready();
  166. }
  167. catch (Exception e)
  168. {
  169. throw new ECSException(
  170. "Code crashed while adding engine ".FastConcat(engine.GetType().ToString(), " "),
  171. e);
  172. }
  173. }
  174. public void Ready()
  175. {
  176. Check.Require(
  177. _enginesWaitForReady == EnginesReadyOption.WaitForReady,
  178. "The engine has not been initialise to wait for an external ready trigger");
  179. foreach (var engine in _enginesSet)
  180. if (engine is IGetReadyEngine getReadyEngine)
  181. getReadyEngine.Ready();
  182. }
  183. static void AddEngineToList<T>(T engine, Type[] entityComponentTypes,
  184. FasterDictionary<ComponentID, FasterList<ReactEngineContainer<T>>> engines, string typeName)
  185. where T : class, IReactEngine
  186. {
  187. for (var i = 0; i < entityComponentTypes.Length; i++)
  188. {
  189. var type = entityComponentTypes[i];
  190. var componentID = ComponentTypeMap.FetchID(type);
  191. if (engines.TryGetValue(componentID, out var list) == false)
  192. {
  193. list = new FasterList<ReactEngineContainer<T>>();
  194. engines.Add(componentID, list);
  195. }
  196. list.Add(new ReactEngineContainer<T>(engine, typeName));
  197. }
  198. }
  199. void CheckReactEngineComponents<T>(Type genericDefinition, T engine,
  200. FasterDictionary<ComponentID, FasterList<ReactEngineContainer<T>>> engines, string typeName)
  201. where T : class, IReactEngine
  202. {
  203. var interfaces = engine.GetType().GetInterfaces();
  204. foreach (var interf in interfaces)
  205. {
  206. if (interf.IsGenericTypeEx() && interf.GetGenericTypeDefinition() == genericDefinition)
  207. {
  208. Type[] genericArguments = interf.GetGenericArgumentsEx();
  209. AddEngineToList(engine, genericArguments, engines, typeName);
  210. }
  211. }
  212. }
  213. void Dispose(bool disposing)
  214. {
  215. if (_isDisposed)
  216. return;
  217. using (var profiler = new PlatformProfiler("Final Dispose"))
  218. {
  219. //Note: The engines are disposed before the the remove callback to give the chance to behave
  220. //differently if a remove happens as a consequence of a dispose
  221. //The pattern is to implement the IDisposable interface and set a flag in the engine. The
  222. //remove callback will then behave differently according the flag.
  223. foreach (var engine in _disposableEngines)
  224. try
  225. {
  226. if (engine is IDisposableEngine dengine)
  227. dengine.isDisposing = true;
  228. engine.Dispose();
  229. }
  230. catch (Exception e)
  231. {
  232. Console.LogException(e);
  233. }
  234. foreach (var groups in _groupEntityComponentsDB)
  235. foreach (var entityList in groups.value)
  236. try
  237. {
  238. ITypeSafeDictionary typeSafeDictionary = entityList.value;
  239. typeSafeDictionary.ExecuteEnginesDisposeCallbacks_Group(
  240. _reactiveEnginesDispose, _reactiveEnginesDisposeEx, groups.key,
  241. profiler);
  242. }
  243. catch (Exception e)
  244. {
  245. Console.LogException(e);
  246. }
  247. foreach (var groups in _groupEntityComponentsDB)
  248. foreach (var entityList in groups.value)
  249. entityList.value.Dispose();
  250. DisposeFilters();
  251. #if UNITY_NATIVE
  252. _nativeAddOperationQueue.Dispose();
  253. _nativeRemoveOperationQueue.Dispose();
  254. _nativeSwapOperationQueue.Dispose();
  255. #endif
  256. _groupEntityComponentsDB.Clear();
  257. _groupsPerEntity.Clear();
  258. _disposableEngines.Clear();
  259. _enginesSet.Clear();
  260. _enginesTypeSet.Clear();
  261. _reactiveEnginesSwap.Clear();
  262. _reactiveEnginesAdd.Clear();
  263. _reactiveEnginesRemove.Clear();
  264. _reactiveEnginesDispose.Clear();
  265. _reactiveEnginesDisposeEx.Clear();
  266. _reactiveEnginesSubmission.Clear();
  267. _reactiveEnginesSubmissionStarted.Clear();
  268. _groupedEntityToAdd.Dispose();
  269. _entityLocator.DisposeEntityReferenceMap();
  270. _entityStreams.Dispose();
  271. scheduler.Dispose();
  272. }
  273. _isDisposed = true;
  274. }
  275. void NotifyReactiveEnginesOnSubmission()
  276. {
  277. var enginesCount = _reactiveEnginesSubmission.count;
  278. for (var i = 0; i < enginesCount; i++)
  279. _reactiveEnginesSubmission[i].EntitiesSubmitted();
  280. }
  281. void NotifyReactiveEnginesOnSubmissionStarted()
  282. {
  283. var enginesCount = _reactiveEnginesSubmissionStarted.count;
  284. for (var i = 0; i < enginesCount; i++)
  285. _reactiveEnginesSubmissionStarted[i].EntitiesSubmissionStarting();
  286. }
  287. public readonly struct EntitiesSubmitter
  288. {
  289. public EntitiesSubmitter(EnginesRoot enginesRoot): this()
  290. {
  291. _enginesRoot = new DataStructures.WeakReference<EnginesRoot>(enginesRoot);
  292. }
  293. internal void SubmitEntities()
  294. {
  295. Check.Require(_enginesRoot.IsValid, "ticking an GCed engines root?");
  296. var enginesRootTarget = _enginesRoot.Target;
  297. var entitiesSubmissionScheduler = enginesRootTarget.scheduler;
  298. if (entitiesSubmissionScheduler.paused == false)
  299. {
  300. enginesRootTarget.NotifyReactiveEnginesOnSubmissionStarted();
  301. Check.Require(
  302. entitiesSubmissionScheduler.isRunning == false,
  303. "A submission started while the previous one was still flushing");
  304. entitiesSubmissionScheduler.isRunning = true;
  305. using (var profiler = new PlatformProfiler("Svelto.ECS - Entities Submission"))
  306. {
  307. var iterations = 0;
  308. var hasEverSubmitted = false;
  309. // We need to clear transient filters before processing callbacks since the callbacks may add
  310. // new entities to these filters.
  311. enginesRootTarget.ClearTransientFilters();
  312. #if UNITY_NATIVE
  313. enginesRootTarget.FlushNativeOperations(profiler);
  314. #endif
  315. while (enginesRootTarget.HasMadeNewStructuralChangesInThisIteration()
  316. && iterations++ < MAX_SUBMISSION_ITERATIONS)
  317. {
  318. hasEverSubmitted = true;
  319. _enginesRoot.Target.SingleSubmission(profiler);
  320. #if UNITY_NATIVE
  321. enginesRootTarget.FlushNativeOperations(profiler);
  322. #endif
  323. }
  324. #if DEBUG && !PROFILE_SVELTO
  325. if (iterations == MAX_SUBMISSION_ITERATIONS)
  326. throw new ECSException("possible circular submission detected");
  327. #endif
  328. if (hasEverSubmitted)
  329. enginesRootTarget.NotifyReactiveEnginesOnSubmission();
  330. }
  331. entitiesSubmissionScheduler.isRunning = false;
  332. ++entitiesSubmissionScheduler.iteration;
  333. }
  334. }
  335. readonly DataStructures.WeakReference<EnginesRoot> _enginesRoot;
  336. }
  337. ~EnginesRoot()
  338. {
  339. Console.LogWarning("Engines Root has been garbage collected, don't forget to call Dispose()!");
  340. Dispose(false);
  341. }
  342. const int MAX_SUBMISSION_ITERATIONS = 10;
  343. readonly FasterList<IDisposable> _disposableEngines;
  344. readonly FasterList<IEngine> _enginesSet;
  345. readonly HashSet<Type> _enginesTypeSet;
  346. readonly EnginesReadyOption _enginesWaitForReady;
  347. readonly FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnAdd>>> _reactiveEnginesAdd;
  348. readonly FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnAddEx>>> _reactiveEnginesAddEx;
  349. readonly FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnRemove>>> _reactiveEnginesRemove;
  350. readonly FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnRemoveEx>>> _reactiveEnginesRemoveEx;
  351. readonly FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnSwap>>> _reactiveEnginesSwap;
  352. readonly FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnSwapEx>>> _reactiveEnginesSwapEx;
  353. readonly FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnDispose>>> _reactiveEnginesDispose;
  354. readonly FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnDisposeEx>>> _reactiveEnginesDisposeEx;
  355. readonly FasterList<IReactOnSubmission> _reactiveEnginesSubmission;
  356. readonly FasterList<IReactOnSubmissionStarted> _reactiveEnginesSubmissionStarted;
  357. bool _isDisposed;
  358. }
  359. //Ready is a callback that can be used to signal that an engine is ready to be used because the entitiesDB is now available
  360. //usually engines are ready to be used when they are added to the enginesRoot, but in some special cases, it is possible to
  361. //wait for the user input to signal that the engine is ready to be used
  362. public enum EnginesReadyOption
  363. {
  364. ReadyAsAdded,
  365. WaitForReady
  366. }
  367. }