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.

324 lines
12KB

  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. // debug/test commands
  99. if (Dependency.Hell("ExtraCommands"))
  100. {
  101. CommandBuilder.Builder()
  102. .Name("Exit")
  103. .Description("Close Gamecraft immediately, without any prompts")
  104. .Action(() => { UnityEngine.Application.Quit(); })
  105. .Build();
  106. CommandBuilder.Builder()
  107. .Name("SetFOV")
  108. .Description("Set the player camera's field of view")
  109. .Action((float d) => { UnityEngine.Camera.main.fieldOfView = d; })
  110. .Build();
  111. CommandBuilder.Builder()
  112. .Name("MoveLastBlock")
  113. .Description("Move the most-recently-placed block, and any connected blocks by the given offset")
  114. .Action((float x, float y, float z) =>
  115. {
  116. if (GameState.IsBuildMode())
  117. foreach (var block in Block.GetLastPlacedBlock().GetConnectedCubes())
  118. block.Position += new Unity.Mathematics.float3(x, y, z);
  119. else
  120. GamecraftModdingAPI.Utility.Logging.CommandLogError("Blocks can only be moved in Build mode!");
  121. }).Build();
  122. CommandBuilder.Builder()
  123. .Name("PlaceAluminium")
  124. .Description("Place a block of aluminium at the given coordinates")
  125. .Action((float x, float y, float z) =>
  126. {
  127. var block = Block.PlaceNew(BlockIDs.AluminiumCube, new float3(x, y, z));
  128. Logging.CommandLog("Block placed with type: " + block.Type);
  129. })
  130. .Build();
  131. CommandBuilder.Builder()
  132. .Name("PlaceAluminiumLots")
  133. .Description("Place a lot of blocks of aluminium at the given coordinates")
  134. .Action((float x, float y, float z) =>
  135. {
  136. Logging.CommandLog("Starting...");
  137. var sw = Stopwatch.StartNew();
  138. for (int i = 0; i < 100; i++)
  139. for (int j = 0; j < 100; j++)
  140. Block.PlaceNew(BlockIDs.AluminiumCube, new float3(x + i, y, z + j));
  141. //Block.Sync();
  142. sw.Stop();
  143. Logging.CommandLog("Finished in " + sw.ElapsedMilliseconds + "ms");
  144. })
  145. .Build();
  146. //With Sync(): 1135ms
  147. //Without Sync(): 134ms
  148. //Async: 348 794ms, doesn't freeze game
  149. //Without Sync() but wait for submission: 530ms
  150. //With Sync() at the end: 380ms
  151. Block b = null;
  152. CommandBuilder.Builder("moveBlockInSim", "Run in build mode first while looking at a block, then in sim to move it up")
  153. .Action(() =>
  154. {
  155. if (b == null)
  156. {
  157. b = new Player(PlayerType.Local).GetBlockLookedAt();
  158. Logging.CommandLog("Block saved: " + b);
  159. }
  160. else
  161. Logging.CommandLog("Block moved to: " + (b.GetSimBody().Position += new float3(0, 2, 0)));
  162. }).Build();
  163. CommandBuilder.Builder("Error", "Throw an error to make sure SimpleCustomCommandEngine's wrapper catches it.")
  164. .Action(() => { throw new Exception("Error Command always throws an error"); })
  165. .Build();
  166. CommandBuilder.Builder("ColorBlock",
  167. "Change color of the block looked at if there's any.")
  168. .Action<string>(str =>
  169. {
  170. if (!Enum.TryParse(str, out BlockColors color))
  171. {
  172. Logging.CommandLog("Color " + str + " not found! Interpreting as 4 color values.");
  173. var s = str.Split(' ');
  174. new Player(PlayerType.Local).GetBlockLookedAt().CustomColor = new float4(float.Parse(s[0]),
  175. float.Parse(s[1]), float.Parse(s[2]), float.Parse(s[3]));
  176. return;
  177. }
  178. new Player(PlayerType.Local).GetBlockLookedAt().Color =
  179. new BlockColor {Color = color};
  180. Logging.CommandLog("Colored block to " + color);
  181. }).Build();
  182. CommandBuilder.Builder("GetBlockByID", "Gets a block based on its object identifier and teleports it up.")
  183. .Action<char>(ch =>
  184. {
  185. foreach (var body in SimBody.GetFromObjectID(ch))
  186. {
  187. Logging.CommandLog("SimBody: " + body);
  188. body.Position += new float3(0, 10, 0);
  189. foreach (var bodyConnectedBody in body.GetConnectedBodies())
  190. {
  191. Logging.CommandLog("Moving " + bodyConnectedBody);
  192. bodyConnectedBody.Position += new float3(0, 10, 0);
  193. }
  194. }
  195. }).Build();
  196. GameClient.SetDebugInfo("InstalledMods", InstalledMods);
  197. Block.Placed += (sender, args) =>
  198. Logging.MetaDebugLog("Placed block " + args.Type + " with ID " + args.ID);
  199. Block.Removed += (sender, args) =>
  200. Logging.MetaDebugLog("Removed block " + args.Type + " with ID " + args.ID);
  201. /*
  202. CommandManager.AddCommand(new SimpleCustomCommandEngine<float>((float d) => { UnityEngine.Camera.main.fieldOfView = d; },
  203. "SetFOV", "Set the player camera's field of view"));
  204. CommandManager.AddCommand(new SimpleCustomCommandEngine<float, float, float>(
  205. (x, y, z) => {
  206. bool success = GamecraftModdingAPI.Blocks.Movement.MoveConnectedBlocks(
  207. GamecraftModdingAPI.Blocks.BlockIdentifiers.LatestBlockID,
  208. new Unity.Mathematics.float3(x, y, z));
  209. if (!success)
  210. {
  211. GamecraftModdingAPI.Utility.Logging.CommandLogError("Blocks can only be moved in Build mode!");
  212. }
  213. }, "MoveLastBlock", "Move the most-recently-placed block, and any connected blocks by the given offset"));
  214. CommandManager.AddCommand(new SimpleCustomCommandEngine<float, float, float>(
  215. (x, y, z) => { Blocks.Placement.PlaceBlock(Blocks.BlockIDs.AluminiumCube, new Unity.Mathematics.float3(x, y, z)); },
  216. "PlaceAluminium", "Place a block of aluminium at the given coordinates"));
  217. System.Random random = new System.Random(); // for command below
  218. CommandManager.AddCommand(new SimpleCustomCommandEngine(
  219. () => {
  220. if (!GameState.IsSimulationMode())
  221. {
  222. Logging.CommandLogError("You must be in simulation mode for this to work!");
  223. return;
  224. }
  225. Tasks.Repeatable task = new Tasks.Repeatable(() => {
  226. uint count = 0;
  227. EGID[] eBlocks = Blocks.Signals.GetElectricBlocks();
  228. for (uint i = 0u; i < eBlocks.Length; i++)
  229. {
  230. uint[] ids = Blocks.Signals.GetSignalIDs(eBlocks[i]);
  231. for (uint j = 0u; j < ids.Length; j++)
  232. {
  233. Blocks.Signals.SetSignalByID(ids[j], (float)random.NextDouble());
  234. count++;
  235. }
  236. }
  237. Logging.MetaDebugLog($"Did the thing on {count} inputs");
  238. },
  239. () => { return GameState.IsSimulationMode(); });
  240. Tasks.Scheduler.Schedule(task);
  241. }, "RandomizeSignalsInputs", "Do the thing"));
  242. */
  243. }
  244. // dependency test
  245. if (Dependency.Hell("GamecraftScripting", new Version("0.0.1.0")))
  246. {
  247. Logging.LogWarning("You're in GamecraftScripting dependency hell");
  248. }
  249. else
  250. {
  251. Logging.Log("Compatible GamecraftScripting detected");
  252. }
  253. }
  254. private string modsString;
  255. private string InstalledMods()
  256. {
  257. if (modsString != null) return modsString;
  258. StringBuilder sb = new StringBuilder("Installed mods:");
  259. foreach (var plugin in PluginManager.Plugins)
  260. sb.Append("\n" + plugin.Name + " - " + plugin.Version);
  261. return modsString = sb.ToString();
  262. }
  263. public void OnFixedUpdate() { }
  264. public void OnLateUpdate() { }
  265. public void OnLevelWasInitialized(int level) { }
  266. public void OnLevelWasLoaded(int level) { }
  267. public void OnUpdate() { }
  268. [HarmonyPatch]
  269. public class MinimumSpecsPatch
  270. {
  271. public static bool Prefix(ref bool __result)
  272. {
  273. __result = true;
  274. return false;
  275. }
  276. public static MethodInfo TargetMethod()
  277. {
  278. return ((Func<bool>)MinimumSpecsCheck.CheckRequirementsMet).Method;
  279. }
  280. }
  281. }
  282. }