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.

EntityComponentInitializer.cs 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System;
  2. using Svelto.DataStructures;
  3. using Svelto.ECS.Internal;
  4. namespace Svelto.ECS
  5. {
  6. public readonly ref struct EntityComponentInitializer
  7. {
  8. public EntityComponentInitializer(EGID id, FasterDictionary<RefWrapperType, ITypeSafeDictionary> group)
  9. {
  10. _group = group;
  11. _ID = id;
  12. }
  13. public EGID EGID => _ID;
  14. public void Init<T>(T initializer) where T : struct, IEntityComponent
  15. {
  16. if (_group.TryGetValue(new RefWrapperType(ComponentBuilder<T>.ENTITY_COMPONENT_TYPE),
  17. out var typeSafeDictionary) == false) return;
  18. var dictionary = (ITypeSafeDictionary<T>) typeSafeDictionary;
  19. if (ComponentBuilder<T>.HAS_EGID)
  20. SetEGIDWithoutBoxing<T>.SetIDWithoutBoxing(ref initializer, _ID);
  21. if (dictionary.TryFindIndex(_ID.entityID, out var findElementIndex))
  22. dictionary.GetDirectValueByRef(findElementIndex) = initializer;
  23. }
  24. public ref T GetOrCreate<T>() where T : struct, IEntityComponent
  25. {
  26. ref var entityDictionary = ref _group.GetOrCreate(new RefWrapperType(ComponentBuilder<T>.ENTITY_COMPONENT_TYPE)
  27. , TypeSafeDictionaryFactory<T>.Create);
  28. var dictionary = (ITypeSafeDictionary<T>) entityDictionary;
  29. return ref dictionary.GetOrCreate(_ID.entityID);
  30. }
  31. public ref T Get<T>() where T : struct, IEntityComponent
  32. {
  33. return ref (_group[new RefWrapperType(ComponentBuilder<T>.ENTITY_COMPONENT_TYPE)] as ITypeSafeDictionary<T>)[
  34. _ID.entityID];
  35. }
  36. public bool Has<T>() where T : struct, IEntityComponent
  37. {
  38. if (_group.TryGetValue(new RefWrapperType(ComponentBuilder<T>.ENTITY_COMPONENT_TYPE),
  39. out var typeSafeDictionary))
  40. {
  41. var dictionary = (ITypeSafeDictionary<T>) typeSafeDictionary;
  42. if (dictionary.ContainsKey(_ID.entityID))
  43. return true;
  44. }
  45. return false;
  46. }
  47. readonly EGID _ID;
  48. readonly FasterDictionary<RefWrapperType, ITypeSafeDictionary> _group;
  49. }
  50. }