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.

Block.cs 12KB

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