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.

NativeEGIDMultiMapper.cs 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System;
  2. using Svelto.DataStructures;
  3. using Svelto.DataStructures.Native;
  4. using Svelto.ECS.DataStructures;
  5. namespace Svelto.ECS.Native
  6. {
  7. /// <summary>
  8. /// Note: this class should really be ref struct by design. It holds the reference of a dictionary that can become
  9. /// invalid. Unfortunately it can be a ref struct, because Jobs needs to hold if by paramater. So the deal is
  10. /// that a job can use it as long as nothing else is modifying the entities database and the NativeEGIDMultiMapper
  11. /// is disposed right after the use.
  12. ///
  13. ///WARNING: REMEMBER THIS MUST BE DISPOSED OF, AS IT USES NATIVE MEMORY. IT WILL LEAK MEMORY OTHERWISE
  14. ///
  15. /// </summary>
  16. public struct NativeEGIDMultiMapper<T> : IDisposable where T : unmanaged, IBaseEntityComponent
  17. {
  18. public NativeEGIDMultiMapper(in SveltoDictionaryNative<ExclusiveGroupStruct, SharedSveltoDictionaryNative<uint, T>> dictionary)
  19. {
  20. _dic = dictionary;
  21. }
  22. public int count => (int)_dic.count;
  23. public void Dispose()
  24. {
  25. _dic.Dispose();
  26. }
  27. public ref T Entity(EGID entity)
  28. {
  29. #if DEBUG && !PROFILE_SVELTO
  30. if (Exists(entity) == false)
  31. throw new Exception($"NativeEGIDMultiMapper: Entity not found {entity}");
  32. #endif
  33. ref var sveltoDictionary = ref _dic.GetValueByRef(entity.groupID);
  34. return ref sveltoDictionary.dictionary.GetValueByRef(entity.entityID);
  35. }
  36. public uint GetIndex(EGID entity)
  37. {
  38. #if DEBUG && !PROFILE_SVELTO
  39. if (Exists(entity) == false)
  40. throw new Exception($"NativeEGIDMultiMapper: Entity not found {entity}");
  41. #endif
  42. ref var sveltoDictionary = ref _dic.GetValueByRef(entity.groupID);
  43. return sveltoDictionary.dictionary.GetIndex(entity.entityID);
  44. }
  45. public bool Exists(EGID entity)
  46. {
  47. return _dic.TryFindIndex(entity.groupID, out var index) &&
  48. _dic.GetDirectValueByRef(index).dictionary.ContainsKey(entity.entityID);
  49. }
  50. public bool TryGetEntity(EGID entity, out T component)
  51. {
  52. component = default;
  53. return _dic.TryFindIndex(entity.groupID, out var index) &&
  54. _dic.GetDirectValueByRef(index).dictionary.TryGetValue(entity.entityID, out component);
  55. }
  56. SveltoDictionaryNative<ExclusiveGroupStruct, SharedSveltoDictionaryNative<uint, T>> _dic;
  57. }
  58. }