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.

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