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.

351 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. // 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("lookedAt", LookedAt);
  197. GameClient.SetDebugInfo("InstalledMods", InstalledMods);
  198. Block.Placed += (sender, args) =>
  199. Logging.MetaDebugLog("Placed block " + args.Type + " with ID " + args.ID);
  200. Block.Removed += (sender, args) =>
  201. Logging.MetaDebugLog("Removed block " + args.Type + " with ID " + args.ID);
  202. /*
  203. CommandManager.AddCommand(new SimpleCustomCommandEngine<float>((float d) => { UnityEngine.Camera.main.fieldOfView = d; },
  204. "SetFOV", "Set the player camera's field of view"));
  205. CommandManager.AddCommand(new SimpleCustomCommandEngine<float, float, float>(
  206. (x, y, z) => {
  207. bool success = GamecraftModdingAPI.Blocks.Movement.MoveConnectedBlocks(
  208. GamecraftModdingAPI.Blocks.BlockIdentifiers.LatestBlockID,
  209. new Unity.Mathematics.float3(x, y, z));
  210. if (!success)
  211. {
  212. GamecraftModdingAPI.Utility.Logging.CommandLogError("Blocks can only be moved in Build mode!");
  213. }
  214. }, "MoveLastBlock", "Move the most-recently-placed block, and any connected blocks by the given offset"));
  215. CommandManager.AddCommand(new SimpleCustomCommandEngine<float, float, float>(
  216. (x, y, z) => { Blocks.Placement.PlaceBlock(Blocks.BlockIDs.AluminiumCube, new Unity.Mathematics.float3(x, y, z)); },
  217. "PlaceAluminium", "Place a block of aluminium at the given coordinates"));
  218. System.Random random = new System.Random(); // for command below
  219. CommandManager.AddCommand(new SimpleCustomCommandEngine(
  220. () => {
  221. if (!GameState.IsSimulationMode())
  222. {
  223. Logging.CommandLogError("You must be in simulation mode for this to work!");
  224. return;
  225. }
  226. Tasks.Repeatable task = new Tasks.Repeatable(() => {
  227. uint count = 0;
  228. EGID[] eBlocks = Blocks.Signals.GetElectricBlocks();
  229. for (uint i = 0u; i < eBlocks.Length; i++)
  230. {
  231. uint[] ids = Blocks.Signals.GetSignalIDs(eBlocks[i]);
  232. for (uint j = 0u; j < ids.Length; j++)
  233. {
  234. Blocks.Signals.SetSignalByID(ids[j], (float)random.NextDouble());
  235. count++;
  236. }
  237. }
  238. Logging.MetaDebugLog($"Did the thing on {count} inputs");
  239. },
  240. () => { return GameState.IsSimulationMode(); });
  241. Tasks.Scheduler.Schedule(task);
  242. }, "RandomizeSignalsInputs", "Do the thing"));
  243. */
  244. }
  245. // dependency test
  246. if (Dependency.Hell("GamecraftScripting", new Version("0.0.1.0")))
  247. {
  248. Logging.LogWarning("You're in GamecraftScripting dependency hell");
  249. }
  250. else
  251. {
  252. Logging.Log("Compatible GamecraftScripting detected");
  253. }
  254. }
  255. private Player player;
  256. private string LookedAt()
  257. {
  258. if (player == null)
  259. player = new Player(PlayerType.Local);
  260. if (GameState.IsBuildMode())
  261. {
  262. Block block = player.GetBlockLookedAt();
  263. if (block == null) return "Block: none";
  264. return "Block: " + block.Type + "\nColor: " + block.Color + "\n" + "At: " + block.Position
  265. + "\nText: " + block.Label;
  266. }
  267. if (GameState.IsSimulationMode())
  268. {
  269. SimBody body = player.GetSimBodyLookedAt();
  270. if (body == null) return "Body: none";
  271. return "Body: " + (body.Static ? "static" : "non-static")
  272. + "\nAt: " + body.Position + " - rotated: " + body.Rotation
  273. + "\nWith mass: " + body.Mass + " - center: " + body.CenterOfMass
  274. + "\nVelocity: " + body.Velocity + " - angular: " + body.AngularVelocity;
  275. }
  276. return "Switching modes...";
  277. }
  278. private string modsString;
  279. private string InstalledMods()
  280. {
  281. if (modsString != null) return modsString;
  282. StringBuilder sb = new StringBuilder("Installed mods:");
  283. foreach (var plugin in PluginManager.Plugins)
  284. sb.Append("\n" + plugin.Name + " - " + plugin.Version);
  285. return modsString = sb.ToString();
  286. }
  287. public void OnFixedUpdate() { }
  288. public void OnLateUpdate() { }
  289. public void OnLevelWasInitialized(int level) { }
  290. public void OnLevelWasLoaded(int level) { }
  291. public void OnUpdate() { }
  292. [HarmonyPatch]
  293. public class MinimumSpecsPatch
  294. {
  295. public static bool Prefix(ref bool __result)
  296. {
  297. __result = true;
  298. return false;
  299. }
  300. public static MethodInfo TargetMethod()
  301. {
  302. return ((Func<bool>)MinimumSpecsCheck.CheckRequirementsMet).Method;
  303. }
  304. }
  305. }
  306. }