Chainloader.cs 5.4 KB

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