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.

572 lines
21KB

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