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.

468 lines
17KB

  1. using System;
  2. using System.Collections.Generic;
  3. using DataLoader;
  4. using Gamecraft.Blocks.BlockGroups;
  5. using Svelto.ECS;
  6. using Svelto.ECS.EntityStructs;
  7. using RobocraftX.Common;
  8. using RobocraftX.Blocks;
  9. using Unity.Mathematics;
  10. using Gamecraft.Blocks.GUI;
  11. using HarmonyLib;
  12. using RobocraftX.PilotSeat;
  13. using TechbloxModdingAPI.Blocks;
  14. using TechbloxModdingAPI.Blocks.Engines;
  15. using TechbloxModdingAPI.Tests;
  16. using TechbloxModdingAPI.Utility;
  17. namespace TechbloxModdingAPI
  18. {
  19. /// <summary>
  20. /// A single (perhaps scaled) block. Properties may return default values if the block is removed and then setting them is ignored.
  21. /// For specific block type operations, use the specialised block classes in the TechbloxModdingAPI.Blocks namespace.
  22. /// </summary>
  23. public class Block : EcsObjectBase, IEquatable<Block>, IEquatable<EGID>
  24. {
  25. protected static readonly PlacementEngine PlacementEngine = new PlacementEngine();
  26. protected static readonly MovementEngine MovementEngine = new MovementEngine();
  27. protected static readonly RotationEngine RotationEngine = new RotationEngine();
  28. protected static readonly RemovalEngine RemovalEngine = new RemovalEngine();
  29. protected static readonly SignalEngine SignalEngine = new SignalEngine();
  30. protected static readonly BlockEventsEngine BlockEventsEngine = new BlockEventsEngine();
  31. protected static readonly ScalingEngine ScalingEngine = new ScalingEngine();
  32. protected static readonly BlockCloneEngine BlockCloneEngine = new BlockCloneEngine();
  33. protected internal static readonly BlockEngine BlockEngine = new BlockEngine();
  34. /// <summary>
  35. /// 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.
  36. /// Place blocks next to each other to connect them.
  37. /// The placed block will be a complete block with a placement grid and collision which will be saved along with the game.
  38. /// </summary>
  39. /// <param name="block">The block's type</param>
  40. /// <param name="position">The block's position - default block size is 0.2</param>
  41. /// <param name="autoWire">Whether the block should be auto-wired (if functional)</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, bool autoWire = false, Player player = null)
  45. {
  46. if (PlacementEngine.IsInGame && GameState.IsBuildMode())
  47. {
  48. var initializer = PlacementEngine.PlaceBlock(block, position, player, autoWire);
  49. var egid = initializer.EGID;
  50. var bl = New(egid);
  51. bl.InitData = initializer;
  52. Placed += bl.OnPlacedInit;
  53. return bl;
  54. }
  55. return null;
  56. }
  57. /// <summary>
  58. /// Returns the most recently placed block.
  59. /// </summary>
  60. /// <returns>The block object or null if doesn't exist</returns>
  61. public static Block GetLastPlacedBlock()
  62. {
  63. uint lastBlockID = (uint) AccessTools.Field(typeof(CommonExclusiveGroups), "_nextBlockEntityID").GetValue(null) - 1;
  64. EGID? egid = BlockEngine.FindBlockEGID(lastBlockID);
  65. return egid.HasValue ? New(egid.Value) : null;
  66. }
  67. /// <summary>
  68. /// An event that fires each time a block is placed.
  69. /// </summary>
  70. public static event EventHandler<BlockPlacedRemovedEventArgs> Placed
  71. {
  72. add => BlockEventsEngine.Placed += ExceptionUtil.WrapHandler(value);
  73. remove => BlockEventsEngine.Placed -= value;
  74. }
  75. /// <summary>
  76. /// An event that fires each time a block is removed.
  77. /// </summary>
  78. public static event EventHandler<BlockPlacedRemovedEventArgs> Removed
  79. {
  80. add => BlockEventsEngine.Removed += ExceptionUtil.WrapHandler(value);
  81. remove => BlockEventsEngine.Removed -= value;
  82. }
  83. private static readonly Dictionary<ExclusiveBuildGroup, (Func<EGID, Block> Constructor, Type Type)> GroupToConstructor =
  84. new Dictionary<ExclusiveBuildGroup, (Func<EGID, Block>, Type)>
  85. {
  86. {CommonExclusiveGroups.DAMPEDSPRING_BLOCK_GROUP, (id => new DampedSpring(id), typeof(DampedSpring))},
  87. {CommonExclusiveGroups.ENGINE_BLOCK_BUILD_GROUP, (id => new Engine(id), typeof(Engine))},
  88. {CommonExclusiveGroups.LOGIC_BLOCK_GROUP, (id => new LogicGate(id), typeof(LogicGate))},
  89. {CommonExclusiveGroups.PISTON_BLOCK_GROUP, (id => new Piston(id), typeof(Piston))},
  90. {SeatGroups.PASSENGER_BLOCK_BUILD_GROUP, (id => new Seat(id), typeof(Seat))},
  91. {SeatGroups.PILOTSEAT_BLOCK_BUILD_GROUP, (id => new Seat(id), typeof(Seat))},
  92. {CommonExclusiveGroups.SERVO_BLOCK_GROUP, (id => new Servo(id), typeof(Servo))},
  93. {CommonExclusiveGroups.WHEELRIG_BLOCK_BUILD_GROUP, (id => new WheelRig(id), typeof(WheelRig))}
  94. };
  95. internal static Block New(EGID egid, bool signaling = false)
  96. {
  97. return GroupToConstructor.ContainsKey(egid.groupID)
  98. ? GroupToConstructor[egid.groupID].Constructor(egid)
  99. : signaling
  100. ? new SignalingBlock(egid)
  101. : new Block(egid);
  102. }
  103. public Block(EGID id)
  104. {
  105. Id = id;
  106. Type expectedType;
  107. if (GroupToConstructor.ContainsKey(id.groupID) &&
  108. !GetType().IsAssignableFrom(expectedType = GroupToConstructor[id.groupID].Type))
  109. throw new BlockSpecializationException($"Incorrect block type! Expected: {expectedType} Actual: {GetType()}");
  110. }
  111. /// <summary>
  112. /// This overload searches for the correct group the block is in.
  113. /// It will throw an exception if the block doesn't exist.
  114. /// Use the EGID constructor where possible or subclasses of Block as those specify the group.
  115. /// </summary>
  116. public Block(uint id) : this(BlockEngine.FindBlockEGID(id)
  117. ?? throw new BlockTypeException(
  118. "Could not find the appropriate group for the block." +
  119. " The block probably doesn't exist or hasn't been submitted."))
  120. {
  121. }
  122. /// <summary>
  123. /// Places a new block in the world.
  124. /// </summary>
  125. /// <param name="type">The block's type</param>
  126. /// <param name="position">The block's position (a block is 0.2 wide in terms of position)</param>
  127. /// <param name="autoWire">Whether the block should be auto-wired (if functional)</param>
  128. /// <param name="player">The player who placed the block</param>
  129. public Block(BlockIDs type, float3 position, bool autoWire = false, Player player = null)
  130. {
  131. if (!PlacementEngine.IsInGame || !GameState.IsBuildMode())
  132. throw new BlockException("Blocks can only be placed in build mode.");
  133. var initializer = PlacementEngine.PlaceBlock(type, position, player, autoWire);
  134. Id = initializer.EGID;
  135. InitData = initializer;
  136. Placed += OnPlacedInit;
  137. }
  138. public override EGID Id { get; }
  139. private EGID copiedFrom;
  140. /// <summary>
  141. /// The block's current position or zero if the block no longer exists.
  142. /// A block is 0.2 wide by default in terms of position.
  143. /// </summary>
  144. public float3 Position
  145. {
  146. get => MovementEngine.GetPosition(this);
  147. set
  148. {
  149. MovementEngine.MoveBlock(this, value);
  150. if (blockGroup != null)
  151. blockGroup.PosAndRotCalculated = false;
  152. BlockEngine.UpdateDisplayedBlock(Id);
  153. }
  154. }
  155. /// <summary>
  156. /// The block's current rotation in degrees or zero if the block doesn't exist.
  157. /// </summary>
  158. public float3 Rotation
  159. {
  160. get => RotationEngine.GetRotation(this);
  161. set
  162. {
  163. RotationEngine.RotateBlock(this, value);
  164. if (blockGroup != null)
  165. blockGroup.PosAndRotCalculated = false;
  166. BlockEngine.UpdateDisplayedBlock(Id);
  167. }
  168. }
  169. /// <summary>
  170. /// The block's non-uniform scale or zero if the block's invalid. Independent of the uniform scaling.
  171. /// The default scale of 1 means 0.2 in terms of position.
  172. /// </summary>
  173. public float3 Scale
  174. {
  175. get => BlockEngine.GetBlockInfo<ScalingEntityStruct>(this).scale;
  176. set
  177. {
  178. int uscale = UniformScale;
  179. if (value.x < 4e-5) value.x = uscale;
  180. if (value.y < 4e-5) value.y = uscale;
  181. if (value.z < 4e-5) value.z = uscale;
  182. BlockEngine.GetBlockInfo<ScalingEntityStruct>(this).scale = value;
  183. //BlockEngine.GetBlockInfo<GridScaleStruct>(this).gridScale = value - (int3) value + 1;
  184. if (!Exists) return; //UpdateCollision needs the block to exist
  185. ScalingEngine.UpdateCollision(Id);
  186. BlockEngine.UpdateDisplayedBlock(Id);
  187. }
  188. }
  189. /// <summary>
  190. /// The block's uniform scale or zero if the block's invalid. Also sets the non-uniform scale.
  191. /// The default scale of 1 means 0.2 in terms of position.
  192. /// </summary>
  193. public int UniformScale
  194. {
  195. get => BlockEngine.GetBlockInfo<UniformBlockScaleEntityStruct>(this).scaleFactor;
  196. set
  197. {
  198. if (value < 1) value = 1;
  199. BlockEngine.GetBlockInfo<UniformBlockScaleEntityStruct>(this).scaleFactor = value;
  200. Scale = new float3(value, value, value);
  201. }
  202. }
  203. /**
  204. * Whether the block is flipped.
  205. */
  206. public bool Flipped
  207. {
  208. get => BlockEngine.GetBlockInfo<ScalingEntityStruct>(this).scale.x < 0;
  209. set
  210. {
  211. ref var st = ref BlockEngine.GetBlockInfo<ScalingEntityStruct>(this);
  212. st.scale.x = math.abs(st.scale.x) * (value ? -1 : 1);
  213. BlockEngine.UpdatePrefab(this, (byte) Material, value);
  214. }
  215. }
  216. /// <summary>
  217. /// The block's type (ID). Returns BlockIDs.Invalid if the block doesn't exist anymore.
  218. /// </summary>
  219. public BlockIDs Type
  220. {
  221. get
  222. {
  223. var opt = BlockEngine.GetBlockInfoOptional<DBEntityStruct>(this);
  224. return opt ? (BlockIDs) opt.Get().DBID : BlockIDs.Invalid;
  225. }
  226. }
  227. /// <summary>
  228. /// The block's color. Returns BlockColors.Default if the block no longer exists.
  229. /// </summary>
  230. public BlockColor Color
  231. {
  232. get
  233. {
  234. var opt = BlockEngine.GetBlockInfoOptional<ColourParameterEntityStruct>(this);
  235. return new BlockColor(opt ? opt.Get().indexInPalette : byte.MaxValue);
  236. }
  237. set
  238. {
  239. if (value.Color == BlockColors.Default)
  240. value = new BlockColor(FullGameFields._dataDb.TryGetValue((int) Type, out CubeListData cld)
  241. ? cld.DefaultColour
  242. : throw new BlockTypeException("Unknown block type! Could not set default color."));
  243. ref var color = ref BlockEngine.GetBlockInfo<ColourParameterEntityStruct>(this);
  244. color.indexInPalette = value.Index;
  245. color.hasNetworkChange = true;
  246. color.paletteColour = BlockEngine.ConvertBlockColor(color.indexInPalette); //Setting to 255 results in black
  247. }
  248. }
  249. /// <summary>
  250. /// The block's exact color. Gets reset to the palette color (Color property) after reentering the game.
  251. /// </summary>
  252. public float4 CustomColor
  253. {
  254. get => BlockEngine.GetBlockInfo<ColourParameterEntityStruct>(this).paletteColour;
  255. set
  256. {
  257. ref var color = ref BlockEngine.GetBlockInfo<ColourParameterEntityStruct>(this);
  258. color.paletteColour = value;
  259. color.hasNetworkChange = true;
  260. }
  261. }
  262. /**
  263. * The block's material.
  264. */
  265. public BlockMaterial Material
  266. {
  267. get
  268. {
  269. var opt = BlockEngine.GetBlockInfoOptional<CubeMaterialStruct>(this);
  270. return opt ? (BlockMaterial) opt.Get().materialId : BlockMaterial.Default;
  271. }
  272. set
  273. {
  274. byte val = (byte) value;
  275. if (value == BlockMaterial.Default)
  276. val = FullGameFields._dataDb.TryGetValue((int) Type, out CubeListData cld)
  277. ? cld.DefaultMaterialID
  278. : throw new BlockTypeException("Unknown block type! Could not set default material.");
  279. if (!FullGameFields._dataDb.ContainsKey<MaterialPropertiesData>(val))
  280. throw new BlockException($"Block material {value} does not exist!");
  281. BlockEngine.GetBlockInfo<CubeMaterialStruct>(this).materialId = val;
  282. BlockEngine.UpdatePrefab(this, val, Flipped); //The default causes the screen to go black
  283. }
  284. }
  285. /// <summary>
  286. /// The text displayed on the block if applicable, or null.
  287. /// Setting it is temporary to the session, it won't be saved.
  288. /// </summary>
  289. [TestValue(null)]
  290. public string Label
  291. {
  292. get => BlockEngine.GetBlockInfoViewComponent<TextLabelEntityViewStruct>(this).textLabelComponent?.text;
  293. set
  294. {
  295. var comp = BlockEngine.GetBlockInfoViewComponent<TextLabelEntityViewStruct>(this).textLabelComponent;
  296. if (comp != null) comp.text = value;
  297. }
  298. }
  299. private BlockGroup blockGroup;
  300. /// <summary>
  301. /// Returns the block group this block is a part of. Block groups can also be placed using blueprints.
  302. /// Returns null if not part of a group, although all blocks should have their own by default.<br />
  303. /// Setting the group after the block has been initialized will not update everything properly,
  304. /// so you can only set this property on blocks newly placed by your code.<br />
  305. /// To set it for existing blocks, you can use the Copy() method and set the property on the resulting block
  306. /// (and remove this block).
  307. /// </summary>
  308. public BlockGroup BlockGroup
  309. {
  310. get
  311. {
  312. if (blockGroup != null) return blockGroup;
  313. var bgec = BlockEngine.GetBlockInfo<BlockGroupEntityComponent>(this);
  314. return blockGroup = bgec.currentBlockGroup == -1 ? null : new BlockGroup(bgec.currentBlockGroup, this);
  315. }
  316. set
  317. {
  318. if (Exists)
  319. {
  320. Logging.LogWarning("Attempted to set group of existing block. This is not supported."
  321. + " Copy the block and set the group of the resulting block.");
  322. return;
  323. }
  324. blockGroup?.RemoveInternal(this);
  325. if (!InitData.Valid)
  326. return;
  327. BlockEngine.GetBlockInfo<BlockGroupEntityComponent>(this).currentBlockGroup = (int?) value?.Id.entityID ?? -1;
  328. value?.AddInternal(this);
  329. blockGroup = value;
  330. }
  331. }
  332. /// <summary>
  333. /// Whether the block should be static in simulation. If set, it cannot be moved. The effect is temporary, it will not be saved with the block.
  334. /// </summary>
  335. public bool Static
  336. {
  337. get => BlockEngine.GetBlockInfo<OverrideStaticComponent>(this).staticIfUnconnected;
  338. set => BlockEngine.GetBlockInfo<OverrideStaticComponent>(this).staticIfUnconnected = value;
  339. }
  340. /// <summary>
  341. /// Whether the block exists. The other properties will return a default value if the block doesn't exist.
  342. /// If the block was just placed, then this will also return false but the properties will work correctly.
  343. /// </summary>
  344. public bool Exists => BlockEngine.BlockExists(Id);
  345. /// <summary>
  346. /// Returns an array of blocks that are connected to this one. Returns an empty array if the block doesn't exist.
  347. /// </summary>
  348. public Block[] GetConnectedCubes() => BlockEngine.GetConnectedBlocks(Id);
  349. /// <summary>
  350. /// Removes this block.
  351. /// </summary>
  352. /// <returns>True if the block exists and could be removed.</returns>
  353. public bool Remove() => RemovalEngine.RemoveBlock(Id);
  354. /// <summary>
  355. /// Returns the rigid body of the chunk of blocks this one belongs to during simulation.
  356. /// Can be used to apply forces or move the block around while the simulation is running.
  357. /// </summary>
  358. /// <returns>The SimBody of the chunk or null if the block doesn't exist or not in simulation mode.</returns>
  359. public SimBody GetSimBody()
  360. {
  361. var st = BlockEngine.GetBlockInfo<GridConnectionsEntityStruct>(this);
  362. return st.machineRigidBodyId != uint.MaxValue
  363. ? new SimBody(st.machineRigidBodyId, st.clusterId)
  364. : null;
  365. }
  366. /// <summary>
  367. /// Creates a copy of the block in the game with the same properties, stats and wires.
  368. /// </summary>
  369. /// <returns></returns>
  370. public Block Copy()
  371. {
  372. var block = PlaceNew(Type, Position);
  373. block.Rotation = Rotation;
  374. block.Color = Color;
  375. block.Material = Material;
  376. block.UniformScale = UniformScale;
  377. block.Scale = Scale;
  378. block.copiedFrom = Id;
  379. return block;
  380. }
  381. private void OnPlacedInit(object sender, BlockPlacedRemovedEventArgs e)
  382. { //Member method instead of lambda to avoid constantly creating delegates
  383. if (e.ID != Id) return;
  384. Placed -= OnPlacedInit; //And we can reference it
  385. InitData = default; //Remove initializer as it's no longer valid - if the block gets removed it shouldn't be used again
  386. if (copiedFrom != EGID.Empty)
  387. BlockCloneEngine.CopyBlockStats(copiedFrom, Id);
  388. }
  389. public override string ToString()
  390. {
  391. return $"{nameof(Id)}: {Id}, {nameof(Position)}: {Position}, {nameof(Type)}: {Type}, {nameof(Color)}: {Color}, {nameof(Exists)}: {Exists}";
  392. }
  393. public bool Equals(Block other)
  394. {
  395. if (ReferenceEquals(null, other)) return false;
  396. if (ReferenceEquals(this, other)) return true;
  397. return Id.Equals(other.Id);
  398. }
  399. public bool Equals(EGID other)
  400. {
  401. return Id.Equals(other);
  402. }
  403. public override bool Equals(object obj)
  404. {
  405. if (ReferenceEquals(null, obj)) return false;
  406. if (ReferenceEquals(this, obj)) return true;
  407. if (obj.GetType() != this.GetType()) return false;
  408. return Equals((Block) obj);
  409. }
  410. public override int GetHashCode()
  411. {
  412. return Id.GetHashCode();
  413. }
  414. public static void Init()
  415. {
  416. GameEngineManager.AddGameEngine(PlacementEngine);
  417. GameEngineManager.AddGameEngine(MovementEngine);
  418. GameEngineManager.AddGameEngine(RotationEngine);
  419. GameEngineManager.AddGameEngine(RemovalEngine);
  420. GameEngineManager.AddGameEngine(BlockEngine);
  421. GameEngineManager.AddGameEngine(BlockEventsEngine);
  422. GameEngineManager.AddGameEngine(ScalingEngine);
  423. GameEngineManager.AddGameEngine(SignalEngine);
  424. GameEngineManager.AddGameEngine(BlockCloneEngine);
  425. Wire.signalEngine = SignalEngine; // requires same functionality, no need to duplicate the engine
  426. }
  427. }
  428. }