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.

369 lines
13KB

  1. using System;
  2. using System.Reflection;
  3. using System.Threading.Tasks;
  4. using Svelto.ECS;
  5. using Svelto.ECS.EntityStructs;
  6. using RobocraftX.Common;
  7. using RobocraftX.Blocks;
  8. using Unity.Mathematics;
  9. using Unity.Entities;
  10. using Gamecraft.Blocks.GUI;
  11. using GamecraftModdingAPI.Blocks;
  12. using GamecraftModdingAPI.Utility;
  13. namespace GamecraftModdingAPI
  14. {
  15. /// <summary>
  16. /// A single (perhaps scaled) block. Properties may return default values if the block is removed and then setting them is ignored.
  17. /// For specific block type operations, use the specialised block classes in the GamecraftModdingAPI.Blocks namespace.
  18. /// </summary>
  19. public class Block : IEquatable<Block>, IEquatable<EGID>
  20. {
  21. protected static readonly PlacementEngine PlacementEngine = new PlacementEngine();
  22. protected static readonly MovementEngine MovementEngine = new MovementEngine();
  23. protected static readonly RotationEngine RotationEngine = new RotationEngine();
  24. protected static readonly RemovalEngine RemovalEngine = new RemovalEngine();
  25. protected static readonly SignalEngine SignalEngine = new SignalEngine();
  26. protected static readonly BlockEventsEngine BlockEventsEngine = new BlockEventsEngine();
  27. protected static readonly ScalingEngine ScalingEngine = new ScalingEngine();
  28. protected internal static readonly BlockEngine BlockEngine = new BlockEngine();
  29. /// <summary>
  30. /// Place a new block at the given position. If scaled, position means the center of the block. The default block size is 0.2 in terms of position.
  31. /// Place blocks next to each other to connect them.
  32. /// The placed block will be a complete block with a placement grid and collision which will be saved along with the game.
  33. /// <para></para>
  34. /// <para>When placing multiple blocks, do not access properties immediately after creation as this
  35. /// triggers a sync each time which can affect performance and may cause issues with the game.
  36. /// You may either use AsyncUtils.WaitForSubmission() after placing all of the blocks
  37. /// or simply access the block properties which will trigger the synchronization the first time a property is used.</para>
  38. /// </summary>
  39. /// <param name="block">The block's type</param>
  40. /// <param name="color">The block's color</param>
  41. /// <param name="darkness">The block color's darkness (0-9) - 0 is default color</param>
  42. /// <param name="position">The block's position in the grid - default block size is 0.2</param>
  43. /// <param name="rotation">The block's rotation in degrees</param>
  44. /// <param name="uscale">The block's uniform scale - default scale is 1 (with 0.2 width)</param>
  45. /// <param name="scale">The block's non-uniform scale - 0 means <paramref name="uscale"/> is used</param>
  46. /// <param name="player">The player who placed the block</param>
  47. /// <returns>The placed block or null if failed</returns>
  48. public static Block PlaceNew(BlockIDs block, float3 position,
  49. float3 rotation = default, BlockColors color = BlockColors.Default, byte darkness = 0,
  50. int uscale = 1, float3 scale = default, Player player = null)
  51. {
  52. if (PlacementEngine.IsInGame && GameState.IsBuildMode())
  53. {
  54. return new Block(PlacementEngine.PlaceBlock(block, color, darkness,
  55. position, uscale, scale, player, rotation));
  56. }
  57. return null;
  58. }
  59. /// <summary>
  60. /// Place a new block at the given position. If scaled, position means the center of the block. The default block size is 0.2 in terms of position.
  61. /// Place blocks next to each other to connect them.
  62. /// The placed block will be a complete block with a placement grid and collision which will be saved along with the game.
  63. /// <para></para>
  64. /// <para>This method waits for the block to be constructed in the game which may take a significant amount of time.
  65. /// Only use this to place a single block.
  66. /// For placing multiple blocks, use PlaceNew() then AsyncUtils.WaitForSubmission() when done with placing blocks.</para>
  67. /// </summary>
  68. /// <param name="block">The block's type</param>
  69. /// <param name="color">The block's color</param>
  70. /// <param name="darkness">The block color's darkness (0-9) - 0 is default color</param>
  71. /// <param name="position">The block's position in the grid - default block size is 0.2</param>
  72. /// <param name="rotation">The block's rotation in degrees</param>
  73. /// <param name="uscale">The block's uniform scale - default scale is 1 (with 0.2 width)</param>
  74. /// <param name="scale">The block's non-uniform scale - 0 means <paramref name="uscale"/> is used</param>
  75. /// <param name="player">The player who placed the block</param>
  76. /// <returns>The placed block or null if failed</returns>
  77. public static async Task<Block> PlaceNewAsync(BlockIDs block, float3 position,
  78. float3 rotation = default, BlockColors color = BlockColors.Default, byte darkness = 0,
  79. int uscale = 1, float3 scale = default, Player player = null)
  80. {
  81. if (PlacementEngine.IsInGame && GameState.IsBuildMode())
  82. {
  83. try
  84. {
  85. var ret = new Block(PlacementEngine.PlaceBlock(block, color, darkness,
  86. position, uscale, scale, player, rotation));
  87. await AsyncUtils.WaitForSubmission();
  88. return ret;
  89. }
  90. catch (Exception e)
  91. {
  92. Logging.MetaDebugLog(e);
  93. }
  94. }
  95. return null;
  96. }
  97. /// <summary>
  98. /// Returns the most recently placed block.
  99. /// </summary>
  100. /// <returns>The block object</returns>
  101. public static Block GetLastPlacedBlock()
  102. {
  103. return new Block(BlockIdentifiers.LatestBlockID);
  104. }
  105. /// <summary>
  106. /// An event that fires each time a block is placed.
  107. /// </summary>
  108. public static event EventHandler<BlockPlacedRemovedEventArgs> Placed
  109. {
  110. add => BlockEventsEngine.Placed += value;
  111. remove => BlockEventsEngine.Placed -= value;
  112. }
  113. /// <summary>
  114. /// An event that fires each time a block is removed.
  115. /// </summary>
  116. public static event EventHandler<BlockPlacedRemovedEventArgs> Removed
  117. {
  118. add => BlockEventsEngine.Removed += value;
  119. remove => BlockEventsEngine.Removed -= value;
  120. }
  121. public Block(EGID id)
  122. {
  123. Id = id;
  124. }
  125. /// <summary>
  126. /// This overload searches for the correct group the block is in.
  127. /// It will throw an exception if the block doesn't exist.
  128. /// Use the EGID constructor where possible or subclasses of Block as those specify the group.
  129. /// </summary>
  130. public Block(uint id)
  131. {
  132. Id = BlockEngine.FindBlockEGID(id) ?? throw new BlockTypeException("Could not find the appropriate group for the block. The block probably doesn't exist or hasn't been submitted.");
  133. }
  134. public EGID Id { get; }
  135. /// <summary>
  136. /// The block's current position or zero if the block no longer exists.
  137. /// A block is 0.2 wide by default in terms of position.
  138. /// </summary>
  139. public float3 Position
  140. {
  141. get => Exists ? MovementEngine.GetPosition(Id) : float3.zero;
  142. set
  143. {
  144. if (Exists) MovementEngine.MoveBlock(Id, value);
  145. }
  146. }
  147. /// <summary>
  148. /// The block's current rotation in degrees or zero if the block doesn't exist.
  149. /// </summary>
  150. public float3 Rotation
  151. {
  152. get => Exists ? RotationEngine.GetRotation(Id) : float3.zero;
  153. set
  154. {
  155. if (Exists) RotationEngine.RotateBlock(Id, value);
  156. }
  157. }
  158. /// <summary>
  159. /// The block's non-uniform scale or zero if the block's invalid. Independent of the uniform scaling.
  160. /// The default scale of 1 means 0.2 in terms of position.
  161. /// </summary>
  162. public float3 Scale
  163. {
  164. get => BlockEngine.GetBlockInfo<ScalingEntityStruct>(Id).scale;
  165. set
  166. {
  167. if (!Exists) return; //UpdateCollision needs the block to exist
  168. ref var scaling = ref BlockEngine.GetBlockInfo<ScalingEntityStruct>(Id);
  169. scaling.scale = value;
  170. ScalingEngine.UpdateCollision(Id);
  171. }
  172. }
  173. /// <summary>
  174. /// The block's uniform scale or zero if the block's invalid. Also sets the non-uniform scale.
  175. /// The default scale of 1 means 0.2 in terms of position.
  176. /// </summary>
  177. public int UniformScale
  178. {
  179. get => BlockEngine.GetBlockInfo<UniformBlockScaleEntityStruct>(Id).scaleFactor;
  180. set
  181. {
  182. ref var scaleStruct = ref BlockEngine.GetBlockInfo<UniformBlockScaleEntityStruct>(Id);
  183. scaleStruct.scaleFactor = value;
  184. Scale = new float3(value, value, value);
  185. }
  186. }
  187. /// <summary>
  188. /// The block's type (ID). Returns BlockIDs.Invalid if the block doesn't exist anymore.
  189. /// </summary>
  190. public BlockIDs Type
  191. {
  192. get
  193. {
  194. var id = (BlockIDs) BlockEngine.GetBlockInfo<DBEntityStruct>(Id, out var exists).DBID;
  195. return exists ? id : BlockIDs.Invalid;
  196. }
  197. }
  198. /// <summary>
  199. /// The block's color. Returns BlockColors.Default if the block no longer exists.
  200. /// </summary>
  201. public BlockColor Color
  202. {
  203. get
  204. {
  205. byte index = BlockEngine.GetBlockInfo<ColourParameterEntityStruct>(Id, out var exists).indexInPalette;
  206. if (!exists) index = byte.MaxValue;
  207. return new BlockColor(index);
  208. }
  209. set
  210. {
  211. ref var color = ref BlockEngine.GetBlockInfo<ColourParameterEntityStruct>(Id);
  212. color.indexInPalette = (byte)(value.Color + value.Darkness * 10);
  213. color.overridePaletteColour = false;
  214. color.needsUpdate = true;
  215. BlockEngine.SetBlockColorFromPalette(ref color);
  216. }
  217. }
  218. /// <summary>
  219. /// The block's exact color. Gets reset to the palette color (Color property) after reentering the game.
  220. /// </summary>
  221. public float4 CustomColor
  222. {
  223. get => BlockEngine.GetBlockInfo<ColourParameterEntityStruct>(Id).overriddenColour;
  224. set
  225. {
  226. ref var color = ref BlockEngine.GetBlockInfo<ColourParameterEntityStruct>(Id);
  227. color.overriddenColour = value;
  228. color.overridePaletteColour = true;
  229. color.needsUpdate = true;
  230. }
  231. }
  232. /// <summary>
  233. /// The short text displayed on the block if applicable, or null.
  234. /// Setting it is temporary to the session, it won't be saved.
  235. /// </summary>
  236. public string Label
  237. {
  238. get => BlockEngine.GetBlockInfo<TextLabelEntityViewStruct>(Id).textLabelComponent?.text;
  239. set
  240. {
  241. ref var text = ref BlockEngine.GetBlockInfo<TextLabelEntityViewStruct>(Id);
  242. if (text.textLabelComponent != null) text.textLabelComponent.text = value;
  243. }
  244. }
  245. /// <summary>
  246. /// Whether the block exists. The other properties will return a default value if the block doesn't exist.
  247. /// </summary>
  248. public bool Exists => BlockEngine.BlockExists(Id);
  249. /// <summary>
  250. /// Returns an array of blocks that are connected to this one. Returns an empty array if the block doesn't exist.
  251. /// </summary>
  252. public Block[] GetConnectedCubes() => BlockEngine.GetConnectedBlocks(Id);
  253. /// <summary>
  254. /// Removes this block.
  255. /// </summary>
  256. /// <returns>True if the block exists and could be removed.</returns>
  257. public bool Remove() => RemovalEngine.RemoveBlock(Id);
  258. /// <summary>
  259. /// Returns the rigid body of the cluster of blocks this one belongs to during simulation.
  260. /// Can be used to apply forces or move the block around while the simulation is running.
  261. /// </summary>
  262. /// <returns>The SimBody of the cluster or null if the block doesn't exist.</returns>
  263. public SimBody GetSimBody()
  264. {
  265. uint id = BlockEngine.GetBlockInfo<GridConnectionsEntityStruct>(Id, out var exists).machineRigidBodyId;
  266. return exists ? new SimBody(id) : null;
  267. }
  268. public override string ToString()
  269. {
  270. return $"{nameof(Id)}: {Id}, {nameof(Position)}: {Position}, {nameof(Type)}: {Type}, {nameof(Color)}: {Color}, {nameof(Exists)}: {Exists}";
  271. }
  272. public bool Equals(Block other)
  273. {
  274. if (ReferenceEquals(null, other)) return false;
  275. if (ReferenceEquals(this, other)) return true;
  276. return Id.Equals(other.Id);
  277. }
  278. public bool Equals(EGID other)
  279. {
  280. return Id.Equals(other);
  281. }
  282. public override bool Equals(object obj)
  283. {
  284. if (ReferenceEquals(null, obj)) return false;
  285. if (ReferenceEquals(this, obj)) return true;
  286. if (obj.GetType() != this.GetType()) return false;
  287. return Equals((Block) obj);
  288. }
  289. public override int GetHashCode()
  290. {
  291. return Id.GetHashCode();
  292. }
  293. public static void Init()
  294. {
  295. GameEngineManager.AddGameEngine(PlacementEngine);
  296. GameEngineManager.AddGameEngine(MovementEngine);
  297. GameEngineManager.AddGameEngine(RotationEngine);
  298. GameEngineManager.AddGameEngine(RemovalEngine);
  299. GameEngineManager.AddGameEngine(BlockEngine);
  300. GameEngineManager.AddGameEngine(BlockEventsEngine);
  301. GameEngineManager.AddGameEngine(ScalingEngine);
  302. }
  303. /// <summary>
  304. /// Convert the block to a specialised block class.
  305. /// </summary>
  306. /// <returns>The block.</returns>
  307. /// <typeparam name="T">The specialised block type.</typeparam>
  308. public T Specialise<T>() where T : Block
  309. {
  310. // What have I gotten myself into?
  311. // C# can't cast to a child of Block unless the object was originally that child type
  312. // And C# doesn't let me make implicit cast operators for child types
  313. // So thanks to Microsoft, we've got this horrible implementation using reflection
  314. ConstructorInfo ctor = typeof(T).GetConstructor(types: new System.Type[] { typeof(EGID) });
  315. if (ctor == null)
  316. {
  317. throw new BlockSpecializationException("Specialized block constructor does not accept an EGID");
  318. }
  319. return (T)ctor.Invoke(new object[] { Id });
  320. }
  321. #if DEBUG
  322. public static EntitiesDB entitiesDB
  323. {
  324. get
  325. {
  326. return BlockEngine.GetEntitiesDB();
  327. }
  328. }
  329. #endif
  330. internal static void Setup(World physicsWorld)
  331. {
  332. ScalingEngine.Setup(physicsWorld.EntityManager);
  333. }
  334. }
  335. }