Mirror of Svelto.ECS because we're a fan of it
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

72 řádky
2.8KB

  1. using System;
  2. using Svelto.Common;
  3. using Svelto.DataStructures.Native;
  4. using Svelto.ECS.Internal;
  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. /// to retrieve a NativeEGIDMultiMapper use entitiesDB.QueryNativeMappedEntities<T>(groups, Svelto.Common.Allocator.TempJob);
  16. ///
  17. /// TODO: this could be extended to support all the query interfaces so that NB can become ref and this used to query entities inside jobs
  18. ///
  19. /// </summary>
  20. public struct NativeEGIDMultiMapper<T> : IEGIDMultiMapper, IDisposable where T : unmanaged, _IInternalEntityComponent
  21. {
  22. internal NativeEGIDMultiMapper(in SveltoDictionaryNative<ExclusiveGroupStruct, SharedSveltoDictionaryNative<uint, T>> dictionary)
  23. {
  24. _dic = dictionary;
  25. }
  26. public int count => (int)_dic.count;
  27. public void Dispose()
  28. {
  29. _dic.Dispose();
  30. }
  31. public ref T Entity(EGID entity)
  32. {
  33. #if DEBUG && !PROFILE_SVELTO
  34. if (Exists(entity) == false)
  35. throw new Exception($"NativeEGIDMultiMapper: Entity not found {entity}");
  36. #endif
  37. ref var sveltoDictionary = ref _dic.GetValueByRef(entity.groupID);
  38. return ref sveltoDictionary.dictionary.GetValueByRef(entity.entityID);
  39. }
  40. public uint GetIndex(EGID entity)
  41. {
  42. #if DEBUG && !PROFILE_SVELTO
  43. if (Exists(entity) == false)
  44. throw new Exception($"NativeEGIDMultiMapper: Entity not found {entity}");
  45. #endif
  46. ref var sveltoDictionary = ref _dic.GetValueByRef(entity.groupID);
  47. return sveltoDictionary.dictionary.GetIndex(entity.entityID);
  48. }
  49. public bool Exists(EGID entity)
  50. {
  51. return _dic.TryFindIndex(entity.groupID, out var index) &&
  52. _dic.GetDirectValueByRef(index).dictionary.ContainsKey(entity.entityID);
  53. }
  54. public bool TryGetEntity(EGID entity, out T component)
  55. {
  56. component = default;
  57. return _dic.TryFindIndex(entity.groupID, out var index) &&
  58. _dic.GetDirectValueByRef(index).dictionary.TryGetValue(entity.entityID, out component);
  59. }
  60. SveltoDictionaryNative<ExclusiveGroupStruct, SharedSveltoDictionaryNative<uint, T>> _dic;
  61. public Type entityType => TypeCache<T>.type;
  62. }
  63. }