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.

GamecraftModdingAPIPluginTest.cs 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. using System;
  2. using System.Linq;
  3. using System.Reflection;
  4. using HarmonyLib;
  5. // test
  6. using Svelto.ECS;
  7. using RobocraftX.Blocks;
  8. using RobocraftX.Common;
  9. using RobocraftX.SimulationModeState;
  10. using RobocraftX.FrontEnd;
  11. using Unity.Mathematics;
  12. using GamecraftModdingAPI.Commands;
  13. using GamecraftModdingAPI.Events;
  14. using GamecraftModdingAPI.Utility;
  15. using GamecraftModdingAPI.Blocks;
  16. using GamecraftModdingAPI.Players;
  17. namespace GamecraftModdingAPI.Tests
  18. {
  19. // unused by design
  20. /// <summary>
  21. /// Modding API implemented as a standalone IPA Plugin.
  22. /// Ideally, GamecraftModdingAPI should be loaded by another mod; not itself
  23. /// </summary>
  24. public class GamecraftModdingAPIPluginTest
  25. #if DEBUG
  26. : IllusionPlugin.IEnhancedPlugin
  27. #endif
  28. {
  29. private static Harmony harmony { get; set; }
  30. public string[] Filter { get; } = new string[] { "Gamecraft", "GamecraftPreview" };
  31. public string Name { get; } = Assembly.GetExecutingAssembly().GetName().Name;
  32. public string Version { get; } = Assembly.GetExecutingAssembly().GetName().Version.ToString();
  33. public string HarmonyID { get; } = "org.git.exmods.modtainers.gamecraftmoddingapi";
  34. public void OnApplicationQuit()
  35. {
  36. GamecraftModdingAPI.Main.Shutdown();
  37. }
  38. public void OnApplicationStart()
  39. {
  40. FileLog.Reset();
  41. Harmony.DEBUG = true;
  42. GamecraftModdingAPI.Main.Init();
  43. Logging.MetaDebugLog($"Version group id {(uint)ApiExclusiveGroups.versionGroup}");
  44. // in case Steam is not installed/running
  45. // this will crash the game slightly later during startup
  46. //SteamInitPatch.ForcePassSteamCheck = true;
  47. // in case running in a VM
  48. //MinimumSpecsCheckPatch.ForcePassMinimumSpecCheck = true;
  49. // disable some Gamecraft analytics
  50. //AnalyticsDisablerPatch.DisableAnalytics = true;
  51. // disable background music
  52. Logging.MetaDebugLog("Audio Mixers: "+string.Join(",", AudioTools.GetMixers()));
  53. //AudioTools.SetVolume(0.0f, "Music"); // The game now sets this from settings again after this is called :(
  54. //Utility.VersionTracking.Enable();//(very) unstable
  55. // debug/test handlers
  56. HandlerBuilder.Builder()
  57. .Name("appinit API debug")
  58. .Handle(EventType.ApplicationInitialized)
  59. .OnActivation(() => { Logging.Log("App Inited event!"); })
  60. .Build();
  61. HandlerBuilder.Builder("menuact API debug")
  62. .Handle(EventType.Menu)
  63. .OnActivation(() => { Logging.Log("Menu Activated event!"); })
  64. .OnDestruction(() => { Logging.Log("Menu Destroyed event!"); })
  65. .Build();
  66. HandlerBuilder.Builder("menuswitch API debug")
  67. .Handle(EventType.MenuSwitchedTo)
  68. .OnActivation(() => { Logging.Log("Menu Switched To event!"); })
  69. .Build();
  70. HandlerBuilder.Builder("gameact API debug")
  71. .Handle(EventType.Menu)
  72. .OnActivation(() => { Logging.Log("Game Activated event!"); })
  73. .OnDestruction(() => { Logging.Log("Game Destroyed event!"); })
  74. .Build();
  75. HandlerBuilder.Builder("gamerel API debug")
  76. .Handle(EventType.GameReloaded)
  77. .OnActivation(() => { Logging.Log("Game Reloaded event!"); })
  78. .Build();
  79. HandlerBuilder.Builder("gameswitch API debug")
  80. .Handle(EventType.GameSwitchedTo)
  81. .OnActivation(() => { Logging.Log("Game Switched To event!"); })
  82. .Build();
  83. HandlerBuilder.Builder("simulationswitch API debug")
  84. .Handle(EventType.SimulationSwitchedTo)
  85. .OnActivation(() => { Logging.Log("Game Mode Simulation Switched To event!"); })
  86. .Build();
  87. HandlerBuilder.Builder("buildswitch API debug")
  88. .Handle(EventType.BuildSwitchedTo)
  89. .OnActivation(() => { Logging.Log("Game Mode Build Switched To event!"); })
  90. .Build();
  91. HandlerBuilder.Builder("menu activated API error thrower test")
  92. .Handle(EventType.Menu)
  93. .OnActivation(() => { throw new Exception("Event Handler always throws an exception!"); })
  94. .Build();
  95. // debug/test commands
  96. if (Dependency.Hell("ExtraCommands"))
  97. {
  98. CommandBuilder.Builder()
  99. .Name("Exit")
  100. .Description("Close Gamecraft immediately, without any prompts")
  101. .Action(() => { UnityEngine.Application.Quit(); })
  102. .Build();
  103. CommandBuilder.Builder()
  104. .Name("SetFOV")
  105. .Description("Set the player camera's field of view")
  106. .Action((float d) => { UnityEngine.Camera.main.fieldOfView = d; })
  107. .Build();
  108. CommandBuilder.Builder()
  109. .Name("MoveLastBlock")
  110. .Description("Move the most-recently-placed block, and any connected blocks by the given offset")
  111. .Action((float x, float y, float z) =>
  112. {
  113. if (GameState.IsBuildMode())
  114. foreach (var block in Block.GetLastPlacedBlock().GetConnectedCubes())
  115. block.Position += new Unity.Mathematics.float3(x, y, z);
  116. else
  117. GamecraftModdingAPI.Utility.Logging.CommandLogError("Blocks can only be moved in Build mode!");
  118. }).Build();
  119. CommandBuilder.Builder()
  120. .Name("PlaceAluminium")
  121. .Description("Place a block of aluminium at the given coordinates")
  122. .Action(async (float x, float y, float z) =>
  123. {
  124. var block = await Block.PlaceNewAsync(BlockIDs.AluminiumCube, new float3(x, y, z));
  125. Logging.MetaDebugLog("Block placed with type: " + block.Type);
  126. })
  127. .Build();
  128. CommandBuilder.Builder("getBlock")
  129. .Action(() => uREPL.Log.Output(new Player(Players.PlayerType.Local).GetBlockLookedAt()+"")).Build();
  130. CommandBuilder.Builder("Error", "Throw an error to make sure SimpleCustomCommandEngine's wrapper catches it.")
  131. .Action(() => { throw new Exception("Error Command always throws an error"); })
  132. .Build();
  133. CommandBuilder.Builder("ColorBlock",
  134. "Change color of the block looked at if there's any.")
  135. .Action<string>(str =>
  136. {
  137. if (!Enum.TryParse(str, out BlockColors color))
  138. {
  139. Logging.CommandLog("Color " + str + " not found! Interpreting as 4 color values.");
  140. var s = str.Split(' ');
  141. new Player(PlayerType.Local).GetBlockLookedAt().CustomColor = new float4(float.Parse(s[0]),
  142. float.Parse(s[1]), float.Parse(s[2]), float.Parse(s[3]));
  143. return;
  144. }
  145. new Player(PlayerType.Local).GetBlockLookedAt().Color =
  146. new BlockColor {Color = color};
  147. Logging.CommandLog("Colored block to " + color);
  148. }).Build();
  149. GameClient.SetDebugInfo("lookedAt", LookedAt);
  150. /*
  151. CommandManager.AddCommand(new SimpleCustomCommandEngine<float>((float d) => { UnityEngine.Camera.main.fieldOfView = d; },
  152. "SetFOV", "Set the player camera's field of view"));
  153. CommandManager.AddCommand(new SimpleCustomCommandEngine<float, float, float>(
  154. (x, y, z) => {
  155. bool success = GamecraftModdingAPI.Blocks.Movement.MoveConnectedBlocks(
  156. GamecraftModdingAPI.Blocks.BlockIdentifiers.LatestBlockID,
  157. new Unity.Mathematics.float3(x, y, z));
  158. if (!success)
  159. {
  160. GamecraftModdingAPI.Utility.Logging.CommandLogError("Blocks can only be moved in Build mode!");
  161. }
  162. }, "MoveLastBlock", "Move the most-recently-placed block, and any connected blocks by the given offset"));
  163. CommandManager.AddCommand(new SimpleCustomCommandEngine<float, float, float>(
  164. (x, y, z) => { Blocks.Placement.PlaceBlock(Blocks.BlockIDs.AluminiumCube, new Unity.Mathematics.float3(x, y, z)); },
  165. "PlaceAluminium", "Place a block of aluminium at the given coordinates"));
  166. System.Random random = new System.Random(); // for command below
  167. CommandManager.AddCommand(new SimpleCustomCommandEngine(
  168. () => {
  169. if (!GameState.IsSimulationMode())
  170. {
  171. Logging.CommandLogError("You must be in simulation mode for this to work!");
  172. return;
  173. }
  174. Tasks.Repeatable task = new Tasks.Repeatable(() => {
  175. uint count = 0;
  176. EGID[] eBlocks = Blocks.Signals.GetElectricBlocks();
  177. for (uint i = 0u; i < eBlocks.Length; i++)
  178. {
  179. uint[] ids = Blocks.Signals.GetSignalIDs(eBlocks[i]);
  180. for (uint j = 0u; j < ids.Length; j++)
  181. {
  182. Blocks.Signals.SetSignalByID(ids[j], (float)random.NextDouble());
  183. count++;
  184. }
  185. }
  186. Logging.MetaDebugLog($"Did the thing on {count} inputs");
  187. },
  188. () => { return GameState.IsSimulationMode(); });
  189. Tasks.Scheduler.Schedule(task);
  190. }, "RandomizeSignalsInputs", "Do the thing"));
  191. */
  192. }
  193. // dependency test
  194. if (Dependency.Hell("GamecraftScripting", new Version("0.0.1.0")))
  195. {
  196. Logging.LogWarning("You're in GamecraftScripting dependency hell");
  197. }
  198. else
  199. {
  200. Logging.Log("Compatible GamecraftScripting detected");
  201. }
  202. }
  203. private Player player;
  204. private string LookedAt()
  205. {
  206. if (player == null)
  207. player = new Player(Players.PlayerType.Local);
  208. Block block = player.GetBlockLookedAt();
  209. if (block == null) return "Block: none";
  210. return "Block: " + block.Type + "\nColor: " + block.Color + "\n" + "At: " + block.Position;
  211. }
  212. public void OnFixedUpdate() { }
  213. public void OnLateUpdate() { }
  214. public void OnLevelWasInitialized(int level) { }
  215. public void OnLevelWasLoaded(int level) { }
  216. public void OnUpdate() { }
  217. [HarmonyPatch]
  218. public class MinimumSpecsPatch
  219. {
  220. public static bool Prefix(ref bool __result)
  221. {
  222. __result = true;
  223. return false;
  224. }
  225. public static MethodInfo TargetMethod()
  226. {
  227. return ((Func<bool>)MinimumSpecsCheck.CheckRequirementsMet).Method;
  228. }
  229. }
  230. }
  231. }