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.

291 lines
9.5KB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using HarmonyLib;
  5. using Gamecraft.ColourPalette;
  6. using Gamecraft.Wires;
  7. using RobocraftX.Blocks;
  8. using RobocraftX.Common;
  9. using RobocraftX.Physics;
  10. using RobocraftX.Rendering;
  11. using RobocraftX.Rendering.GPUI;
  12. using Svelto.DataStructures;
  13. using Svelto.ECS;
  14. using Svelto.ECS.EntityStructs;
  15. using Svelto.ECS.Experimental;
  16. using Svelto.ECS.Hybrid;
  17. using Techblox.BuildingDrone;
  18. using Techblox.ObjectIDBlockServer;
  19. using Unity.Mathematics;
  20. using TechbloxModdingAPI.Engines;
  21. using TechbloxModdingAPI.Utility;
  22. using PrefabsID = RobocraftX.Common.PrefabsID;
  23. namespace TechbloxModdingAPI.Blocks.Engines
  24. {
  25. /// <summary>
  26. /// Engine for executing general block actions
  27. /// </summary>
  28. public partial class BlockEngine : IApiEngine
  29. {
  30. public string Name { get; } = "TechbloxModdingAPIBlockGameEngine";
  31. public EntitiesDB entitiesDB { set; private get; }
  32. public bool isRemovable => false;
  33. public void Dispose()
  34. {
  35. }
  36. public void Ready()
  37. {
  38. }
  39. public Block[] GetConnectedBlocks(EGID blockID)
  40. {
  41. if (!BlockExists(blockID)) return Array.Empty<Block>();
  42. Stack<EGID> cubeStack = new Stack<EGID>();
  43. FasterList<EGID> cubes = new FasterList<EGID>(10);
  44. var coll = entitiesDB.QueryEntities<GridConnectionsEntityStruct>();
  45. foreach (var ((ecoll, count), _) in coll)
  46. {
  47. for(int i = 0; i < count; i++)
  48. {
  49. ecoll[i].areConnectionsAssigned = false;
  50. }
  51. }
  52. //TODO: GetConnectedCubesUtility
  53. /*ConnectedCubesUtility.TreeTraversal.GetConnectedCubes(entitiesDB, blockID, cubeStack, cubes,
  54. (in GridConnectionsEntityStruct _) => false);*/
  55. var ret = new Block[cubes.count];
  56. for (int i = 0; i < cubes.count; i++)
  57. ret[i] = Block.New(cubes[i]);
  58. return ret;
  59. }
  60. public float4 ConvertBlockColor(byte index) => index == byte.MaxValue
  61. ? new float4(-1f, -1f, -1f, -1f)
  62. : entitiesDB.QueryEntity<PaletteEntryEntityStruct>(index,
  63. ColourPaletteExclusiveGroups.COLOUR_PALETTE_GROUP).Colour;
  64. public OptionalRef<T> GetBlockInfoOptional<T>(Block block) where T : unmanaged, IEntityComponent
  65. {
  66. return entitiesDB.QueryEntityOptional<T>(block);
  67. }
  68. public ref T GetBlockInfo<T>(Block block) where T : unmanaged, IEntityComponent
  69. {
  70. #if DEBUG
  71. if (!typeof(BlockTagEntityStruct).IsAssignableFrom(typeof(T)) && block.Exists && block.InitData.Valid)
  72. throw new ArgumentException("The block exists but the init data has not been removed!");
  73. #endif
  74. return ref entitiesDB.QueryEntityOrDefault<T>(block);
  75. }
  76. internal ref T GetBlockInfo<T>(EcsObjectBase obj) where T : unmanaged, IEntityComponent
  77. {
  78. return ref entitiesDB.QueryEntityOrDefault<T>(obj);
  79. }
  80. public ref T GetBlockInfoViewComponent<T>(Block block) where T : struct, IEntityViewComponent
  81. {
  82. return ref entitiesDB.QueryEntityOrDefault<T>(block);
  83. }
  84. internal object GetBlockInfo(Block block, Type type, string name)
  85. {
  86. var opt = AccessTools.Method(typeof(NativeApiExtensions), "QueryEntityOptional",
  87. new[] { typeof(EntitiesDB), typeof(EcsObjectBase), typeof(ExclusiveGroupStruct) }, new[] { type })
  88. .Invoke(null, new object[] { entitiesDB, block, null });
  89. var str = AccessTools.Property(opt.GetType(), "Value").GetValue(opt);
  90. return AccessTools.Field(str.GetType(), name).GetValue(str);
  91. }
  92. internal void SetBlockInfo(Block block, Type type, string name, object value)
  93. {
  94. var opt = AccessTools.Method(typeof(BlockEngine), "GetBlockInfoOptional", generics: new[] { type })
  95. .Invoke(this, new object[] { block });
  96. var prop = AccessTools.Property(opt.GetType(), "Value");
  97. var str = prop.GetValue(opt);
  98. AccessTools.Field(str.GetType(), name).SetValue(str, value);
  99. prop.SetValue(opt, str);
  100. }
  101. public void UpdateDisplayedBlock(EGID id)
  102. {
  103. if (!BlockExists(id)) return;
  104. var pos = entitiesDB.QueryEntity<PositionEntityStruct>(id);
  105. var rot = entitiesDB.QueryEntity<RotationEntityStruct>(id);
  106. var scale = entitiesDB.QueryEntity<ScalingEntityStruct>(id);
  107. var skew = entitiesDB.QueryEntity<SkewComponent>(id);
  108. entitiesDB.QueryEntity<RenderingDataStruct>(id).matrix =
  109. math.mul(float4x4.TRS(pos.position, rot.rotation, scale.scale), skew.skewMatrix);
  110. entitiesDB.PublishEntityChangeDelayed<GFXPrefabEntityStructGPUI>(id, 30); // Signal a prefab change so it updates the render buffers
  111. }
  112. internal void UpdatePrefab(Block block, byte material, bool flipped)
  113. {
  114. var prefabAssetIDOpt = entitiesDB.QueryEntityOptional<PrefabAssetIDComponent>(block);
  115. uint prefabAssetID = prefabAssetIDOpt
  116. ? prefabAssetIDOpt.Get().prefabAssetID
  117. : uint.MaxValue;
  118. if (prefabAssetID == uint.MaxValue)
  119. {
  120. if (entitiesDB.QueryEntityOptional<BlockTagEntityStruct>(block)) //The block exists
  121. throw new BlockException("Prefab asset ID not found for block " + block); //Set by the game
  122. return;
  123. }
  124. uint prefabId =
  125. PrefabsID.GetOrAddPrefabID((ushort) prefabAssetID, material, 1, flipped);
  126. entitiesDB.QueryEntityOrDefault<GFXPrefabEntityStructGPUI>(block).prefabID = prefabId;
  127. if (block.Exists)
  128. {
  129. entitiesDB.PublishEntityChangeDelayed<CubeMaterialStruct>(block.Id, 30);
  130. entitiesDB.PublishEntityChangeDelayed<GFXPrefabEntityStructGPUI>(block.Id, 30);
  131. ref BuildingActionComponent local =
  132. ref entitiesDB.QueryEntity<BuildingActionComponent>(BuildingDroneUtility
  133. .GetLocalBuildingDrone(entitiesDB).ToEGID(entitiesDB));
  134. local.buildAction = BuildAction.ChangeMaterial;
  135. local.targetPosition = block.Position;
  136. this.entitiesDB.PublishEntityChangeDelayed<BuildingActionComponent>(local.ID);
  137. }
  138. //Phyiscs prefab: prefabAssetID, set on block creation from the CubeListData
  139. }
  140. public void UpdateBlockColor(EGID id)
  141. {
  142. entitiesDB.PublishEntityChangeDelayed<ColourParameterEntityStruct>(id, 30);
  143. }
  144. public bool BlockExists(EGID blockID)
  145. {
  146. return entitiesDB.Exists<BlockTagEntityStruct>(blockID);
  147. }
  148. public SimBody[] GetSimBodiesFromID(byte id)
  149. {
  150. var ret = new FasterList<SimBody>(4);
  151. var oids = entitiesDB.QueryEntitiesOptional<ObjectIdEntityStruct>(ObjectIDBlockExclusiveGroups.OBJECT_ID_BLOCK_GROUP);
  152. EGIDMapper<GridConnectionsEntityStruct>? connections = null;
  153. foreach (var oid in oids)
  154. {
  155. if (oid.Get().objectId != id) continue;
  156. if (!connections.HasValue) //Would need reflection to get the group from the build group otherwise
  157. connections = entitiesDB.QueryMappedEntities<GridConnectionsEntityStruct>(oid.EGID.groupID);
  158. //var rid = connections.Value.Entity(tag.ID.entityID).machineRigidBodyId;
  159. /*foreach (var rb in ret) - TODO
  160. {
  161. if (rb.Id.entityID == rid)
  162. goto DUPLICATE; //Multiple Object Identifiers on one rigid body
  163. }
  164. ret.Add(new SimBody(rid));
  165. DUPLICATE: ;*/
  166. }
  167. return ret.ToArray();
  168. }
  169. public SimBody[] GetConnectedSimBodies(uint id)
  170. {
  171. var (joints, count) = entitiesDB.QueryEntities<JointEntityStruct>(MachineSimulationGroups.JOINTS_GROUP);
  172. var list = new FasterList<SimBody>(4);
  173. for (int i = 0; i < count; i++)
  174. {
  175. ref var joint = ref joints[i];
  176. if (joint.isBroken) continue;
  177. /*if (joint.connectedEntityA == id) list.Add(new SimBody(joint.connectedEntityB)); - TODO:
  178. else if (joint.connectedEntityB == id) list.Add(new SimBody(joint.connectedEntityA));*/
  179. }
  180. return list.ToArray();
  181. }
  182. public SimBody[] GetClusterBodies(uint cid)
  183. {
  184. var groups = entitiesDB.QueryEntities<GridConnectionsEntityStruct>();
  185. var bodies = new HashSet<uint>();
  186. foreach (var ((coll, count), _) in groups)
  187. {
  188. for (var index = 0; index < count; index++)
  189. {
  190. var conn = coll[index];
  191. /*if (conn.clusterId == cid) - TODO
  192. bodies.Add(conn.machineRigidBodyId);*/
  193. }
  194. }
  195. return bodies.Select(id => new SimBody(id, cid)).ToArray();
  196. }
  197. public EGID? FindBlockEGID(uint id)
  198. {
  199. var groups = entitiesDB.FindGroups<BlockTagEntityStruct>();
  200. foreach (ExclusiveGroupStruct group in groups)
  201. {
  202. if (entitiesDB.Exists<BlockTagEntityStruct>(id, group))
  203. return new EGID(id, group);
  204. }
  205. return null;
  206. }
  207. public Cluster GetCluster(uint sbid)
  208. {
  209. var groups = entitiesDB.QueryEntities<GridConnectionsEntityStruct>();
  210. foreach (var ((coll, count), _) in groups)
  211. {
  212. for (var index = 0; index < count; index++)
  213. {
  214. var conn = coll[index];
  215. //Static blocks don't have a cluster ID but the cluster destruction manager should have one
  216. /*if (conn.machineRigidBodyId == sbid && conn.clusterId != uint.MaxValue) - TODO:
  217. return new Cluster(conn.clusterId);*/
  218. }
  219. }
  220. return null;
  221. }
  222. public Block[] GetBodyBlocks(uint sbid)
  223. {
  224. var groups = entitiesDB.FindGroups<GridConnectionsEntityStruct>();
  225. groups = new QueryGroups(groups).Except(CommonExclusiveGroups.DISABLED_JOINTS_IN_SIM_GROUP).Evaluate().result;
  226. var set = new HashSet<Block>();
  227. foreach (var ((coll, tags, count), _) in entitiesDB.QueryEntities<GridConnectionsEntityStruct, BlockTagEntityStruct>(groups))
  228. {
  229. for (var index = 0; index < count; index++)
  230. {
  231. var conn = coll[index];
  232. /*if (conn.machineRigidBodyId == sbid) - TODO
  233. set.Add(Block.New(tags[index].ID));*/
  234. }
  235. }
  236. return set.ToArray();
  237. }
  238. public ObjectID[] GetObjectIDsFromID(byte id)
  239. {
  240. if (!entitiesDB.HasAny<ObjectIDTweakableComponent>(ObjectIDBlockExclusiveGroups.OBJECT_ID_BLOCK_GROUP))
  241. return Array.Empty<ObjectID>();
  242. var ret = new FasterList<ObjectID>(4);
  243. var oids = entitiesDB.QueryEntitiesOptional<ObjectIDTweakableComponent>(ObjectIDBlockExclusiveGroups.OBJECT_ID_BLOCK_GROUP);
  244. foreach (var oid in oids)
  245. {
  246. if (oid.Get().objectIDToTrigger == id)
  247. ret.Add(new ObjectID(oid.EGID));
  248. }
  249. return ret.ToArray();
  250. }
  251. }
  252. }