Chainloader.cs 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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.Text;
  8. using BepInEx.Logging;
  9. using UnityEngine;
  10. using UnityInjector.ConsoleUtil;
  11. namespace BepInEx.Bootstrap
  12. {
  13. /// <summary>
  14. /// The manager and loader for all plugins, and the entry point for BepInEx plugin system.
  15. /// </summary>
  16. public static class Chainloader
  17. {
  18. /// <summary>
  19. /// The loaded and initialized list of plugins.
  20. /// </summary>
  21. public static List<BaseUnityPlugin> Plugins { get; private set; } = new List<BaseUnityPlugin>();
  22. /// <summary>
  23. /// The GameObject that all plugins are attached to as components.
  24. /// </summary>
  25. public static GameObject ManagerObject { get; private set; }
  26. private static bool _loaded = false;
  27. private static bool _initialized = false;
  28. /// <summary>
  29. /// Initializes BepInEx to be able to start the chainloader.
  30. /// </summary>
  31. public static void Initialize(string containerExePath, bool startConsole = true)
  32. {
  33. if (_initialized)
  34. return;
  35. //Set vitals
  36. Paths.SetExecutablePath(containerExePath);
  37. Paths.SetPluginPath(Config.GetEntry("chainloader-plugins-directory", "plugins", "BepInEx"));
  38. //Start logging
  39. if (startConsole)
  40. {
  41. ConsoleWindow.Attach();
  42. ConsoleEncoding.ConsoleCodePage = (uint)Encoding.UTF8.CodePage;
  43. Console.OutputEncoding = Encoding.UTF8;
  44. Logger.Listeners.Add(new ConsoleLogListener());
  45. }
  46. //Fix for standard output getting overwritten by UnityLogger
  47. Console.SetOut(ConsoleWindow.StandardOut);
  48. Logger.Listeners.Add(new UnityLogListener());
  49. if (!TraceLogSource.IsListening)
  50. Logger.Sources.Add(TraceLogSource.CreateSource());
  51. if (bool.Parse(Config.GetEntry("chainloader-log-unity-messages", "false", "BepInEx")))
  52. Logger.Sources.Add(new UnityLogSource());
  53. Logger.Log(LogLevel.Message, "Chainloader ready");
  54. _initialized = true;
  55. }
  56. /// <summary>
  57. /// The entrypoint for the BepInEx plugin system.
  58. /// </summary>
  59. public static void Start()
  60. {
  61. if (_loaded)
  62. return;
  63. if (!_initialized)
  64. throw new InvalidOperationException("BepInEx has not been initialized. Please call Chainloader.Initialize prior to starting the chainloader instance.");
  65. if (!Directory.Exists(Paths.PluginPath))
  66. Directory.CreateDirectory(Paths.PluginPath);
  67. if (!Directory.Exists(Paths.PatcherPluginPath))
  68. Directory.CreateDirectory(Paths.PatcherPluginPath);
  69. try
  70. {
  71. var productNameProp = typeof(Application).GetProperty("productName", BindingFlags.Public | BindingFlags.Static);
  72. if (productNameProp != null)
  73. ConsoleWindow.Title =
  74. $"BepInEx {Assembly.GetExecutingAssembly().GetName().Version} - {productNameProp.GetValue(null, null)}";
  75. Logger.Log(LogLevel.Message, "Chainloader started");
  76. ManagerObject = new GameObject("BepInEx_Manager");
  77. UnityEngine.Object.DontDestroyOnLoad(ManagerObject);
  78. string currentProcess = Process.GetCurrentProcess().ProcessName.ToLower();
  79. var pluginTypes = TypeLoader.LoadTypes<BaseUnityPlugin>(Paths.PluginPath)
  80. .Where(plugin =>
  81. {
  82. //Perform a filter for currently running process
  83. var filters = MetadataHelper.GetAttributes<BepInProcess>(plugin);
  84. if (!filters.Any())
  85. return true;
  86. return filters.Any(x => x.ProcessName.ToLower().Replace(".exe", "") == currentProcess);
  87. })
  88. .ToList();
  89. Logger.Log(LogLevel.Info, $"{pluginTypes.Count} plugins selected");
  90. Dictionary<Type, IEnumerable<Type>> dependencyDict = new Dictionary<Type, IEnumerable<Type>>();
  91. foreach (Type t in pluginTypes)
  92. {
  93. try
  94. {
  95. IEnumerable<Type> dependencies = MetadataHelper.GetDependencies(t, pluginTypes);
  96. dependencyDict[t] = dependencies;
  97. }
  98. catch (MissingDependencyException)
  99. {
  100. var metadata = MetadataHelper.GetMetadata(t);
  101. Logger.Log(LogLevel.Info, $"Cannot load [{metadata.Name}] due to missing dependencies.");
  102. }
  103. }
  104. pluginTypes = Utility.TopologicalSort(dependencyDict.Keys, x => dependencyDict[x]).ToList();
  105. foreach (Type t in pluginTypes)
  106. {
  107. try
  108. {
  109. var metadata = MetadataHelper.GetMetadata(t);
  110. var plugin = (BaseUnityPlugin)ManagerObject.AddComponent(t);
  111. Plugins.Add(plugin);
  112. Logger.Log(LogLevel.Info, $"Loaded [{metadata.Name} {metadata.Version}]");
  113. }
  114. catch (Exception ex)
  115. {
  116. Logger.Log(LogLevel.Info, $"Error loading [{t.Name}] : {ex.Message}");
  117. }
  118. }
  119. }
  120. catch (Exception ex)
  121. {
  122. ConsoleWindow.Attach();
  123. Console.WriteLine("Error occurred starting the game");
  124. Console.WriteLine(ex.ToString());
  125. }
  126. _loaded = true;
  127. }
  128. }
  129. }