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.

460 lines
17KB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection.Emit;
  5. using Svelto.ECS;
  6. using Svelto.ECS.EntityStructs;
  7. using RobocraftX.Common;
  8. using RobocraftX.Blocks;
  9. using Unity.Mathematics;
  10. using Unity.Entities;
  11. using Gamecraft.Blocks.GUI;
  12. using GamecraftModdingAPI.Blocks;
  13. using GamecraftModdingAPI.Utility;
  14. namespace GamecraftModdingAPI
  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 GamecraftModdingAPI.Blocks namespace.
  19. /// </summary>
  20. public class Block : 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 internal static readonly BlockEngine BlockEngine = new BlockEngine();
  30. /// <summary>
  31. /// 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.
  32. /// Place blocks next to each other to connect them.
  33. /// The placed block will be a complete block with a placement grid and collision which will be saved along with the game.
  34. /// <para></para>
  35. /// <para>When placing multiple blocks, do not access properties immediately after creation as this
  36. /// triggers a sync each time which can affect performance and may cause issues with the game.
  37. /// You may either use AsyncUtils.WaitForSubmission() after placing all of the blocks
  38. /// or simply access the block properties which will trigger the synchronization the first time a property is used.</para>
  39. /// </summary>
  40. /// <param name="block">The block's type</param>
  41. /// <param name="color">The block's color</param>
  42. /// <param name="darkness">The block color's darkness (0-9) - 0 is default color</param>
  43. /// <param name="position">The block's position in the grid - default block size is 0.2</param>
  44. /// <param name="rotation">The block's rotation in degrees</param>
  45. /// <param name="uscale">The block's uniform scale - default scale is 1 (with 0.2 width)</param>
  46. /// <param name="scale">The block's non-uniform scale - 0 means <paramref name="uscale"/> is used</param>
  47. /// <param name="player">The player who placed the block</param>
  48. /// <returns>The placed block or null if failed</returns>
  49. public static Block PlaceNew(BlockIDs block, float3 position,
  50. float3 rotation = default, BlockColors color = BlockColors.Default, byte darkness = 0,
  51. int uscale = 1, float3 scale = default, Player player = null)
  52. {
  53. return PlaceNew<Block>(block, position, rotation, color, darkness, uscale, scale, player);
  54. }
  55. /// <summary>
  56. /// 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.
  57. /// Place blocks next to each other to connect them.
  58. /// The placed block will be a complete block with a placement grid and collision which will be saved along with the game.
  59. /// </summary>
  60. /// <param name="block">The block's type</param>
  61. /// <param name="color">The block's color</param>
  62. /// <param name="darkness">The block color's darkness (0-9) - 0 is default color</param>
  63. /// <param name="position">The block's position in the grid - default block size is 0.2</param>
  64. /// <param name="rotation">The block's rotation in degrees</param>
  65. /// <param name="uscale">The block's uniform scale - default scale is 1 (with 0.2 width)</param>
  66. /// <param name="scale">The block's non-uniform scale - 0 means <paramref name="uscale"/> is used</param>
  67. /// <param name="player">The player who placed the block</param>
  68. /// <returns>The placed block or null if failed</returns>
  69. public static T PlaceNew<T>(BlockIDs block, float3 position,
  70. float3 rotation = default, BlockColors color = BlockColors.Default, byte darkness = 0,
  71. int uscale = 1, float3 scale = default, Player player = null) where T : Block
  72. {
  73. if (PlacementEngine.IsInGame && GameState.IsBuildMode())
  74. {
  75. var egid = PlacementEngine.PlaceBlock(block, color, darkness,
  76. position, uscale, scale, player, rotation, out var initializer);
  77. var bl = New<T>(egid.entityID, egid.groupID);
  78. bl.InitData.Group = BlockEngine.InitGroup(initializer);
  79. Placed += bl.OnPlacedInit;
  80. return bl;
  81. }
  82. return null;
  83. }
  84. /// <summary>
  85. /// Returns the most recently placed block.
  86. /// </summary>
  87. /// <returns>The block object</returns>
  88. public static Block GetLastPlacedBlock()
  89. {
  90. return New<Block>(BlockIdentifiers.LatestBlockID);
  91. }
  92. /// <summary>
  93. /// An event that fires each time a block is placed.
  94. /// </summary>
  95. public static event EventHandler<BlockPlacedRemovedEventArgs> Placed
  96. {
  97. add => BlockEventsEngine.Placed += value;
  98. remove => BlockEventsEngine.Placed -= value;
  99. }
  100. /// <summary>
  101. /// An event that fires each time a block is removed.
  102. /// </summary>
  103. public static event EventHandler<BlockPlacedRemovedEventArgs> Removed
  104. {
  105. add => BlockEventsEngine.Removed += value;
  106. remove => BlockEventsEngine.Removed -= value;
  107. }
  108. private static Dictionary<Type, Func<EGID, Block>> initializers = new Dictionary<Type, Func<EGID, Block>>();
  109. private static Dictionary<Type, ExclusiveGroupStruct[]> typeToGroup =
  110. new Dictionary<Type, ExclusiveGroupStruct[]>
  111. {
  112. {typeof(ConsoleBlock), new[] {CommonExclusiveGroups.BUILD_CONSOLE_BLOCK_GROUP}},
  113. {typeof(LogicGate), new [] {CommonExclusiveGroups.BUILD_LOGIC_BLOCK_GROUP}},
  114. {typeof(Motor), new[] {CommonExclusiveGroups.BUILD_MOTOR_BLOCK_GROUP}},
  115. {typeof(MusicBlock), new[] {CommonExclusiveGroups.BUILD_MUSIC_BLOCK_GROUP}},
  116. {typeof(Piston), new[] {CommonExclusiveGroups.BUILD_PISTON_BLOCK_GROUP}},
  117. {typeof(Servo), new[] {CommonExclusiveGroups.BUILD_SERVO_BLOCK_GROUP}},
  118. {
  119. typeof(SpawnPoint),
  120. new[]
  121. {
  122. CommonExclusiveGroups.BUILD_SPAWNPOINT_BLOCK_GROUP,
  123. CommonExclusiveGroups.BUILD_BUILDINGSPAWN_BLOCK_GROUP
  124. }
  125. },
  126. {typeof(TextBlock), new[] {CommonExclusiveGroups.BUILD_TEXT_BLOCK_GROUP}},
  127. {typeof(Timer), new[] {CommonExclusiveGroups.BUILD_TIMER_BLOCK_GROUP}}
  128. };
  129. /// <summary>
  130. /// Constructs a new instance of T with the given ID and group using dynamically created delegates.
  131. /// It's equivalent to new T(EGID) with a minimal overhead thanks to caching the created delegates.
  132. /// </summary>
  133. /// <param name="id">The block ID</param>
  134. /// <param name="group">The block group</param>
  135. /// <typeparam name="T">The block's type or Block itself</typeparam>
  136. /// <returns>An instance of the provided type</returns>
  137. /// <exception cref="BlockTypeException">The block group doesn't match or cannot be found</exception>
  138. /// <exception cref="MissingMethodException">The block class doesn't have the needed constructor</exception>
  139. private static T New<T>(uint id, ExclusiveGroupStruct? group = null) where T : Block
  140. {
  141. var type = typeof(T);
  142. EGID egid;
  143. if (!group.HasValue)
  144. {
  145. if (typeToGroup.TryGetValue(type, out var gr) && gr.Length == 1)
  146. egid = new EGID(id, gr[0]);
  147. else
  148. egid = BlockEngine.FindBlockEGID(id) ?? throw new BlockTypeException("Could not find block group!");
  149. }
  150. else
  151. {
  152. egid = new EGID(id, group.Value);
  153. if (typeToGroup.TryGetValue(type, out var gr)
  154. && gr.All(egs => egs != group.Value)) //If this subclass has a specific group, then use that - so Block should still work
  155. throw new BlockTypeException($"Incompatible block type! Type {type.Name} belongs to group {gr.Select(g => g.ToString()).Aggregate((a, b) => a + ", " + b)} instead of {group.Value}");
  156. }
  157. if (initializers.TryGetValue(type, out var func))
  158. {
  159. var bl = (T) func(egid);
  160. return bl;
  161. }
  162. //https://stackoverflow.com/a/10593806/2703239
  163. var ctor = type.GetConstructor(new[] {typeof(EGID)});
  164. if (ctor == null)
  165. throw new MissingMethodException("There is no constructor with an EGID parameter for this object");
  166. DynamicMethod dynamic = new DynamicMethod(string.Empty,
  167. type,
  168. new[] {typeof(EGID)},
  169. type);
  170. ILGenerator il = dynamic.GetILGenerator();
  171. il.DeclareLocal(type);
  172. il.Emit(OpCodes.Ldarg_0); //Load EGID and pass to constructor
  173. il.Emit(OpCodes.Newobj, ctor); //Call constructor
  174. //il.Emit(OpCodes.Stloc_0); - doesn't seem like we need these
  175. //il.Emit(OpCodes.Ldloc_0);
  176. il.Emit(OpCodes.Ret);
  177. func = (Func<EGID, T>) dynamic.CreateDelegate(typeof(Func<EGID, T>));
  178. initializers.Add(type, func);
  179. var block = (T) func(egid);
  180. return block;
  181. }
  182. public Block(EGID id)
  183. {
  184. Id = id;
  185. var type = GetType();
  186. if (typeToGroup.TryGetValue(type, out var groups))
  187. {
  188. if (groups.All(gr => gr != id.groupID))
  189. throw new BlockTypeException("The block has the wrong group! The type is " + GetType() +
  190. " while the group is " + id.groupID);
  191. }
  192. else if (type != typeof(Block))
  193. Logging.LogWarning($"Unknown block type! Add {type} to the dictionary.");
  194. }
  195. /// <summary>
  196. /// This overload searches for the correct group the block is in.
  197. /// It will throw an exception if the block doesn't exist.
  198. /// Use the EGID constructor where possible or subclasses of Block as those specify the group.
  199. /// </summary>
  200. public Block(uint id)
  201. {
  202. Id = BlockEngine.FindBlockEGID(id) ?? throw new BlockTypeException("Could not find the appropriate group for the block. The block probably doesn't exist or hasn't been submitted.");
  203. }
  204. public EGID Id { get; }
  205. internal BlockEngine.BlockInitData InitData;
  206. /// <summary>
  207. /// The block's current position or zero if the block no longer exists.
  208. /// A block is 0.2 wide by default in terms of position.
  209. /// </summary>
  210. public float3 Position
  211. {
  212. get => MovementEngine.GetPosition(Id, InitData);
  213. set
  214. {
  215. MovementEngine.MoveBlock(Id, InitData, value);
  216. }
  217. }
  218. /// <summary>
  219. /// The block's current rotation in degrees or zero if the block doesn't exist.
  220. /// </summary>
  221. public float3 Rotation
  222. {
  223. get => RotationEngine.GetRotation(Id, InitData);
  224. set
  225. {
  226. RotationEngine.RotateBlock(Id, InitData, value);
  227. }
  228. }
  229. /// <summary>
  230. /// The block's non-uniform scale or zero if the block's invalid. Independent of the uniform scaling.
  231. /// The default scale of 1 means 0.2 in terms of position.
  232. /// </summary>
  233. public float3 Scale
  234. {
  235. get => BlockEngine.GetBlockInfo(this, (ScalingEntityStruct st) => st.scale);
  236. set
  237. {
  238. BlockEngine.SetBlockInfo(this, (ref ScalingEntityStruct st, float3 val) => st.scale = val, value);
  239. if (!Exists) return; //UpdateCollision needs the block to exist
  240. ScalingEngine.UpdateCollision(Id);
  241. }
  242. }
  243. /// <summary>
  244. /// The block's uniform scale or zero if the block's invalid. Also sets the non-uniform scale.
  245. /// The default scale of 1 means 0.2 in terms of position.
  246. /// </summary>
  247. public int UniformScale
  248. {
  249. get => BlockEngine.GetBlockInfo(this, (UniformBlockScaleEntityStruct st) => st.scaleFactor);
  250. set
  251. {
  252. BlockEngine.SetBlockInfo(this, (ref UniformBlockScaleEntityStruct st, int val) => st.scaleFactor = val,
  253. value);
  254. Scale = new float3(value, value, value);
  255. }
  256. }
  257. /// <summary>
  258. /// The block's type (ID). Returns BlockIDs.Invalid if the block doesn't exist anymore.
  259. /// </summary>
  260. public BlockIDs Type
  261. {
  262. get
  263. {
  264. return BlockEngine.GetBlockInfo(this, (DBEntityStruct st) => (BlockIDs) st.DBID, BlockIDs.Invalid);
  265. }
  266. }
  267. /// <summary>
  268. /// The block's color. Returns BlockColors.Default if the block no longer exists.
  269. /// </summary>
  270. public BlockColor Color
  271. {
  272. get
  273. {
  274. byte index = BlockEngine.GetBlockInfo(this, (ColourParameterEntityStruct st) => st.indexInPalette,
  275. byte.MaxValue);
  276. return new BlockColor(index);
  277. }
  278. set
  279. {
  280. BlockEngine.SetBlockInfo(this, (ref ColourParameterEntityStruct color, BlockColor val) =>
  281. {
  282. color.indexInPalette = (byte) (val.Color + val.Darkness * 10);
  283. color.overridePaletteColour = false;
  284. color.needsUpdate = true;
  285. BlockEngine.SetBlockColorFromPalette(ref color);
  286. }, value);
  287. }
  288. }
  289. /// <summary>
  290. /// The block's exact color. Gets reset to the palette color (Color property) after reentering the game.
  291. /// </summary>
  292. public float4 CustomColor
  293. {
  294. get => BlockEngine.GetBlockInfo(this, (ColourParameterEntityStruct st) => st.overriddenColour);
  295. set
  296. {
  297. BlockEngine.SetBlockInfo(this, (ref ColourParameterEntityStruct color, float4 val) =>
  298. {
  299. color.overriddenColour = val;
  300. color.overridePaletteColour = true;
  301. color.needsUpdate = true;
  302. }, value);
  303. }
  304. }
  305. /// <summary>
  306. /// The text displayed on the block if applicable, or null.
  307. /// Setting it is temporary to the session, it won't be saved.
  308. /// </summary>
  309. public string Label
  310. {
  311. get => BlockEngine.GetBlockInfo(this, (TextLabelEntityViewStruct st) => st.textLabelComponent?.text);
  312. set
  313. {
  314. BlockEngine.SetBlockInfo(this, (ref TextLabelEntityViewStruct text, string val) =>
  315. {
  316. if (text.textLabelComponent != null) text.textLabelComponent.text = val;
  317. }, value);
  318. }
  319. }
  320. /// <summary>
  321. /// Whether the block exists. The other properties will return a default value if the block doesn't exist.
  322. /// If the block was just placed, then this will also return false but the properties will work correctly.
  323. /// </summary>
  324. public bool Exists => BlockEngine.BlockExists(Id);
  325. /// <summary>
  326. /// Returns an array of blocks that are connected to this one. Returns an empty array if the block doesn't exist.
  327. /// </summary>
  328. public Block[] GetConnectedCubes() => BlockEngine.GetConnectedBlocks(Id);
  329. /// <summary>
  330. /// Removes this block.
  331. /// </summary>
  332. /// <returns>True if the block exists and could be removed.</returns>
  333. public bool Remove() => RemovalEngine.RemoveBlock(Id);
  334. /// <summary>
  335. /// Returns the rigid body of the chunk of blocks this one belongs to during simulation.
  336. /// Can be used to apply forces or move the block around while the simulation is running.
  337. /// </summary>
  338. /// <returns>The SimBody of the chunk or null if the block doesn't exist.</returns>
  339. public SimBody GetSimBody()
  340. {
  341. return BlockEngine.GetBlockInfo(this,
  342. (GridConnectionsEntityStruct st) => new SimBody(st.machineRigidBodyId));
  343. }
  344. private void OnPlacedInit(object sender, BlockPlacedRemovedEventArgs e)
  345. { //Member method instead of lambda to avoid constantly creating delegates
  346. if (e.ID != Id) return;
  347. Placed -= OnPlacedInit; //And we can reference it
  348. InitData = default; //Remove initializer as it's no longer valid - if the block gets removed it shouldn't be used again
  349. }
  350. public override string ToString()
  351. {
  352. return $"{nameof(Id)}: {Id}, {nameof(Position)}: {Position}, {nameof(Type)}: {Type}, {nameof(Color)}: {Color}, {nameof(Exists)}: {Exists}";
  353. }
  354. public bool Equals(Block other)
  355. {
  356. if (ReferenceEquals(null, other)) return false;
  357. if (ReferenceEquals(this, other)) return true;
  358. return Id.Equals(other.Id);
  359. }
  360. public bool Equals(EGID other)
  361. {
  362. return Id.Equals(other);
  363. }
  364. public override bool Equals(object obj)
  365. {
  366. if (ReferenceEquals(null, obj)) return false;
  367. if (ReferenceEquals(this, obj)) return true;
  368. if (obj.GetType() != this.GetType()) return false;
  369. return Equals((Block) obj);
  370. }
  371. public override int GetHashCode()
  372. {
  373. return Id.GetHashCode();
  374. }
  375. public static void Init()
  376. {
  377. GameEngineManager.AddGameEngine(PlacementEngine);
  378. GameEngineManager.AddGameEngine(MovementEngine);
  379. GameEngineManager.AddGameEngine(RotationEngine);
  380. GameEngineManager.AddGameEngine(RemovalEngine);
  381. GameEngineManager.AddGameEngine(BlockEngine);
  382. GameEngineManager.AddGameEngine(BlockEventsEngine);
  383. GameEngineManager.AddGameEngine(ScalingEngine);
  384. GameEngineManager.AddGameEngine(SignalEngine);
  385. Wire.signalEngine = SignalEngine; // requires same functionality, no need to duplicate the engine
  386. }
  387. /// <summary>
  388. /// Convert the block to a specialised block class.
  389. /// </summary>
  390. /// <returns>The block.</returns>
  391. /// <typeparam name="T">The specialised block type.</typeparam>
  392. public T Specialise<T>() where T : Block
  393. {
  394. // What have I gotten myself into?
  395. // C# can't cast to a child of Block unless the object was originally that child type
  396. // And C# doesn't let me make implicit cast operators for child types
  397. // So thanks to Microsoft, we've got this horrible implementation using reflection
  398. //Lets improve that using delegates
  399. var block = New<T>(Id.entityID, Id.groupID);
  400. block.InitData = this.InitData;
  401. return block;
  402. }
  403. #if DEBUG
  404. public static EntitiesDB entitiesDB
  405. {
  406. get
  407. {
  408. return BlockEngine.GetEntitiesDB();
  409. }
  410. }
  411. #endif
  412. internal static void Setup(World physicsWorld)
  413. {
  414. ScalingEngine.Setup(physicsWorld.EntityManager);
  415. }
  416. }
  417. }