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.

495 lines
18KB

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