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.

363 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. public Block(uint id) : this(new EGID(id, CommonExclusiveGroups.OWNED_BLOCKS_GROUP))
  126. {
  127. }
  128. public EGID Id { get; }
  129. /// <summary>
  130. /// The block's current position or zero if the block no longer exists.
  131. /// A block is 0.2 wide by default in terms of position.
  132. /// </summary>
  133. public float3 Position
  134. {
  135. get => Exists ? MovementEngine.GetPosition(Id.entityID) : float3.zero;
  136. set
  137. {
  138. if (Exists) MovementEngine.MoveBlock(Id.entityID, value);
  139. }
  140. }
  141. /// <summary>
  142. /// The block's current rotation in degrees or zero if the block doesn't exist.
  143. /// </summary>
  144. public float3 Rotation
  145. {
  146. get => Exists ? RotationEngine.GetRotation(Id.entityID) : float3.zero;
  147. set
  148. {
  149. if (Exists) RotationEngine.RotateBlock(Id.entityID, value);
  150. }
  151. }
  152. /// <summary>
  153. /// The block's non-uniform scale or zero if the block's invalid. Independent of the uniform scaling.
  154. /// The default scale of 1 means 0.2 in terms of position.
  155. /// </summary>
  156. public float3 Scale
  157. {
  158. get => BlockEngine.GetBlockInfo<ScalingEntityStruct>(Id).scale;
  159. set
  160. {
  161. if (!Exists) return; //UpdateCollision needs the block to exist
  162. ref var scaling = ref BlockEngine.GetBlockInfo<ScalingEntityStruct>(Id);
  163. scaling.scale = value;
  164. ScalingEngine.UpdateCollision(Id);
  165. }
  166. }
  167. /// <summary>
  168. /// The block's uniform scale or zero if the block's invalid. Also sets the non-uniform scale.
  169. /// The default scale of 1 means 0.2 in terms of position.
  170. /// </summary>
  171. public int UniformScale
  172. {
  173. get => BlockEngine.GetBlockInfo<UniformBlockScaleEntityStruct>(Id).scaleFactor;
  174. set
  175. {
  176. ref var scaleStruct = ref BlockEngine.GetBlockInfo<UniformBlockScaleEntityStruct>(Id);
  177. scaleStruct.scaleFactor = value;
  178. Scale = new float3(value, value, value);
  179. }
  180. }
  181. /// <summary>
  182. /// The block's type (ID). Returns BlockIDs.Invalid if the block doesn't exist anymore.
  183. /// </summary>
  184. public BlockIDs Type
  185. {
  186. get
  187. {
  188. var id = (BlockIDs) BlockEngine.GetBlockInfo<DBEntityStruct>(Id, out var exists).DBID;
  189. return exists ? id : BlockIDs.Invalid;
  190. }
  191. }
  192. /// <summary>
  193. /// The block's color. Returns BlockColors.Default if the block no longer exists.
  194. /// </summary>
  195. public BlockColor Color
  196. {
  197. get
  198. {
  199. byte index = BlockEngine.GetBlockInfo<ColourParameterEntityStruct>(Id, out var exists).indexInPalette;
  200. if (!exists) index = byte.MaxValue;
  201. return new BlockColor(index);
  202. }
  203. set
  204. {
  205. ref var color = ref BlockEngine.GetBlockInfo<ColourParameterEntityStruct>(Id);
  206. color.indexInPalette = (byte)(value.Color + value.Darkness * 10);
  207. color.overridePaletteColour = false;
  208. color.needsUpdate = true;
  209. BlockEngine.SetBlockColorFromPalette(ref color);
  210. }
  211. }
  212. /// <summary>
  213. /// The block's exact color. Gets reset to the palette color (Color property) after reentering the game.
  214. /// </summary>
  215. public float4 CustomColor
  216. {
  217. get => BlockEngine.GetBlockInfo<ColourParameterEntityStruct>(Id).overriddenColour;
  218. set
  219. {
  220. ref var color = ref BlockEngine.GetBlockInfo<ColourParameterEntityStruct>(Id);
  221. color.overriddenColour = value;
  222. color.overridePaletteColour = true;
  223. color.needsUpdate = true;
  224. }
  225. }
  226. /// <summary>
  227. /// The short text displayed on the block if applicable, or null.
  228. /// Setting it is temporary to the session, it won't be saved.
  229. /// </summary>
  230. public string Label
  231. {
  232. get => BlockEngine.GetBlockInfo<TextLabelEntityViewStruct>(Id).textLabelComponent?.text;
  233. set
  234. {
  235. ref var text = ref BlockEngine.GetBlockInfo<TextLabelEntityViewStruct>(Id);
  236. if (text.textLabelComponent != null) text.textLabelComponent.text = value;
  237. }
  238. }
  239. /// <summary>
  240. /// Whether the block exists. The other properties will return a default value if the block doesn't exist.
  241. /// </summary>
  242. public bool Exists => BlockEngine.BlockExists(Id);
  243. /// <summary>
  244. /// Returns an array of blocks that are connected to this one. Returns an empty array if the block doesn't exist.
  245. /// </summary>
  246. public Block[] GetConnectedCubes() => BlockEngine.GetConnectedBlocks(Id);
  247. /// <summary>
  248. /// Removes this block.
  249. /// </summary>
  250. /// <returns>True if the block exists and could be removed.</returns>
  251. public bool Remove() => RemovalEngine.RemoveBlock(Id);
  252. /// <summary>
  253. /// Returns the rigid body of the cluster of blocks this one belongs to during simulation.
  254. /// Can be used to apply forces or move the block around while the simulation is running.
  255. /// </summary>
  256. /// <returns>The SimBody of the cluster or null if the block doesn't exist.</returns>
  257. public SimBody GetSimBody()
  258. {
  259. uint id = BlockEngine.GetBlockInfo<GridConnectionsEntityStruct>(Id, out var exists).machineRigidBodyId;
  260. return exists ? new SimBody(id) : null;
  261. }
  262. public override string ToString()
  263. {
  264. return $"{nameof(Id)}: {Id}, {nameof(Position)}: {Position}, {nameof(Type)}: {Type}, {nameof(Color)}: {Color}, {nameof(Exists)}: {Exists}";
  265. }
  266. public bool Equals(Block other)
  267. {
  268. if (ReferenceEquals(null, other)) return false;
  269. if (ReferenceEquals(this, other)) return true;
  270. return Id.Equals(other.Id);
  271. }
  272. public bool Equals(EGID other)
  273. {
  274. return Id.Equals(other);
  275. }
  276. public override bool Equals(object obj)
  277. {
  278. if (ReferenceEquals(null, obj)) return false;
  279. if (ReferenceEquals(this, obj)) return true;
  280. if (obj.GetType() != this.GetType()) return false;
  281. return Equals((Block) obj);
  282. }
  283. public override int GetHashCode()
  284. {
  285. return Id.GetHashCode();
  286. }
  287. public static void Init()
  288. {
  289. GameEngineManager.AddGameEngine(PlacementEngine);
  290. GameEngineManager.AddGameEngine(MovementEngine);
  291. GameEngineManager.AddGameEngine(RotationEngine);
  292. GameEngineManager.AddGameEngine(RemovalEngine);
  293. GameEngineManager.AddGameEngine(BlockEngine);
  294. GameEngineManager.AddGameEngine(BlockEventsEngine);
  295. GameEngineManager.AddGameEngine(ScalingEngine);
  296. }
  297. /// <summary>
  298. /// Convert the block to a specialised block class.
  299. /// </summary>
  300. /// <returns>The block.</returns>
  301. /// <typeparam name="T">The specialised block type.</typeparam>
  302. public T Specialise<T>() where T : Block
  303. {
  304. // What have I gotten myself into?
  305. // C# can't cast to a child of Block unless the object was originally that child type
  306. // And C# doesn't let me make implicit cast operators for child types
  307. // So thanks to Microsoft, we've got this horrible implementation using reflection
  308. ConstructorInfo ctor = typeof(T).GetConstructor(types: new System.Type[] { typeof(EGID) });
  309. if (ctor == null)
  310. {
  311. throw new BlockSpecializationException("Specialized block constructor does not accept an EGID");
  312. }
  313. return (T)ctor.Invoke(new object[] { Id });
  314. }
  315. #if DEBUG
  316. public static EntitiesDB entitiesDB
  317. {
  318. get
  319. {
  320. return BlockEngine.GetEntitiesDB();
  321. }
  322. }
  323. #endif
  324. internal static void Setup(World physicsWorld)
  325. {
  326. ScalingEngine.Setup(physicsWorld.EntityManager);
  327. }
  328. }
  329. }