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.

397 lines
14KB

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