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.

304 lines
11KB

  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 GamecraftModdingAPI.Blocks;
  10. using GamecraftModdingAPI.Utility;
  11. namespace GamecraftModdingAPI
  12. {
  13. /// <summary>
  14. /// A single (perhaps scaled) block. Properties may return default values if the block is removed and then setting them is ignored.
  15. /// For specific block type operations, use the specialised block classes in the GamecraftModdingAPI.Blocks namespace.
  16. /// </summary>
  17. public class Block
  18. {
  19. protected static readonly PlacementEngine PlacementEngine = new PlacementEngine();
  20. protected static readonly MovementEngine MovementEngine = new MovementEngine();
  21. protected static readonly RotationEngine RotationEngine = new RotationEngine();
  22. protected static readonly RemovalEngine RemovalEngine = new RemovalEngine();
  23. protected static readonly SignalEngine SignalEngine = new SignalEngine();
  24. protected internal static readonly BlockEngine BlockEngine = new BlockEngine();
  25. /// <summary>
  26. /// 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.
  27. /// Place blocks next to each other to connect them.
  28. /// The placed block will be a complete block with a placement grid and collision which will be saved along with the game.
  29. /// </summary>
  30. /// <param name="block">The block's type</param>
  31. /// <param name="color">The block's color</param>
  32. /// <param name="darkness">The block color's darkness (0-9) - 0 is default color</param>
  33. /// <param name="position">The block's position in the grid - default block size is 0.2</param>
  34. /// <param name="rotation">The block's rotation in degrees</param>
  35. /// <param name="uscale">The block's uniform scale - default scale is 1 (with 0.2 width)</param>
  36. /// <param name="scale">The block's non-uniform scale - 0 means <paramref name="uscale"/> is used</param>
  37. /// <param name="player">The player who placed the block</param>
  38. /// <returns>The placed block or null if failed</returns>
  39. public static Block PlaceNew(BlockIDs block, float3 position,
  40. float3 rotation = default, BlockColors color = BlockColors.Default, byte darkness = 0,
  41. int uscale = 1, float3 scale = default, Player player = null)
  42. {
  43. if (PlacementEngine.IsInGame && GameState.IsBuildMode())
  44. {
  45. return new Block(PlacementEngine.PlaceBlock(block, color, darkness,
  46. position, uscale, scale, player, rotation));
  47. }
  48. return null;
  49. }
  50. /// <summary>
  51. /// 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.
  52. /// Place blocks next to each other to connect them.
  53. /// The placed block will be a complete block with a placement grid and collision which will be saved along with the game.
  54. /// <para></para>
  55. /// <para>This method waits for the block to be constructed in the game.</para>
  56. /// </summary>
  57. /// <param name="block">The block's type</param>
  58. /// <param name="color">The block's color</param>
  59. /// <param name="darkness">The block color's darkness (0-9) - 0 is default color</param>
  60. /// <param name="position">The block's position in the grid - default block size is 0.2</param>
  61. /// <param name="rotation">The block's rotation in degrees</param>
  62. /// <param name="uscale">The block's uniform scale - default scale is 1 (with 0.2 width)</param>
  63. /// <param name="scale">The block's non-uniform scale - 0 means <paramref name="uscale"/> is used</param>
  64. /// <param name="player">The player who placed the block</param>
  65. /// <returns>The placed block or null if failed</returns>
  66. public static async Task<Block> PlaceNewAsync(BlockIDs block, float3 position,
  67. float3 rotation = default, BlockColors color = BlockColors.Default, byte darkness = 0,
  68. int uscale = 1, float3 scale = default, Player player = null)
  69. {
  70. if (PlacementEngine.IsInGame && GameState.IsBuildMode())
  71. {
  72. try
  73. {
  74. var ret = new Block(PlacementEngine.PlaceBlock(block, color, darkness,
  75. position, uscale, scale, player, rotation));
  76. await AsyncUtils.WaitForSubmission();
  77. return ret;
  78. }
  79. catch (Exception e)
  80. {
  81. Logging.MetaDebugLog(e);
  82. }
  83. }
  84. return null;
  85. }
  86. /// <summary>
  87. /// Returns the most recently placed block.
  88. /// </summary>
  89. /// <returns>The block object</returns>
  90. public static Block GetLastPlacedBlock()
  91. {
  92. return new Block(BlockIdentifiers.LatestBlockID);
  93. }
  94. public Block(EGID id)
  95. {
  96. Id = id;
  97. if (!BlockEngine.BlockExists(Id))
  98. {
  99. Sync();
  100. if (!BlockEngine.BlockExists(Id))
  101. {
  102. throw new BlockDoesNotExistException($"Block {Id.entityID} must be placed using PlaceNew(...) since it does not exist yet");
  103. }
  104. }
  105. }
  106. public Block(uint id) : this(new EGID(id, CommonExclusiveGroups.OWNED_BLOCKS_GROUP))
  107. {
  108. }
  109. /// <summary>
  110. /// Synchronize newly created entity components with entities DB.
  111. /// This forces a partial game tick, so it may be slow.
  112. /// This also has the potential to make Gamecraft unstable.
  113. /// Use this sparingly.
  114. /// </summary>
  115. protected static void Sync()
  116. {
  117. DeterministicStepCompositionRootPatch.SubmitEntitiesNow();
  118. }
  119. public EGID Id { get; protected set; }
  120. /// <summary>
  121. /// The block's current position or zero if the block no longer exists.
  122. /// A block is 0.2 wide by default in terms of position.
  123. /// </summary>
  124. public float3 Position
  125. {
  126. get => Exists ? MovementEngine.GetPosition(Id.entityID) : float3.zero;
  127. set
  128. {
  129. if (Exists) MovementEngine.MoveBlock(Id.entityID, value);
  130. }
  131. }
  132. /// <summary>
  133. /// The block's current rotation in degrees or zero if the block doesn't exist.
  134. /// </summary>
  135. public float3 Rotation
  136. {
  137. get => Exists ? RotationEngine.GetRotation(Id.entityID) : float3.zero;
  138. set
  139. {
  140. if (Exists) RotationEngine.RotateBlock(Id.entityID, value);
  141. }
  142. }
  143. /// <summary>
  144. /// The block's non-uniform scale or zero if the block's invalid. Independent of the uniform scaling.
  145. /// </summary>
  146. public float3 Scale
  147. {
  148. get => BlockEngine.GetBlockInfo<ScalingEntityStruct>(Id).scale;
  149. set
  150. {
  151. BlockEngine.GetBlockInfo<ScalingEntityStruct>(Id).scale = value;
  152. }
  153. }
  154. /// <summary>
  155. /// The block's uniform scale or zero if the block's invalid. Also sets the non-uniform scale.
  156. /// </summary>
  157. public int UniformScale
  158. {
  159. get => BlockEngine.GetBlockInfo<UniformBlockScaleEntityStruct>(Id).scaleFactor;
  160. set
  161. {
  162. ref var scaleStruct = ref BlockEngine.GetBlockInfo<UniformBlockScaleEntityStruct>(Id);
  163. scaleStruct.scaleFactor = value;
  164. Scale = new float3(value, value, value);
  165. }
  166. }
  167. /// <summary>
  168. /// The block's type (ID). Returns BlockIDs.Invalid if the block doesn't exist anymore.
  169. /// </summary>
  170. public BlockIDs Type
  171. {
  172. get
  173. {
  174. var id = (BlockIDs) BlockEngine.GetBlockInfo<DBEntityStruct>(Id, out var exists).DBID;
  175. return exists ? id : BlockIDs.Invalid;
  176. }
  177. }
  178. /// <summary>
  179. /// The block's color. Returns BlockColors.Default if the block no longer exists.
  180. /// </summary>
  181. public BlockColor Color
  182. {
  183. get
  184. {
  185. byte index = BlockEngine.GetBlockInfo<ColourParameterEntityStruct>(Id, out var exists).indexInPalette;
  186. if (!exists) index = byte.MaxValue;
  187. if (index == byte.MaxValue) return new BlockColor { Color = BlockColors.Default };
  188. return new BlockColor { Color = (BlockColors)(index % 10), Darkness = (byte)(index / 10) };
  189. }
  190. set
  191. {
  192. ref var color = ref BlockEngine.GetBlockInfo<ColourParameterEntityStruct>(Id);
  193. color.indexInPalette = (byte)(value.Color + value.Darkness * 10);
  194. color.overridePaletteColour = false;
  195. color.needsUpdate = true;
  196. BlockEngine.SetBlockColorFromPalette(ref color);
  197. }
  198. }
  199. /// <summary>
  200. /// The block's exact color. Gets reset to the palette color (Color property) after reentering the game.
  201. /// </summary>
  202. public float4 CustomColor
  203. {
  204. get => BlockEngine.GetBlockInfo<ColourParameterEntityStruct>(Id).overriddenColour;
  205. set
  206. {
  207. ref var color = ref BlockEngine.GetBlockInfo<ColourParameterEntityStruct>(Id);
  208. color.overriddenColour = value;
  209. color.overridePaletteColour = true;
  210. color.needsUpdate = true;
  211. }
  212. }
  213. /// <summary>
  214. /// Whether the block exists. The other properties will return a default value if the block doesn't exist.
  215. /// </summary>
  216. public bool Exists => BlockEngine.BlockExists(Id);
  217. /// <summary>
  218. /// Returns an array of blocks that are connected to this one. Returns an empty array if the block doesn't exist.
  219. /// </summary>
  220. public Block[] GetConnectedCubes() => BlockEngine.GetConnectedBlocks(Id);
  221. /// <summary>
  222. /// Removes this block.
  223. /// </summary>
  224. /// <returns>True if the block exists and could be removed.</returns>
  225. public bool Remove() => RemovalEngine.RemoveBlock(Id);
  226. /// <summary>
  227. /// Returns the rigid body of the cluster of blocks this one belongs to during simulation.
  228. /// Can be used to apply forces or move the block around while the simulation is running.
  229. /// </summary>
  230. /// <returns></returns>
  231. public SimBody ToSimBody()
  232. {
  233. uint id = BlockEngine.GetBlockInfo<GridConnectionsEntityStruct>(Id).machineRigidBodyId;
  234. return new SimBody(id);
  235. }
  236. public override string ToString()
  237. {
  238. return $"{nameof(Id)}: {Id}, {nameof(Position)}: {Position}, {nameof(Rotation)}: {Rotation}";
  239. }
  240. public static void Init()
  241. {
  242. GameEngineManager.AddGameEngine(PlacementEngine);
  243. GameEngineManager.AddGameEngine(MovementEngine);
  244. GameEngineManager.AddGameEngine(RotationEngine);
  245. GameEngineManager.AddGameEngine(RemovalEngine);
  246. GameEngineManager.AddGameEngine(BlockEngine);
  247. }
  248. /// <summary>
  249. /// Convert the block to a specialised block class.
  250. /// </summary>
  251. /// <returns>The block.</returns>
  252. /// <typeparam name="T">The specialised block type.</typeparam>
  253. public T Specialise<T>() where T : Block
  254. {
  255. // What have I gotten myself into?
  256. // C# can't cast to a child of Block unless the object was originally that child type
  257. // And C# doesn't let me make implicit cast operators for child types
  258. // So thanks to Microsoft, we've got this horrible implementation using reflection
  259. ConstructorInfo ctor = typeof(T).GetConstructor(types: new System.Type[] { typeof(EGID) });
  260. if (ctor == null)
  261. {
  262. throw new BlockSpecializationException("Specialized block constructor does not accept an EGID");
  263. }
  264. return (T)ctor.Invoke(new object[] { Id });
  265. }
  266. #if DEBUG
  267. public static EntitiesDB entitiesDB
  268. {
  269. get
  270. {
  271. return BlockEngine.GetEntitiesDB();
  272. }
  273. }
  274. #endif
  275. }
  276. }