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.

389 lines
13KB

  1. using System;
  2. using Gamecraft.Wires;
  3. using Svelto.DataStructures;
  4. using Svelto.ECS;
  5. using TechbloxModdingAPI.Engines;
  6. using TechbloxModdingAPI.Utility;
  7. namespace TechbloxModdingAPI.Blocks.Engines
  8. {
  9. /// <summary>
  10. /// Engine which executes signal actions
  11. /// </summary>
  12. public class SignalEngine : IApiEngine, IFactoryEngine
  13. {
  14. public const float POSITIVE_HIGH = 1.0f;
  15. public const float NEGATIVE_HIGH = -1.0f;
  16. public const float HIGH = 1.0f;
  17. public const float ZERO = 0.0f;
  18. public string Name { get; } = "TechbloxModdingAPISignalGameEngine";
  19. public EntitiesDB entitiesDB { set; private get; }
  20. public IEntityFactory Factory { get; set; }
  21. public bool isRemovable => false;
  22. public bool IsInGame = false;
  23. public void Dispose()
  24. {
  25. IsInGame = false;
  26. }
  27. public void Ready()
  28. {
  29. IsInGame = true;
  30. }
  31. // implementations for block wiring
  32. public WireEntityStruct CreateNewWire(EGID startBlock, byte startPort, EGID endBlock, byte endPort)
  33. {
  34. EGID wireEGID = new EGID(BuildModeWiresGroups.NewWireEntityId, BuildModeWiresGroups.WiresGroup.Group);
  35. EntityInitializer wireInitializer = Factory.BuildEntity<WireEntityDescriptor>(wireEGID);
  36. wireInitializer.Init(new WireEntityStruct
  37. {
  38. sourceBlockEGID = startBlock,
  39. sourcePortUsage = startPort,
  40. destinationBlockEGID = endBlock,
  41. destinationPortUsage = endPort,
  42. ID = wireEGID
  43. });
  44. return wireInitializer.Get<WireEntityStruct>();
  45. }
  46. public ref WireEntityStruct GetWire(EGID wire)
  47. {
  48. if (!entitiesDB.Exists<WireEntityStruct>(wire))
  49. {
  50. throw new WiringException($"Wire {wire} does not exist");
  51. }
  52. return ref entitiesDB.QueryEntity<WireEntityStruct>(wire);
  53. }
  54. public ref PortEntityStruct GetPort(EGID port)
  55. {
  56. if (!entitiesDB.Exists<PortEntityStruct>(port))
  57. {
  58. throw new WiringException($"Port {port} does not exist (yet?)");
  59. }
  60. return ref entitiesDB.QueryEntity<PortEntityStruct>(port);
  61. }
  62. public ref PortEntityStruct GetPortByOffset(BlockPortsStruct bps, byte portNumber, bool input)
  63. {
  64. ExclusiveGroup group = input
  65. ? NamedExclusiveGroup<BuildModeWiresGroups.InputPortsGroup>.Group
  66. : NamedExclusiveGroup<BuildModeWiresGroups.OutputPortsGroup>.Group;
  67. uint id = (input ? bps.firstInputID : bps.firstOutputID) + portNumber;
  68. EGID egid = new EGID(id, group);
  69. if (!entitiesDB.Exists<PortEntityStruct>(egid))
  70. {
  71. throw new WiringException("Port does not exist");
  72. }
  73. return ref entitiesDB.QueryEntity<PortEntityStruct>(egid);
  74. }
  75. public ref PortEntityStruct GetPortByOffset(Block block, byte portNumber, bool input)
  76. {
  77. var bps = entitiesDB.QueryEntityOptional<BlockPortsStruct>(block);
  78. if (!bps)
  79. {
  80. throw new BlockException("Block does not exist");
  81. }
  82. return ref GetPortByOffset(bps, portNumber, input);
  83. }
  84. public ref T GetComponent<T>(EGID egid) where T : unmanaged, IEntityComponent
  85. {
  86. return ref entitiesDB.QueryEntity<T>(egid);
  87. }
  88. public bool Exists<T>(EGID egid) where T : struct, IEntityComponent
  89. {
  90. return entitiesDB.Exists<T>(egid);
  91. }
  92. public bool SetSignal(EGID blockID, float signal, out uint signalID, bool input = true)
  93. {
  94. signalID = GetSignalIDs(blockID, input)[0];
  95. return SetSignal(signalID, signal);
  96. }
  97. public bool SetSignal(uint signalID, float signal, bool input = true)
  98. {
  99. var array = GetSignalStruct(signalID, out uint index, input);
  100. var arrayB = array.ToBuffer();
  101. if (array.count > 0) arrayB.buffer[index].valueAsFloat = signal;
  102. return false;
  103. }
  104. public float AddSignal(EGID blockID, float signal, out uint signalID, bool clamp = true, bool input = true)
  105. {
  106. signalID = GetSignalIDs(blockID, input)[0];
  107. return AddSignal(signalID, signal, clamp, input);
  108. }
  109. public float AddSignal(uint signalID, float signal, bool clamp = true, bool input = true)
  110. {
  111. var array = GetSignalStruct(signalID, out uint index, input);
  112. var arrayB = array.ToBuffer();
  113. if (array.count > 0)
  114. {
  115. ref var channelData = ref arrayB.buffer[index];
  116. channelData.valueAsFloat += signal;
  117. if (clamp)
  118. {
  119. if (channelData.valueAsFloat > POSITIVE_HIGH)
  120. {
  121. channelData.valueAsFloat = POSITIVE_HIGH;
  122. }
  123. else if (channelData.valueAsFloat < NEGATIVE_HIGH)
  124. {
  125. channelData.valueAsFloat = NEGATIVE_HIGH;
  126. }
  127. return channelData.valueAsFloat;
  128. }
  129. }
  130. return signal;
  131. }
  132. public float GetSignal(EGID blockID, out uint signalID, bool input = true)
  133. {
  134. signalID = GetSignalIDs(blockID, input)[0];
  135. return GetSignal(signalID, input);
  136. }
  137. public float GetSignal(uint signalID, bool input = true)
  138. {
  139. var array = GetSignalStruct(signalID, out uint index, input);
  140. var arrayB = array.ToBuffer();
  141. return array.count > 0 ? arrayB.buffer[index].valueAsFloat : 0f;
  142. }
  143. public uint[] GetSignalIDs(EGID blockID, bool input = true)
  144. {
  145. ref BlockPortsStruct bps = ref entitiesDB.QueryEntity<BlockPortsStruct>(blockID);
  146. uint[] signals;
  147. if (input) {
  148. signals = new uint[bps.inputCount];
  149. for (uint i = 0u; i < bps.inputCount; i++)
  150. {
  151. signals[i] = bps.firstInputID + i;
  152. }
  153. } else {
  154. signals = new uint[bps.outputCount];
  155. for (uint i = 0u; i < bps.outputCount; i++)
  156. {
  157. signals[i] = bps.firstOutputID + i;
  158. }
  159. }
  160. return signals;
  161. }
  162. public EGID[] GetSignalInputs(EGID blockID)
  163. {
  164. BlockPortsStruct ports = entitiesDB.QueryEntity<BlockPortsStruct>(blockID);
  165. EGID[] inputs = new EGID[ports.inputCount];
  166. for (uint i = 0; i < ports.inputCount; i++)
  167. {
  168. inputs[i] = new EGID(i + ports.firstInputID, NamedExclusiveGroup<BuildModeWiresGroups.InputPortsGroup>.Group);
  169. }
  170. return inputs;
  171. }
  172. public EGID[] GetSignalOutputs(EGID blockID)
  173. {
  174. BlockPortsStruct ports = entitiesDB.QueryEntity<BlockPortsStruct>(blockID);
  175. EGID[] outputs = new EGID[ports.outputCount];
  176. for (uint i = 0; i < ports.outputCount; i++)
  177. {
  178. outputs[i] = new EGID(i + ports.firstOutputID, NamedExclusiveGroup<BuildModeWiresGroups.OutputPortsGroup>.Group);
  179. }
  180. return outputs;
  181. }
  182. public OptionalRef<PortEntityStruct> MatchBlockIOToPort(Block block, byte portUsage, bool output)
  183. {
  184. return MatchBlockIOToPort(block.Id, portUsage, output);
  185. }
  186. public OptionalRef<PortEntityStruct> MatchBlockIOToPort(EGID block, byte portUsage, bool output)
  187. {
  188. if (!entitiesDB.Exists<BlockPortsStruct>(block))
  189. return default;
  190. var group = output
  191. ? NamedExclusiveGroup<BuildModeWiresGroups.OutputPortsGroup>.Group
  192. : NamedExclusiveGroup<BuildModeWiresGroups.InputPortsGroup>.Group;
  193. BlockPortsStruct ports = entitiesDB.QueryEntity<BlockPortsStruct>(block);
  194. if (!entitiesDB.TryQueryMappedEntities<PortEntityStruct>(group, out var mapper))
  195. return default;
  196. for (uint i = 0; i < (output ? ports.outputCount : ports.inputCount); ++i)
  197. {
  198. uint entityID = (output ? ports.firstOutputID : ports.firstInputID) + i;
  199. if (!mapper.TryGetArrayAndEntityIndex(entityID, out var index, out var array) ||
  200. array[index].usage != portUsage) continue;
  201. return new OptionalRef<PortEntityStruct>(array, index);
  202. }
  203. return default;
  204. }
  205. public ref WireEntityStruct MatchPortToWire(PortEntityStruct port, EGID blockID, out bool exists)
  206. {
  207. var wires = entitiesDB.QueryEntities<WireEntityStruct>(NamedExclusiveGroup<BuildModeWiresGroups.WiresGroup>.Group);
  208. var wiresB = wires.ToBuffer().buffer;
  209. for (uint i = 0; i < wires.count; i++)
  210. {
  211. if ((wiresB[i].destinationPortUsage == port.usage && wiresB[i].destinationBlockEGID == blockID)
  212. || (wiresB[i].sourcePortUsage == port.usage && wiresB[i].sourceBlockEGID == blockID))
  213. {
  214. exists = true;
  215. return ref wiresB[i];
  216. }
  217. }
  218. exists = false;
  219. WireEntityStruct[] defRef = new WireEntityStruct[1];
  220. return ref defRef[0];
  221. }
  222. public EGID MatchBlocksToWire(EGID startBlock, EGID endBlock, byte startPort = byte.MaxValue, byte endPort = byte.MaxValue)
  223. {
  224. EGID[] startPorts;
  225. if (startPort == byte.MaxValue)
  226. {
  227. // search all output ports on source block
  228. startPorts = GetSignalOutputs(startBlock);
  229. }
  230. else
  231. {
  232. BlockPortsStruct ports = entitiesDB.QueryEntity<BlockPortsStruct>(startBlock);
  233. startPorts = new EGID[] {new EGID(ports.firstOutputID + startPort, NamedExclusiveGroup<BuildModeWiresGroups.OutputPortsGroup>.Group) };
  234. }
  235. EGID[] endPorts;
  236. if (startPort == byte.MaxValue)
  237. {
  238. // search all input ports on destination block
  239. endPorts = GetSignalInputs(endBlock);
  240. }
  241. else
  242. {
  243. BlockPortsStruct ports = entitiesDB.QueryEntity<BlockPortsStruct>(endBlock);
  244. endPorts = new EGID[] {new EGID(ports.firstInputID + endPort, NamedExclusiveGroup<BuildModeWiresGroups.InputPortsGroup>.Group) };
  245. }
  246. EntityCollection<WireEntityStruct> wires = entitiesDB.QueryEntities<WireEntityStruct>(NamedExclusiveGroup<BuildModeWiresGroups.WiresGroup>.Group);
  247. var wiresB = wires.ToBuffer().buffer;
  248. for (int endIndex = 0; endIndex < endPorts.Length; endIndex++)
  249. {
  250. PortEntityStruct endPES = entitiesDB.QueryEntity<PortEntityStruct>(endPorts[endIndex]);
  251. for (int startIndex = 0; startIndex < startPorts.Length; startIndex++)
  252. {
  253. PortEntityStruct startPES = entitiesDB.QueryEntity<PortEntityStruct>(startPorts[startIndex]);
  254. for (int w = 0; w < wires.count; w++)
  255. {
  256. if ((wiresB[w].destinationPortUsage == endPES.usage && wiresB[w].destinationBlockEGID == endBlock)
  257. && (wiresB[w].sourcePortUsage == startPES.usage && wiresB[w].sourceBlockEGID == startBlock))
  258. {
  259. return wiresB[w].ID;
  260. }
  261. }
  262. }
  263. }
  264. return default;
  265. }
  266. public OptionalRef<ChannelDataStruct> GetChannelDataStruct(EGID portID)
  267. {
  268. var port = GetPort(portID);
  269. var channels = entitiesDB.QueryEntities<ChannelDataStruct>(NamedExclusiveGroup<BuildModeWiresGroups.ChannelDataGroup>.Group);
  270. var channelsB = channels.ToBuffer();
  271. return port.firstChannelIndexCachedInSim < channels.count
  272. ? new OptionalRef<ChannelDataStruct>(channelsB.buffer, port.firstChannelIndexCachedInSim)
  273. : default;
  274. }
  275. public EGID[] GetElectricBlocks()
  276. {
  277. var res = new FasterList<EGID>();
  278. foreach (var (coll, _) in entitiesDB.QueryEntities<BlockPortsStruct>())
  279. {
  280. var collB = coll.ToBuffer();
  281. for (int i = 0; i < coll.count; i++)
  282. {
  283. ref BlockPortsStruct s = ref collB.buffer[i];
  284. res.Add(s.ID);
  285. }
  286. }
  287. return res.ToArray();
  288. }
  289. public EGID[] WiredToInput(EGID block, byte port)
  290. {
  291. WireEntityStruct[] wireEntityStructs = Search(NamedExclusiveGroup<BuildModeWiresGroups.WiresGroup>.Group,
  292. (WireEntityStruct wes) => wes.destinationPortUsage == port && wes.destinationBlockEGID == block);
  293. EGID[] result = new EGID[wireEntityStructs.Length];
  294. for (uint i = 0; i < wireEntityStructs.Length; i++)
  295. {
  296. result[i] = wireEntityStructs[i].ID;
  297. }
  298. return result;
  299. }
  300. public EGID[] WiredToOutput(EGID block, byte port)
  301. {
  302. WireEntityStruct[] wireEntityStructs = Search(NamedExclusiveGroup<BuildModeWiresGroups.WiresGroup>.Group,
  303. (WireEntityStruct wes) => wes.sourcePortUsage == port && wes.sourceBlockEGID == block);
  304. EGID[] result = new EGID[wireEntityStructs.Length];
  305. for (uint i = 0; i < wireEntityStructs.Length; i++)
  306. {
  307. result[i] = wireEntityStructs[i].ID;
  308. }
  309. return result;
  310. }
  311. private T[] Search<T>(ExclusiveGroup group, Func<T, bool> isMatch) where T : unmanaged, IEntityComponent
  312. {
  313. FasterList<T> results = new FasterList<T>();
  314. EntityCollection<T> components = entitiesDB.QueryEntities<T>(group);
  315. var componentsB = components.ToBuffer();
  316. for (uint i = 0; i < components.count; i++)
  317. {
  318. if (isMatch(componentsB.buffer[i]))
  319. {
  320. results.Add(componentsB.buffer[i]);
  321. }
  322. }
  323. return results.ToArray();
  324. }
  325. private EntityCollection<ChannelDataStruct> GetSignalStruct(uint signalID, out uint index, bool input = true)
  326. {
  327. ExclusiveGroup group = input
  328. ? NamedExclusiveGroup<BuildModeWiresGroups.InputPortsGroup>.Group
  329. : NamedExclusiveGroup<BuildModeWiresGroups.OutputPortsGroup>.Group;
  330. if (entitiesDB.Exists<PortEntityStruct>(signalID, group))
  331. {
  332. index = entitiesDB.QueryEntity<PortEntityStruct>(signalID, group).anyChannelIndex;
  333. var channelData =
  334. entitiesDB.QueryEntities<ChannelDataStruct>(NamedExclusiveGroup<BuildModeWiresGroups.ChannelDataGroup>.Group);
  335. return channelData;
  336. }
  337. index = 0;
  338. return default; //count: 0
  339. }
  340. }
  341. }