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.

369 lines
13KB

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