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.

498 lines
18KB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Reflection.Emit;
  7. using System.Text;
  8. using HarmonyLib;
  9. using IllusionInjector;
  10. // test
  11. using GPUInstancer;
  12. using Svelto.ECS;
  13. using RobocraftX.Blocks;
  14. using RobocraftX.Common;
  15. using RobocraftX.SimulationModeState;
  16. using RobocraftX.FrontEnd;
  17. using Unity.Mathematics;
  18. using UnityEngine;
  19. using GamecraftModdingAPI.Commands;
  20. using GamecraftModdingAPI.Events;
  21. using GamecraftModdingAPI.Utility;
  22. using GamecraftModdingAPI.Blocks;
  23. using GamecraftModdingAPI.Players;
  24. using EventType = GamecraftModdingAPI.Events.EventType;
  25. namespace GamecraftModdingAPI.Tests
  26. {
  27. #if DEBUG
  28. // unused by design
  29. /// <summary>
  30. /// Modding API implemented as a standalone IPA Plugin.
  31. /// Ideally, GamecraftModdingAPI should be loaded by another mod; not itself
  32. /// </summary>
  33. public class GamecraftModdingAPIPluginTest : IllusionPlugin.IEnhancedPlugin
  34. {
  35. private static Harmony harmony { get; set; }
  36. public override string Name { get; } = Assembly.GetExecutingAssembly().GetName().Name;
  37. public override string Version { get; } = Assembly.GetExecutingAssembly().GetName().Version.ToString();
  38. public string HarmonyID { get; } = "org.git.exmods.modtainers.gamecraftmoddingapi";
  39. public override void OnApplicationQuit()
  40. {
  41. GamecraftModdingAPI.Main.Shutdown();
  42. }
  43. public override void OnApplicationStart()
  44. {
  45. FileLog.Reset();
  46. Harmony.DEBUG = true;
  47. GamecraftModdingAPI.Main.Init();
  48. Logging.MetaDebugLog($"Version group id {(uint)ApiExclusiveGroups.versionGroup}");
  49. // in case Steam is not installed/running
  50. // this will crash the game slightly later during startup
  51. //SteamInitPatch.ForcePassSteamCheck = true;
  52. // in case running in a VM
  53. //MinimumSpecsCheckPatch.ForcePassMinimumSpecCheck = true;
  54. // disable some Gamecraft analytics
  55. //AnalyticsDisablerPatch.DisableAnalytics = true;
  56. // disable background music
  57. Logging.MetaDebugLog("Audio Mixers: " + string.Join(",", AudioTools.GetMixers()));
  58. //AudioTools.SetVolume(0.0f, "Music"); // The game now sets this from settings again after this is called :(
  59. //Utility.VersionTracking.Enable();//(very) unstable
  60. // debug/test handlers
  61. #pragma warning disable 0612
  62. HandlerBuilder.Builder()
  63. .Name("appinit API debug")
  64. .Handle(EventType.ApplicationInitialized)
  65. .OnActivation(() => { Logging.Log("App Inited event!"); })
  66. .Build();
  67. HandlerBuilder.Builder("menuact API debug")
  68. .Handle(EventType.Menu)
  69. .OnActivation(() => { Logging.Log("Menu Activated event!"); })
  70. .OnDestruction(() => { Logging.Log("Menu Destroyed event!"); })
  71. .Build();
  72. HandlerBuilder.Builder("menuswitch API debug")
  73. .Handle(EventType.MenuSwitchedTo)
  74. .OnActivation(() => { Logging.Log("Menu Switched To event!"); })
  75. .Build();
  76. HandlerBuilder.Builder("gameact API debug")
  77. .Handle(EventType.Menu)
  78. .OnActivation(() => { Logging.Log("Game Activated event!"); })
  79. .OnDestruction(() => { Logging.Log("Game Destroyed event!"); })
  80. .Build();
  81. HandlerBuilder.Builder("gamerel API debug")
  82. .Handle(EventType.GameReloaded)
  83. .OnActivation(() => { Logging.Log("Game Reloaded event!"); })
  84. .Build();
  85. HandlerBuilder.Builder("gameswitch API debug")
  86. .Handle(EventType.GameSwitchedTo)
  87. .OnActivation(() => { Logging.Log("Game Switched To event!"); })
  88. .Build();
  89. HandlerBuilder.Builder("simulationswitch API debug")
  90. .Handle(EventType.SimulationSwitchedTo)
  91. .OnActivation(() => { Logging.Log("Game Mode Simulation Switched To event!"); })
  92. .Build();
  93. HandlerBuilder.Builder("buildswitch API debug")
  94. .Handle(EventType.BuildSwitchedTo)
  95. .OnActivation(() => { Logging.Log("Game Mode Build Switched To event!"); })
  96. .Build();
  97. HandlerBuilder.Builder("menu activated API error thrower test")
  98. .Handle(EventType.Menu)
  99. .OnActivation(() => { throw new Exception("Event Handler always throws an exception!"); })
  100. .Build();
  101. #pragma warning restore 0612
  102. /*HandlerBuilder.Builder("enter game from menu test")
  103. .Handle(EventType.Menu)
  104. .OnActivation(() =>
  105. {
  106. Tasks.Scheduler.Schedule(new Tasks.Repeatable(enterGame, shouldRetry, 0.2f));
  107. })
  108. .Build();*/
  109. // debug/test commands
  110. if (Dependency.Hell("ExtraCommands"))
  111. {
  112. CommandBuilder.Builder()
  113. .Name("Exit")
  114. .Description("Close Gamecraft immediately, without any prompts")
  115. .Action(() => { UnityEngine.Application.Quit(); })
  116. .Build();
  117. CommandBuilder.Builder()
  118. .Name("SetFOV")
  119. .Description("Set the player camera's field of view")
  120. .Action((float d) => { UnityEngine.Camera.main.fieldOfView = d; })
  121. .Build();
  122. CommandBuilder.Builder()
  123. .Name("MoveLastBlock")
  124. .Description("Move the most-recently-placed block, and any connected blocks by the given offset")
  125. .Action((float x, float y, float z) =>
  126. {
  127. if (GameState.IsBuildMode())
  128. foreach (var block in Block.GetLastPlacedBlock().GetConnectedCubes())
  129. block.Position += new Unity.Mathematics.float3(x, y, z);
  130. else
  131. GamecraftModdingAPI.Utility.Logging.CommandLogError("Blocks can only be moved in Build mode!");
  132. }).Build();
  133. CommandBuilder.Builder()
  134. .Name("PlaceAluminium")
  135. .Description("Place a block of aluminium at the given coordinates")
  136. .Action((float x, float y, float z) =>
  137. {
  138. var block = Block.PlaceNew(BlockIDs.AluminiumCube, new float3(x, y, z));
  139. Logging.CommandLog("Block placed with type: " + block.Type);
  140. })
  141. .Build();
  142. CommandBuilder.Builder()
  143. .Name("PlaceAluminiumLots")
  144. .Description("Place a lot of blocks of aluminium at the given coordinates")
  145. .Action((float x, float y, float z) =>
  146. {
  147. Logging.CommandLog("Starting...");
  148. var sw = Stopwatch.StartNew();
  149. for (int i = 0; i < 100; i++)
  150. for (int j = 0; j < 100; j++)
  151. Block.PlaceNew(BlockIDs.AluminiumCube, new float3(x + i, y, z + j));
  152. //Block.Sync();
  153. sw.Stop();
  154. Logging.CommandLog("Finished in " + sw.ElapsedMilliseconds + "ms");
  155. })
  156. .Build();
  157. Block b = null;
  158. CommandBuilder.Builder("moveBlockInSim", "Run in build mode first while looking at a block, then in sim to move it up")
  159. .Action(() =>
  160. {
  161. if (b == null)
  162. {
  163. b = new Player(PlayerType.Local).GetBlockLookedAt();
  164. Logging.CommandLog("Block saved: " + b);
  165. }
  166. else
  167. Logging.CommandLog("Block moved to: " + (b.GetSimBody().Position += new float3(0, 2, 0)));
  168. }).Build();
  169. CommandBuilder.Builder("Error", "Throw an error to make sure SimpleCustomCommandEngine's wrapper catches it.")
  170. .Action(() => { throw new Exception("Error Command always throws an error"); })
  171. .Build();
  172. CommandBuilder.Builder("ColorBlock",
  173. "Change color of the block looked at if there's any.")
  174. .Action<string>(str =>
  175. {
  176. if (!Enum.TryParse(str, out BlockColors color))
  177. {
  178. Logging.CommandLog("Color " + str + " not found! Interpreting as 4 color values.");
  179. var s = str.Split(' ');
  180. new Player(PlayerType.Local).GetBlockLookedAt().CustomColor = new float4(float.Parse(s[0]),
  181. float.Parse(s[1]), float.Parse(s[2]), float.Parse(s[3]));
  182. return;
  183. }
  184. new Player(PlayerType.Local).GetBlockLookedAt().Color =
  185. new BlockColor { Color = color };
  186. Logging.CommandLog("Colored block to " + color);
  187. }).Build();
  188. CommandBuilder.Builder("GetBlockByID", "Gets a block based on its object identifier and teleports it up.")
  189. .Action<char>(ch =>
  190. {
  191. foreach (var body in SimBody.GetFromObjectID(ch))
  192. {
  193. Logging.CommandLog("SimBody: " + body);
  194. body.Position += new float3(0, 10, 0);
  195. foreach (var bodyConnectedBody in body.GetConnectedBodies())
  196. {
  197. Logging.CommandLog("Moving " + bodyConnectedBody);
  198. bodyConnectedBody.Position += new float3(0, 10, 0);
  199. }
  200. }
  201. }).Build();
  202. CommandBuilder.Builder()
  203. .Name("PlaceConsole")
  204. .Description("Place a bunch of console block with a given text - entering simulation with them crashes the game as the cmd doesn't exist")
  205. .Action((float x, float y, float z) =>
  206. {
  207. Stopwatch sw = new Stopwatch();
  208. sw.Start();
  209. for (int i = 0; i < 100; i++)
  210. {
  211. for (int j = 0; j < 100; j++)
  212. {
  213. var block = Block.PlaceNew<ConsoleBlock>(BlockIDs.ConsoleBlock,
  214. new float3(x + i, y, z + j));
  215. block.Command = "test_command";
  216. }
  217. }
  218. sw.Stop();
  219. Logging.CommandLog($"Blocks placed in {sw.ElapsedMilliseconds} ms");
  220. })
  221. .Build();
  222. CommandBuilder.Builder()
  223. .Name("WireTest")
  224. .Description("Place two blocks and then wire them together")
  225. .Action(() =>
  226. {
  227. LogicGate notBlock = Block.PlaceNew<LogicGate>(BlockIDs.NOTLogicBlock, new float3(1, 2, 0));
  228. LogicGate andBlock = Block.PlaceNew<LogicGate>(BlockIDs.ANDLogicBlock, new float3(2, 2, 0));
  229. // connect NOT Gate output to AND Gate input #2 (ports are zero-indexed, so 1 is 2nd position and 0 is 1st position)
  230. Wire conn = notBlock.Connect(0, andBlock, 1);
  231. Logging.CommandLog(conn.ToString());
  232. })
  233. .Build();
  234. CommandBuilder.Builder("TestChunkHealth", "Sets the chunk looked at to the given health.")
  235. .Action((float val, float max) =>
  236. {
  237. var body = new Player(PlayerType.Local).GetSimBodyLookedAt();
  238. if (body == null) return;
  239. body.CurrentHealth = val;
  240. body.InitialHealth = max;
  241. Logging.CommandLog("Health set to: " + val);
  242. }).Build();
  243. CommandBuilder.Builder("placeBlockGroup", "Places some blocks in a group")
  244. .Action((float x, float y, float z) =>
  245. {
  246. var pos = new float3(x, y, z);
  247. var group = BlockGroup.Create(Block.PlaceNew(BlockIDs.AluminiumCube, pos,
  248. color: BlockColors.Aqua));
  249. Block.PlaceNew(BlockIDs.AluminiumCube, pos += new float3(1, 0, 0), color: BlockColors.Blue)
  250. .BlockGroup = group;
  251. Block.PlaceNew(BlockIDs.AluminiumCube, pos += new float3(1, 0, 0), color: BlockColors.Green)
  252. .BlockGroup = group;
  253. Block.PlaceNew(BlockIDs.AluminiumCube, pos += new float3(1, 0, 0), color: BlockColors.Lime)
  254. .BlockGroup = group;
  255. }).Build();
  256. GameClient.SetDebugInfo("InstalledMods", InstalledMods);
  257. Block.Placed += (sender, args) =>
  258. Logging.MetaDebugLog("Placed block " + args.Type + " with ID " + args.ID);
  259. Block.Removed += (sender, args) =>
  260. Logging.MetaDebugLog("Removed block " + args.Type + " with ID " + args.ID);
  261. /*
  262. CommandManager.AddCommand(new SimpleCustomCommandEngine<float>((float d) => { UnityEngine.Camera.main.fieldOfView = d; },
  263. "SetFOV", "Set the player camera's field of view"));
  264. CommandManager.AddCommand(new SimpleCustomCommandEngine<float, float, float>(
  265. (x, y, z) => {
  266. bool success = GamecraftModdingAPI.Blocks.Movement.MoveConnectedBlocks(
  267. GamecraftModdingAPI.Blocks.BlockIdentifiers.LatestBlockID,
  268. new Unity.Mathematics.float3(x, y, z));
  269. if (!success)
  270. {
  271. GamecraftModdingAPI.Utility.Logging.CommandLogError("Blocks can only be moved in Build mode!");
  272. }
  273. }, "MoveLastBlock", "Move the most-recently-placed block, and any connected blocks by the given offset"));
  274. CommandManager.AddCommand(new SimpleCustomCommandEngine<float, float, float>(
  275. (x, y, z) => { Blocks.Placement.PlaceBlock(Blocks.BlockIDs.AluminiumCube, new Unity.Mathematics.float3(x, y, z)); },
  276. "PlaceAluminium", "Place a block of aluminium at the given coordinates"));
  277. System.Random random = new System.Random(); // for command below
  278. CommandManager.AddCommand(new SimpleCustomCommandEngine(
  279. () => {
  280. if (!GameState.IsSimulationMode())
  281. {
  282. Logging.CommandLogError("You must be in simulation mode for this to work!");
  283. return;
  284. }
  285. Tasks.Repeatable task = new Tasks.Repeatable(() => {
  286. uint count = 0;
  287. EGID[] eBlocks = Blocks.Signals.GetElectricBlocks();
  288. for (uint i = 0u; i < eBlocks.Length; i++)
  289. {
  290. uint[] ids = Blocks.Signals.GetSignalIDs(eBlocks[i]);
  291. for (uint j = 0u; j < ids.Length; j++)
  292. {
  293. Blocks.Signals.SetSignalByID(ids[j], (float)random.NextDouble());
  294. count++;
  295. }
  296. }
  297. Logging.MetaDebugLog($"Did the thing on {count} inputs");
  298. },
  299. () => { return GameState.IsSimulationMode(); });
  300. Tasks.Scheduler.Schedule(task);
  301. }, "RandomizeSignalsInputs", "Do the thing"));
  302. */
  303. }
  304. // dependency test
  305. if (Dependency.Hell("GamecraftScripting", new Version("0.0.1.0")))
  306. {
  307. Logging.LogWarning("You're in GamecraftScripting dependency hell");
  308. }
  309. else
  310. {
  311. Logging.Log("Compatible GamecraftScripting detected");
  312. }
  313. #if TEST
  314. TestRoot.RunTests();
  315. #endif
  316. }
  317. private string modsString;
  318. private string InstalledMods()
  319. {
  320. if (modsString != null) return modsString;
  321. StringBuilder sb = new StringBuilder("Installed mods:");
  322. foreach (var plugin in PluginManager.Plugins)
  323. sb.Append("\n" + plugin.Name + " - " + plugin.Version);
  324. return modsString = sb.ToString();
  325. }
  326. private bool retry = true;
  327. private bool shouldRetry()
  328. {
  329. return retry;
  330. }
  331. private void enterGame()
  332. {
  333. App.Client app = new App.Client();
  334. App.Game[] myGames = app.MyGames;
  335. Logging.MetaDebugLog($"MyGames count {myGames.Length}");
  336. if (myGames.Length != 0)
  337. {
  338. Logging.MetaDebugLog($"MyGames[0] EGID {myGames[0].EGID}");
  339. retry = false;
  340. try
  341. {
  342. //myGames[0].Description = "test msg pls ignore"; // make sure game exists first
  343. Logging.MetaDebugLog($"Entering game {myGames[0].Name}");
  344. myGames[0].EnterGame();
  345. }
  346. catch (Exception e)
  347. {
  348. Logging.MetaDebugLog($"Failed to enter game; exception: {e}");
  349. retry = true;
  350. }
  351. }
  352. else
  353. {
  354. Logging.MetaDebugLog("MyGames not populated yet :(");
  355. }
  356. }
  357. [HarmonyPatch]
  358. public class MinimumSpecsPatch
  359. {
  360. public static bool Prefix()
  361. {
  362. return false;
  363. }
  364. public static MethodInfo TargetMethod()
  365. {
  366. return ((Action) MinimumSpecsCheck.CheckRequirementsMet).Method;
  367. }
  368. }
  369. [HarmonyPatch]
  370. public class BugHuntPatch
  371. {
  372. public static MethodInfo method =
  373. SymbolExtensions.GetMethodInfo<string>(str => Console.WriteLine(str));
  374. public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
  375. {
  376. int i = 0;
  377. foreach (var instruction in instructions)
  378. {
  379. i++;
  380. yield return instruction; //Return the instruction first
  381. //stloc, dup, callvirt
  382. if (instruction.opcode.Name.ToLower().StartsWith("stloc")
  383. || instruction.opcode == OpCodes.Dup
  384. || instruction.opcode == OpCodes.Callvirt)
  385. {
  386. yield return new CodeInstruction(OpCodes.Ldstr,
  387. "Just ran the " + i + ". instruction ending with " + instruction.opcode.Name);
  388. yield return new CodeInstruction(OpCodes.Call, method);
  389. }
  390. }
  391. }
  392. public static MethodInfo TargetMethod()
  393. {
  394. return AccessTools.Method("RobocraftX.CR.MachineEditing.BoxSelect.CopySelectionEngine:GenerateThumbnail");
  395. }
  396. }
  397. [HarmonyPatch]
  398. public class BugHuntPatch2
  399. {
  400. public static void Prefix(int width, float fieldOfView, Vector3 cameraDirection, Vector3 lightDirection)
  401. {
  402. Console.WriteLine("TakeThumbnail invoked with parameters: " + width + ", " + fieldOfView + ", " +
  403. cameraDirection + ", " + lightDirection);
  404. GPUInstancerManager manager = GPUInstancerAPI.GetActiveManagers().Find(m => m is GPUInstancerPrefabManager);
  405. Bounds instancesBounds = manager.ComputeInstancesBounds(2);
  406. Console.WriteLine("Bounds: " + instancesBounds);
  407. Console.WriteLine("Size: " + instancesBounds.size);
  408. Console.WriteLine("Size.x < 0: " + (instancesBounds.size.x < 0));
  409. }
  410. public static void Postfix(Texture2D __result)
  411. {
  412. Console.WriteLine("TakeThumbnail returned: " + (__result == null ? null : __result.name));
  413. }
  414. private delegate Texture2D TakeThumbnailDel(int width, float fieldOfView, Vector3 cameraDirection,
  415. Vector3 lightDirection);
  416. public static MethodInfo TargetMethod()
  417. {
  418. return ((TakeThumbnailDel) ThumbnailUtility.TakeThumbnail).Method;
  419. }
  420. }
  421. [HarmonyPatch]
  422. public class BugHuntPatch3
  423. {
  424. public static void Prefix(int width, int filterLayerMask, GPUInstancerManager manager,
  425. Vector3 cameraPosition, Quaternion cameraRotation, float cameraFov, Vector3 lightDirection,
  426. int cullingLayer)
  427. {
  428. Console.WriteLine("Inner TakeThumbnail invoked with parameters: " + width + ", " + filterLayerMask +
  429. ", " + (manager != null ? manager.name : null) + ", " + cameraPosition + ", " +
  430. cameraRotation + ", " + cameraFov + ", " + lightDirection + ", " + cullingLayer);
  431. }
  432. private delegate Texture2D TakeThumbnailDel(int width, int filterLayerMask, GPUInstancerManager manager,
  433. Vector3 cameraPosition, Quaternion cameraRotation, float cameraFov, Vector3 lightDirection,
  434. int cullingLayer);
  435. public static MethodInfo TargetMethod()
  436. {
  437. return ((TakeThumbnailDel) ThumbnailUtility.TakeThumbnail).Method;
  438. }
  439. }
  440. }
  441. #endif
  442. }