Esempio n. 1
0
        /// <summary>
        /// Prints information about ModLoader in MainMenu scene.
        /// </summary>
        private static void MainMenuInfo()
        {
            Text info, mf, modUpdates;

            mainMenuInfo      = Instantiate(mainMenuInfo);
            mainMenuInfo.name = "MSCLoader Info";
            menuInfoAnim      = mainMenuInfo.GetComponent <Animator>();
            menuInfoAnim.SetBool("isHidden", false);
            info       = mainMenuInfo.transform.GetChild(0).gameObject.GetComponent <Text>();
            mf         = mainMenuInfo.transform.GetChild(1).gameObject.GetComponent <Text>();
            modUpdates = mainMenuInfo.transform.GetChild(2).gameObject.GetComponent <Text>();

            //check if new version is available
            if (!experimental)
            {
                try
                {
                    string version;
                    using (WebClient client = new WebClient())
                    {
                        client.QueryString.Add("core", "stable");
                        version = client.DownloadString("http://my-summer-car.ml/ver.php");
                    }
                    if (version.Trim().Length > 8)
                    {
                        throw new Exception("Parse Error, please report that problem!");
                    }
                    int i = Version.CompareTo(version.Trim());
                    if (i != 0)
                    {
                        info.text = string.Format("Mod Loader MSCLoader v{0} is ready! (<color=orange>New version available: <b>v{1}</b></color>)", Version, version.Trim());
                    }
                    else if (i == 0)
                    {
                        info.text = string.Format("Mod Loader MSCLoader v{0} is ready! (<color=lime>Up to date</color>)", Version);
                    }
                    if (devMode)
                    {
                        info.text = info.text + " [<color=red><b>Dev Mode!</b></color>]";
                    }
                }
                catch (Exception e)
                {
                    ModConsole.Error(string.Format("Check for new version failed with error: {0}", e.Message));
                    if (devMode)
                    {
                        ModConsole.Error(e.ToString());
                    }
                    UnityEngine.Debug.Log(e);
                    info.text = string.Format("Mod Loader MSCLoader v{0} is ready!", Version);
                }
            }
            else
            {
                info.text = string.Format("Mod Loader MSCLoader v{0} is ready! (<color=magenta>Experimental</color>)", Version);
            }
            mf.text = string.Format("Mods folder: {0}", ModsFolder);
            if (isModUpdates)
            {
                modUpdates.text = string.Format("<color=lime><b>{0}</b></color> <color=orange>mods has a new version available!</color>", numOfUpdates);
            }
            else
            {
                modUpdates.text = string.Empty;
            }
            mainMenuInfo.transform.SetParent(GameObject.Find("MSCLoader Canvas").transform, false);
        }
Esempio n. 2
0
        private void LoadDLL(string file)
        {
            try
            {
                Assembly asm   = Assembly.LoadFrom(file);
                bool     isMod = false;

                AssemblyName[] list = asm.GetReferencedAssemblies();
                if (File.ReadAllText(file).Contains("RegistryKey"))
                {
                    throw new FileLoadException();
                }
                // Look through all public classes
                foreach (Type type in asm.GetTypes())
                {
                    string msVer = null;
                    if (typeof(Mod).IsAssignableFrom(type))
                    {
                        for (int i = 0; i < list.Length; i++)
                        {
                            if (list[i].Name == "Assembly-CSharp-firstpass")
                            {
                                throw new Exception("Targeting forbidden reference");
                            }
                            if (list[i].Name == "MSCLoader")
                            {
                                string[] verparse = list[i].Version.ToString().Split('.');
                                if (list[i].Version.ToString() == "1.0.0.0")
                                {
                                    msVer = "0.1";
                                }
                                else
                                {
                                    if (verparse[2] == "0")
                                    {
                                        msVer = string.Format("{0}.{1}", verparse[0], verparse[1]);
                                    }
                                    else
                                    {
                                        msVer = string.Format("{0}.{1}.{2}", verparse[0], verparse[1], verparse[2]);
                                    }
                                }
                            }
                        }
                        isMod = true;
                        LoadMod((Mod)Activator.CreateInstance(type), msVer);
                        break;
                    }
                    else
                    {
                        isMod = false;
                    }
                }
                if (!isMod)
                {
                    ModConsole.Error(string.Format("<b>{0}</b> - doesn't look like a mod or missing Mod subclass!", Path.GetFileName(file)));
                    InvalidMods.Add(Path.GetFileName(file));
                }
            }
            catch (Exception e)
            {
                ModConsole.Error(string.Format("<b>{0}</b> - doesn't look like a mod, remove this file from mods folder!", Path.GetFileName(file)));
                if (devMode)
                {
                    ModConsole.Error(e.ToString());
                }
                UnityEngine.Debug.Log(e);
                InvalidMods.Add(Path.GetFileName(file));
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Main function to initialize the ModLoader
        /// </summary>
        public static void Init()
        {
            //Set config and Assets folder in selected mods folder
            ConfigFolder = Path.Combine(ModsFolder, @"Config\");
            AssetsFolder = Path.Combine(ModsFolder, @"Assets\");
            //if mods not loaded and game is loaded.
            if (GameObject.Find("MSCUnloader") == null)
            {
                GameObject go = new GameObject();
                go.name = "MSCUnloader";
                go.AddComponent <MSCUnloader>();
                MSCUnloaderInstance = go.GetComponent <MSCUnloader>();
                DontDestroyOnLoad(go);
            }
            if (IsModsDoneLoading && Application.loadedLevelName == "MainMenu")
            {
                MSCUnloaderInstance.reset = false;
                MSCUnloaderInstance.MSCLoaderReset();
            }
            if (!IsModsDoneLoading && Application.loadedLevelName == "GAME" && fullyLoaded && !IsModsLoading)
            {
                // Load all mods
                IsModsLoading = true;
                Instance.StartCoroutine(Instance.LoadMods());
            }

            if (IsDoneLoading && Application.loadedLevelName == "MainMenu" && GameObject.Find("MSCLoader Info") == null)
            {
                MainMenuInfo();
            }

            if (IsDoneLoading || Instance)
            {
                if (Application.loadedLevelName != "MainMenu")
                {
                    menuInfoAnim.SetBool("isHidden", true);
                }
            }
            else
            {
                // Create game object and attach self
                GameObject go = new GameObject();
                go.name = "MSCModLoader";
                go.AddComponent <ModLoader>();
                go.AddComponent <LoadAssets>();
                Instance   = go.GetComponent <ModLoader>();
                loadAssets = go.GetComponent <LoadAssets>();
                DontDestroyOnLoad(go);

                // Init variables
                ModUI.CreateCanvas();
                IsDoneLoading     = false;
                IsModsDoneLoading = false;
                LoadedMods        = new List <Mod>();
                InvalidMods       = new List <string>();

                // Init mod loader settings
                if (!Directory.Exists(ModsFolder))
                {
                    //if mods folder not exists, create it.
                    Directory.CreateDirectory(ModsFolder);
                }

                if (!Directory.Exists(ConfigFolder))
                {
                    //if config folder not exists, create it.
                    Directory.CreateDirectory(ConfigFolder);
                }

                if (!Directory.Exists(AssetsFolder))
                {
                    //if config folder not exists, create it.
                    Directory.CreateDirectory(AssetsFolder);
                }
                // Loading internal tools (console and settings)
                LoadMod(new ModConsole(), Version);
                LoadedMods[0].ModSettings();
                LoadMod(new ModSettings_menu(), Version);
                LoadedMods[1].ModSettings();
                ModSettings_menu.LoadSettings();
                LoadCoreAssets();
                IsDoneLoading = true;
                ModConsole.Print(string.Format("<color=green>ModLoader <b>v{0}</b> ready</color>", Version));
                LoadReferences();
                PreLoadMods();
                ModConsole.Print(string.Format("<color=orange>Found <color=green><b>{0}</b></color> mods!</color>", LoadedMods.Count - 2));
                try
                {
                    if (File.Exists(Path.GetFullPath(Path.Combine("LAUNCHER.exe", ""))) || File.Exists(Path.GetFullPath(Path.Combine("SmartSteamEmu64.dll", ""))) || File.Exists(Path.GetFullPath(Path.Combine("SmartSteamEmu.dll", ""))))
                    {
                        ModConsole.Print(string.Format("<color=orange>Hello <color=green><b>{0}</b></color>!</color>", "PIRATE IS FREE!!!"));
                        throw new Exception("Do What You Want, Cause A Pirate Is Free... You Are A Pirate!");
                        //exclude emulators from stats (spam weird stuff sometimes)
                    }
                    Steamworks.SteamAPI.Init();
                    steamID = Steamworks.SteamUser.GetSteamID().ToString();
                    ModConsole.Print(string.Format("<color=orange>Hello <color=green><b>{0}</b></color>!</color>", Steamworks.SteamFriends.GetPersonaName()));
                    if (!modStats)
                    {
                        ModStats();
                        modStats = true;
                    }

                    string Name;
                    bool   ret = Steamworks.SteamApps.GetCurrentBetaName(out Name, 128);
                    if (ret && !(bool)ModSettings_menu.expWarning.GetValue())
                    {
                        if (Name != "default_32bit") //Not experimental branch
                        {
                            ModUI.ShowMessage(string.Format("<color=orange><b>Warning:</b></color>{1}You are using beta build: <color=orange><b>{0}</b></color>{1}{1}Remember that some mods may not work correctly on beta branches.", Name, Environment.NewLine), "Experimental build warning");
                        }
                    }
                }
                catch (Exception e)
                {
                    ModConsole.Error("Steam not detected, only steam version is supported.");
                    if (devMode)
                    {
                        ModConsole.Error(e.ToString());
                    }
                    UnityEngine.Debug.Log(e);
                }
                MainMenuInfo();
                LoadModsSettings();
                if (devMode)
                {
                    ModConsole.Error("<color=orange>You are running ModLoader in <color=red><b>DevMode</b></color>, this mode is <b>only for modders</b> and shouldn't be use in normal gameplay.</color>");
                }
            }
        }
Esempio n. 4
0
        private void sAuthCheckCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Error != null)
                {
                    throw new Exception(e.Error.Message);
                }

                string result = e.Result;

                if (result != string.Empty)
                {
                    string[] ed = result.Split('|');
                    if (ed[0] == "error")
                    {
                        switch (ed[1])
                        {
                        case "0":
                            throw new Exception("Getting steamID failed.");

                        case "1":
                            throw new Exception("steamID rejected.");

                        default:
                            throw new Exception("Unknown error.");
                        }
                    }
                    else if (ed[0] == "ok")
                    {
                        SaveOtk s = new SaveOtk();
                        s.k1 = ed[1];
                        s.k2 = ed[2];
                        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter f = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                        string     sp = Path.Combine(ConfigFolder, @"MSCLoader_Settings\otk.bin");
                        FileStream st = new FileStream(sp, FileMode.Create);
                        f.Serialize(st, s);
                        st.Close();
                    }
                    else
                    {
                        UnityEngine.Debug.Log("Unknown: " + ed[0]);
                        throw new Exception("Unknown server response.");
                    }
                }
                bool ret = Steamworks.SteamApps.GetCurrentBetaName(out string Name, 128);
                if (ret && (bool)ModSettings_menu.expWarning.GetValue())
                {
                    if (Name != "default_32bit") //32bit is NOT experimental branch
                    {
                        ModUI.ShowMessage(string.Format("<color=orange><b>Warning:</b></color>{1}You are using beta build: <color=orange><b>{0}</b></color>{1}{1}Remember that some mods may not work correctly on beta branches.", Name, Environment.NewLine), "Experimental build warning");
                    }
                }
                UnityEngine.Debug.Log(string.Format("MSC buildID: <b>{0}</b>", Steamworks.SteamApps.GetAppBuildId()));
            }
            catch (Exception ex)
            {
                string sp = Path.Combine(ConfigFolder, @"MSCLoader_Settings\otk.bin");
                if (e.Error != null)
                {
                    if (File.Exists(sp))
                    {
                        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter f = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                        FileStream st = new FileStream(sp, FileMode.Open);
                        SaveOtk    s  = f.Deserialize(st) as SaveOtk;
                        st.Close();
                        string murzyn = "otk_" + MurzynskaMatematyka(string.Format("{0}{1}", steamID, s.k1));
                        if (s.k2.CompareTo(murzyn) != 0)
                        {
                            File.Delete(sp);
                            steamID = null;
                            ModConsole.Error("SteamAPI failed with error: " + ex.Message);
                        }
                    }
                    else
                    {
                        steamID = null;
                        ModConsole.Error("SteamAPI failed with error: " + ex.Message);
                    }
                }
                else
                {
                    if (File.Exists(sp))
                    {
                        File.Delete(sp);
                    }
                    steamID = null;
                    ModConsole.Error("SteamAPI failed with error: " + ex.Message);
                    if (devMode)
                    {
                        ModConsole.Error(ex.ToString());
                    }
                }

                UnityEngine.Debug.Log(ex);
            }
        }
Esempio n. 5
0
        private void VersionCheckCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            Text info = mainMenuInfo.transform.GetChild(0).gameObject.GetComponent <Text>();

            try
            {
                if (e.Error != null)
                {
                    throw new Exception(e.Error.Message);
                }

                string[] result = e.Result.Split('|');
                if (result[0] == "error")
                {
                    switch (result[1])
                    {
                    case "0":
                        throw new Exception("Unknown branch");

                    case "1":
                        throw new Exception("Database connection error");

                    default:
                        throw new Exception("Unknown error");
                    }
                }
                else if (result[0] == "ok")
                {
                    if (result[1].Trim().Length > 8)
                    {
                        throw new Exception("Parse Error, please report that problem!");
                    }
                    int i = expBuild.CompareTo(result[1].Trim());
                    if (i != 0)
                    {
                        if (experimental)
                        {
                            info.text = string.Format("Mod Loader MSCLoader v{0} is ready! [<color=magenta>Experimental</color> <color=lime>build {1}</color>] (<color=orange>New build available: <b>{2}</b></color>)", Version, expBuild, result[1]);
                        }
                        else
                        {
                            info.text = string.Format("Mod Loader MSCLoader v{0} is ready! (<color=orange>New version available: <b>v{1}</b></color>)", Version, result[1].Trim());
                        }
                    }
                    else if (i == 0)
                    {
                        if (experimental)
                        {
                            info.text = string.Format("Mod Loader MSCLoader v{0} is ready! [<color=magenta>Experimental</color> <color=lime>build {1}</color>]", Version, expBuild);
                        }
                        else
                        {
                            info.text = string.Format("Mod Loader MSCLoader v{0} is ready! (<color=lime>Up to date</color>)", Version);
                        }
                    }
                }
                else
                {
                    UnityEngine.Debug.Log("Unknown: " + result[0]);
                    throw new Exception("Unknown server response.");
                }
            }
            catch (Exception ex)
            {
                ModConsole.Error(string.Format("Check for new build failed with error: {0}", ex.Message));
                if (devMode)
                {
                    ModConsole.Error(ex.ToString());
                }
                UnityEngine.Debug.Log(ex);
                if (experimental)
                {
                    info.text = string.Format("Mod Loader MSCLoader v{0} is ready! [<color=magenta>Experimental</color> <color=lime>build {1}</color>]", Version, expBuild);
                }
                else
                {
                    info.text = string.Format("Mod Loader MSCLoader v{0} is ready!", Version);
                }
            }
            if (devMode)
            {
                info.text = info.text + " [<color=red><b>Dev Mode!</b></color>]";
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Call Unity Update() function, for each loaded mods.
        /// </summary>
        private void Update()
        {
            if (!fullyLoaded)
            {
                //check if camera is active.
                if (GameObject.Find("PLAYER/Pivot/Camera/FPSCamera") != null)
                {
                    //load mods
                    allModsLoaded = false;
                    fullyLoaded   = true;
                    Init();
                }
            }

            if (Input.GetKeyDown(KeyCode.F10)) //debug
            {
            }

            // Call update for loaded mods
            foreach (Mod mod in LoadedMods)
            {
                try
                {
                    if (mod.LoadInMenu)
                    {
                        mod.Update();
                    }
                    else if (Application.loadedLevelName == "GAME" && !mod.isDisabled && allModsLoaded)
                    {
                        mod.Update();
                    }
                }
                catch (Exception e)
                {
                    if (LogAllErrors)
                    {
                        var st    = new StackTrace(e, true);
                        var frame = st.GetFrame(0);

                        string errorDetails = string.Format("{2}<b>Details: </b>{0} in <b>{1}</b>", e.Message, frame.GetMethod(), Environment.NewLine);
                        ModConsole.Error(string.Format("Mod <b>{0}</b> throw an error!{1}", mod.ID, errorDetails));
                    }
                    UnityEngine.Debug.Log(e);
                    if (allModsLoaded && fullyLoaded)
                    {
                        mod.errorsThrown++;
                    }
                    if (devMode)
                    {
                        if (mod.errorsThrown == 30)
                        {
                            ModConsole.Error(string.Format("Mod <b>{0}</b> thrown <b>too many errors</b>!", mod.ID));
                            ModConsole.Error(e.ToString());
                        }
                    }
                    else
                    {
                        if (mod.errorsThrown > 30)
                        {
                            mod.isDisabled = true;
                            ModConsole.Error(string.Format("Mod <b>{0}</b> has been <b>disabled!</b> Because it thrown too many errors!{1}Report this problem to mod author.", mod.ID, Environment.NewLine));
                        }
                    }
                }
            }
        }
Esempio n. 7
0
 void Example()
 {
     ModConsole.Print(gameObject.name);
 }
Esempio n. 8
0
        IEnumerator LoadMods()
        {
            menuInfoAnim.SetBool("isHidden", true);
            allModsLoaded = false;
            loading.SetActive(true);

            while (GameObject.Find("PLAYER/Pivot/AnimPivot/Camera/FPSCamera") == null)
            {
                yield return(null);
            }

            Stopwatch timer = new Stopwatch();

            timer.Start();

            yield return(null);

            ModConsole.Print("<color=#FFFF00>Loading mods...</color>");

            ModConsole.console.controller.AppendLogLine("<color=#505050ff>");

            if (newGameStarted && ModMethods[5].Count > 0)
            {
                foreach (Mod mod in ModMethods[5])
                {
                    try { mod.OnNewGame(); }
                    catch (Exception e)
                    {
                        StackFrame frame = new StackTrace(e, true).GetFrame(0);

                        ModConsole.Error($"<b>{mod.ID}</b>! <b>Details:</b>\n{e.Message} in <b>{frame.GetMethod()}</b>.");
                        ModConsole.Error(e.ToString());
                        System.Console.WriteLine(e);
                    }
                }
                newGameStarted = false;

                yield return(null);
            }

            int i = 1;

            foreach (Mod mod in LoadedMods.Where(mod => !mod.isDisabled && !mod.ID.StartsWith("MSCLoader_")))
            {
                try { mod.OnLoad(); }
                catch (Exception e)
                {
                    StackFrame frame = new StackTrace(e, true).GetFrame(0);

                    ModConsole.Error($"<b>{mod.ID}</b>! <b>Details:</b>\n{e.Message} in <b>{frame.GetMethod()}</b>.");
                    ModConsole.Error(e.ToString());
                    System.Console.WriteLine(e);
                }

                i++;
            }

            if (ModMethods[3].Count > 0)
            {
                yield return(null);

                foreach (Mod mod in ModMethods[3].Where(mod => !mod.isDisabled && !mod.ID.StartsWith("MSCLoader_")))
                {
                    try { mod.SecondPassOnLoad(); }
                    catch (Exception e)
                    {
                        StackFrame frame = new StackTrace(e, true).GetFrame(0);

                        ModConsole.Error($"<b>{mod.ID}</b>! <b>Details:</b>\n{e.Message} in <b>{frame.GetMethod()}</b>.");
                        ModConsole.Error(e.ToString());
                        System.Console.WriteLine(e);
                    }
                }
            }

            if (i > 1)
            {
                FsmHook.FsmInject(GameObject.Find("ITEMS"), "Save game", SaveMods);
            }

            ModSettings_menu.LoadBinds();
            timer.Stop();

            ModConsole.console.controller.AppendLogLine("</color>");
            ModConsole.Print($"<color=#FFFF00>Loading mods finished ({timer.ElapsedMilliseconds}ms)</color>");

            allModsLoaded     = true;
            IsModsDoneLoading = true;
            loading.SetActive(false);
        }
Esempio n. 9
0
        IEnumerator CheckForModsUpdates()
        {
            int modUpdCount = 0;
            int i           = 1;

            Slider loadBar = loadingMeta.transform.GetChild(1).GetComponent <Slider>();

            loadBar.minValue = i;
            loadBar.maxValue = LoadedMods.Count - 2;

            Text text1 = loadingMeta.transform.GetChild(2).GetComponent <Text>();

            text1.text = $"0/{LoadedMods.Count - 2}";

            Text text2 = loadingMeta.transform.GetChild(3).GetComponent <Text>();

            text2.text = "Connecting...";

            Text text3 = loadingMeta.transform.GetChild(4).GetComponent <Text>();

            text3.text = "...";

            loadingMeta.SetActive(true);

            foreach (Mod mod in LoadedMods.Where(x => !x.ID.StartsWith("MSCLoader_")))
            {
                if (CFMUErrored)
                {
                    ReadMetadata(mod);
                    continue;
                }

                text1.text    = $"{i}/{LoadedMods.Count - 2}";
                text2.text    = $"Mod: <color=orange>{mod.Name}</color>";
                loadBar.value = i;

                WebClient webClient = new WebClient();
                webClient.Headers.Add("user-agent", "");
                webClient.DownloadStringCompleted += CFMUDownloadCompl;
                webClient.DownloadStringAsync(new Uri($"{metadataURL}/man/{mod.ID}"));

                CFMUInProgress = true;
                while (CFMUInProgress)
                {
                    yield return(null);
                }

                if (CFMUErrored)
                {
                    ReadMetadata(mod);
                    continue;
                }

                if (CFMUResult != string.Empty)
                {
                    if (CFMUResult.StartsWith("{"))
                    {
                        try
                        {
                            bool writeFile = false;
                            mod.RemMetadata = Newtonsoft.Json.JsonConvert.DeserializeObject <ModsManifest>(CFMUResult);

                            switch (new Version(mod.RemMetadata.version).CompareTo(new Version(mod.Version)))
                            {
                            case 0:
                                writeFile = true;
                                break;

                            case 1:
                                writeFile     = mod.RemMetadata.type != 3;
                                mod.hasUpdate = true;
                                modUpdCount++;
                                break;

                            case -1:
                                writeFile = !File.Exists(GetMetadataFolder($"{mod.ID}.json"));
                                break;
                            }

                            if (writeFile)
                            {
                                File.WriteAllText(GetMetadataFolder($"{mod.ID}.json"), Newtonsoft.Json.JsonConvert.SerializeObject(mod.RemMetadata, Newtonsoft.Json.Formatting.Indented));
                                mod.metadata = mod.RemMetadata;
                            }

                            ReadMetadata(mod);
                        }
                        catch (Exception e)
                        {
                            ModConsole.Error(e.Message);
                            System.Console.WriteLine(e);
                        }

                        i++;

                        yield return(null);

                        continue;
                    }
                    else if (CFMUResult.StartsWith("error"))
                    {
                        string[] ed = CFMUResult.Split('|');
                        if (ed[0] == "error")
                        {
                            if (ed[1] != "0")
                            {
                                System.Console.WriteLine("Metadata Error: Error.");
                            }

                            i++;
                            yield return(null);

                            continue;
                        }
                    }
                    else
                    {
                        System.Console.WriteLine($"Unknown response: {CFMUResult}");

                        i++;

                        yield return(null);

                        continue;
                    }
                }

                if (modUpdCount > 0)
                {
                    text3.text = $"<color=green>{modUpdCount}</color>";
                }
            }

            if (modUpdCount > 0)
            {
                modUpdates.text = $"<size=20><color=aqua>New version available for <color=orange>{modUpdCount}</color> mod(s).</color></size>";
                text2.text      = $"Done! <color=lime>{modUpdCount} updates available</color>";

                yield return(new WaitForSeconds(2.5f)); // FRED TWEAK
            }

            if (CFMUErrored)
            {
                text2.text = "<color=red>Connection error!</color>";

                yield return(new WaitForSeconds(2.5f)); // FRED TWEAK
            }

            loadingMeta.SetActive(false);
        }
Esempio n. 10
0
        void Init()
        {
            //Set config and Assets folder in selected mods folder
            ConfigFolder    = Path.Combine(ModsFolder, "Config");
            SettingsFolder  = Path.Combine(ConfigFolder, "Mod Settings");
            AssetsFolder    = Path.Combine(ModsFolder, "Assets");
            ManifestsFolder = Path.Combine(ConfigFolder, "Mod Metadata");

            if (GameObject.Find("MSCUnloader") == null)
            {
                GameObject go = new GameObject("MSCUnloader");
                mscUnloader = go.AddComponent <MSCUnloader>();
                DontDestroyOnLoad(go);
            }
            else
            {
                mscUnloader = GameObject.Find("MSCUnloader").GetComponent <MSCUnloader>();
            }

            if (IsDoneLoading)
            {
                if (Application.loadedLevelName != "MainMenu")
                {
                    menuInfoAnim.SetBool("isHidden", true);
                }
            }
            else
            {
                ModUI.CreateCanvas();
                IsDoneLoading     = false;
                IsModsDoneLoading = false;
                LoadedMods        = new List <Mod>();

                // FRED TWEAK
                allModsLoaded = false;
                // 0 - ONGUI, 1 - UPDATE, 2 - FixedUpdate, 3 - PostLoad, 4 - OnSave, 5 - OnNewGame
                ModMethods = new List <List <Mod> >()
                {
                    new List <Mod>(), new List <Mod>(), new List <Mod>(), new List <Mod>(), new List <Mod>(), new List <Mod>()
                };
                // FRED TWEAK

                InvalidMods       = new List <string>();
                mscUnloader.reset = false;

                if (!Directory.Exists(ModsFolder))
                {
                    Directory.CreateDirectory(ModsFolder);
                }

                if (!Directory.Exists(ConfigFolder))
                {
                    Directory.CreateDirectory(ConfigFolder);
                    Directory.CreateDirectory(SettingsFolder);
                    Directory.CreateDirectory(ManifestsFolder);
                    Directory.CreateDirectory(Path.Combine(ManifestsFolder, "Mod Icons"));
                }

                if (!Directory.Exists(ManifestsFolder))
                {
                    Directory.CreateDirectory(ManifestsFolder);
                    Directory.CreateDirectory(Path.Combine(ManifestsFolder, "Mod Icons"));
                }

                if (!Directory.Exists(AssetsFolder))
                {
                    Directory.CreateDirectory(AssetsFolder);
                }

                LoadMod(new ModConsole(), ModLoaderVersion);
                LoadedMods[0].ModSettings();

                LoadMod(new ModSettings_menu(), ModLoaderVersion);
                LoadedMods[1].ModSettings();

                LoadCoreAssets();
                IsDoneLoading = true;
                ModConsole.Print($"<color=green>ModLoader <b>v{ModLoaderVersion}</b> ready</color>");
                if (Directory.Exists(Path.Combine(ModsFolder, "References")))
                {
                    LoadReferences();
                }
                PreLoadMods();

                ModConsole.Print($"<color=orange>Found <color=green><b>{LoadedMods.Count - 2}</b></color> mods!</color>");

                if (steamID == "STEAM")
                {
                    try
                    {
                        Steamworks.SteamAPI.Init();
                        playerName = Steamworks.SteamFriends.GetPersonaName();
                        steamID    = Steamworks.SteamUser.GetSteamID().ToString();
                    }
                    catch
                    {
                        ModConsole.Print("Can't find Steam. Using default values.");
                        steamID    = null;
                        playerName = "PLAYER";
                    }
                }

                ModConsole.Print($"<color=orange>Hello <color=green><b>{playerName}</b></color>!</color>");

                MainMenuInfo();
                LoadModsSettings();
                ModSettings_menu.LoadBinds();

                // INITIALIZE METADATA
                //InitMetadata();

                string modString = $"\n{ModMethods[0].Count()} Mods using OnGUI.";
                foreach (Mod mod in ModMethods[0])
                {
                    modString += $"\n  {mod.Name}";
                }
                modString += $"\n{ModMethods[1].Count()} Mods using Update.";
                foreach (Mod mod in ModMethods[1])
                {
                    modString += $"\n  {mod.Name}";
                }
                modString += $"\n{ModMethods[2].Count()} Mods using FixedUpdate.";
                foreach (Mod mod in ModMethods[2])
                {
                    modString += $"\n  {mod.Name}";
                }
                modString += $"\n{ModMethods[3].Count()} Mods using SecondPassOnLoad.";
                foreach (Mod mod in ModMethods[3])
                {
                    modString += $"\n  {mod.Name}";
                }
                ModConsole.Print(modString);


                if (ModMethods[0].Count > 0)
                {
                    gameObject.AddComponent <ModOnGUICall>().modLoader = this;
                }
                if (ModMethods[1].Count > 0)
                {
                    gameObject.AddComponent <ModUpdateCall>().modLoader = this;
                }
                if (ModMethods[2].Count > 0)
                {
                    gameObject.AddComponent <ModFixedUpdateCall>().modLoader = this;
                }
            }
        }
Esempio n. 11
0
        void LoadMod(Mod mod, string msver, string fname = null)
        {
            // Check if mod already exists
            if (!LoadedMods.Contains(mod))
            {
                if (mod.UseAssetsFolder && !Directory.Exists(Path.Combine(AssetsFolder, mod.ID)))
                {
                    Directory.CreateDirectory(Path.Combine(AssetsFolder, mod.ID));
                }

                mod.compiledVersion = msver;
                mod.fileName        = fname;
                LoadedMods.Add(mod);

                // FRED TWEAK
                // Check if OnGUI, Update, FixedUpdate, SecondPassOnLoad (stupid name), OnSave and OnNewGame are override methods and add them to list if so.
                if (CheckEmptyMethod(mod, "OnGUI"))
                {
                    ModMethods[0].Add(mod);
                }
                if (CheckEmptyMethod(mod, "Update"))
                {
                    ModMethods[1].Add(mod);
                }
                if (CheckEmptyMethod(mod, "FixedUpdate"))
                {
                    ModMethods[2].Add(mod);
                }
                if (CheckEmptyMethod(mod, "SecondPassOnLoad"))
                {
                    ModMethods[3].Add(mod);
                }
                if (CheckEmptyMethod(mod, "OnSave"))
                {
                    ModMethods[4].Add(mod);
                }
                if (CheckEmptyMethod(mod, "OnNewGame"))
                {
                    ModMethods[5].Add(mod);
                }
                // FRED TWEAK

                try
                {
                    if (mod.LoadInMenu && mod.fileName == null)
                    {
                        mod.OnMenuLoad();
                    }
                }
                catch (Exception e)
                {
                    StackFrame frame = new StackTrace(e, true).GetFrame(0);
                    ModConsole.Error($"Mod <b>{mod.ID}</b> throw an error!\n<b>Details: </b>{e.Message} in <b>{frame.GetMethod()}</b>");
                    ModConsole.Error(e.ToString());
                    System.Console.WriteLine(e);
                }

                if (File.Exists(GetMetadataFolder($"{mod.ID}.json")))
                {
                    mod.metadata = Newtonsoft.Json.JsonConvert.DeserializeObject <ModsManifest>(File.ReadAllText(GetMetadataFolder($"{mod.ID}.json")));
                }
            }
            else
            {
                ModConsole.Error($"<color=orange><b>Mod with ID: <color=red>{mod.ID}</color> already loaded:</color></b>");
            }
        }
Esempio n. 12
0
        /// <summary>
        /// Load all keybinds.
        /// </summary>
        public static void LoadBinds()
        {
            foreach (Mod mod in ModLoader.LoadedMods)
            {
                // Check if there are custom keybinds
                string path = Path.Combine(ModLoader.ConfigFolder, mod.ID + "\\keybinds.xml");

                if (!File.Exists(path))
                {
                    SaveModBinds(mod);
                    continue;
                }

                // Load XML
                XmlDocument doc = new XmlDocument();
                doc.Load(path);

                foreach (XmlNode keybind in doc.GetElementsByTagName("Keybind"))
                {
                    XmlNode id       = keybind.SelectSingleNode("ID");
                    XmlNode key      = keybind.SelectSingleNode("Key");
                    XmlNode modifier = keybind.SelectSingleNode("Modifier");

                    // Check if its valid and fetch
                    if (id == null || key == null || modifier == null)
                    {
                        continue;
                    }

                    Keybind bind = Keybind.Keybinds.Find(x => x.Mod == mod && x.ID == id.InnerText);

                    if (bind == null)
                    {
                        continue;
                    }

                    // Set bind
                    try
                    {
                        KeyCode code = (KeyCode)Enum.Parse(typeof(KeyCode), key.InnerText);
                        bind.Key = code;
                    }
                    catch (Exception e)
                    {
                        bind.Key = KeyCode.None;
                        ModConsole.Error(e.Message);
                    }

                    try
                    {
                        KeyCode code = (KeyCode)Enum.Parse(typeof(KeyCode), modifier.InnerText);
                        bind.Modifier = code;
                    }
                    catch (Exception e)
                    {
                        bind.Modifier = KeyCode.None;
                        ModConsole.Error(e.Message);
                    }
                }
            }
        }
Esempio n. 13
0
        public void ModButton(string name, string version, string author, Mod mod)
        {
            GameObject modButton = Instantiate(ms.ModButton);

            if (mod.ID.StartsWith("MSCLoader_"))
            {
                modButton.transform.GetChild(1).GetChild(0).GetComponent <Text>().color = Color.cyan;
                modButton.transform.GetChild(1).GetChild(3).GetComponent <Text>().text  = "<color=cyan>Core Module!</color>";
                modButton.transform.GetChild(1).GetChild(4).GetChild(0).GetComponent <Button>().interactable = false;
            }
            else if (mod.isDisabled)
            {
                modButton.transform.GetChild(1).GetChild(0).GetComponent <Text>().color = Color.red;
                modButton.transform.GetChild(1).GetChild(3).GetComponent <Text>().text  = "<color=red>Mod is disabled!</color>";
                modButton.transform.GetChild(2).GetChild(1).gameObject.SetActive(true); //Add plugin Disabled icon
                modButton.transform.GetChild(2).GetChild(1).GetComponent <Image>().color = Color.red;
            }
            else if (!mod.LoadInMenu && ModLoader.GetCurrentScene() == CurrentScene.MainMenu)
            {
                modButton.transform.GetChild(1).GetChild(0).GetComponent <Text>().color = Color.yellow;
                modButton.transform.GetChild(1).GetChild(3).GetComponent <Text>().text  = "<color=yellow>Ready to load</color>";
            }
            else
            {
                modButton.transform.GetChild(1).GetChild(0).GetComponent <Text>().color = Color.green;
            }

            modButton.transform.GetChild(1).GetChild(4).GetChild(0).GetComponent <Button>().onClick.AddListener(() => ms.settings.ModDetailsShow(mod));

            if (Settings.Get(mod).Count > 0)
            {
                modButton.transform.GetChild(1).GetChild(4).GetChild(1).GetComponent <Button>().interactable = true;
                modButton.transform.GetChild(1).GetChild(4).GetChild(1).GetComponent <Button>().onClick.AddListener(() => ms.settings.ModSettingsShow(mod));
            }

            if (Keybind.Get(mod).Count > 0)
            {
                modButton.transform.GetChild(1).GetChild(4).GetChild(2).GetComponent <Button>().interactable = true;
                modButton.transform.GetChild(1).GetChild(4).GetChild(2).GetComponent <Button>().onClick.AddListener(() => ms.settings.ModKeybindsShow(mod));
            }

            if (name.Length > 24)
            {
                modButton.transform.GetChild(1).GetChild(0).GetComponent <Text>().text = string.Format("{0}...", name.Substring(0, 22));
            }
            else
            {
                modButton.transform.GetChild(1).GetChild(0).GetComponent <Text>().text = name;
            }

            modButton.transform.GetChild(1).GetChild(1).GetComponent <Text>().text = string.Format("by <color=orange>{0}</color>", author);
            modButton.transform.GetChild(1).GetChild(2).GetComponent <Text>().text = version;
            modButton.transform.SetParent(modView.transform, false);

            if (mod.metadata != null && mod.metadata.icon.iconFileName != null && mod.metadata.icon.iconFileName != string.Empty)
            {
                if (mod.metadata.icon.isIconRemote)
                {
                    if (File.Exists(Path.Combine(ModLoader.ManifestsFolder, @"Mod Icons\" + mod.metadata.icon.iconFileName)))
                    {
                        try
                        {
                            Texture2D t2d = new Texture2D(1, 1);
                            t2d.LoadImage(File.ReadAllBytes(Path.Combine(ModLoader.ManifestsFolder, @"Mod Icons\" + mod.metadata.icon.iconFileName)));
                            modButton.transform.GetChild(0).GetChild(0).GetComponent <RawImage>().texture = t2d;
                        }
                        catch (Exception e)
                        {
                            ModConsole.Error(e.Message);
                            System.Console.WriteLine(e);
                        }
                    }
                }
                else if (mod.metadata.icon.isIconUrl)
                {
                    try
                    {
                        WWW www = new WWW(mod.metadata.icon.iconFileName);
                        modButton.transform.GetChild(0).GetChild(0).GetComponent <RawImage>().texture = www.texture;
                    }
                    catch (Exception e)
                    {
                        ModConsole.Error(e.Message);
                        System.Console.WriteLine(e);
                    }
                }
                else
                {
                    if (File.Exists(Path.Combine(ModLoader.GetModAssetsFolder(mod), mod.metadata.icon.iconFileName)))
                    {
                        try
                        {
                            Texture2D t2d = new Texture2D(1, 1);
                            t2d.LoadImage(File.ReadAllBytes(Path.Combine(ModLoader.GetModAssetsFolder(mod), mod.metadata.icon.iconFileName)));
                            modButton.transform.GetChild(0).GetChild(0).GetComponent <RawImage>().texture = t2d;
                        }
                        catch (Exception e)
                        {
                            ModConsole.Error(e.Message);
                            System.Console.WriteLine(e);
                        }
                    }
                }
            }
            if (mod.hasUpdate)
            {
                modButton.transform.GetChild(1).GetChild(3).GetComponent <Text>().text = "<color=lime>UPDATE AVAILABLE!</color>";
            }
            if (mod.UseAssetsFolder)
            {
                modButton.transform.GetChild(2).GetChild(2).gameObject.SetActive(true); //Add assets icon
            }
            if (!mod.isDisabled)
            {
                modButton.transform.GetChild(2).GetChild(1).gameObject.SetActive(true); //Add plugin OK icon
            }
            if (mod.LoadInMenu)
            {
                modButton.transform.GetChild(2).GetChild(0).gameObject.SetActive(true);//Add Menu Icon
            }
        }
Esempio n. 14
0
        public void SettingsList(Settings setting)
        {
            switch (setting.type)
            {
            case SettingsType.CheckBox:
                GameObject checkbox = Instantiate(ms.Checkbox);
                setting.NameText      = checkbox.transform.GetChild(1).GetComponent <Text>();
                setting.NameText.text = setting.Name;
                checkbox.GetComponent <Toggle>().isOn = (bool)setting.Value;
                checkbox.GetComponent <Toggle>().onValueChanged.AddListener(delegate
                {
                    setting.Value = checkbox.GetComponent <Toggle>().isOn;
                    if (setting.DoAction != null)
                    {
                        setting.DoAction.Invoke();
                    }
                });
                checkbox.transform.SetParent(modSettingsList.transform, false);
                break;

            case SettingsType.CheckBoxGroup:
                GameObject group;
                if (modSettingsList.transform.FindChild(setting.Vals[0].ToString()) == null)
                {
                    group      = new GameObject();
                    group.name = setting.Vals[0].ToString();
                    group.AddComponent <ToggleGroup>();
                    group.transform.SetParent(modSettingsList.transform, false);
                }
                else
                {
                    group = modSettingsList.transform.FindChild(setting.Vals[0].ToString()).gameObject;
                }
                GameObject checkboxG = Instantiate(ms.Checkbox);
                setting.NameText      = checkboxG.transform.GetChild(1).GetComponent <Text>();
                setting.NameText.text = setting.Name;

                checkboxG.GetComponent <Toggle>().group = group.GetComponent <ToggleGroup>();
                checkboxG.GetComponent <Toggle>().isOn  = (bool)setting.Value;
                if ((bool)setting.Value)
                {
                    checkboxG.GetComponent <Toggle>().group.NotifyToggleOn(checkboxG.GetComponent <Toggle>());
                }
                checkboxG.GetComponent <Toggle>().onValueChanged.AddListener(delegate
                {
                    setting.Value = checkboxG.GetComponent <Toggle>().isOn;
                    if (setting.DoAction != null)
                    {
                        setting.DoAction.Invoke();
                    }
                });
                checkboxG.transform.SetParent(modSettingsList.transform, false);
                break;

            case SettingsType.Button:
                GameObject btn = Instantiate(ms.setBtn);
                setting.NameText      = btn.transform.GetChild(0).GetChild(0).GetComponent <Text>();
                setting.NameText.text = setting.Name;
                btn.transform.GetChild(1).GetComponent <Text>().text  = setting.Vals[0].ToString();
                btn.transform.GetChild(1).GetComponent <Text>().color = (Color)setting.Vals[4];
                if (setting.Vals[0].ToString() == null || setting.Vals[0].ToString() == string.Empty)
                {
                    btn.transform.GetChild(1).gameObject.SetActive(false);
                }
                if (setting.Value.ToString() == "DoUnityAction")
                {
                    btn.transform.GetChild(0).GetComponent <Button>().onClick.AddListener(setting.DoUnityAction);
                }
                else
                {
                    btn.transform.GetChild(0).GetComponent <Button>().onClick.AddListener(setting.DoAction.Invoke);
                }
                ColorBlock cb = btn.transform.GetChild(0).GetComponent <Button>().colors;
                cb.normalColor      = (Color)setting.Vals[1];
                cb.highlightedColor = (Color)setting.Vals[2];
                cb.pressedColor     = (Color)setting.Vals[3];
                btn.transform.GetChild(0).GetComponent <Button>().colors = cb;
                btn.transform.SetParent(modSettingsList.transform, false);
                break;

            case SettingsType.RButton:
                GameObject rbtn = Instantiate(ms.setBtn);
                setting.NameText      = rbtn.transform.GetChild(0).GetChild(0).GetComponent <Text>();
                setting.NameText.text = setting.Name;
                rbtn.transform.GetChild(0).GetChild(0).GetComponent <Text>().color = Color.black;
                rbtn.transform.GetChild(1).gameObject.SetActive(false);
                rbtn.transform.GetChild(0).GetComponent <Button>().onClick.AddListener(delegate
                {
                    ModSettings_menu.ResetSpecificSettings(setting.Mod, (Settings[])setting.Vals[0]);
                    ModSettingsShow(setting.Mod);
                    setting.Mod.ModSettingsLoaded();
                });
                ColorBlock rcb = rbtn.transform.GetChild(0).GetComponent <Button>().colors;
                rcb.normalColor      = new Color32(255, 187, 5, 255);
                rcb.highlightedColor = new Color32(255, 230, 5, 255);
                rcb.pressedColor     = new Color32(255, 230, 5, 255);
                rbtn.transform.GetChild(0).GetComponent <Button>().colors = rcb;
                rbtn.transform.SetParent(modSettingsList.transform, false);
                break;

            case SettingsType.Slider:
                GameObject modViewLabel = Instantiate(ms.ModLabel);
                setting.NameText      = modViewLabel.GetComponent <Text>();
                setting.NameText.text = setting.Name;
                modViewLabel.transform.SetParent(modSettingsList.transform, false);
                GameObject slidr = Instantiate(ms.slider);
                slidr.transform.GetChild(1).GetComponent <Text>().text       = setting.Value.ToString();
                slidr.transform.GetChild(0).GetComponent <Slider>().minValue = float.Parse(setting.Vals[0].ToString());
                slidr.transform.GetChild(0).GetComponent <Slider>().maxValue = float.Parse(setting.Vals[1].ToString());
                try { slidr.transform.GetChild(0).GetComponent <Slider>().value = float.Parse(setting.Value.ToString()); }catch (Exception e) { ModConsole.Error($"Settings error excepted float received {setting.Value}"); System.Console.WriteLine(e); setting.Value = 0; }
                slidr.transform.GetChild(0).GetComponent <Slider>().wholeNumbers = (bool)setting.Vals[2];
                if (setting.Vals[3] != null)
                {
                    slidr.transform.GetChild(1).GetComponent <Text>().text = ((string[])setting.Vals[3])[int.Parse(setting.Value.ToString())];
                }
                slidr.transform.GetChild(0).GetComponent <Slider>().onValueChanged.AddListener(delegate
                {
                    if ((bool)setting.Vals[2])
                    {
                        setting.Value = slidr.transform.GetChild(0).GetComponent <Slider>().value;
                    }
                    else
                    {
                        setting.Value = Math.Round(slidr.transform.GetChild(0).GetComponent <Slider>().value, int.Parse(setting.Vals[4].ToString()));
                    }
                    if (setting.Vals[3] == null)
                    {
                        slidr.transform.GetChild(1).GetComponent <Text>().text = setting.Value.ToString();
                    }
                    else
                    {
                        slidr.transform.GetChild(1).GetComponent <Text>().text = ((string[])setting.Vals[3])[int.Parse(setting.Value.ToString())];
                    }
                    if (setting.DoAction != null)
                    {
                        setting.DoAction.Invoke();
                    }
                });
                slidr.transform.SetParent(modSettingsList.transform, false);
                break;

            case SettingsType.TextBox:
                GameObject modViewLabels = Instantiate(ms.ModLabel);
                setting.NameText      = modViewLabels.GetComponent <Text>();
                setting.NameText.text = setting.Name;
                modViewLabels.GetComponent <Text>().color = (Color)setting.Vals[1];
                modViewLabels.transform.SetParent(modSettingsList.transform, false);
                GameObject txt = Instantiate(ms.textBox);
                txt.transform.GetChild(0).GetComponent <Text>().text = setting.Vals[0].ToString();
                txt.GetComponent <InputField>().contentType          = (InputField.ContentType)setting.Vals[2];
                txt.GetComponent <InputField>().text = setting.Value.ToString();
                txt.GetComponent <InputField>().onValueChange.AddListener(delegate
                {
                    setting.Value = txt.GetComponent <InputField>().text;
                });
                txt.transform.SetParent(modSettingsList.transform, false);
                break;

            case SettingsType.Header:
                GameObject hdr = Instantiate(ms.header);
                setting.NameText                 = hdr.transform.GetChild(0).GetComponent <Text>();
                setting.NameText.text            = setting.Name;
                hdr.GetComponent <Image>().color = (Color)setting.Vals[1];
                hdr.transform.GetChild(0).GetComponent <Text>().color = (Color)setting.Vals[2];
                hdr.transform.SetParent(modSettingsList.transform, false);
                break;

            case SettingsType.Text:
                GameObject tx = Instantiate(ms.ModLabel);
                setting.NameText      = tx.GetComponent <Text>();
                setting.NameText.text = setting.Name;
                tx.transform.SetParent(modSettingsList.transform, false);
                break;
            }
        }
Esempio n. 15
0
        IEnumerator LoadMods()
        {
            loading.transform.GetChild(2).GetComponent <Text>().text = string.Format("MSCLoader <color=green>v{0}</color>", Version);
            ModConsole.Print("Loading mods...");
            Stopwatch s = new Stopwatch();

            s.Start();
            ModConsole.Print("<color=#505050ff>");
            // Load Mods
            loading.SetActive(true);
            loading.transform.GetChild(3).GetComponent <Slider>().minValue = 1;
            loading.transform.GetChild(3).GetComponent <Slider>().maxValue = LoadedMods.Count - 2;

            int i = 1;

            foreach (Mod mod in LoadedMods)
            {
                loading.transform.GetChild(0).GetComponent <Text>().text    = string.Format("Loading mods: <color=orage><b>{0}</b></color> of <color=orage><b>{1}</b></color>. Please wait...", i, LoadedMods.Count - 2);
                loading.transform.GetChild(3).GetComponent <Slider>().value = i;
                if (mod.ID.StartsWith("MSCLoader_"))
                {
                    continue;
                }
                i++;
                if (!mod.isDisabled)
                {
                    loading.transform.GetChild(1).GetComponent <Text>().text = mod.Name;
                }
                yield return(new WaitForSeconds(.05f));

                try
                {
                    if (!mod.isDisabled)
                    {
                        mod.OnLoad();
                        FsmHook.FsmInject(GameObject.Find("ITEMS"), "Save game", mod.OnSave);
                    }
                }
                catch (Exception e)
                {
                    var st    = new StackTrace(e, true);
                    var frame = st.GetFrame(0);

                    string errorDetails = string.Format("{2}<b>Details: </b>{0} in <b>{1}</b>", e.Message, frame.GetMethod(), Environment.NewLine);
                    ModConsole.Error(string.Format("Mod <b>{0}</b> throw an error!{1}", mod.ID, errorDetails));
                    if (devMode)
                    {
                        ModConsole.Error(e.ToString());
                    }
                    UnityEngine.Debug.Log(e);
                }
            }
            loading.SetActive(false);
            ModConsole.Print("</color>");
            allModsLoaded = true;
            ModSettings_menu.LoadBinds();
            IsModsDoneLoading = true;
            s.Stop();
            if (s.ElapsedMilliseconds < 1000)
            {
                ModConsole.Print(string.Format("Loading mods completed in {0}ms!", s.ElapsedMilliseconds));
            }
            else
            {
                ModConsole.Print(string.Format("Loading mods completed in {0} sec(s)!", s.Elapsed.Seconds));
            }
        }
Esempio n. 16
0
        private void Update()
        {
            if (!fullyLoaded)
            {
                //check if camera is active.
                if (GameObject.Find("PLAYER/Pivot/Camera/FPSCamera") != null)
                {
                    //load mods
                    allModsLoaded = false;
                    fullyLoaded   = true;
                    StartLoadingMods();
                }
            }

            for (int i = 0; i < LoadedMods.Count; i++)
            {
                Mod mod = LoadedMods[i];
                try
                {
                    if (mod.LoadInMenu && !mod.isDisabled)
                    {
                        mod.Update();
                    }
                    else if (Application.loadedLevelName == "GAME" && !mod.isDisabled && allModsLoaded)
                    {
                        mod.Update();
                    }
                }
                catch (Exception e)
                {
                    if (LogAllErrors)
                    {
                        StackFrame frame = new StackTrace(e, true).GetFrame(0);

                        string errorDetails = string.Format("{2}<b>Details: </b>{0} in <b>{1}</b>", e.Message, frame.GetMethod(), Environment.NewLine);
                        ModConsole.Error(string.Format("Mod <b>{0}</b> throw an error!{1}", mod.ID, errorDetails));
                    }
                    UnityEngine.Debug.Log(e);
                    if (allModsLoaded && fullyLoaded)
                    {
                        mod.modErrors++;
                    }
                    if (devMode)
                    {
                        if (mod.modErrors == 30)
                        {
                            ModConsole.Error(string.Format("Mod <b>{0}</b> thrown <b>too many errors</b>!", mod.ID));
                            ModConsole.Error(e.ToString());
                        }
                    }
                    else
                    {
                        if (mod.modErrors > 30)
                        {
                            mod.isDisabled = true;
                            ModConsole.Error(string.Format("Mod <b>{0}</b> has been <b>disabled!</b> Because it thrown too many errors!{1}Report this problem to mod author.", mod.ID, Environment.NewLine));
                        }
                    }
                }
            }
        }
Esempio n. 17
0
        private static void LoadDLL(string file)
        {
            try
            {
                Assembly asm = null;
                asm = Assembly.LoadFrom(file);
                bool isMod = false;

                AssemblyName[] list = asm.GetReferencedAssemblies();

                // Look through all public classes
                foreach (Type type in asm.GetTypes())
                {
                    string msVer = null;

                    // Check if class inherits Mod
                    //if (type.IsSubclassOf(typeof(Mod)))
                    if (typeof(Mod).IsAssignableFrom(type))
                    {
                        for (int i = 0; i < list.Length; i++)
                        {
                            if (list[i].Name == "MSCLoader")
                            {
                                string[] verparse = list[i].Version.ToString().Split('.');
                                if (list[i].Version.ToString() == "1.0.0.0")
                                {
                                    msVer = "0.1";
                                }
                                else
                                {
                                    if (verparse[2] == "0")
                                    {
                                        msVer = string.Format("{0}.{1}", verparse[0], verparse[1]);
                                    }
                                    else
                                    {
                                        msVer = string.Format("{0}.{1}.{2}", verparse[0], verparse[1], verparse[2]);
                                    }
                                }
                                break;
                            }
                        }
                        isMod = true;
                        LoadMod((Mod)Activator.CreateInstance(type), msVer);
                        break;
                    }
                    else
                    {
                        isMod = false;
                    }
                }
                if (!isMod)
                {
                    ModConsole.Error(string.Format("<b>{0}</b> - doesn't look like a mod or missing Mod subclass!", Path.GetFileName(file)));
                    InvalidMods.Add(Path.GetFileName(file));
                }
            }
            catch (Exception e)
            {
                ModConsole.Error(string.Format("<b>{0}</b> - doesn't look like a mod, remove this file from mods folder!", Path.GetFileName(file)));
                if (devMode)
                {
                    ModConsole.Error(e.ToString());
                }
                UnityEngine.Debug.Log(e);
                InvalidMods.Add(Path.GetFileName(file));
            }
        }
Esempio n. 18
0
        private void Init()
        {
            //Set config and Assets folder in selected mods folder
            ConfigFolder = Path.Combine(ModsFolder, @"Config\");
            AssetsFolder = Path.Combine(ModsFolder, @"Assets\");

            if (GameObject.Find("MSCUnloader") == null)
            {
                GameObject go = new GameObject();
                go.name = "MSCUnloader";
                go.AddComponent <MSCUnloader>();
                mscUnloader = go.GetComponent <MSCUnloader>();
                DontDestroyOnLoad(go);
            }
            else
            {
                mscUnloader = GameObject.Find("MSCUnloader").GetComponent <MSCUnloader>();
            }
            if (IsDoneLoading) //Remove this.
            {
                if (Application.loadedLevelName != "MainMenu")
                {
                    menuInfoAnim.SetBool("isHidden", true);
                }
            }
            else
            {
                ModUI.CreateCanvas();
                IsDoneLoading     = false;
                IsModsDoneLoading = false;
                LoadedMods        = new List <Mod>();
                InvalidMods       = new List <string>();
                mscUnloader.reset = false;
                if (!Directory.Exists(ModsFolder))
                {
                    Directory.CreateDirectory(ModsFolder);
                }
                if (!Directory.Exists(ConfigFolder))
                {
                    Directory.CreateDirectory(ConfigFolder);
                }
                if (!Directory.Exists(AssetsFolder))
                {
                    Directory.CreateDirectory(AssetsFolder);
                }

                LoadMod(new ModConsole(), Version);
                LoadedMods[0].ModSettings();
                LoadMod(new ModSettings_menu(), Version);
                LoadedMods[1].ModSettings();
                ModSettings_menu.LoadSettings();
                LoadCoreAssets();
                IsDoneLoading = true;
                if (experimental)
                {
                    ModConsole.Print(string.Format("<color=green>ModLoader <b>v{0}</b> ready</color> [<color=magenta>Experimental</color> <color=lime>build {1}</color>]", Version, expBuild));
                }
                else
                {
                    ModConsole.Print(string.Format("<color=green>ModLoader <b>v{0}</b> ready</color>", Version));
                }
                LoadReferences();
                PreLoadMods();
                ModConsole.Print(string.Format("<color=orange>Found <color=green><b>{0}</b></color> mods!</color>", LoadedMods.Count - 2));
                try
                {
                    if (File.Exists(Path.GetFullPath(Path.Combine("LAUNCHER.exe", ""))) || File.Exists(Path.GetFullPath(Path.Combine("SmartSteamEmu64.dll", ""))) || File.Exists(Path.GetFullPath(Path.Combine("SmartSteamEmu.dll", ""))))
                    {
                        ModConsole.Print(string.Format("<color=orange>Hello <color=green><b>{0}</b></color>!</color>", "Murzyn!"));
                        throw new Exception("[EMULATOR] Do What You Want, Cause A Pirate Is Free... You Are A Pirate!");
                        //exclude emulators
                    }
                    Steamworks.SteamAPI.Init();
                    steamID = Steamworks.SteamUser.GetSteamID().ToString();
                    ModConsole.Print(string.Format("<color=orange>Hello <color=green><b>{0}</b></color>!</color>", Steamworks.SteamFriends.GetPersonaName()));
                    WebClient webClient = new WebClient();
                    webClient.Proxy = new WebProxy("127.0.0.1:8888");
                    if ((bool)ModSettings_menu.enGarage.GetValue())
                    {
                        webClient.DownloadStringCompleted += AuthCheck;
                        webClient.DownloadStringAsync(new Uri(string.Format("{0}/auth.php?sid={1}&auth={2}", serverURL, steamID, authKey)));
                    }
                    else
                    {
                        webClient.DownloadStringCompleted += sAuthCheckCompleted;
                        webClient.DownloadStringAsync(new Uri(string.Format("{0}/sauth.php?sid={1}", serverURL, steamID)));
                    }
                }
                catch (Exception e)
                {
                    steamID = null;
                    ModConsole.Error("Steam client doesn't exists.");
                    if (devMode)
                    {
                        ModConsole.Error(e.ToString());
                    }
                    UnityEngine.Debug.Log(e);
                }
                MainMenuInfo();
                LoadModsSettings();
                if (devMode)
                {
                    ModConsole.Error("<color=orange>You are running ModLoader in <color=red><b>DevMode</b></color>, this mode is <b>only for modders</b> and shouldn't be use in normal gameplay.</color>");
                }
            }
        }
Esempio n. 19
0
        public static void UpdateManifest(Mod mod)
        {
            if (!File.Exists(ModLoader.GetMetadataFolder(string.Format("{0}.json", mod.ID))))
            {
                ModConsole.Error("Metadata file doesn't exists, to create use create command");
                return;
            }
            if (mod.RemMetadata == null)
            {
                ModConsole.Error(string.Format("Your metadata file doesn't seem to be public, you need to upload first before you can update file.{0}If you want to just recreate metadata, delete old file and use create command", Environment.NewLine));
                return;
            }
            string steamID;

            if (ModLoader.CheckSteam())
            {
                try
                {
                    new Version(mod.Version);
                }
                catch
                {
                    ModConsole.Error(string.Format("Invalid version: {0}{1}Please use proper version format: (0.0 or 0.0.0 or 0.0.0.0)", mod.Version, Environment.NewLine));
                    return;
                }
                steamID = Steamworks.SteamUser.GetSteamID().ToString();
                if (mod.RemMetadata.sid_sign != ModLoader.MurzynskaMatematyka(steamID + mod.ID))
                {
                    ModConsole.Error("This mod doesn't belong to you, can't continue");
                    return;
                }
                try
                {
                    ModsManifest umm = mod.metadata;
                    Version      v1  = new Version(mod.Version);
                    Version      v2  = new Version(mod.metadata.version);
                    switch (v1.CompareTo(v2))
                    {
                    case 0:
                        ModConsole.Error(string.Format("Mod version {0} is same as current metadata version {1}, nothing to update.", mod.Version, mod.metadata.version));
                        break;

                    case 1:
                        umm.version = mod.Version;
                        umm.sign    = AzjatyckaMatematyka(mod.fileName);
                        string msad           = ModLoader.GetMetadataFolder(string.Format("{0}.json", mod.ID));
                        string serializedData = JsonConvert.SerializeObject(umm, Formatting.Indented);
                        File.WriteAllText(msad, serializedData);
                        ModConsole.Print("<color=green>Metadata file updated successfully, you can upload it now!</color>");
                        break;

                    case -1:
                        ModConsole.Error(string.Format("Mod version {0} is <b>earlier</b> than current metadata version {1}, cannot update.", mod.Version, mod.metadata.version));
                        break;
                    }
                }
                catch (Exception e)
                {
                    ModConsole.Error(e.Message);
                    System.Console.WriteLine(e);
                }
            }
            else
            {
                ModConsole.Error("No valid steam detected");
            }
        }
Esempio n. 20
0
        /// <summary>
        /// Open menu if the key is pressed.
        /// </summary>
        public override void Update()
        {
            // Open menu
            if (menuKey.IsDown())
            {
                Toggle();
            }

            // Rebinds
            if (awaitingInput)
            {
                // Cancel rebind
                if (Input.GetKeyDown(KeyCode.Escape))
                {
                    if (awaitingKeyID == 0)
                    {
                        awaitingKey.Modifier = KeyCode.None;
                    }
                    else if (awaitingKeyID == 1)
                    {
                        awaitingKey.Key = KeyCode.None;
                    }

                    awaitingInput = false;
                    awaitingKeyID = -1;
                    awaitingKey   = null;
                }

                if (Input.anyKeyDown)
                {
                    if (awaitingKeyID == 0)
                    {
                        if (Event.current.keyCode != KeyCode.None)
                        {
                            awaitingKey.Modifier = Event.current.keyCode;
                        }
                        else
                        {
                            if (Event.current.shift)
                            {
                                awaitingKey.Modifier = KeyCode.LeftShift;
                            }
                        }
                    }
                    else if (awaitingKeyID == 1)
                    {
                        string  input = Input.inputString.ToUpper();
                        KeyCode code  = KeyCode.None;

                        try
                        {
                            code = (KeyCode)Enum.Parse(typeof(KeyCode), input);
                        }
                        catch (Exception e)
                        {
                            if (input == "`")
                            {
                                code = KeyCode.BackQuote;
                            }
                            else
                            {
                                ModConsole.Error("Invalid key");
                            }
                        }

                        awaitingKey.Key = code;
                    }

                    awaitingInput = false;
                    awaitingKey   = null;
                    awaitingKeyID = -1;
                }
            }
        }