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.

292 lines
9.5KB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using HarmonyLib;
  6. using Gamecraft.ColourPalette;
  7. using Gamecraft.TimeRunning;
  8. using Gamecraft.Wires;
  9. using RobocraftX.Blocks;
  10. using RobocraftX.Common;
  11. using RobocraftX.Physics;
  12. using RobocraftX.Rendering;
  13. using RobocraftX.Rendering.GPUI;
  14. using Svelto.DataStructures;
  15. using Svelto.ECS;
  16. using Svelto.ECS.EntityStructs;
  17. using Svelto.ECS.Experimental;
  18. using Svelto.ECS.Hybrid;
  19. using Techblox.BuildingDrone;
  20. using Techblox.ObjectIDBlockServer;
  21. using Unity.Mathematics;
  22. using TechbloxModdingAPI.Engines;
  23. using TechbloxModdingAPI.Utility;
  24. namespace TechbloxModdingAPI.Blocks.Engines
  25. {
  26. /// <summary>
  27. /// Engine for executing general block actions
  28. /// </summary>
  29. public partial class BlockEngine : IApiEngine
  30. {
  31. public string Name { get; } = "TechbloxModdingAPIBlockGameEngine";
  32. public EntitiesDB entitiesDB { set; private get; }
  33. public bool isRemovable => false;
  34. public void Dispose()
  35. {
  36. }
  37. public void Ready()
  38. {
  39. }
  40. public Block[] GetConnectedBlocks(EGID blockID)
  41. {
  42. if (!BlockExists(blockID)) return Array.Empty<Block>();
  43. Stack<EGID> cubeStack = new Stack<EGID>();
  44. FasterList<EGID> cubes = new FasterList<EGID>(10);
  45. var coll = entitiesDB.QueryEntities<GridConnectionsEntityStruct>();
  46. foreach (var ((ecoll, count), _) in coll)
  47. {
  48. for(int i = 0; i < count; i++)
  49. {
  50. ecoll[i].isProcessed = false;
  51. }
  52. }
  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. CommonExclusiveGroups.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); // 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);
  130. entitiesDB.PublishEntityChangeDelayed<GFXPrefabEntityStructGPUI>(block.Id);
  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.PublishEntityChange<ColourParameterEntityStruct>(id);
  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, tags, count) = entitiesDB.QueryEntities<ObjectIdEntityStruct, BlockTagEntityStruct>(ObjectIDBlockExclusiveGroups.OBJECT_ID_BLOCK_GROUP);
  152. EGIDMapper<GridConnectionsEntityStruct>? connections = null;
  153. for (int i = 0; i < count; i++)
  154. {
  155. if (oids[i].objectId != id) continue;
  156. var tag = tags[i];
  157. if (!connections.HasValue) //Would need reflection to get the group from the build group otherwise
  158. connections = entitiesDB.QueryMappedEntities<GridConnectionsEntityStruct>(tag.ID.groupID);
  159. var rid = connections.Value.Entity(tag.ID.entityID).machineRigidBodyId;
  160. foreach (var rb in ret)
  161. {
  162. if (rb.Id.entityID == rid)
  163. goto DUPLICATE; //Multiple Object Identifiers on one rigid body
  164. }
  165. ret.Add(new SimBody(rid));
  166. DUPLICATE: ;
  167. }
  168. return ret.ToArray();
  169. }
  170. public SimBody[] GetConnectedSimBodies(uint id)
  171. {
  172. var (joints, count) = entitiesDB.QueryEntities<JointEntityStruct>(MachineSimulationGroups.JOINTS_GROUP);
  173. var list = new FasterList<SimBody>(4);
  174. for (int i = 0; i < count; i++)
  175. {
  176. ref var joint = ref joints[i];
  177. if (joint.isBroken) continue;
  178. if (joint.connectedEntityA == id) list.Add(new SimBody(joint.connectedEntityB));
  179. else if (joint.connectedEntityB == id) list.Add(new SimBody(joint.connectedEntityA));
  180. }
  181. return list.ToArray();
  182. }
  183. public SimBody[] GetClusterBodies(uint cid)
  184. {
  185. var groups = entitiesDB.QueryEntities<GridConnectionsEntityStruct>();
  186. var bodies = new HashSet<uint>();
  187. foreach (var ((coll, count), _) in groups)
  188. {
  189. for (var index = 0; index < count; index++)
  190. {
  191. var conn = coll[index];
  192. if (conn.clusterId == cid)
  193. bodies.Add(conn.machineRigidBodyId);
  194. }
  195. }
  196. return bodies.Select(id => new SimBody(id, cid)).ToArray();
  197. }
  198. public EGID? FindBlockEGID(uint id)
  199. {
  200. var groups = entitiesDB.FindGroups<BlockTagEntityStruct>();
  201. foreach (ExclusiveGroupStruct group in groups)
  202. {
  203. if (entitiesDB.Exists<BlockTagEntityStruct>(id, group))
  204. return new EGID(id, group);
  205. }
  206. return null;
  207. }
  208. public Cluster GetCluster(uint sbid)
  209. {
  210. var groups = entitiesDB.QueryEntities<GridConnectionsEntityStruct>();
  211. foreach (var ((coll, count), _) in groups)
  212. {
  213. for (var index = 0; index < count; index++)
  214. {
  215. var conn = coll[index];
  216. //Static blocks don't have a cluster ID but the cluster destruction manager should have one
  217. if (conn.machineRigidBodyId == sbid && conn.clusterId != uint.MaxValue)
  218. return new Cluster(conn.clusterId);
  219. }
  220. }
  221. return null;
  222. }
  223. public Block[] GetBodyBlocks(uint sbid)
  224. {
  225. var groups = entitiesDB.FindGroups<GridConnectionsEntityStruct>();
  226. groups = new QueryGroups(groups).Except(CommonExclusiveGroups.DISABLED_JOINTS_IN_SIM_GROUP).Evaluate().result;
  227. var set = new HashSet<Block>();
  228. foreach (var ((coll, tags, count), _) in entitiesDB.QueryEntities<GridConnectionsEntityStruct, BlockTagEntityStruct>(groups))
  229. {
  230. for (var index = 0; index < count; index++)
  231. {
  232. var conn = coll[index];
  233. if (conn.machineRigidBodyId == sbid)
  234. set.Add(Block.New(tags[index].ID));
  235. }
  236. }
  237. return set.ToArray();
  238. }
  239. public ObjectID[] GetObjectIDsFromID(byte id)
  240. {
  241. if (!entitiesDB.HasAny<ObjectIDTweakableComponent>(ObjectIDBlockExclusiveGroups.OBJECT_ID_BLOCK_GROUP))
  242. return Array.Empty<ObjectID>();
  243. var ret = new FasterList<ObjectID>(4);
  244. var (oids, tags, count) = entitiesDB.QueryEntities<ObjectIDTweakableComponent, BlockTagEntityStruct>(ObjectIDBlockExclusiveGroups.OBJECT_ID_BLOCK_GROUP);
  245. for (var index = 0; index < count; index++)
  246. {
  247. if (oids[index].objectIDToTrigger == id)
  248. ret.Add(new ObjectID(tags[index].ID));
  249. }
  250. return ret.ToArray();
  251. }
  252. }
  253. }