Chainloader.cs 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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.LogMessage("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.LogMessage("Chainloader started");
  76. ManagerObject = new GameObject("BepInEx_Manager");
  77. UnityEngine.Object.DontDestroyOnLoad(ManagerObject);
  78. string currentProcess = Process.GetCurrentProcess().ProcessName.ToLower();
  79. var globalPluginTypes = TypeLoader.LoadTypes<BaseUnityPlugin>(Paths.PluginPath).ToList();
  80. var selectedPluginTypes = globalPluginTypes
  81. .Where(plugin =>
  82. {
  83. //Ensure metadata exists
  84. var metadata = MetadataHelper.GetMetadata(plugin);
  85. if (metadata == null)
  86. {
  87. Logger.LogWarning($"Skipping over type [{plugin.Name}] as no metadata attribute is specified");
  88. return false;
  89. }
  90. //Perform a filter for currently running process
  91. var filters = MetadataHelper.GetAttributes<BepInProcess>(plugin);
  92. if (filters.Length == 0) //no filters means it loads everywhere
  93. return true;
  94. var result = filters.Any(x => x.ProcessName.ToLower().Replace(".exe", "") == currentProcess);
  95. if (!result)
  96. Logger.LogInfo($"Skipping over plugin [{metadata.GUID}] due to process filter");
  97. return result;
  98. })
  99. .ToList();
  100. Logger.LogInfo($"{selectedPluginTypes.Count} / {globalPluginTypes.Count} plugins to load");
  101. Dictionary<Type, IEnumerable<Type>> dependencyDict = new Dictionary<Type, IEnumerable<Type>>();
  102. foreach (Type t in selectedPluginTypes)
  103. {
  104. try
  105. {
  106. IEnumerable<Type> dependencies = MetadataHelper.GetDependencies(t, selectedPluginTypes);
  107. dependencyDict[t] = dependencies;
  108. }
  109. catch (MissingDependencyException)
  110. {
  111. var metadata = MetadataHelper.GetMetadata(t);
  112. Logger.LogWarning($"Cannot load [{metadata.Name}] due to missing dependencies.");
  113. }
  114. }
  115. var sortedTypes = Utility.TopologicalSort(dependencyDict.Keys, x => dependencyDict[x]).ToList();
  116. foreach (Type t in sortedTypes)
  117. {
  118. try
  119. {
  120. var metadata = MetadataHelper.GetMetadata(t);
  121. Logger.LogInfo($"Loading [{metadata.Name} {metadata.Version}]");
  122. var plugin = (BaseUnityPlugin)ManagerObject.AddComponent(t);
  123. Plugins.Add(plugin);
  124. }
  125. catch (Exception ex)
  126. {
  127. Logger.LogError($"Error loading [{t.Name}] : {ex.Message}");
  128. Logger.LogDebug(ex);
  129. }
  130. }
  131. }
  132. catch (Exception ex)
  133. {
  134. ConsoleWindow.Attach();
  135. Console.WriteLine("Error occurred starting the game");
  136. Console.WriteLine(ex.ToString());
  137. }
  138. Logger.LogMessage("Chainloader startup complete");
  139. _loaded = true;
  140. }
  141. }
  142. }