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.

516 lines
19KB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Reflection.Emit;
  8. using System.Text;
  9. using TechbloxModdingAPI.App;
  10. using HarmonyLib;
  11. using IllusionInjector;
  12. // test
  13. using GPUInstancer;
  14. using Svelto.ECS;
  15. using RobocraftX.Blocks;
  16. using RobocraftX.Common;
  17. using RobocraftX.SimulationModeState;
  18. using RobocraftX.FrontEnd;
  19. using Unity.Mathematics;
  20. using UnityEngine;
  21. using RobocraftX.Schedulers;
  22. using Svelto.Tasks.ExtraLean;
  23. using uREPL;
  24. using TechbloxModdingAPI.Interface.IMGUI;
  25. using TechbloxModdingAPI.Tasks;
  26. using RobocraftX.Common.Input;
  27. using RobocraftX.CR.MainGame;
  28. using RobocraftX.GUI.CommandLine;
  29. using RobocraftX.Multiplayer;
  30. using RobocraftX.StateSync;
  31. using Svelto.Context;
  32. using Svelto.DataStructures;
  33. using Svelto.Services;
  34. using TechbloxModdingAPI.Blocks;
  35. using TechbloxModdingAPI.Commands;
  36. using TechbloxModdingAPI.Events;
  37. using TechbloxModdingAPI.Input;
  38. using TechbloxModdingAPI.Players;
  39. using TechbloxModdingAPI.Utility;
  40. using UnityEngine.AddressableAssets;
  41. using UnityEngine.AddressableAssets.ResourceLocators;
  42. using UnityEngine.ResourceManagement.AsyncOperations;
  43. using UnityEngine.ResourceManagement.ResourceLocations;
  44. using UnityEngine.ResourceManagement.ResourceProviders;
  45. using Debug = FMOD.Debug;
  46. using EventType = TechbloxModdingAPI.Events.EventType;
  47. using Label = TechbloxModdingAPI.Interface.IMGUI.Label;
  48. using ScalingPermission = DataLoader.ScalingPermission;
  49. namespace TechbloxModdingAPI.Tests
  50. {
  51. #if DEBUG
  52. // unused by design
  53. /// <summary>
  54. /// Modding API implemented as a standalone IPA Plugin.
  55. /// Ideally, TechbloxModdingAPI should be loaded by another mod; not itself
  56. /// </summary>
  57. public class TechbloxModdingAPIPluginTest : IllusionPlugin.IEnhancedPlugin
  58. {
  59. private static Harmony harmony { get; set; }
  60. public override string Name { get; } = Assembly.GetExecutingAssembly().GetName().Name;
  61. public override string Version { get; } = Assembly.GetExecutingAssembly().GetName().Version.ToString();
  62. public string HarmonyID { get; } = "org.git.exmods.modtainers.techbloxmoddingapi";
  63. public override void OnApplicationQuit()
  64. {
  65. Main.Shutdown();
  66. }
  67. public override void OnApplicationStart()
  68. {
  69. FileLog.Reset();
  70. Harmony.DEBUG = true;
  71. Main.Init();
  72. Logging.MetaDebugLog($"Version group id {(uint)ApiExclusiveGroups.versionGroup}");
  73. // in case Steam is not installed/running
  74. // this will crash the game slightly later during startup
  75. //SteamInitPatch.ForcePassSteamCheck = true;
  76. // in case running in a VM
  77. //MinimumSpecsCheckPatch.ForcePassMinimumSpecCheck = true;
  78. // disable some Techblox analytics
  79. //AnalyticsDisablerPatch.DisableAnalytics = true;
  80. // disable background music
  81. Logging.MetaDebugLog("Audio Mixers: " + string.Join(",", AudioTools.GetMixers()));
  82. //AudioTools.SetVolume(0.0f, "Music"); // The game now sets this from settings again after this is called :(
  83. //Utility.VersionTracking.Enable();//(very) unstable
  84. // debug/test handlers
  85. #pragma warning disable 0612
  86. HandlerBuilder.Builder()
  87. .Name("appinit API debug")
  88. .Handle(EventType.ApplicationInitialized)
  89. .OnActivation(() => { Logging.Log("App Inited event!"); })
  90. .Build();
  91. HandlerBuilder.Builder("menuact API debug")
  92. .Handle(EventType.Menu)
  93. .OnActivation(() => { Logging.Log("Menu Activated event!"); })
  94. .OnDestruction(() => { Logging.Log("Menu Destroyed event!"); })
  95. .Build();
  96. HandlerBuilder.Builder("menuswitch API debug")
  97. .Handle(EventType.MenuSwitchedTo)
  98. .OnActivation(() => { Logging.Log("Menu Switched To event!"); })
  99. .Build();
  100. HandlerBuilder.Builder("gameact API debug")
  101. .Handle(EventType.Menu)
  102. .OnActivation(() => { Logging.Log("Game Activated event!"); })
  103. .OnDestruction(() => { Logging.Log("Game Destroyed event!"); })
  104. .Build();
  105. HandlerBuilder.Builder("gamerel API debug")
  106. .Handle(EventType.GameReloaded)
  107. .OnActivation(() => { Logging.Log("Game Reloaded event!"); })
  108. .Build();
  109. HandlerBuilder.Builder("gameswitch API debug")
  110. .Handle(EventType.GameSwitchedTo)
  111. .OnActivation(() => { Logging.Log("Game Switched To event!"); })
  112. .Build();
  113. HandlerBuilder.Builder("simulationswitch API debug")
  114. .Handle(EventType.SimulationSwitchedTo)
  115. .OnActivation(() => { Logging.Log("Game Mode Simulation Switched To event!"); })
  116. .Build();
  117. HandlerBuilder.Builder("buildswitch API debug")
  118. .Handle(EventType.BuildSwitchedTo)
  119. .OnActivation(() => { Logging.Log("Game Mode Build Switched To event!"); })
  120. .Build();
  121. HandlerBuilder.Builder("menu activated API error thrower test")
  122. .Handle(EventType.Menu)
  123. .OnActivation(() => { throw new Exception("Event Handler always throws an exception!"); })
  124. .Build();
  125. #pragma warning restore 0612
  126. /*HandlerBuilder.Builder("enter game from menu test")
  127. .Handle(EventType.Menu)
  128. .OnActivation(() =>
  129. {
  130. Tasks.Scheduler.Schedule(new Tasks.Repeatable(enterGame, shouldRetry, 0.2f));
  131. })
  132. .Build();*/
  133. // debug/test commands
  134. if (Dependency.Hell("ExtraCommands"))
  135. {
  136. CommandBuilder.Builder()
  137. .Name("Exit")
  138. .Description("Close Techblox immediately, without any prompts")
  139. .Action(() => { UnityEngine.Application.Quit(); })
  140. .Build();
  141. CommandBuilder.Builder()
  142. .Name("SetFOV")
  143. .Description("Set the player camera's field of view")
  144. .Action((float d) => { UnityEngine.Camera.main.fieldOfView = d; })
  145. .Build();
  146. CommandBuilder.Builder()
  147. .Name("MoveLastBlock")
  148. .Description("Move the most-recently-placed block, and any connected blocks by the given offset")
  149. .Action((float x, float y, float z) =>
  150. {
  151. if (GameState.IsBuildMode())
  152. foreach (var block in Block.GetLastPlacedBlock().GetConnectedCubes())
  153. block.Position += new Unity.Mathematics.float3(x, y, z);
  154. else
  155. Logging.CommandLogError("Blocks can only be moved in Build mode!");
  156. }).Build();
  157. CommandBuilder.Builder()
  158. .Name("PlaceAluminium")
  159. .Description("Place a block of aluminium at the given coordinates")
  160. .Action((float x, float y, float z) =>
  161. {
  162. var block = Block.PlaceNew(BlockIDs.Cube, new float3(x, y, z));
  163. Logging.CommandLog("Block placed with type: " + block.Type);
  164. })
  165. .Build();
  166. CommandBuilder.Builder()
  167. .Name("PlaceAluminiumLots")
  168. .Description("Place a lot of blocks of aluminium at the given coordinates")
  169. .Action((float x, float y, float z) =>
  170. {
  171. Logging.CommandLog("Starting...");
  172. var sw = Stopwatch.StartNew();
  173. for (int i = 0; i < 100; i++)
  174. for (int j = 0; j < 100; j++)
  175. Block.PlaceNew(BlockIDs.Cube, new float3(x + i, y, z + j));
  176. //Block.Sync();
  177. sw.Stop();
  178. Logging.CommandLog("Finished in " + sw.ElapsedMilliseconds + "ms");
  179. })
  180. .Build();
  181. Block b = null;
  182. CommandBuilder.Builder("moveBlockInSim", "Run in build mode first while looking at a block, then in sim to move it up")
  183. .Action(() =>
  184. {
  185. if (b == null)
  186. {
  187. b = new Player(PlayerType.Local).GetBlockLookedAt();
  188. Logging.CommandLog("Block saved: " + b);
  189. }
  190. else
  191. Logging.CommandLog("Block moved to: " + (b.GetSimBody().Position += new float3(0, 2, 0)));
  192. }).Build();
  193. CommandBuilder.Builder("Error", "Throw an error to make sure SimpleCustomCommandEngine's wrapper catches it.")
  194. .Action(() => { throw new Exception("Error Command always throws an error"); })
  195. .Build();
  196. CommandBuilder.Builder("ColorBlock",
  197. "Change color of the block looked at if there's any.")
  198. .Action<string>(str =>
  199. {
  200. if (!Enum.TryParse(str, out BlockColors color))
  201. {
  202. Logging.CommandLog("Color " + str + " not found! Interpreting as 4 color values.");
  203. var s = str.Split(' ');
  204. new Player(PlayerType.Local).GetBlockLookedAt().CustomColor = new float4(float.Parse(s[0]),
  205. float.Parse(s[1]), float.Parse(s[2]), float.Parse(s[3]));
  206. return;
  207. }
  208. new Player(PlayerType.Local).GetBlockLookedAt().Color = color;
  209. Logging.CommandLog("Colored block to " + color);
  210. }).Build();
  211. CommandBuilder.Builder("GetBlockByID", "Gets a block based on its object identifier and teleports it up.")
  212. .Action<char>(ch =>
  213. {
  214. foreach (var body in SimBody.GetFromObjectID(ch))
  215. {
  216. Logging.CommandLog("SimBody: " + body);
  217. body.Position += new float3(0, 10, 0);
  218. foreach (var bodyConnectedBody in body.GetConnectedBodies())
  219. {
  220. Logging.CommandLog("Moving " + bodyConnectedBody);
  221. bodyConnectedBody.Position += new float3(0, 10, 0);
  222. }
  223. }
  224. }).Build();
  225. /*CommandBuilder.Builder()
  226. .Name("PlaceConsole")
  227. .Description("Place a bunch of console block with a given text - entering simulation with them crashes the game as the cmd doesn't exist")
  228. .Action((float x, float y, float z) =>
  229. {
  230. Stopwatch sw = new Stopwatch();
  231. sw.Start();
  232. for (int i = 0; i < 100; i++)
  233. {
  234. for (int j = 0; j < 100; j++)
  235. {
  236. var block = Block.PlaceNew<ConsoleBlock>(BlockIDs.ConsoleBlock,
  237. new float3(x + i, y, z + j));
  238. block.Command = "test_command";
  239. }
  240. }
  241. sw.Stop();
  242. Logging.CommandLog($"Blocks placed in {sw.ElapsedMilliseconds} ms");
  243. })
  244. .Build();*/
  245. /*CommandBuilder.Builder()
  246. .Name("WireTest")
  247. .Description("Place two blocks and then wire them together")
  248. .Action(() =>
  249. {
  250. LogicGate notBlock = Block.PlaceNew<LogicGate>(BlockIDs.NOTLogicBlock, new float3(1, 2, 0));
  251. LogicGate andBlock = Block.PlaceNew<LogicGate>(BlockIDs.ANDLogicBlock, new float3(2, 2, 0));
  252. // connect NOT Gate output to AND Gate input #2 (ports are zero-indexed, so 1 is 2nd position and 0 is 1st position)
  253. Wire conn = notBlock.Connect(0, andBlock, 1);
  254. Logging.CommandLog(conn.ToString());
  255. })
  256. .Build();*/
  257. CommandBuilder.Builder("TestChunkHealth", "Sets the chunk looked at to the given health.")
  258. .Action((float val, float max) =>
  259. {
  260. var body = new Player(PlayerType.Local).GetSimBodyLookedAt();
  261. if (body == null) return;
  262. body.CurrentHealth = val;
  263. body.InitialHealth = max;
  264. Logging.CommandLog("Health set to: " + val);
  265. }).Build();
  266. CommandBuilder.Builder("placeBlockGroup", "Places some blocks in a group")
  267. .Action((float x, float y, float z) =>
  268. {
  269. var pos = new float3(x, y, z);
  270. var group = BlockGroup.Create(new Block(BlockIDs.Cube, pos) {Color = BlockColors.Aqua});
  271. new Block(BlockIDs.Cube, pos += new float3(1, 0, 0))
  272. {Color = BlockColors.Blue, BlockGroup = group};
  273. new Block(BlockIDs.Cube, pos += new float3(1, 0, 0))
  274. {Color = BlockColors.Green, BlockGroup = group};
  275. new Block(BlockIDs.Cube, pos + new float3(1, 0, 0))
  276. {Color = BlockColors.Lime, BlockGroup = group};
  277. }).Build();
  278. CommandBuilder.Builder("placeCustomBlock", "Places a custom block, needs a custom catalog and assets.")
  279. .Action((float x, float y, float z) =>
  280. {
  281. Logging.CommandLog("Block placed: " +
  282. Block.PlaceNew<TestBlock>((BlockIDs) 500, new float3(0, 0, 0)));
  283. }).Build();
  284. GameClient.SetDebugInfo("InstalledMods", InstalledMods);
  285. Block.Placed += (sender, args) =>
  286. Logging.MetaDebugLog("Placed block " + args.Type + " with ID " + args.ID);
  287. Block.Removed += (sender, args) =>
  288. Logging.MetaDebugLog("Removed block " + args.Type + " with ID " + args.ID);
  289. /*
  290. CommandManager.AddCommand(new SimpleCustomCommandEngine<float>((float d) => { UnityEngine.Camera.main.fieldOfView = d; },
  291. "SetFOV", "Set the player camera's field of view"));
  292. CommandManager.AddCommand(new SimpleCustomCommandEngine<float, float, float>(
  293. (x, y, z) => {
  294. bool success = TechbloxModdingAPI.Blocks.Movement.MoveConnectedBlocks(
  295. TechbloxModdingAPI.Blocks.BlockIdentifiers.LatestBlockID,
  296. new Unity.Mathematics.float3(x, y, z));
  297. if (!success)
  298. {
  299. TechbloxModdingAPI.Utility.Logging.CommandLogError("Blocks can only be moved in Build mode!");
  300. }
  301. }, "MoveLastBlock", "Move the most-recently-placed block, and any connected blocks by the given offset"));
  302. CommandManager.AddCommand(new SimpleCustomCommandEngine<float, float, float>(
  303. (x, y, z) => { Blocks.Placement.PlaceBlock(Blocks.BlockIDs.Cube, new Unity.Mathematics.float3(x, y, z)); },
  304. "PlaceAluminium", "Place a block of aluminium at the given coordinates"));
  305. System.Random random = new System.Random(); // for command below
  306. CommandManager.AddCommand(new SimpleCustomCommandEngine(
  307. () => {
  308. if (!GameState.IsSimulationMode())
  309. {
  310. Logging.CommandLogError("You must be in simulation mode for this to work!");
  311. return;
  312. }
  313. Tasks.Repeatable task = new Tasks.Repeatable(() => {
  314. uint count = 0;
  315. EGID[] eBlocks = Blocks.Signals.GetElectricBlocks();
  316. for (uint i = 0u; i < eBlocks.Length; i++)
  317. {
  318. uint[] ids = Blocks.Signals.GetSignalIDs(eBlocks[i]);
  319. for (uint j = 0u; j < ids.Length; j++)
  320. {
  321. Blocks.Signals.SetSignalByID(ids[j], (float)random.NextDouble());
  322. count++;
  323. }
  324. }
  325. Logging.MetaDebugLog($"Did the thing on {count} inputs");
  326. },
  327. () => { return GameState.IsSimulationMode(); });
  328. Tasks.Scheduler.Schedule(task);
  329. }, "RandomizeSignalsInputs", "Do the thing"));
  330. */
  331. }
  332. // dependency test
  333. if (Dependency.Hell("TechbloxScripting", new Version("0.0.1.0")))
  334. {
  335. Logging.LogWarning("You're in TechbloxScripting dependency hell");
  336. }
  337. else
  338. {
  339. Logging.Log("Compatible TechbloxScripting detected");
  340. }
  341. // Interface test
  342. /*Interface.IMGUI.Group uiGroup = new Group(new Rect(20, 20, 200, 500), "TechbloxModdingAPI_UITestGroup", true);
  343. Interface.IMGUI.Button button = new Button("TEST");
  344. button.OnClick += (b, __) => { Logging.MetaDebugLog($"Click on {((Interface.IMGUI.Button)b).Name}");};
  345. Interface.IMGUI.Button button2 = new Button("TEST2");
  346. button2.OnClick += (b, __) => { Logging.MetaDebugLog($"Click on {((Interface.IMGUI.Button)b).Name}");};
  347. Text uiText = new Text("This is text!", multiline: true);
  348. uiText.OnEdit += (t, txt) => { Logging.MetaDebugLog($"Text in {((Text)t).Name} is now '{txt}'"); };
  349. Label uiLabel = new Label("Label!");
  350. Image uiImg = new Image(name:"Behold this texture!");
  351. uiImg.Enabled = false;
  352. uiGroup.AddElement(button);
  353. uiGroup.AddElement(button2);
  354. uiGroup.AddElement(uiText);
  355. uiGroup.AddElement(uiLabel);
  356. uiGroup.AddElement(uiImg);*/
  357. /*Addressables.LoadAssetAsync<Texture2D>("Assets/Art/Textures/UI/FrontEndMap/RCX_Blue_Background_5k.jpg")
  358. .Completed +=
  359. handle =>
  360. {
  361. uiImg.Texture = handle.Result;
  362. uiImg.Enabled = true;
  363. Logging.MetaDebugLog($"Got blue bg asset {handle.Result}");
  364. };*/
  365. CommandBuilder.Builder("enableCompletions")
  366. .Action(() =>
  367. {
  368. var p = Window.selected.main.parameters;
  369. p.useCommandCompletion = true;
  370. p.useMonoCompletion = true;
  371. p.useGlobalClassCompletion = true;
  372. Log.Output("Submitted: " + Window.selected.submittedCode);
  373. })
  374. .Build();
  375. try
  376. {
  377. CustomBlock.RegisterCustomBlock<TestBlock>();
  378. Logging.MetaDebugLog("Registered test custom block");
  379. }
  380. catch (FileNotFoundException)
  381. {
  382. Logging.MetaDebugLog("Test custom block catalog not found");
  383. }
  384. CustomBlock.ChangeExistingBlock((ushort) BlockIDs.CarWheel,
  385. cld => cld.scalingPermission = ScalingPermission.NonUniform);
  386. /*((FasterList<GuiInputMap.GuiInputMapElement>)AccessTools.Property(typeof(GuiInputMap), "GuiInputsButtonDown").GetValue(null))
  387. .Add(new GuiInputMap.GuiInputMapElement(RewiredConsts.Action.ToggleCommandLine, GuiIn))*/
  388. #if TEST
  389. TestRoot.RunTests();
  390. #endif
  391. }
  392. private string modsString;
  393. private string InstalledMods()
  394. {
  395. if (modsString != null) return modsString;
  396. StringBuilder sb = new StringBuilder("Installed mods:");
  397. foreach (var plugin in PluginManager.Plugins)
  398. sb.Append("\n" + plugin.Name + " - " + plugin.Version);
  399. return modsString = sb.ToString();
  400. }
  401. private bool retry = true;
  402. private bool shouldRetry()
  403. {
  404. return retry;
  405. }
  406. private void enterGame()
  407. {
  408. App.Client app = new App.Client();
  409. App.Game[] myGames = app.MyGames;
  410. Logging.MetaDebugLog($"MyGames count {myGames.Length}");
  411. if (myGames.Length != 0)
  412. {
  413. Logging.MetaDebugLog($"MyGames[0] EGID {myGames[0].EGID}");
  414. retry = false;
  415. try
  416. {
  417. //myGames[0].Description = "test msg pls ignore"; // make sure game exists first
  418. Logging.MetaDebugLog($"Entering game {myGames[0].Name}");
  419. myGames[0].EnterGame();
  420. }
  421. catch (Exception e)
  422. {
  423. Logging.MetaDebugLog($"Failed to enter game; exception: {e}");
  424. retry = true;
  425. }
  426. }
  427. else
  428. {
  429. Logging.MetaDebugLog("MyGames not populated yet :(");
  430. }
  431. }
  432. public override void OnUpdate()
  433. {
  434. if (UnityEngine.Input.GetKeyDown(KeyCode.End))
  435. {
  436. Console.WriteLine("Pressed button to toggle console");
  437. FakeInput.CustomInput(new LocalInputEntityStruct {commandLineToggleInput = true});
  438. }
  439. }
  440. [HarmonyPatch]
  441. public class MinimumSpecsPatch
  442. {
  443. public static bool Prefix()
  444. {
  445. return false;
  446. }
  447. public static MethodInfo TargetMethod()
  448. {
  449. return ((Action) MinimumSpecsCheck.CheckRequirementsMet).Method;
  450. }
  451. }
  452. [CustomBlock("customCatalog.json", "Assets/Prefabs/Cube.prefab", "strAluminiumCube", SortIndex = 12)]
  453. public class TestBlock : CustomBlock
  454. {
  455. public TestBlock(EGID id) : base(id)
  456. {
  457. }
  458. public TestBlock(uint id) : base(id)
  459. {
  460. }
  461. }
  462. }
  463. #endif
  464. }