A stable modding interface between Techblox and mods https://mod.exmods.org/
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

434 lines
15KB

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