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.

538 lines
20KB

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