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.

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