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

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