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.

415 line
15KB

  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. #pragma warning disable 0612
  60. HandlerBuilder.Builder()
  61. .Name("appinit API debug")
  62. .Handle(EventType.ApplicationInitialized)
  63. .OnActivation(() => { Logging.Log("App Inited event!"); })
  64. .Build();
  65. HandlerBuilder.Builder("menuact API debug")
  66. .Handle(EventType.Menu)
  67. .OnActivation(() => { Logging.Log("Menu Activated event!"); })
  68. .OnDestruction(() => { Logging.Log("Menu Destroyed event!"); })
  69. .Build();
  70. HandlerBuilder.Builder("menuswitch API debug")
  71. .Handle(EventType.MenuSwitchedTo)
  72. .OnActivation(() => { Logging.Log("Menu Switched To event!"); })
  73. .Build();
  74. HandlerBuilder.Builder("gameact API debug")
  75. .Handle(EventType.Menu)
  76. .OnActivation(() => { Logging.Log("Game Activated event!"); })
  77. .OnDestruction(() => { Logging.Log("Game Destroyed event!"); })
  78. .Build();
  79. HandlerBuilder.Builder("gamerel API debug")
  80. .Handle(EventType.GameReloaded)
  81. .OnActivation(() => { Logging.Log("Game Reloaded event!"); })
  82. .Build();
  83. HandlerBuilder.Builder("gameswitch API debug")
  84. .Handle(EventType.GameSwitchedTo)
  85. .OnActivation(() => { Logging.Log("Game Switched To event!"); })
  86. .Build();
  87. HandlerBuilder.Builder("simulationswitch API debug")
  88. .Handle(EventType.SimulationSwitchedTo)
  89. .OnActivation(() => { Logging.Log("Game Mode Simulation Switched To event!"); })
  90. .Build();
  91. HandlerBuilder.Builder("buildswitch API debug")
  92. .Handle(EventType.BuildSwitchedTo)
  93. .OnActivation(() => { Logging.Log("Game Mode Build Switched To event!"); })
  94. .Build();
  95. HandlerBuilder.Builder("menu activated API error thrower test")
  96. .Handle(EventType.Menu)
  97. .OnActivation(() => { throw new Exception("Event Handler always throws an exception!"); })
  98. .Build();
  99. #pragma warning restore 0612
  100. /*HandlerBuilder.Builder("enter game from menu test")
  101. .Handle(EventType.Menu)
  102. .OnActivation(() =>
  103. {
  104. Tasks.Scheduler.Schedule(new Tasks.Repeatable(enterGame, shouldRetry, 0.2f));
  105. })
  106. .Build();*/
  107. // debug/test commands
  108. if (Dependency.Hell("ExtraCommands"))
  109. {
  110. CommandBuilder.Builder()
  111. .Name("Exit")
  112. .Description("Close Gamecraft immediately, without any prompts")
  113. .Action(() => { UnityEngine.Application.Quit(); })
  114. .Build();
  115. CommandBuilder.Builder()
  116. .Name("SetFOV")
  117. .Description("Set the player camera's field of view")
  118. .Action((float d) => { UnityEngine.Camera.main.fieldOfView = d; })
  119. .Build();
  120. CommandBuilder.Builder()
  121. .Name("MoveLastBlock")
  122. .Description("Move the most-recently-placed block, and any connected blocks by the given offset")
  123. .Action((float x, float y, float z) =>
  124. {
  125. if (GameState.IsBuildMode())
  126. foreach (var block in Block.GetLastPlacedBlock().GetConnectedCubes())
  127. block.Position += new Unity.Mathematics.float3(x, y, z);
  128. else
  129. GamecraftModdingAPI.Utility.Logging.CommandLogError("Blocks can only be moved in Build mode!");
  130. }).Build();
  131. CommandBuilder.Builder()
  132. .Name("PlaceAluminium")
  133. .Description("Place a block of aluminium at the given coordinates")
  134. .Action((float x, float y, float z) =>
  135. {
  136. var block = Block.PlaceNew(BlockIDs.AluminiumCube, new float3(x, y, z));
  137. Logging.CommandLog("Block placed with type: " + block.Type);
  138. })
  139. .Build();
  140. CommandBuilder.Builder()
  141. .Name("PlaceAluminiumLots")
  142. .Description("Place a lot of blocks of aluminium at the given coordinates")
  143. .Action((float x, float y, float z) =>
  144. {
  145. Logging.CommandLog("Starting...");
  146. var sw = Stopwatch.StartNew();
  147. for (int i = 0; i < 100; i++)
  148. for (int j = 0; j < 100; j++)
  149. Block.PlaceNew(BlockIDs.AluminiumCube, new float3(x + i, y, z + j));
  150. //Block.Sync();
  151. sw.Stop();
  152. Logging.CommandLog("Finished in " + sw.ElapsedMilliseconds + "ms");
  153. })
  154. .Build();
  155. //With Sync(): 1135ms
  156. //Without Sync(): 134ms
  157. //Async: 348 794ms, doesn't freeze game
  158. //Without Sync() but wait for submission: 530ms
  159. //With Sync() at the end: 380ms
  160. Block b = null;
  161. CommandBuilder.Builder("moveBlockInSim", "Run in build mode first while looking at a block, then in sim to move it up")
  162. .Action(() =>
  163. {
  164. if (b == null)
  165. {
  166. b = new Player(PlayerType.Local).GetBlockLookedAt();
  167. Logging.CommandLog("Block saved: " + b);
  168. }
  169. else
  170. Logging.CommandLog("Block moved to: " + (b.GetSimBody().Position += new float3(0, 2, 0)));
  171. }).Build();
  172. CommandBuilder.Builder("Error", "Throw an error to make sure SimpleCustomCommandEngine's wrapper catches it.")
  173. .Action(() => { throw new Exception("Error Command always throws an error"); })
  174. .Build();
  175. CommandBuilder.Builder("ColorBlock",
  176. "Change color of the block looked at if there's any.")
  177. .Action<string>(str =>
  178. {
  179. if (!Enum.TryParse(str, out BlockColors color))
  180. {
  181. Logging.CommandLog("Color " + str + " not found! Interpreting as 4 color values.");
  182. var s = str.Split(' ');
  183. new Player(PlayerType.Local).GetBlockLookedAt().CustomColor = new float4(float.Parse(s[0]),
  184. float.Parse(s[1]), float.Parse(s[2]), float.Parse(s[3]));
  185. return;
  186. }
  187. new Player(PlayerType.Local).GetBlockLookedAt().Color =
  188. new BlockColor { Color = color };
  189. Logging.CommandLog("Colored block to " + color);
  190. }).Build();
  191. CommandBuilder.Builder("GetBlockByID", "Gets a block based on its object identifier and teleports it up.")
  192. .Action<char>(ch =>
  193. {
  194. foreach (var body in SimBody.GetFromObjectID(ch))
  195. {
  196. Logging.CommandLog("SimBody: " + body);
  197. body.Position += new float3(0, 10, 0);
  198. foreach (var bodyConnectedBody in body.GetConnectedBodies())
  199. {
  200. Logging.CommandLog("Moving " + bodyConnectedBody);
  201. bodyConnectedBody.Position += new float3(0, 10, 0);
  202. }
  203. }
  204. }).Build();
  205. CommandBuilder.Builder()
  206. .Name("PlaceConsole")
  207. .Description("Place a bunch of console block with a given text - entering simulation with them crashes the game as the cmd doesn't exist")
  208. .Action((float x, float y, float z) =>
  209. {
  210. Stopwatch sw = new Stopwatch();
  211. sw.Start();
  212. for (int i = 0; i < 100; i++)
  213. {
  214. for (int j = 0; j < 100; j++)
  215. {
  216. var block = Block.PlaceNew<ConsoleBlock>(BlockIDs.ConsoleBlock,
  217. new float3(x + i, y, z + j));
  218. block.Command = "test_command";
  219. }
  220. }
  221. sw.Stop();
  222. Logging.CommandLog($"Blocks placed in {sw.ElapsedMilliseconds} ms");
  223. })
  224. .Build();
  225. CommandBuilder.Builder()
  226. .Name("WireTest")
  227. .Description("Place two blocks and then wire them together")
  228. .Action(() =>
  229. {
  230. LogicGate notBlock = Block.PlaceNew<LogicGate>(BlockIDs.NOTLogicBlock, new float3(1, 2, 0));
  231. LogicGate andBlock = Block.PlaceNew<LogicGate>(BlockIDs.ANDLogicBlock, new float3(2, 2, 0));
  232. // connect NOT Gate output to AND Gate input #2 (ports are zero-indexed, so 1 is 2nd position and 0 is 1st position)
  233. Wire conn = notBlock.Connect(0, andBlock, 1);
  234. Logging.CommandLog(conn.ToString());
  235. })
  236. .Build();
  237. CommandBuilder.Builder("TestChunkHealth", "Sets the chunk looked at to the given health.")
  238. .Action((float val, float max) =>
  239. {
  240. var body = new Player(PlayerType.Local).GetSimBodyLookedAt();
  241. if (body == null) return;
  242. body.CurrentHealth = val;
  243. body.InitialHealth = max;
  244. Logging.CommandLog("Health set to: " + val);
  245. }).Build();
  246. GameClient.SetDebugInfo("InstalledMods", InstalledMods);
  247. Block.Placed += (sender, args) =>
  248. Logging.MetaDebugLog("Placed block " + args.Type + " with ID " + args.ID);
  249. Block.Removed += (sender, args) =>
  250. Logging.MetaDebugLog("Removed block " + args.Type + " with ID " + args.ID);
  251. /*
  252. CommandManager.AddCommand(new SimpleCustomCommandEngine<float>((float d) => { UnityEngine.Camera.main.fieldOfView = d; },
  253. "SetFOV", "Set the player camera's field of view"));
  254. CommandManager.AddCommand(new SimpleCustomCommandEngine<float, float, float>(
  255. (x, y, z) => {
  256. bool success = GamecraftModdingAPI.Blocks.Movement.MoveConnectedBlocks(
  257. GamecraftModdingAPI.Blocks.BlockIdentifiers.LatestBlockID,
  258. new Unity.Mathematics.float3(x, y, z));
  259. if (!success)
  260. {
  261. GamecraftModdingAPI.Utility.Logging.CommandLogError("Blocks can only be moved in Build mode!");
  262. }
  263. }, "MoveLastBlock", "Move the most-recently-placed block, and any connected blocks by the given offset"));
  264. CommandManager.AddCommand(new SimpleCustomCommandEngine<float, float, float>(
  265. (x, y, z) => { Blocks.Placement.PlaceBlock(Blocks.BlockIDs.AluminiumCube, new Unity.Mathematics.float3(x, y, z)); },
  266. "PlaceAluminium", "Place a block of aluminium at the given coordinates"));
  267. System.Random random = new System.Random(); // for command below
  268. CommandManager.AddCommand(new SimpleCustomCommandEngine(
  269. () => {
  270. if (!GameState.IsSimulationMode())
  271. {
  272. Logging.CommandLogError("You must be in simulation mode for this to work!");
  273. return;
  274. }
  275. Tasks.Repeatable task = new Tasks.Repeatable(() => {
  276. uint count = 0;
  277. EGID[] eBlocks = Blocks.Signals.GetElectricBlocks();
  278. for (uint i = 0u; i < eBlocks.Length; i++)
  279. {
  280. uint[] ids = Blocks.Signals.GetSignalIDs(eBlocks[i]);
  281. for (uint j = 0u; j < ids.Length; j++)
  282. {
  283. Blocks.Signals.SetSignalByID(ids[j], (float)random.NextDouble());
  284. count++;
  285. }
  286. }
  287. Logging.MetaDebugLog($"Did the thing on {count} inputs");
  288. },
  289. () => { return GameState.IsSimulationMode(); });
  290. Tasks.Scheduler.Schedule(task);
  291. }, "RandomizeSignalsInputs", "Do the thing"));
  292. */
  293. }
  294. // dependency test
  295. if (Dependency.Hell("GamecraftScripting", new Version("0.0.1.0")))
  296. {
  297. Logging.LogWarning("You're in GamecraftScripting dependency hell");
  298. }
  299. else
  300. {
  301. Logging.Log("Compatible GamecraftScripting detected");
  302. }
  303. #if TEST
  304. TestRoot.RunTests();
  305. #endif
  306. }
  307. private string modsString;
  308. private string InstalledMods()
  309. {
  310. if (modsString != null) return modsString;
  311. StringBuilder sb = new StringBuilder("Installed mods:");
  312. foreach (var plugin in PluginManager.Plugins)
  313. sb.Append("\n" + plugin.Name + " - " + plugin.Version);
  314. return modsString = sb.ToString();
  315. }
  316. private bool retry = true;
  317. private bool shouldRetry()
  318. {
  319. return retry;
  320. }
  321. private void enterGame()
  322. {
  323. App.Client app = new App.Client();
  324. App.Game[] myGames = app.MyGames;
  325. Logging.MetaDebugLog($"MyGames count {myGames.Length}");
  326. if (myGames.Length != 0)
  327. {
  328. Logging.MetaDebugLog($"MyGames[0] EGID {myGames[0].EGID}");
  329. retry = false;
  330. try
  331. {
  332. //myGames[0].Description = "test msg pls ignore"; // make sure game exists first
  333. Logging.MetaDebugLog($"Entering game {myGames[0].Name}");
  334. myGames[0].EnterGame();
  335. }
  336. catch (Exception e)
  337. {
  338. Logging.MetaDebugLog($"Failed to enter game; exception: {e}");
  339. retry = true;
  340. }
  341. }
  342. else
  343. {
  344. Logging.MetaDebugLog("MyGames not populated yet :(");
  345. }
  346. }
  347. public void OnFixedUpdate() { }
  348. public void OnLateUpdate() { }
  349. public void OnLevelWasInitialized(int level) { }
  350. public void OnLevelWasLoaded(int level) { }
  351. public void OnUpdate() { }
  352. [HarmonyPatch]
  353. public class MinimumSpecsPatch
  354. {
  355. public static bool Prefix()
  356. {
  357. return false;
  358. }
  359. public static MethodInfo TargetMethod()
  360. {
  361. return ((Action) MinimumSpecsCheck.CheckRequirementsMet).Method;
  362. }
  363. }
  364. }
  365. }