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.

60 line
2.4KB

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