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.

61 lines
2.5KB

  1. using System;
  2. using Svelto.DataStructures;
  3. using Svelto.ECS.Internal;
  4. namespace Svelto.ECS
  5. {
  6. /// <summary>
  7. /// I eventually realised that, with the ECS design, no form of engines (systems) communication other
  8. /// than polling entity components is effective.
  9. /// The only purpose of this publisher/consumer model is to let two enginesroots communicate with each other
  10. /// through a thread safe ring buffer.
  11. /// The engines root A publishes entities.
  12. /// The engines root B can consume those entities at any time, as they will be a copy of the original
  13. /// entities and won't point directly to the database of the engines root A
  14. /// </summary>
  15. struct EntitiesStreams : IDisposable
  16. {
  17. internal Consumer<T> GenerateConsumer<T>(string name, uint capacity)
  18. where T : unmanaged, _IInternalEntityComponent
  19. {
  20. if (_streams.ContainsKey(TypeRefWrapper<T>.wrapper) == false)
  21. _streams[TypeRefWrapper<T>.wrapper] = new EntityStream<T>();
  22. return (_streams[TypeRefWrapper<T>.wrapper] as EntityStream<T>).GenerateConsumer(name, capacity);
  23. }
  24. public Consumer<T> GenerateConsumer<T>(ExclusiveGroupStruct group, string name, uint capacity)
  25. where T : unmanaged, _IInternalEntityComponent
  26. {
  27. if (_streams.ContainsKey(TypeRefWrapper<T>.wrapper) == false)
  28. _streams[TypeRefWrapper<T>.wrapper] = new EntityStream<T>();
  29. var typeSafeStream = (EntityStream<T>) _streams[TypeRefWrapper<T>.wrapper];
  30. return typeSafeStream.GenerateConsumer(group, name, capacity);
  31. }
  32. internal void PublishEntity<T>(ref T entity, EGID egid) where T : unmanaged, _IInternalEntityComponent
  33. {
  34. if (_streams.TryGetValue(TypeRefWrapper<T>.wrapper, out var typeSafeStream))
  35. (typeSafeStream as EntityStream<T>).PublishEntity(ref entity, egid);
  36. else
  37. Console.LogDebug($"No Consumers are waiting for this entity to change {typeof(T)}");
  38. }
  39. public void Dispose()
  40. {
  41. foreach (var stream in _streams)
  42. stream.value.Dispose();
  43. }
  44. public static EntitiesStreams Create()
  45. {
  46. var stream = new EntitiesStreams();
  47. stream._streams = FasterDictionary<RefWrapperType, ITypeSafeStream>.Construct();
  48. return stream;
  49. }
  50. FasterDictionary<RefWrapperType, ITypeSafeStream> _streams;
  51. }
  52. }