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 11KB

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