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.

467 lines
17KB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection.Emit;
  5. using Svelto.ECS;
  6. using Svelto.ECS.EntityStructs;
  7. using RobocraftX.Common;
  8. using RobocraftX.Blocks;
  9. using Unity.Mathematics;
  10. using Unity.Entities;
  11. using Gamecraft.Blocks.GUI;
  12. using GamecraftModdingAPI.Blocks;
  13. using GamecraftModdingAPI.Utility;
  14. namespace GamecraftModdingAPI
  15. {
  16. /// <summary>
  17. /// A single (perhaps scaled) block. Properties may return default values if the block is removed and then setting them is ignored.
  18. /// For specific block type operations, use the specialised block classes in the GamecraftModdingAPI.Blocks namespace.
  19. /// </summary>
  20. public class Block : IEquatable<Block>, IEquatable<EGID>
  21. {
  22. protected static readonly PlacementEngine PlacementEngine = new PlacementEngine();
  23. protected static readonly MovementEngine MovementEngine = new MovementEngine();
  24. protected static readonly RotationEngine RotationEngine = new RotationEngine();
  25. protected static readonly RemovalEngine RemovalEngine = new RemovalEngine();
  26. protected static readonly SignalEngine SignalEngine = new SignalEngine();
  27. protected static readonly BlockEventsEngine BlockEventsEngine = new BlockEventsEngine();
  28. protected static readonly ScalingEngine ScalingEngine = new ScalingEngine();
  29. protected internal static readonly BlockEngine BlockEngine = new BlockEngine();
  30. /// <summary>
  31. /// 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.
  32. /// Place blocks next to each other to connect them.
  33. /// The placed block will be a complete block with a placement grid and collision which will be saved along with the game.
  34. /// </summary>
  35. /// <param name="block">The block's type</param>
  36. /// <param name="color">The block's color</param>
  37. /// <param name="darkness">The block color's darkness (0-9) - 0 is default color</param>
  38. /// <param name="position">The block's position - default block size is 0.2</param>
  39. /// <param name="rotation">The block's rotation in degrees</param>
  40. /// <param name="uscale">The block's uniform scale - default scale is 1 (with 0.2 width)</param>
  41. /// <param name="scale">The block's non-uniform scale - 0 means <paramref name="uscale"/> is used</param>
  42. /// <param name="player">The player who placed the block</param>
  43. /// <returns>The placed block or null if failed</returns>
  44. public static Block PlaceNew(BlockIDs block, float3 position,
  45. float3 rotation = default, BlockColors color = BlockColors.Default, byte darkness = 0,
  46. int uscale = 1, float3 scale = default, Player player = null)
  47. {
  48. return PlaceNew<Block>(block, position, rotation, color, darkness, uscale, scale, player);
  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. /// </summary>
  55. /// <param name="block">The block's type</param>
  56. /// <param name="color">The block's color</param>
  57. /// <param name="darkness">The block color's darkness (0-9) - 0 is default color</param>
  58. /// <param name="position">The block's position - default block size is 0.2</param>
  59. /// <param name="rotation">The block's rotation in degrees</param>
  60. /// <param name="uscale">The block's uniform scale - default scale is 1 (with 0.2 width)</param>
  61. /// <param name="scale">The block's non-uniform scale - 0 means <paramref name="uscale"/> is used</param>
  62. /// <param name="player">The player who placed the block</param>
  63. /// <returns>The placed block or null if failed</returns>
  64. public static T PlaceNew<T>(BlockIDs block, float3 position,
  65. float3 rotation = default, BlockColors color = BlockColors.Default, byte darkness = 0,
  66. int uscale = 1, float3 scale = default, Player player = null) where T : Block
  67. {
  68. if (PlacementEngine.IsInGame && GameState.IsBuildMode())
  69. {
  70. var egid = PlacementEngine.PlaceBlock(block, color, darkness,
  71. position, uscale, scale, player, rotation, out var initializer);
  72. var bl = New<T>(egid.entityID, egid.groupID);
  73. bl.InitData.Group = BlockEngine.InitGroup(initializer);
  74. Placed += bl.OnPlacedInit;
  75. return bl;
  76. }
  77. return null;
  78. }
  79. /// <summary>
  80. /// Returns the most recently placed block.
  81. /// </summary>
  82. /// <returns>The block object</returns>
  83. public static Block GetLastPlacedBlock()
  84. {
  85. return New<Block>(BlockIdentifiers.LatestBlockID);
  86. }
  87. /// <summary>
  88. /// An event that fires each time a block is placed.
  89. /// </summary>
  90. public static event EventHandler<BlockPlacedRemovedEventArgs> Placed
  91. {
  92. add => BlockEventsEngine.Placed += value;
  93. remove => BlockEventsEngine.Placed -= value;
  94. }
  95. /// <summary>
  96. /// An event that fires each time a block is removed.
  97. /// </summary>
  98. public static event EventHandler<BlockPlacedRemovedEventArgs> Removed
  99. {
  100. add => BlockEventsEngine.Removed += value;
  101. remove => BlockEventsEngine.Removed -= value;
  102. }
  103. private static Dictionary<Type, Func<EGID, Block>> initializers = new Dictionary<Type, Func<EGID, Block>>();
  104. private static Dictionary<Type, ExclusiveGroupStruct[]> typeToGroup =
  105. new Dictionary<Type, ExclusiveGroupStruct[]>
  106. {
  107. {typeof(ConsoleBlock), new[] {CommonExclusiveGroups.BUILD_CONSOLE_BLOCK_GROUP}},
  108. {typeof(LogicGate), new [] {CommonExclusiveGroups.BUILD_LOGIC_BLOCK_GROUP}},
  109. {typeof(Motor), new[] {CommonExclusiveGroups.BUILD_MOTOR_BLOCK_GROUP}},
  110. {typeof(MusicBlock), new[] {CommonExclusiveGroups.BUILD_MUSIC_BLOCK_GROUP}},
  111. {typeof(ObjectIdentifier), new[]{CommonExclusiveGroups.BUILD_OBJID_BLOCK_GROUP}},
  112. {typeof(Piston), new[] {CommonExclusiveGroups.BUILD_PISTON_BLOCK_GROUP}},
  113. {typeof(Servo), new[] {CommonExclusiveGroups.BUILD_SERVO_BLOCK_GROUP}},
  114. {
  115. typeof(SpawnPoint),
  116. new[]
  117. {
  118. CommonExclusiveGroups.BUILD_SPAWNPOINT_BLOCK_GROUP,
  119. CommonExclusiveGroups.BUILD_BUILDINGSPAWN_BLOCK_GROUP
  120. }
  121. },
  122. {
  123. typeof(SfxBlock),
  124. new[]
  125. {
  126. CommonExclusiveGroups.BUILD_SIMPLESFX_BLOCK_GROUP,
  127. CommonExclusiveGroups.BUILD_LOOPEDSFX_BLOCK_GROUP
  128. }
  129. },
  130. {typeof(TextBlock), new[] {CommonExclusiveGroups.BUILD_TEXT_BLOCK_GROUP}},
  131. {typeof(Timer), new[] {CommonExclusiveGroups.BUILD_TIMER_BLOCK_GROUP}}
  132. };
  133. /// <summary>
  134. /// Constructs a new instance of T with the given ID and group using dynamically created delegates.
  135. /// It's equivalent to new T(EGID) with a minimal overhead thanks to caching the created delegates.
  136. /// </summary>
  137. /// <param name="id">The block ID</param>
  138. /// <param name="group">The block group</param>
  139. /// <typeparam name="T">The block's type or Block itself</typeparam>
  140. /// <returns>An instance of the provided type</returns>
  141. /// <exception cref="BlockTypeException">The block group doesn't match or cannot be found</exception>
  142. /// <exception cref="MissingMethodException">The block class doesn't have the needed constructor</exception>
  143. private static T New<T>(uint id, ExclusiveGroupStruct? group = null) where T : Block
  144. {
  145. var type = typeof(T);
  146. EGID egid;
  147. if (!group.HasValue)
  148. {
  149. if (typeToGroup.TryGetValue(type, out var gr) && gr.Length == 1)
  150. egid = new EGID(id, gr[0]);
  151. else
  152. egid = BlockEngine.FindBlockEGID(id) ?? throw new BlockTypeException("Could not find block group!");
  153. }
  154. else
  155. {
  156. egid = new EGID(id, group.Value);
  157. if (typeToGroup.TryGetValue(type, out var gr)
  158. && gr.All(egs => egs != group.Value)) //If this subclass has a specific group, then use that - so Block should still work
  159. throw new BlockTypeException($"Incompatible block type! Type {type.Name} belongs to group {gr.Select(g => g.ToString()).Aggregate((a, b) => a + ", " + b)} instead of {group.Value}");
  160. }
  161. if (initializers.TryGetValue(type, out var func))
  162. {
  163. var bl = (T) func(egid);
  164. return bl;
  165. }
  166. //https://stackoverflow.com/a/10593806/2703239
  167. var ctor = type.GetConstructor(new[] {typeof(EGID)});
  168. if (ctor == null)
  169. throw new MissingMethodException("There is no constructor with an EGID parameter for this object");
  170. DynamicMethod dynamic = new DynamicMethod(string.Empty,
  171. type,
  172. new[] {typeof(EGID)},
  173. type);
  174. ILGenerator il = dynamic.GetILGenerator();
  175. //il.DeclareLocal(type);
  176. il.Emit(OpCodes.Ldarg_0); //Load EGID and pass to constructor
  177. il.Emit(OpCodes.Newobj, ctor); //Call constructor
  178. //il.Emit(OpCodes.Stloc_0); - doesn't seem like we need these
  179. //il.Emit(OpCodes.Ldloc_0);
  180. il.Emit(OpCodes.Ret);
  181. func = (Func<EGID, T>) dynamic.CreateDelegate(typeof(Func<EGID, T>));
  182. initializers.Add(type, func);
  183. var block = (T) func(egid);
  184. return block;
  185. }
  186. public Block(EGID id)
  187. {
  188. Id = id;
  189. var type = GetType();
  190. if (typeToGroup.TryGetValue(type, out var groups))
  191. {
  192. if (groups.All(gr => gr != id.groupID))
  193. throw new BlockTypeException("The block has the wrong group! The type is " + GetType() +
  194. " while the group is " + id.groupID);
  195. }
  196. else if (type != typeof(Block))
  197. Logging.LogWarning($"Unknown block type! Add {type} to the dictionary.");
  198. }
  199. /// <summary>
  200. /// This overload searches for the correct group the block is in.
  201. /// It will throw an exception if the block doesn't exist.
  202. /// Use the EGID constructor where possible or subclasses of Block as those specify the group.
  203. /// </summary>
  204. public Block(uint id)
  205. {
  206. Id = BlockEngine.FindBlockEGID(id) ?? throw new BlockTypeException("Could not find the appropriate group for the block. The block probably doesn't exist or hasn't been submitted.");
  207. }
  208. public EGID Id { get; }
  209. internal BlockEngine.BlockInitData InitData;
  210. /// <summary>
  211. /// The block's current position or zero if the block no longer exists.
  212. /// A block is 0.2 wide by default in terms of position.
  213. /// </summary>
  214. public float3 Position
  215. {
  216. get => MovementEngine.GetPosition(Id, InitData);
  217. set
  218. {
  219. MovementEngine.MoveBlock(Id, InitData, value);
  220. }
  221. }
  222. /// <summary>
  223. /// The block's current rotation in degrees or zero if the block doesn't exist.
  224. /// </summary>
  225. public float3 Rotation
  226. {
  227. get => RotationEngine.GetRotation(Id, InitData);
  228. set
  229. {
  230. RotationEngine.RotateBlock(Id, InitData, value);
  231. }
  232. }
  233. /// <summary>
  234. /// The block's non-uniform scale or zero if the block's invalid. Independent of the uniform scaling.
  235. /// The default scale of 1 means 0.2 in terms of position.
  236. /// </summary>
  237. public float3 Scale
  238. {
  239. get => BlockEngine.GetBlockInfo(this, (ScalingEntityStruct st) => st.scale);
  240. set
  241. {
  242. BlockEngine.SetBlockInfo(this, (ref ScalingEntityStruct st, float3 val) => st.scale = val, value);
  243. if (!Exists) return; //UpdateCollision needs the block to exist
  244. ScalingEngine.UpdateCollision(Id);
  245. }
  246. }
  247. /// <summary>
  248. /// The block's uniform scale or zero if the block's invalid. Also sets the non-uniform scale.
  249. /// The default scale of 1 means 0.2 in terms of position.
  250. /// </summary>
  251. public int UniformScale
  252. {
  253. get => BlockEngine.GetBlockInfo(this, (UniformBlockScaleEntityStruct st) => st.scaleFactor);
  254. set
  255. {
  256. BlockEngine.SetBlockInfo(this, (ref UniformBlockScaleEntityStruct st, int val) => st.scaleFactor = val,
  257. value);
  258. Scale = new float3(value, value, value);
  259. }
  260. }
  261. /// <summary>
  262. /// The block's type (ID). Returns BlockIDs.Invalid if the block doesn't exist anymore.
  263. /// </summary>
  264. public BlockIDs Type
  265. {
  266. get
  267. {
  268. return BlockEngine.GetBlockInfo(this, (DBEntityStruct st) => (BlockIDs) st.DBID, BlockIDs.Invalid);
  269. }
  270. }
  271. /// <summary>
  272. /// The block's color. Returns BlockColors.Default if the block no longer exists.
  273. /// </summary>
  274. public BlockColor Color
  275. {
  276. get
  277. {
  278. byte index = BlockEngine.GetBlockInfo(this, (ColourParameterEntityStruct st) => st.indexInPalette,
  279. byte.MaxValue);
  280. return new BlockColor(index);
  281. }
  282. set
  283. {
  284. BlockEngine.SetBlockInfo(this, (ref ColourParameterEntityStruct color, BlockColor val) =>
  285. {
  286. color.indexInPalette = (byte) (val.Color + val.Darkness * 10);
  287. color.overridePaletteColour = false;
  288. color.needsUpdate = true;
  289. color.paletteColour = BlockEngine.ConvertBlockColor(color.indexInPalette);
  290. }, value);
  291. }
  292. }
  293. /// <summary>
  294. /// The block's exact color. Gets reset to the palette color (Color property) after reentering the game.
  295. /// </summary>
  296. public float4 CustomColor
  297. {
  298. get => BlockEngine.GetBlockInfo(this, (ColourParameterEntityStruct st) => st.overriddenColour);
  299. set
  300. {
  301. BlockEngine.SetBlockInfo(this, (ref ColourParameterEntityStruct color, float4 val) =>
  302. {
  303. color.overriddenColour = val;
  304. color.overridePaletteColour = true;
  305. color.needsUpdate = true;
  306. }, value);
  307. }
  308. }
  309. /// <summary>
  310. /// The text displayed on the block if applicable, or null.
  311. /// Setting it is temporary to the session, it won't be saved.
  312. /// </summary>
  313. public string Label
  314. {
  315. get => BlockEngine.GetBlockInfoViewStruct(this, (TextLabelEntityViewStruct st) => st.textLabelComponent?.text);
  316. set
  317. {
  318. BlockEngine.SetBlockInfoViewStruct(this, (ref TextLabelEntityViewStruct text, string val) =>
  319. {
  320. if (text.textLabelComponent != null) text.textLabelComponent.text = val;
  321. }, value);
  322. }
  323. }
  324. /// <summary>
  325. /// Whether the block exists. The other properties will return a default value if the block doesn't exist.
  326. /// If the block was just placed, then this will also return false but the properties will work correctly.
  327. /// </summary>
  328. public bool Exists => BlockEngine.BlockExists(Id);
  329. /// <summary>
  330. /// Returns an array of blocks that are connected to this one. Returns an empty array if the block doesn't exist.
  331. /// </summary>
  332. public Block[] GetConnectedCubes() => BlockEngine.GetConnectedBlocks(Id);
  333. /// <summary>
  334. /// Removes this block.
  335. /// </summary>
  336. /// <returns>True if the block exists and could be removed.</returns>
  337. public bool Remove() => RemovalEngine.RemoveBlock(Id);
  338. /// <summary>
  339. /// Returns the rigid body of the chunk of blocks this one belongs to during simulation.
  340. /// Can be used to apply forces or move the block around while the simulation is running.
  341. /// </summary>
  342. /// <returns>The SimBody of the chunk or null if the block doesn't exist or not in simulation mode.</returns>
  343. public SimBody GetSimBody()
  344. {
  345. return BlockEngine.GetBlockInfo(this,
  346. (GridConnectionsEntityStruct st) => st.machineRigidBodyId != uint.MaxValue
  347. ? new SimBody(st.machineRigidBodyId, st.clusterId)
  348. : null);
  349. }
  350. private void OnPlacedInit(object sender, BlockPlacedRemovedEventArgs e)
  351. { //Member method instead of lambda to avoid constantly creating delegates
  352. if (e.ID != Id) return;
  353. Placed -= OnPlacedInit; //And we can reference it
  354. InitData = default; //Remove initializer as it's no longer valid - if the block gets removed it shouldn't be used again
  355. }
  356. public override string ToString()
  357. {
  358. return $"{nameof(Id)}: {Id}, {nameof(Position)}: {Position}, {nameof(Type)}: {Type}, {nameof(Color)}: {Color}, {nameof(Exists)}: {Exists}";
  359. }
  360. public bool Equals(Block other)
  361. {
  362. if (ReferenceEquals(null, other)) return false;
  363. if (ReferenceEquals(this, other)) return true;
  364. return Id.Equals(other.Id);
  365. }
  366. public bool Equals(EGID other)
  367. {
  368. return Id.Equals(other);
  369. }
  370. public override bool Equals(object obj)
  371. {
  372. if (ReferenceEquals(null, obj)) return false;
  373. if (ReferenceEquals(this, obj)) return true;
  374. if (obj.GetType() != this.GetType()) return false;
  375. return Equals((Block) obj);
  376. }
  377. public override int GetHashCode()
  378. {
  379. return Id.GetHashCode();
  380. }
  381. public static void Init()
  382. {
  383. GameEngineManager.AddGameEngine(PlacementEngine);
  384. GameEngineManager.AddGameEngine(MovementEngine);
  385. GameEngineManager.AddGameEngine(RotationEngine);
  386. GameEngineManager.AddGameEngine(RemovalEngine);
  387. GameEngineManager.AddGameEngine(BlockEngine);
  388. GameEngineManager.AddGameEngine(BlockEventsEngine);
  389. GameEngineManager.AddGameEngine(ScalingEngine);
  390. GameEngineManager.AddGameEngine(SignalEngine);
  391. Wire.signalEngine = SignalEngine; // requires same functionality, no need to duplicate the engine
  392. }
  393. /// <summary>
  394. /// Convert the block to a specialised block class.
  395. /// </summary>
  396. /// <returns>The block.</returns>
  397. /// <typeparam name="T">The specialised block type.</typeparam>
  398. public T Specialise<T>() where T : Block
  399. {
  400. // What have I gotten myself into?
  401. // C# can't cast to a child of Block unless the object was originally that child type
  402. // And C# doesn't let me make implicit cast operators for child types
  403. // So thanks to Microsoft, we've got this horrible implementation using reflection
  404. //Lets improve that using delegates
  405. var block = New<T>(Id.entityID, Id.groupID);
  406. if (this.InitData.Group != null)
  407. {
  408. block.InitData = this.InitData;
  409. Placed += block.OnPlacedInit; //Reset InitData of new object
  410. }
  411. return block;
  412. }
  413. #if DEBUG
  414. public static EntitiesDB entitiesDB
  415. {
  416. get
  417. {
  418. return BlockEngine.GetEntitiesDB();
  419. }
  420. }
  421. #endif
  422. }
  423. }