浏览代码

Load a GameObject as a hook

Bepis 7 年之前
父节点
当前提交
02e8772de6

+ 6 - 32
BepInEx.Patcher/Program.cs

@@ -43,11 +43,11 @@ namespace BepInEx.Patcher
             IPatchPlugin exitScene = new ExitScenePlugin();
             exitScene.Patch(assembly);
 
-            IPatchPlugin slider = new SliderPlugin();
-            slider.Patch(assembly);
+            //IPatchPlugin slider = new SliderPlugin();
+            //slider.Patch(assembly);
 
-            IPatchPlugin title = new TitleScenePlugin();
-            title.Patch(assembly);
+            //IPatchPlugin title = new TitleScenePlugin();
+            //title.Patch(assembly);
 
 
             InjectAssembly(assembly, unity, injected);
@@ -59,10 +59,7 @@ namespace BepInEx.Patcher
 
         static void InjectAssembly(AssemblyDefinition assembly, AssemblyDefinition unity, AssemblyDefinition injected)
         {
-            ILProcessor IL;
-
-            //Initialize
-            var originalInjectMethod = injected.MainModule.Types.First(x => x.Name == "Target").Methods.First(x => x.Name == "Initialize");
+            var originalInjectMethod = injected.MainModule.Types.First(x => x.Name == "Chainloader").Methods.First(x => x.Name == "Initialize");
 
             var injectMethod = unity.MainModule.Import(originalInjectMethod);
 
@@ -70,33 +67,10 @@ namespace BepInEx.Patcher
 
             foreach (var loadScene in sceneManager.Methods.Where(x => x.Name == "LoadScene"))
             {
-                IL = loadScene.Body.GetILProcessor();
+                ILProcessor IL = loadScene.Body.GetILProcessor();
 
                 IL.InsertBefore(loadScene.Body.Instructions[0], IL.Create(OpCodes.Call, injectMethod));
             }
-
-
-            //CustomInitializer
-            originalInjectMethod = injected.MainModule.Types.First(x => x.Name == "Target").Methods.First(x => x.Name == "InitializeCustomBase");
-
-            injectMethod = assembly.MainModule.Import(originalInjectMethod);
-
-            var customControl = assembly.MainModule.Types.First(x => x.Name == "CustomControl");
-
-            var customInitialize = customControl.Methods.First(x => x.Name == "Initialize");
-
-            IL = customInitialize.Body.GetILProcessor();
-
-            //IL.Replace(customInitialize.Body.Instructions[169], IL.Create(OpCodes.Call, customControl.Properties[4].GetMethod));
-            //IL.Append(IL.Create(OpCodes.Call, injectMethod));
-
-            IL.Replace(customInitialize.Body.Instructions[169], IL.Create(OpCodes.Call, injectMethod));
-
-            customInitialize.Body.Instructions[169].Offset = 0x01f0;
-
-            IL.Append(IL.Create(OpCodes.Ret));
-
-            //injected.MainModule.Import(assembly.MainModule.Types.First(x => x.Name == "CustomBase"));
         }
     }
 }

+ 57 - 0
BepInEx/BepInComponent.cs

@@ -0,0 +1,57 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using UnityEngine;
+
+namespace BepInEx
+{
+    //Adapted from https://github.com/Eusth/IPA/blob/0df8b1ecb87fdfc9e169365cb4a8fd5a909a2ad6/IllusionInjector/PluginComponent.cs
+    public class BepInComponent : MonoBehaviour
+    {
+        private bool quitting = false;
+
+        public static BepInComponent Create()
+        {
+            return new GameObject("BepInEx_Manager").AddComponent<BepInComponent>();
+        }
+
+        void Awake()
+        {
+            DontDestroyOnLoad(gameObject);
+        }
+
+        void Start()
+        {
+            Console.WriteLine("Component ready");
+        }
+
+        void Update()
+        {
+            //Console.WriteLine("Update");
+        }
+
+        void LateUpdate()
+        {
+            
+        }
+
+        void FixedUpdate()
+        {
+            
+        }
+
+        void OnDestroy()
+        {
+            if (!quitting)
+            {
+                Create();
+            }
+        }
+
+        void OnApplicationQuit()
+        {
+            quitting = true;
+        }
+    }
+}

+ 9 - 1
BepInEx/BepInEx.csproj

@@ -57,7 +57,15 @@
     </Reference>
   </ItemGroup>
   <ItemGroup>
-    <Compile Include="Target.cs" />
+    <Compile Include="BepInComponent.cs" />
+    <Compile Include="ConsoleUtil\ConsoleEncoding\ConsoleEncoding.Buffers.cs" />
+    <Compile Include="ConsoleUtil\ConsoleEncoding\ConsoleEncoding.cs" />
+    <Compile Include="ConsoleUtil\ConsoleEncoding\ConsoleEncoding.PInvoke.cs" />
+    <Compile Include="ConsoleUtil\ConsoleMirror.cs" />
+    <Compile Include="ConsoleUtil\ConsoleWindow.cs" />
+    <Compile Include="ConsoleUtil\Extensions.cs" />
+    <Compile Include="ConsoleUtil\SafeConsole.cs" />
+    <Compile Include="Chainloader.cs" />
     <Compile Include="Properties\AssemblyInfo.cs" />
   </ItemGroup>
   <ItemGroup>

+ 26 - 0
BepInEx/Chainloader.cs

@@ -0,0 +1,26 @@
+using ChaCustom;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace BepInEx
+{
+    public class Chainloader
+    {
+        static bool loaded = false;
+
+        public static void Initialize()
+        {
+            if (loaded)
+                return;
+
+            UnityInjector.ConsoleUtil.ConsoleWindow.Attach();
+            Console.WriteLine("Chainloader started");
+            
+            BepInComponent.Create();
+
+            loaded = true;
+        }
+    }
+}

+ 61 - 0
BepInEx/ConsoleUtil/ConsoleEncoding/ConsoleEncoding.Buffers.cs

@@ -0,0 +1,61 @@
+// --------------------------------------------------
+// UnityInjector - ConsoleEncoding.Buffers.cs
+// Copyright (c) Usagirei 2015 - 2015
+// --------------------------------------------------
+
+namespace UnityInjector.ConsoleUtil
+{
+    // --------------------------------------------------
+    // Code ported from
+    // https://gist.github.com/asm256/9bfb88336a1433e2328a
+    // Which in turn was seemingly ported from
+    // http://jonskeet.uk/csharp/ebcdic/
+    // using only safe (managed) code
+    // --------------------------------------------------
+
+    partial class ConsoleEncoding
+    {
+        private byte[] _byteBuffer = new byte[256];
+        private char[] _charBuffer = new char[256];
+        private byte[] _zeroByte = new byte[0];
+        private char[] _zeroChar = new char[0];
+
+        private void ExpandByteBuffer(int count)
+        {
+            if (_byteBuffer.Length < count)
+                _byteBuffer = new byte[count];
+        }
+
+        private void ExpandCharBuffer(int count)
+        {
+            if (_charBuffer.Length < count)
+                _charBuffer = new char[count];
+        }
+
+        private void ReadByteBuffer(byte[] bytes, int index, int count)
+        {
+            for (int i = 0; i < count; i++)
+                bytes[index + i] = _byteBuffer[i];
+        }
+
+        private void ReadCharBuffer(char[] chars, int index, int count)
+        {
+            for (int i = 0; i < count; i++)
+                chars[index + i] = _charBuffer[i];
+        }
+
+        private void WriteByteBuffer(byte[] bytes, int index, int count)
+        {
+            ExpandByteBuffer(count);
+            for (int i = 0; i < count; i++)
+                _byteBuffer[i] = bytes[index + i];
+        }
+
+        private void WriteCharBuffer(char[] chars, int index, int count)
+        {
+            ExpandCharBuffer(count);
+            for (int i = 0; i < count; i++)
+                _charBuffer[i] = chars[index + i];
+        }
+    }
+}

+ 49 - 0
BepInEx/ConsoleUtil/ConsoleEncoding/ConsoleEncoding.PInvoke.cs

@@ -0,0 +1,49 @@
+// --------------------------------------------------
+// UnityInjector - ConsoleEncoding.PInvoke.cs
+// Copyright (c) Usagirei 2015 - 2015
+// --------------------------------------------------
+
+using System;
+using System.Runtime.InteropServices;
+
+namespace UnityInjector.ConsoleUtil
+{
+    // --------------------------------------------------
+    // Code ported from
+    // https://gist.github.com/asm256/9bfb88336a1433e2328a
+    // Which in turn was seemingly ported from
+    // http://jonskeet.uk/csharp/ebcdic/
+    // using only safe (managed) code
+    // --------------------------------------------------
+    partial class ConsoleEncoding
+    {
+        [DllImport("kernel32.dll")]
+        private static extern uint GetConsoleOutputCP();
+
+        [DllImport("kernel32.dll")]
+        private static extern uint GetACP();
+
+        [DllImport("kernel32.dll", SetLastError = true)]
+        private static extern int MultiByteToWideChar(
+            uint codePage,
+            uint dwFlags,
+            [In, MarshalAs(UnmanagedType.LPArray)] byte[] lpMultiByteStr,
+            int cbMultiByte,
+            [Out, MarshalAs(UnmanagedType.LPArray)] char[] lpWideCharStr,
+            int cchWideChar);
+
+        [DllImport("kernel32.dll")]
+        private static extern IntPtr SetConsoleOutputCP(uint codepage);
+
+        [DllImport("kernel32.dll", SetLastError = true)]
+        private static extern int WideCharToMultiByte(
+            uint codePage,
+            uint dwFlags,
+            [In, MarshalAs(UnmanagedType.LPArray)] char[] lpWideCharStr,
+            int cchWideChar,
+            [Out, MarshalAs(UnmanagedType.LPArray)] byte[] lpMultiByteStr,
+            int cbMultiByte,
+            IntPtr lpDefaultChar,
+            IntPtr lpUsedDefaultChar);
+    }
+}

+ 87 - 0
BepInEx/ConsoleUtil/ConsoleEncoding/ConsoleEncoding.cs

@@ -0,0 +1,87 @@
+// --------------------------------------------------
+// UnityInjector - ConsoleEncoding.cs
+// Copyright (c) Usagirei 2015 - 2015
+// --------------------------------------------------
+
+using System;
+using System.Text;
+
+namespace UnityInjector.ConsoleUtil
+{
+    // --------------------------------------------------
+    // Code ported from
+    // https://gist.github.com/asm256/9bfb88336a1433e2328a
+    // Which in turn was seemingly ported from
+    // http://jonskeet.uk/csharp/ebcdic/
+    // using only safe (managed) code
+    // --------------------------------------------------
+    internal partial class ConsoleEncoding : Encoding
+    {
+        private readonly uint _codePage;
+        public override int CodePage => (int) _codePage;
+
+        public static uint ConsoleCodePage
+        {
+            get { return GetConsoleOutputCP(); }
+            set { SetConsoleOutputCP(value); }
+        }
+
+        public static uint GetActiveCodePage()
+        {
+            return GetACP();
+        }
+
+        private ConsoleEncoding(uint codePage)
+        {
+            _codePage = codePage;
+        }
+
+        public static ConsoleEncoding GetEncoding(uint codePage)
+        {
+            return new ConsoleEncoding(codePage);
+        }
+
+        public override int GetByteCount(char[] chars, int index, int count)
+        {
+            WriteCharBuffer(chars, index, count);
+            int result = WideCharToMultiByte(_codePage, 0, _charBuffer, count, _zeroByte, 0, IntPtr.Zero, IntPtr.Zero);
+            return result;
+        }
+
+        public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
+        {
+            var byteCount = GetMaxByteCount(charCount);
+
+            WriteCharBuffer(chars, charIndex, charCount);
+
+            ExpandByteBuffer(byteCount);
+            int result = WideCharToMultiByte(_codePage, 0, chars, charCount, _byteBuffer, byteCount, IntPtr.Zero, IntPtr.Zero);
+            ReadByteBuffer(bytes, byteIndex, byteCount);
+
+            return result;
+        }
+
+        public override int GetCharCount(byte[] bytes, int index, int count)
+        {
+            WriteByteBuffer(bytes, index, count);
+            int result = MultiByteToWideChar(_codePage, 0, bytes, count, _zeroChar, 0);
+            return result;
+        }
+
+        public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
+        {
+            var charCount = GetMaxCharCount(byteCount);
+
+            WriteByteBuffer(bytes, byteIndex, byteCount);
+
+            ExpandCharBuffer(charCount);
+            int result = MultiByteToWideChar(_codePage, 0, bytes, byteCount, _charBuffer, charCount);
+            ReadCharBuffer(chars, charIndex, charCount);
+
+            return result;
+        }
+
+        public override int GetMaxByteCount(int charCount) => charCount * 2;
+        public override int GetMaxCharCount(int byteCount) => byteCount;
+    }
+}

+ 84 - 0
BepInEx/ConsoleUtil/ConsoleMirror.cs

@@ -0,0 +1,84 @@
+// --------------------------------------------------
+// UnityInjector - ConsoleMirror.cs
+// Copyright (c) Usagirei 2015 - 2015
+// --------------------------------------------------
+
+using System;
+using System.Diagnostics;
+using System.IO;
+using System.Text;
+
+namespace UnityInjector.ConsoleUtil
+{
+    internal class ConsoleMirror : IDisposable
+    {
+        private readonly MirrorWriter _tWriter;
+
+        public ConsoleMirror(string path)
+        {
+            try
+            {
+                var fileStream = File.Open(path, FileMode.Append, FileAccess.Write, FileShare.Read);
+                var fileWriter = new StreamWriter(fileStream)
+                {
+                    AutoFlush = true
+                };
+                _tWriter = new MirrorWriter(fileWriter, Console.Out);
+            }
+            catch (Exception e)
+            {
+                SafeConsole.ForegroundColor = ConsoleColor.DarkGray;
+                Console.WriteLine("Couldn't open file to write: {0}", Path.GetFileName(path));
+                Console.WriteLine(e.Message);
+                SafeConsole.ForegroundColor = ConsoleColor.Gray;
+
+                return;
+            }
+            Console.SetOut(_tWriter);
+
+            Console.WriteLine();
+
+            var processName = Process.GetCurrentProcess().ProcessName;
+            var now = DateTime.Now;
+
+            Console.WriteLine($" {processName} - {now:dd-MM-yyyy hh:mm:ss} ".PadCenter(79, '='));
+            Console.WriteLine();
+        }
+
+        public void Dispose()
+        {
+            var cOld = _tWriter.Console;
+            var fOld = _tWriter.File;
+            Console.SetOut(cOld);
+            if (fOld == null)
+                return;
+            fOld.Flush();
+            fOld.Close();
+        }
+
+        private class MirrorWriter : TextWriter
+        {
+            public TextWriter Console { get; }
+            public override Encoding Encoding => File.Encoding;
+            public TextWriter File { get; }
+
+            public MirrorWriter(TextWriter file, TextWriter console)
+            {
+                File = file;
+                Console = console;
+            }
+
+            public override void Flush()
+            {
+                File.Flush();
+                Console.Flush();
+            }
+
+            public override void Write(char value)
+            {
+                File.Write(value);
+                Console.Write(value);
+            }
+        }
+    }
+}

+ 101 - 0
BepInEx/ConsoleUtil/ConsoleWindow.cs

@@ -0,0 +1,101 @@
+// --------------------------------------------------
+// UnityInjector - ConsoleWindow.cs
+// Copyright (c) Usagirei 2015 - 2015
+// --------------------------------------------------
+
+using System;
+using System.IO;
+using System.Runtime.InteropServices;
+using System.Text;
+
+namespace UnityInjector.ConsoleUtil
+{
+    internal class ConsoleWindow
+    {
+        private static bool _attached;
+        private static IntPtr _cOut;
+        private static IntPtr _oOut;
+
+        public static void Attach()
+        {
+            if (_attached)
+                return;
+            if (_oOut == IntPtr.Zero)
+                _oOut = GetStdHandle(-11);
+
+            // Store Current Window
+            IntPtr currWnd = GetForegroundWindow();
+
+            if (!AllocConsole())
+                throw new Exception("AllocConsole() failed");
+
+            // Restore Foreground
+            SetForegroundWindow(currWnd);
+
+            _cOut = CreateFile("CONOUT$", 0x40000000, 2, IntPtr.Zero, 3, 0, IntPtr.Zero);
+            if (!SetStdHandle(-11, _cOut))
+                throw new Exception("SetStdHandle() failed");
+            Init();
+            _attached = true;
+        }
+
+        public static void Detach()
+        {
+            if (!_attached)
+                return;
+            if (!CloseHandle(_cOut))
+                throw new Exception("CloseHandle() failed");
+            _cOut = IntPtr.Zero;
+            if (!FreeConsole())
+                throw new Exception("FreeConsole() failed");
+            if (!SetStdHandle(-11, _oOut))
+                throw new Exception("SetStdHandle() failed");
+            Init();
+            _attached = false;
+            
+        }
+
+        [DllImport("user32.dll")]
+        private static extern IntPtr GetForegroundWindow();
+
+        [DllImport("user32.dll")]
+        [return: MarshalAs(UnmanagedType.Bool)]
+        static extern bool SetForegroundWindow(IntPtr hWnd);
+
+        [DllImport("kernel32.dll", SetLastError = true)]
+        private static extern bool AllocConsole();
+
+        [DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)]
+        private static extern bool CloseHandle(IntPtr handle);
+
+        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
+        private static extern IntPtr CreateFile(
+            string fileName,
+            int desiredAccess,
+            int shareMode,
+            IntPtr securityAttributes,
+            int creationDisposition,
+            int flagsAndAttributes,
+            IntPtr templateFile);
+
+        [DllImport("kernel32.dll", SetLastError = false)]
+        private static extern bool FreeConsole();
+
+        [DllImport("kernel32.dll", SetLastError = true)]
+        private static extern IntPtr GetStdHandle(int nStdHandle);
+
+        private static void Init()
+        {
+            var stdOut = Console.OpenStandardOutput();
+            var stdWriter = new StreamWriter(stdOut, Encoding.Default)
+            {
+                AutoFlush = true
+            };
+            Console.SetOut(stdWriter);
+            Console.SetError(stdWriter);
+        }
+
+        [DllImport("kernel32.dll", SetLastError = true)]
+        private static extern bool SetStdHandle(int nStdHandle, IntPtr hConsoleOutput);
+    }
+}

+ 34 - 0
BepInEx/ConsoleUtil/Extensions.cs

@@ -0,0 +1,34 @@
+// --------------------------------------------------
+// UnityInjector - Extensions.cs
+// Copyright (c) Usagirei 2015 - 2015
+// --------------------------------------------------
+
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Text.RegularExpressions;
+
+namespace UnityInjector
+{
+    internal static class Extensions
+    {
+        public static string PluginsPath { get; } = Path.Combine(Environment.CurrentDirectory, "UnityInjector");
+        public static string UserDataPath { get; } = Path.Combine(PluginsPath, "Config");
+        public static string Asciify(this string s) => Regex.Replace(s, @"[^0-9A-Za-z]", "_");
+        public static string CombinePaths(params string[] parts) => parts.Aggregate(Path.Combine);
+
+        public static void ForEach<T>(this IEnumerable<T> tees, Action<T> action)
+        {
+            foreach (var tee in tees)
+                action(tee);
+        }
+
+        public static string PadCenter(this string str, int totalWidth, char paddingChar = ' ')
+        {
+            int spaces = totalWidth - str.Length;
+            int padLeft = spaces / 2 + str.Length;
+            return str.PadLeft(padLeft, paddingChar).PadRight(totalWidth, paddingChar);
+        }
+    }
+}

+ 66 - 0
BepInEx/ConsoleUtil/SafeConsole.cs

@@ -0,0 +1,66 @@
+// --------------------------------------------------
+// UnityInjector - SafeConsole.cs
+// Copyright (c) Usagirei 2015 - 2015
+// --------------------------------------------------
+
+using System;
+using System.Reflection;
+
+namespace UnityInjector.ConsoleUtil
+{
+    public static class SafeConsole
+    {
+        private static GetColorDelegate _getBackgroundColor;
+        private static GetColorDelegate _getForegroundColor;
+        private static SetColorDelegate _setBackgroundColor;
+        private static SetColorDelegate _setForegroundColor;
+
+        public static ConsoleColor BackgroundColor
+        {
+            get { return _getBackgroundColor(); }
+            set { _setBackgroundColor(value); }
+        }
+
+        public static ConsoleColor ForegroundColor
+        {
+            get { return _getForegroundColor(); }
+            set { _setForegroundColor(value); }
+        }
+
+        static SafeConsole()
+        {
+            var tConsole = typeof(Console);
+            InitColors(tConsole);
+        }
+
+        private static void InitColors(Type tConsole)
+        {
+            const BindingFlags BINDING_FLAGS = BindingFlags.Public | BindingFlags.Static;
+
+            var sfc = tConsole.GetMethod("set_ForegroundColor", BINDING_FLAGS);
+            var sbc = tConsole.GetMethod("set_BackgroundColor", BINDING_FLAGS);
+            var gfc = tConsole.GetMethod("get_ForegroundColor", BINDING_FLAGS);
+            var gbc = tConsole.GetMethod("get_BackgroundColor", BINDING_FLAGS);
+
+            _setForegroundColor = sfc != null
+                                      ? (SetColorDelegate) Delegate.CreateDelegate(typeof(SetColorDelegate), sfc)
+                                      : (value => {});
+
+            _setBackgroundColor = sbc != null
+                                      ? (SetColorDelegate) Delegate.CreateDelegate(typeof(SetColorDelegate), sbc)
+                                      : (value => {});
+
+            _getForegroundColor = gfc != null
+                                      ? (GetColorDelegate) Delegate.CreateDelegate(typeof(GetColorDelegate), gfc)
+                                      : (() => ConsoleColor.Gray);
+
+            _getBackgroundColor = gbc != null
+                                      ? (GetColorDelegate) Delegate.CreateDelegate(typeof(GetColorDelegate), gbc)
+                                      : (() => ConsoleColor.Black);
+        }
+
+        private delegate ConsoleColor GetColorDelegate();
+
+        private delegate void SetColorDelegate(ConsoleColor value);
+    }
+}

+ 0 - 38
BepInEx/Target.cs

@@ -1,38 +0,0 @@
-using ChaCustom;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-
-namespace BepInEx
-{
-    public class Target
-    {
-        static bool loaded = false;
-
-        public static void Initialize()
-        {
-            if (loaded)
-                return;
-
-            UnityEngine.Debug.logger.Log("inject: Loaded!!!");
-
-
-
-            loaded = true;
-        }
-
-        public static void InitializeCustomBase() //CustomBase customBase
-        {
-            UnityEngine.Debug.logger.Log("inject: CustomBase loaded!!!");
-
-            CustomBase customBase = Singleton<CustomBase>.Instance;
-
-            foreach (var entry in customBase.lstSelectList)
-            {
-                UnityEngine.Debug.Log(entry.list[2]);
-                entry.list[2] = "TL TEST TL TEST";
-            }
-        }
-    }
-}