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.

455 lines
16KB

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