A stable modding interface between Techblox and mods https://mod.exmods.org/
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.

110 lines
4.6KB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq.Expressions;
  4. using Svelto.DataStructures;
  5. using Svelto.ECS;
  6. using Svelto.ECS.Internal;
  7. using TechbloxModdingAPI.Utility;
  8. namespace TechbloxModdingAPI
  9. {
  10. public abstract class EcsObjectBase
  11. {
  12. public abstract EGID Id { get; } //Abstract to support the 'place' Block constructor
  13. private static readonly Dictionary<Type, WeakDictionary<EGID, EcsObjectBase>> _instances =
  14. new Dictionary<Type, WeakDictionary<EGID, EcsObjectBase>>();
  15. private static readonly WeakDictionary<EGID, EcsObjectBase> _noInstance =
  16. new WeakDictionary<EGID, EcsObjectBase>();
  17. internal static WeakDictionary<EGID, EcsObjectBase> GetInstances(Type type)
  18. {
  19. return _instances.TryGetValue(type, out var dict) ? dict : null;
  20. }
  21. /// <summary>
  22. /// Returns a cached instance if there's an actively used instance of the object already.
  23. /// Objects still get garbage collected and then they will be removed from the cache.
  24. /// </summary>
  25. /// <param name="egid">The EGID of the entity</param>
  26. /// <param name="constructor">The constructor to construct the object</param>
  27. /// <typeparam name="T">The object type</typeparam>
  28. /// <returns></returns>
  29. internal static T GetInstance<T>(EGID egid, Func<EGID, T> constructor, Type type = null) where T : EcsObjectBase
  30. {
  31. var instances = GetInstances(type ?? typeof(T));
  32. if (instances == null || !instances.TryGetValue(egid, out var instance))
  33. return constructor(egid); // It will be added by the constructor
  34. return (T)instance;
  35. }
  36. protected EcsObjectBase()
  37. {
  38. if (!_instances.TryGetValue(GetType(), out var dict))
  39. {
  40. dict = new WeakDictionary<EGID, EcsObjectBase>();
  41. _instances.Add(GetType(), dict);
  42. }
  43. // ReSharper disable VirtualMemberCallInConstructor
  44. // The ID should not depend on the constructor
  45. if (!dict.ContainsKey(Id)) // Multiple instances may be created
  46. dict.Add(Id, this);
  47. // ReSharper enable VirtualMemberCallInConstructor
  48. }
  49. #region ECS initializer stuff
  50. protected internal EcsInitData InitData;
  51. /// <summary>
  52. /// Holds information needed to construct a component initializer
  53. /// </summary>
  54. protected internal struct EcsInitData
  55. {
  56. private FasterDictionary<RefWrapperType, ITypeSafeDictionary> group;
  57. private EntityReference reference;
  58. public static implicit operator EcsInitData(EntityInitializer initializer) => new EcsInitData
  59. { group = GetInitGroup(initializer), reference = initializer.reference };
  60. public EntityInitializer Initializer(EGID id) => new EntityInitializer(id, group, reference);
  61. public bool Valid => group != null;
  62. }
  63. private delegate FasterDictionary<RefWrapperType, ITypeSafeDictionary> GetInitGroupFunc(
  64. EntityInitializer initializer);
  65. /// <summary>
  66. /// Accesses the group field of the initializer
  67. /// </summary>
  68. private static GetInitGroupFunc GetInitGroup = CreateAccessor<GetInitGroupFunc>("_group");
  69. //https://stackoverflow.com/questions/55878525/unit-testing-ref-structs-with-private-fields-via-reflection
  70. private static TDelegate CreateAccessor<TDelegate>(string memberName) where TDelegate : Delegate
  71. {
  72. var invokeMethod = typeof(TDelegate).GetMethod("Invoke");
  73. if (invokeMethod == null)
  74. throw new InvalidOperationException($"{typeof(TDelegate)} signature could not be determined.");
  75. var delegateParameters = invokeMethod.GetParameters();
  76. if (delegateParameters.Length != 1)
  77. throw new InvalidOperationException("Delegate must have a single parameter.");
  78. var paramType = delegateParameters[0].ParameterType;
  79. var objParam = Expression.Parameter(paramType, "obj");
  80. var memberExpr = Expression.PropertyOrField(objParam, memberName);
  81. Expression returnExpr = memberExpr;
  82. if (invokeMethod.ReturnType != memberExpr.Type)
  83. returnExpr = Expression.ConvertChecked(memberExpr, invokeMethod.ReturnType);
  84. var lambda =
  85. Expression.Lambda<TDelegate>(returnExpr, $"Access{paramType.Name}_{memberName}", new[] { objParam });
  86. return lambda.Compile();
  87. }
  88. #endregion
  89. }
  90. }