Mirror of Svelto.ECS because we're a fan of it
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

440 行
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. #if SVELTO_LEGACY_FILTERS
  72. _groupFilters =
  73. new FasterDictionary<ComponentID, FasterDictionary<ExclusiveGroupStruct, LegacyGroupFilters>>();
  74. #endif
  75. _entityLocator.InitEntityReferenceMap();
  76. _entitiesDB = new EntitiesDB(this, _entityLocator);
  77. InitFilters();
  78. scheduler = entitiesComponentScheduler;
  79. scheduler.onTick = new EntitiesSubmitter(this);
  80. #if UNITY_NATIVE
  81. AllocateNativeOperations();
  82. #endif
  83. }
  84. protected EnginesRoot(EntitiesSubmissionScheduler entitiesComponentScheduler,
  85. EnginesReadyOption enginesWaitForReady): this(entitiesComponentScheduler)
  86. {
  87. _enginesWaitForReady = enginesWaitForReady;
  88. }
  89. public EntitiesSubmissionScheduler scheduler { get; }
  90. /// <summary>
  91. /// Dispose an EngineRoot once not used anymore, so that all the
  92. /// engines are notified with the entities removed.
  93. /// It's a clean up process.
  94. /// </summary>
  95. public void Dispose()
  96. {
  97. Dispose(true);
  98. GC.SuppressFinalize(this);
  99. }
  100. public bool IsValid()
  101. {
  102. return _isDisposed == false;
  103. }
  104. public void AddEngine(IEngine engine)
  105. {
  106. var type = engine.GetType();
  107. var refWrapper = new RefWrapperType(type);
  108. Check.Require(engine != null, "Engine to add is invalid or null");
  109. Check.Require(
  110. _enginesTypeSet.Contains(refWrapper) == false ||
  111. type.ContainsCustomAttribute(typeof(AllowMultipleAttribute)),
  112. "The same engine has been added more than once, if intentional, use [AllowMultiple] class attribute "
  113. .FastConcat(engine.ToString()));
  114. try
  115. {
  116. if (engine is IReactOnAdd viewEngineAdd)
  117. #pragma warning disable CS0612
  118. CheckReactEngineComponents(typeof(IReactOnAdd<>), viewEngineAdd, _reactiveEnginesAdd, type.Name);
  119. #pragma warning restore CS0612
  120. if (engine is IReactOnAddEx viewEngineAddEx)
  121. CheckReactEngineComponents(
  122. typeof(IReactOnAddEx<>), viewEngineAddEx, _reactiveEnginesAddEx, type.Name);
  123. if (engine is IReactOnRemove viewEngineRemove)
  124. CheckReactEngineComponents(
  125. #pragma warning disable CS0612
  126. typeof(IReactOnRemove<>), viewEngineRemove, _reactiveEnginesRemove, type.Name);
  127. #pragma warning restore CS0612
  128. if (engine is IReactOnRemoveEx viewEngineRemoveEx)
  129. CheckReactEngineComponents(
  130. typeof(IReactOnRemoveEx<>), viewEngineRemoveEx, _reactiveEnginesRemoveEx, type.Name);
  131. if (engine is IReactOnDispose viewEngineDispose)
  132. CheckReactEngineComponents(
  133. #pragma warning disable CS0618
  134. typeof(IReactOnDispose<>), viewEngineDispose, _reactiveEnginesDispose, type.Name);
  135. #pragma warning restore CS0618
  136. if (engine is IReactOnDisposeEx viewEngineDisposeEx)
  137. CheckReactEngineComponents(
  138. typeof(IReactOnDisposeEx<>), viewEngineDisposeEx, _reactiveEnginesDisposeEx, type.Name);
  139. if (engine is IReactOnSwap viewEngineSwap)
  140. #pragma warning disable CS0612
  141. #pragma warning disable CS0618
  142. CheckReactEngineComponents(typeof(IReactOnSwap<>), viewEngineSwap, _reactiveEnginesSwap, type.Name);
  143. #pragma warning restore CS0618
  144. #pragma warning restore CS0612
  145. if (engine is IReactOnSwapEx viewEngineSwapEx)
  146. CheckReactEngineComponents(
  147. typeof(IReactOnSwapEx<>), viewEngineSwapEx, _reactiveEnginesSwapEx, type.Name);
  148. if (engine is IReactOnSubmission submissionEngine)
  149. _reactiveEnginesSubmission.Add(submissionEngine);
  150. if (engine is IReactOnSubmissionStarted submissionEngineStarted)
  151. _reactiveEnginesSubmissionStarted.Add(submissionEngineStarted);
  152. if (engine is IGroupEngine stepGroupEngine)
  153. foreach (var stepEngine in stepGroupEngine.engines)
  154. AddEngine(stepEngine);
  155. _enginesTypeSet.Add(refWrapper);
  156. _enginesSet.Add(engine);
  157. if (engine is IDisposable)
  158. _disposableEngines.Add(engine as IDisposable);
  159. if (engine is IQueryingEntitiesEngine queryableEntityComponentEngine)
  160. queryableEntityComponentEngine.entitiesDB = _entitiesDB;
  161. if (_enginesWaitForReady == EnginesReadyOption.ReadyAsAdded && engine is IGetReadyEngine getReadyEngine)
  162. getReadyEngine.Ready();
  163. }
  164. catch (Exception e)
  165. {
  166. throw new ECSException(
  167. "Code crashed while adding engine ".FastConcat(engine.GetType().ToString(), " "),
  168. e);
  169. }
  170. }
  171. public void Ready()
  172. {
  173. Check.Require(
  174. _enginesWaitForReady == EnginesReadyOption.WaitForReady,
  175. "The engine has not been initialise to wait for an external ready trigger");
  176. foreach (var engine in _enginesSet)
  177. if (engine is IGetReadyEngine getReadyEngine)
  178. getReadyEngine.Ready();
  179. }
  180. static void AddEngineToList<T>(T engine, Type[] entityComponentTypes,
  181. FasterDictionary<ComponentID, FasterList<ReactEngineContainer<T>>> engines, string typeName)
  182. where T : class, IReactEngine
  183. {
  184. for (var i = 0; i < entityComponentTypes.Length; i++)
  185. {
  186. var type = entityComponentTypes[i];
  187. var componentID = ComponentTypeMap.FetchID(type);
  188. if (engines.TryGetValue(componentID, out var list) == false)
  189. {
  190. list = new FasterList<ReactEngineContainer<T>>();
  191. engines.Add(componentID, list);
  192. }
  193. list.Add(new ReactEngineContainer<T>(engine, typeName));
  194. }
  195. }
  196. void CheckReactEngineComponents<T>(Type genericDefinition, T engine,
  197. FasterDictionary<ComponentID, FasterList<ReactEngineContainer<T>>> engines, string typeName)
  198. where T : class, IReactEngine
  199. {
  200. var interfaces = engine.GetType().GetInterfaces();
  201. foreach (var interf in interfaces)
  202. {
  203. if (interf.IsGenericTypeEx() && interf.GetGenericTypeDefinition() == genericDefinition)
  204. {
  205. Type[] genericArguments = interf.GetGenericArgumentsEx();
  206. AddEngineToList(engine, genericArguments, engines, typeName);
  207. }
  208. }
  209. }
  210. void Dispose(bool disposing)
  211. {
  212. if (_isDisposed)
  213. return;
  214. using (var profiler = new PlatformProfiler("Final Dispose"))
  215. {
  216. //Note: The engines are disposed before the the remove callback to give the chance to behave
  217. //differently if a remove happens as a consequence of a dispose
  218. //The pattern is to implement the IDisposable interface and set a flag in the engine. The
  219. //remove callback will then behave differently according the flag.
  220. foreach (var engine in _disposableEngines)
  221. try
  222. {
  223. if (engine is IDisposableEngine dengine)
  224. dengine.isDisposing = true;
  225. engine.Dispose();
  226. }
  227. catch (Exception e)
  228. {
  229. Console.LogException(e);
  230. }
  231. foreach (var groups in _groupEntityComponentsDB)
  232. foreach (var entityList in groups.value)
  233. try
  234. {
  235. ITypeSafeDictionary typeSafeDictionary = entityList.value;
  236. typeSafeDictionary.ExecuteEnginesDisposeCallbacks_Group(
  237. _reactiveEnginesDispose, _reactiveEnginesDisposeEx, groups.key,
  238. profiler);
  239. }
  240. catch (Exception e)
  241. {
  242. Console.LogException(e);
  243. }
  244. foreach (var groups in _groupEntityComponentsDB)
  245. foreach (var entityList in groups.value)
  246. entityList.value.Dispose();
  247. #if SVELTO_LEGACY_FILTERS
  248. foreach (var type in _groupFilters)
  249. foreach (var group in type.value)
  250. group.value.Dispose();
  251. _groupFilters.Clear();
  252. #endif
  253. DisposeFilters();
  254. #if UNITY_NATIVE
  255. _nativeAddOperationQueue.Dispose();
  256. _nativeRemoveOperationQueue.Dispose();
  257. _nativeSwapOperationQueue.Dispose();
  258. #endif
  259. _groupEntityComponentsDB.Clear();
  260. _groupsPerEntity.Clear();
  261. _disposableEngines.Clear();
  262. _enginesSet.Clear();
  263. _enginesTypeSet.Clear();
  264. _reactiveEnginesSwap.Clear();
  265. _reactiveEnginesAdd.Clear();
  266. _reactiveEnginesRemove.Clear();
  267. _reactiveEnginesDispose.Clear();
  268. _reactiveEnginesDisposeEx.Clear();
  269. _reactiveEnginesSubmission.Clear();
  270. _reactiveEnginesSubmissionStarted.Clear();
  271. _groupedEntityToAdd.Dispose();
  272. _entityLocator.DisposeEntityReferenceMap();
  273. _entityStreams.Dispose();
  274. scheduler.Dispose();
  275. }
  276. _isDisposed = true;
  277. }
  278. void NotifyReactiveEnginesOnSubmission()
  279. {
  280. var enginesCount = _reactiveEnginesSubmission.count;
  281. for (var i = 0; i < enginesCount; i++)
  282. _reactiveEnginesSubmission[i].EntitiesSubmitted();
  283. }
  284. void NotifyReactiveEnginesOnSubmissionStarted()
  285. {
  286. var enginesCount = _reactiveEnginesSubmissionStarted.count;
  287. for (var i = 0; i < enginesCount; i++)
  288. _reactiveEnginesSubmissionStarted[i].EntitiesSubmissionStarting();
  289. }
  290. public readonly struct EntitiesSubmitter
  291. {
  292. public EntitiesSubmitter(EnginesRoot enginesRoot): this()
  293. {
  294. _enginesRoot = new DataStructures.WeakReference<EnginesRoot>(enginesRoot);
  295. }
  296. internal void SubmitEntities()
  297. {
  298. Check.Require(_enginesRoot.IsValid, "ticking an GCed engines root?");
  299. var enginesRootTarget = _enginesRoot.Target;
  300. var entitiesSubmissionScheduler = enginesRootTarget.scheduler;
  301. if (entitiesSubmissionScheduler.paused == false)
  302. {
  303. enginesRootTarget.NotifyReactiveEnginesOnSubmissionStarted();
  304. Check.Require(
  305. entitiesSubmissionScheduler.isRunning == false,
  306. "A submission started while the previous one was still flushing");
  307. entitiesSubmissionScheduler.isRunning = true;
  308. using (var profiler = new PlatformProfiler("Svelto.ECS - Entities Submission"))
  309. {
  310. var iterations = 0;
  311. var hasEverSubmitted = false;
  312. // We need to clear transient filters before processing callbacks since the callbacks may add
  313. // new entities to these filters.
  314. enginesRootTarget.ClearTransientFilters();
  315. #if UNITY_NATIVE
  316. enginesRootTarget.FlushNativeOperations(profiler);
  317. #endif
  318. while (enginesRootTarget.HasMadeNewStructuralChangesInThisIteration()
  319. && iterations++ < MAX_SUBMISSION_ITERATIONS)
  320. {
  321. hasEverSubmitted = true;
  322. _enginesRoot.Target.SingleSubmission(profiler);
  323. #if UNITY_NATIVE
  324. enginesRootTarget.FlushNativeOperations(profiler);
  325. #endif
  326. }
  327. #if DEBUG && !PROFILE_SVELTO
  328. if (iterations == MAX_SUBMISSION_ITERATIONS)
  329. throw new ECSException("possible circular submission detected");
  330. #endif
  331. if (hasEverSubmitted)
  332. enginesRootTarget.NotifyReactiveEnginesOnSubmission();
  333. }
  334. entitiesSubmissionScheduler.isRunning = false;
  335. ++entitiesSubmissionScheduler.iteration;
  336. }
  337. }
  338. readonly DataStructures.WeakReference<EnginesRoot> _enginesRoot;
  339. }
  340. ~EnginesRoot()
  341. {
  342. Console.LogWarning("Engines Root has been garbage collected, don't forget to call Dispose()!");
  343. Dispose(false);
  344. }
  345. const int MAX_SUBMISSION_ITERATIONS = 10;
  346. readonly FasterList<IDisposable> _disposableEngines;
  347. readonly FasterList<IEngine> _enginesSet;
  348. readonly HashSet<Type> _enginesTypeSet;
  349. readonly EnginesReadyOption _enginesWaitForReady;
  350. readonly FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnAdd>>> _reactiveEnginesAdd;
  351. readonly FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnAddEx>>> _reactiveEnginesAddEx;
  352. readonly FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnRemove>>> _reactiveEnginesRemove;
  353. readonly FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnRemoveEx>>> _reactiveEnginesRemoveEx;
  354. readonly FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnSwap>>> _reactiveEnginesSwap;
  355. readonly FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnSwapEx>>> _reactiveEnginesSwapEx;
  356. readonly FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnDispose>>> _reactiveEnginesDispose;
  357. readonly FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnDisposeEx>>> _reactiveEnginesDisposeEx;
  358. readonly FasterList<IReactOnSubmission> _reactiveEnginesSubmission;
  359. readonly FasterList<IReactOnSubmissionStarted> _reactiveEnginesSubmissionStarted;
  360. bool _isDisposed;
  361. }
  362. public enum EnginesReadyOption
  363. {
  364. ReadyAsAdded,
  365. WaitForReady
  366. }
  367. }