A stable modding interface between Techblox and mods https://mod.exmods.org/
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

93 wiersze
2.9KB

  1. using System;
  2. using System.Runtime.InteropServices;
  3. using Svelto.DataStructures;
  4. using Svelto.ECS;
  5. namespace TechbloxModdingAPI.Utility
  6. {
  7. public ref struct OptionalRef<T> where T : struct, IEntityComponent
  8. {
  9. private readonly State state;
  10. private readonly uint index;
  11. private NB<T> array;
  12. private MB<T> managedArray;
  13. private readonly EntityInitializer initializer;
  14. //The possible fields are: (index && (array || managedArray)) || initializer
  15. public OptionalRef(NB<T> array, uint index)
  16. {
  17. state = State.Native;
  18. this.array = array;
  19. this.index = index;
  20. initializer = default;
  21. }
  22. public OptionalRef(MB<T> array, uint index)
  23. {
  24. state = State.Managed;
  25. managedArray = array;
  26. this.index = index;
  27. initializer = default;
  28. this.array = default;
  29. }
  30. /// <summary>
  31. /// Wraps the initializer data, if present.
  32. /// </summary>
  33. /// <param name="obj">The object with the initializer</param>
  34. /// <param name="unmanaged">Whether the struct is unmanaged</param>
  35. public OptionalRef(EcsObjectBase obj, bool unmanaged)
  36. {
  37. if (obj.InitData.Valid)
  38. {
  39. initializer = obj.InitData.Initializer(obj.Id);
  40. state = (unmanaged ? State.Native : State.Managed) | State.Initializer;
  41. }
  42. else
  43. {
  44. initializer = default;
  45. state = State.Empty;
  46. }
  47. array = default;
  48. index = default;
  49. }
  50. /// <summary>
  51. /// Returns the value or a default value if empty. Supports objects that are being initialized.
  52. /// </summary>
  53. /// <returns>The value or the default value</returns>
  54. public ref T Get()
  55. {
  56. if (state == State.Empty) return ref CompRefCache.Default;
  57. if ((state & State.Initializer) != State.Empty) return ref initializer.GetOrCreate<T>();
  58. if ((state & State.Native) != State.Empty) return ref array[index];
  59. return ref managedArray[index];
  60. }
  61. public bool Exists => state != State.Empty;
  62. public static implicit operator T(OptionalRef<T> opt) => opt.Get();
  63. public static implicit operator bool(OptionalRef<T> opt) => opt.state != State.Empty;
  64. /// <summary>
  65. /// Creates an instance of a struct T that can be referenced.
  66. /// </summary>
  67. internal struct CompRefCache
  68. {
  69. public static T Default;
  70. }
  71. /// <summary>
  72. /// A byte that holds state in its bits.
  73. /// </summary>
  74. [Flags]
  75. private enum State : byte
  76. {
  77. Empty,
  78. Native,
  79. Managed,
  80. Initializer = 4
  81. }
  82. }
  83. }