Chainloader.cs 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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. if (ConsoleWindow.StandardOut != null)
  49. Console.SetOut(ConsoleWindow.StandardOut);
  50. Logger.Listeners.Add(new UnityLogListener());
  51. if (!TraceLogSource.IsListening)
  52. Logger.Sources.Add(TraceLogSource.CreateSource());
  53. if (bool.Parse(Config.GetEntry("chainloader-log-unity-messages", "false", "BepInEx")))
  54. Logger.Sources.Add(new UnityLogSource());
  55. Logger.LogMessage("Chainloader ready");
  56. _initialized = true;
  57. }
  58. /// <summary>
  59. /// The entrypoint for the BepInEx plugin system.
  60. /// </summary>
  61. public static void Start()
  62. {
  63. if (_loaded)
  64. return;
  65. if (!_initialized)
  66. throw new InvalidOperationException("BepInEx has not been initialized. Please call Chainloader.Initialize prior to starting the chainloader instance.");
  67. if (!Directory.Exists(Paths.PluginPath))
  68. Directory.CreateDirectory(Paths.PluginPath);
  69. if (!Directory.Exists(Paths.PatcherPluginPath))
  70. Directory.CreateDirectory(Paths.PatcherPluginPath);
  71. try
  72. {
  73. var productNameProp = typeof(Application).GetProperty("productName", BindingFlags.Public | BindingFlags.Static);
  74. if (productNameProp != null)
  75. ConsoleWindow.Title =
  76. $"BepInEx {Assembly.GetExecutingAssembly().GetName().Version} - {productNameProp.GetValue(null, null)}";
  77. Logger.LogMessage("Chainloader started");
  78. ManagerObject = new GameObject("BepInEx_Manager");
  79. UnityEngine.Object.DontDestroyOnLoad(ManagerObject);
  80. string currentProcess = Process.GetCurrentProcess().ProcessName.ToLower();
  81. var globalPluginTypes = TypeLoader.LoadTypes<BaseUnityPlugin>(Paths.PluginPath).ToList();
  82. var selectedPluginTypes = globalPluginTypes
  83. .Where(plugin =>
  84. {
  85. //Ensure metadata exists
  86. var metadata = MetadataHelper.GetMetadata(plugin);
  87. if (metadata == null)
  88. {
  89. Logger.LogWarning($"Skipping over type [{plugin.Name}] as no metadata attribute is specified");
  90. return false;
  91. }
  92. //Perform a filter for currently running process
  93. var filters = MetadataHelper.GetAttributes<BepInProcess>(plugin);
  94. if (filters.Length == 0) //no filters means it loads everywhere
  95. return true;
  96. var result = filters.Any(x => x.ProcessName.ToLower().Replace(".exe", "") == currentProcess);
  97. if (!result)
  98. Logger.LogInfo($"Skipping over plugin [{metadata.GUID}] due to process filter");
  99. return result;
  100. })
  101. .ToList();
  102. Logger.LogInfo($"{selectedPluginTypes.Count} / {globalPluginTypes.Count} plugins to load");
  103. Dictionary<Type, IEnumerable<Type>> dependencyDict = new Dictionary<Type, IEnumerable<Type>>();
  104. foreach (Type t in selectedPluginTypes)
  105. {
  106. try
  107. {
  108. IEnumerable<Type> dependencies = MetadataHelper.GetDependencies(t, selectedPluginTypes);
  109. dependencyDict[t] = dependencies;
  110. }
  111. catch (MissingDependencyException)
  112. {
  113. var metadata = MetadataHelper.GetMetadata(t);
  114. Logger.LogWarning($"Cannot load [{metadata.Name}] due to missing dependencies.");
  115. }
  116. }
  117. var sortedTypes = Utility.TopologicalSort(dependencyDict.Keys, x => dependencyDict[x]).ToList();
  118. foreach (Type t in sortedTypes)
  119. {
  120. try
  121. {
  122. var metadata = MetadataHelper.GetMetadata(t);
  123. Logger.LogInfo($"Loading [{metadata.Name} {metadata.Version}]");
  124. var plugin = (BaseUnityPlugin)ManagerObject.AddComponent(t);
  125. Plugins.Add(plugin);
  126. }
  127. catch (Exception ex)
  128. {
  129. Logger.LogError($"Error loading [{t.Name}] : {ex.Message}");
  130. Logger.LogDebug(ex);
  131. }
  132. }
  133. }
  134. catch (Exception ex)
  135. {
  136. ConsoleWindow.Attach();
  137. Console.WriteLine("Error occurred starting the game");
  138. Console.WriteLine(ex.ToString());
  139. }
  140. Logger.LogMessage("Chainloader startup complete");
  141. _loaded = true;
  142. }
  143. }
  144. }