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.

339 lines
12KB

  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
  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; protected set; }
  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. if (index == byte.MaxValue) return new BlockColor { Color = BlockColors.Default };
  202. return new BlockColor { Color = (BlockColors)(index % 10), Darkness = (byte)(index / 10) };
  203. }
  204. set
  205. {
  206. ref var color = ref BlockEngine.GetBlockInfo<ColourParameterEntityStruct>(Id);
  207. color.indexInPalette = (byte)(value.Color + value.Darkness * 10);
  208. color.overridePaletteColour = false;
  209. color.needsUpdate = true;
  210. BlockEngine.SetBlockColorFromPalette(ref color);
  211. }
  212. }
  213. /// <summary>
  214. /// The block's exact color. Gets reset to the palette color (Color property) after reentering the game.
  215. /// </summary>
  216. public float4 CustomColor
  217. {
  218. get => BlockEngine.GetBlockInfo<ColourParameterEntityStruct>(Id).overriddenColour;
  219. set
  220. {
  221. ref var color = ref BlockEngine.GetBlockInfo<ColourParameterEntityStruct>(Id);
  222. color.overriddenColour = value;
  223. color.overridePaletteColour = true;
  224. color.needsUpdate = true;
  225. }
  226. }
  227. /// <summary>
  228. /// The short text displayed on the block if applicable, or null.
  229. /// Setting it is temporary to the session, it won't be saved.
  230. /// </summary>
  231. public string Label
  232. {
  233. get => BlockEngine.GetBlockInfo<TextLabelEntityViewStruct>(Id).textLabelComponent?.text;
  234. set
  235. {
  236. ref var text = ref BlockEngine.GetBlockInfo<TextLabelEntityViewStruct>(Id);
  237. if (text.textLabelComponent != null) text.textLabelComponent.text = value;
  238. }
  239. }
  240. /// <summary>
  241. /// Whether the block exists. The other properties will return a default value if the block doesn't exist.
  242. /// </summary>
  243. public bool Exists => BlockEngine.BlockExists(Id);
  244. /// <summary>
  245. /// Returns an array of blocks that are connected to this one. Returns an empty array if the block doesn't exist.
  246. /// </summary>
  247. public Block[] GetConnectedCubes() => BlockEngine.GetConnectedBlocks(Id);
  248. /// <summary>
  249. /// Removes this block.
  250. /// </summary>
  251. /// <returns>True if the block exists and could be removed.</returns>
  252. public bool Remove() => RemovalEngine.RemoveBlock(Id);
  253. /// <summary>
  254. /// Returns the rigid body of the cluster of blocks this one belongs to during simulation.
  255. /// Can be used to apply forces or move the block around while the simulation is running.
  256. /// </summary>
  257. /// <returns>The SimBody of the cluster or null if the block doesn't exist.</returns>
  258. public SimBody GetSimBody()
  259. {
  260. uint id = BlockEngine.GetBlockInfo<GridConnectionsEntityStruct>(Id, out var exists).machineRigidBodyId;
  261. return exists ? new SimBody(id) : null;
  262. }
  263. public override string ToString()
  264. {
  265. return $"{nameof(Id)}: {Id}, {nameof(Position)}: {Position}, {nameof(Type)}: {Type}, {nameof(Color)}: {Color}, {nameof(Exists)}: {Exists}";
  266. }
  267. public static void Init()
  268. {
  269. GameEngineManager.AddGameEngine(PlacementEngine);
  270. GameEngineManager.AddGameEngine(MovementEngine);
  271. GameEngineManager.AddGameEngine(RotationEngine);
  272. GameEngineManager.AddGameEngine(RemovalEngine);
  273. GameEngineManager.AddGameEngine(BlockEngine);
  274. GameEngineManager.AddGameEngine(BlockEventsEngine);
  275. GameEngineManager.AddGameEngine(ScalingEngine);
  276. }
  277. /// <summary>
  278. /// Convert the block to a specialised block class.
  279. /// </summary>
  280. /// <returns>The block.</returns>
  281. /// <typeparam name="T">The specialised block type.</typeparam>
  282. public T Specialise<T>() where T : Block
  283. {
  284. // What have I gotten myself into?
  285. // C# can't cast to a child of Block unless the object was originally that child type
  286. // And C# doesn't let me make implicit cast operators for child types
  287. // So thanks to Microsoft, we've got this horrible implementation using reflection
  288. ConstructorInfo ctor = typeof(T).GetConstructor(types: new System.Type[] { typeof(EGID) });
  289. if (ctor == null)
  290. {
  291. throw new BlockSpecializationException("Specialized block constructor does not accept an EGID");
  292. }
  293. return (T)ctor.Invoke(new object[] { Id });
  294. }
  295. #if DEBUG
  296. public static EntitiesDB entitiesDB
  297. {
  298. get
  299. {
  300. return BlockEngine.GetEntitiesDB();
  301. }
  302. }
  303. #endif
  304. internal static void Setup(World physicsWorld)
  305. {
  306. ScalingEngine.Setup(physicsWorld.EntityManager);
  307. }
  308. }
  309. }