A stable modding interface between Techblox and mods https://mod.exmods.org/
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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