private void Start()
    {
        Logger          = base.Logger;
        MapHooks.Logger = Logger;
        MapHooks.InstallHooks();

        foreach (var xDocument in Sideloader.Sideloader.Manifests.Values.Where(x => x.manifestDocument != null).Select(x => x.manifestDocument))
        {
            if (xDocument.Root == null)
            {
                continue;
            }
            var root = xDocument.Element("manifest");
            if (root == null)
            {
                continue;
            }

            foreach (var data in root.Elements("ai-maps")?.Elements("map-data"))
            {
                if (!CustomMapInformation.TryMakeFromXML(data, out var result))
                {
                    continue;
                }
                Data.CustomMapInformations.Add(result.ID, result);
            }
        }

        Logger.LogWarning($"Map Integration Plugin found {Data.CustomMapInformations.Count} maps from the mod folder");
        foreach (var data in Data.CustomMapInformations.Values)
        {
            Logger.LogWarning($"Map Integration Plugin successfully Registered Custom Map {data.Name}({data.ID}).");
        }
    }
Esempio n. 2
0
File: R2API.cs Progetto: x753/R2API
        public R2API()
        {
            Logger = base.Logger;
            CheckForIncompatibleAssemblies();

            Environment.SetEnvironmentVariable("MONOMOD_DMD_TYPE", "Cecil");

            InitConfig();

            Hooks.InitializeHooks();

            RoR2Application.isModded = true;

            On.RoR2.DisableIfGameModded.OnEnable += (orig, self) => {
                RoR2Application.isModded = true;
                orig(self);
            };

            On.RoR2.RoR2Application.OnLoad += (orig, self) => {
                orig(self);

                var build = typeof(RoR2Application).GetFieldValue <string>("steamBuildId");
                if (GameBuild == build)
                {
                    return;
                }

                Logger.LogWarning($"This version of R2API was built for build id \"{GameBuild}\", you are running \"{build}\".");
                Logger.LogWarning("Should any problems arise, please check for a new version before reporting issues.");
            };
        }
Esempio n. 3
0
        public void OnConnectionRequestSafe(ConnectionRequest request, NetDataWriter writer)
        {
            var reader = request.Data;

            Version version;

            try
            {
                version = reader.GetVersion();
            }
            catch
            {
                _log.LogWarning($"Connection request from {request.RemoteEndPoint} denied because of a malformed version.");

                writer.Put(ConnectionError.MalformedVersion);
                request.Reject(writer);

                return;
            }

            if (!_version.CompatibleWith(version))
            {
                _log.LogWarning($"Connection request from {request.RemoteEndPoint} denied because of version mismatch (server: {_version}; client: {version})");

                writer.Put(ConnectionError.MismatchedVersion);
                writer.Put(new MismatchedVersionErrorMessage(_version, version));
                request.Reject(writer);

                return;
            }
        }
Esempio n. 4
0
        internal void Awake()
        {
            Logger = base.Logger;

            Hooks.InstallHooks();
            UniversalAutoResolver.Hooks.InstallHooks();
            Lists.Hooks.InstallHooks();

            ResourceRedirection.EnableSyncOverAsyncAssetLoads();
            ResourceRedirection.EnableRedirectMissingAssetBundlesToEmptyAssetBundle(-1000);
            ResourceRedirection.RegisterAsyncAndSyncAssetLoadingHook(RedirectHook);
            ResourceRedirection.RegisterAssetBundleLoadingHook(AssetBundleLoadingHook);

            MissingModWarning       = Config.AddSetting("Settings", "Show missing mod warnings", true, new ConfigDescription("Whether missing mod warnings will be displayed on screen. Messages will still be written to the log."));
            DebugLogging            = Config.AddSetting("Settings", "Debug logging", false, new ConfigDescription("Enable additional logging useful for debugging issues with Sideloader and sideloader mods.\nWarning: Will increase load and save times noticeably and will result in very large log sizes."));
            DebugResolveInfoLogging = Config.AddSetting("Settings", "Debug resolve info logging", false, new ConfigDescription("Enable verbose logging for debugging issues with Sideloader and sideloader mods.\nWarning: Will increase game start up time and will result in very large log sizes."));
            ModLoadingLogging       = Config.AddSetting("Settings", "Mod loading logging", true, new ConfigDescription("Enable verbose logging when loading mods.", tags: "Advanced"));
            KeepMissingAccessories  = Config.AddSetting("Settings", "Keep missing accessories", false, new ConfigDescription("Missing accessories will be replaced by a default item with color and position information intact when loaded in the character maker."));
            MigrationEnabled        = Config.AddSetting("Settings", "Migration enabled", true, new ConfigDescription("Attempt to change the GUID and or ID of mods based on the data configured in the manifest.xml."));
            AdditionalModsDirectory = Config.AddSetting("General", "Additional mods directory", FindKoiZipmodDir(), new ConfigDescription("Additional directory to load zipmods from."));

            if (!Directory.Exists(ModsDirectory))
            {
                Logger.LogWarning("Could not find the mods directory: " + ModsDirectory);
            }

            if (!AdditionalModsDirectory.Value.IsNullOrWhiteSpace() && !Directory.Exists(AdditionalModsDirectory.Value))
            {
                Logger.LogWarning("Could not find the additional mods directory specified in config: " + AdditionalModsDirectory.Value);
            }

            LoadModsFromDirectories(ModsDirectory, AdditionalModsDirectory.Value);
        }
Esempio n. 5
0
        public static string GetAssetPath(string assetName, bool isDirectory = false)
        {
            string text = Path.Combine(BepInEx.Paths.PluginPath, "SeedTotem", assetName);

            if (isDirectory)
            {
                if (!Directory.Exists(text))
                {
                    Assembly assembly = typeof(SeedTotemMod).Assembly;
                    text = Path.Combine(Path.GetDirectoryName(assembly.Location), assetName);
                    if (!Directory.Exists(text))
                    {
                        logger.LogWarning($"Could not find directory ({assetName}).");
                        return(null);
                    }
                }
                return(text);
            }
            if (!File.Exists(text))
            {
                Assembly assembly = typeof(SeedTotemMod).Assembly;
                text = Path.Combine(Path.GetDirectoryName(assembly.Location), assetName);
                if (!File.Exists(text))
                {
                    logger.LogWarning($"Could not find asset ({assetName}).");
                    return(null);
                }
            }
            return(text);
        }
Esempio n. 6
0
File: R2API.cs Progetto: zkitX/R2API
        public R2API()
        {
            Logger     = base.Logger;
            ModManager = new DetourModManager();
            AddHookLogging();
            CheckForIncompatibleAssemblies();
            CheckR2APIMonomodPatch();

            Environment.SetEnvironmentVariable("MONOMOD_DMD_TYPE", "Cecil");

            On.RoR2.RoR2Application.UnitySystemConsoleRedirector.Redirect += orig => { };

            var submoduleHandler = new APISubmoduleHandler(GameBuild, Logger);

            loadedSubmodules = submoduleHandler.LoadRequested();

            //Currently disabled until manifest v2
            //ModListAPI.Init();

            RoR2Application.isModded = true;

            // Temporary fix as the new quickplay button currently don't have the DisableIfGameModded Script attached to it
            On.RoR2.UI.QuickPlayButtonController.Start += (orig, self) => {
                orig(self);
                self.gameObject.SetActive(false);
            };

            On.RoR2.DisableIfGameModded.OnEnable += (orig, self) => {
                // TODO: If we can enable quick play without regrets, uncomment.
                //if (self.name == "Button, QP")
                //    return;

                self.gameObject.SetActive(false);
            };

            On.RoR2.Networking.SteamLobbyFinder.CCSteamQuickplayStart += (orig, args) => {
                Debug.Log("QuickPlay is disabled in mods due to social contracts and lack of general support");
            };

            SteamworksClientManager.onLoaded += () => {
                var buildId =
                    SteamworksClientManager.instance.GetFieldValue <Client>("steamworksClient").BuildId;

                if (GameBuild == buildId)
                {
                    return;
                }

                Logger.LogWarning($"This version of R2API was built for build id \"{GameBuild}\", you are running \"{buildId}\".");
                Logger.LogWarning("Should any problems arise, please check for a new version before reporting issues.");
            };

            // Make sure that modded dedicated servers are recognizable from the server browser
            On.RoR2.SteamworksServerManager.UpdateHostName += (orig, self, hostname) => {
                var server = ((SteamworksServerManager)self).GetFieldValue <Server>("steamworksServer");
                server.GameTags = "mod," + server.GameTags;
            };
        }
Esempio n. 7
0
        internal void ScanHammer(bool lateAdd)
        {
            try
            {
                logger.LogDebug("Scanning Hammer PieceTable for Pieces");
                foreach (GameObject hammerRecipe in PieceManager.Instance.GetPieceTable("Hammer").m_pieces)
                {
                    if (hammerRecipe == null)
                    {
                        logger.LogWarning("null recipe in Hammer PieceTable");
                        continue;
                    }
                    Piece piece = hammerRecipe.GetComponent <Piece>();

                    if (piece.name == "piece_repair")
                    {
                        if (!addedHammer)
                        {
                            PieceTable planHammerPieceTable = PieceManager.Instance.GetPieceTable(PlanHammerPrefabConfig.pieceTableName);
                            if (planHammerPieceTable != null)
                            {
                                planHammerPieceTable.m_pieces.Add(hammerRecipe);
                                addedHammer = true;
                            }
                        }
                        continue;
                    }
                    if (planPiecePrefabConfigs.ContainsKey(piece.name))
                    {
                        continue;
                    }
                    if (!piece.m_enabled ||
                        piece.GetComponent <Ship>() != null ||
                        piece.GetComponent <Plant>() != null ||
                        piece.GetComponent <TerrainModifier>() != null ||
                        piece.m_resources.Length == 0)
                    {
                        continue;
                    }
                    PlanPiecePrefabConfig prefabConfig = new PlanPiecePrefabConfig(piece);
                    PieceManager.Instance.AddPiece(prefabConfig);
                    planPiecePrefabConfigs.Add(piece.name, prefabConfig);
                    PrefabManager.Instance.RegisterToZNetScene(prefabConfig.PiecePrefab);
                    if (lateAdd)
                    {
                        PieceTable pieceTable = PieceManager.Instance.GetPieceTable(PlanHammerPrefabConfig.pieceTableName);
                        if (!pieceTable.m_pieces.Contains(prefabConfig.PiecePrefab))
                        {
                            pieceTable.m_pieces.Add(prefabConfig.PiecePrefab);
                        }
                    }
                }
            }
            finally
            {
                PieceManager.OnPiecesRegistered -= ScanHammer;
            }
        }
Esempio n. 8
0
        private void Awake()
        {
            Logger = base.Logger;

            Logger.LogWarning("This plugin has been deprecated and has been integrated into H3VR.Sideloader.");
            Logger.LogWarning("It should only be used for hassle-free rapid prototyping from Unity into H3VR.");

            Harmony.CreateAndPatchAll(typeof(VirtualObjectsInjectorPlugin));
        }
Esempio n. 9
0
 public IEnumerator PostCleanupCoroutine()
 {
     if (!_latestBackup.IsNullOrWhiteSpace() && File.Exists(_latestBackup))
     {
         Logger.LogWarning("Something unexpected happened. Restoring previous translation cache.");
         MoveReplaceFile(_latestBackup, AutoTranslationsFilePath);
         yield return(StartCoroutine(CoroutineUtils.CreateCoroutine(ReloadTranslations)));
     }
 }
Esempio n. 10
0
        private static RequirementConfig[] LoadJsonFile(string filename)
        {
            RequirementConfig[] defaultRecipe = new RequirementConfig[] {
                new RequirementConfig()
                {
                    Item    = "FineWood",
                    Amount  = 5,
                    Recover = true
                },
                new RequirementConfig()
                {
                    Item    = "GreydwarfEye",
                    Amount  = 5,
                    Recover = true
                },
                new RequirementConfig()
                {
                    Item    = "SurtlingCore",
                    Amount  = 1,
                    Recover = true
                },
                new RequirementConfig()
                {
                    Item    = "AncientSeed",
                    Amount  = 1,
                    Recover = true
                }
            };
            if (SeedTotem.configCustomRecipe.Value)
            {
                string assetPath = SeedTotemMod.GetAssetPath(filename);
                bool   fileFound = string.IsNullOrEmpty(assetPath);
                if (fileFound)
                {
                    logger.LogWarning("File not found: " + filename + " using default recipe");
                    return(defaultRecipe);
                }

                Dictionary <string, int> reqDict = ReadDict(assetPath);
                RequirementConfig[]      result  = new RequirementConfig[reqDict.Count];
                int i = 0;
                foreach (KeyValuePair <string, int> pair in reqDict)
                {
                    result[i] = new RequirementConfig()
                    {
                        Item    = pair.Key,
                        Amount  = pair.Value,
                        Recover = true
                    };
                }
                return(result);
            }
            else
            {
                return(defaultRecipe);
            }
        }
Esempio n. 11
0
        [HarmonyPatch(typeof(AlreadyReadInfo), "Load")]                                                 // already read adv text
        private static Exception CatchCrash(MethodBase __originalMethod, Exception __exception)
        {
            if (__exception != null)
            {
                Logger.Log(LogLevel.Warning | LogLevel.Message, $"Corrupted save file detected in {__originalMethod.DeclaringType?.Name}, some progress might be lost.");
                Logger.LogWarning(__exception);
            }

            return(null);
        }
Esempio n. 12
0
 public static void Initialize()
 {
     try
     {
         InitializeInternal();
     }
     catch (Exception e)
     {
         Logger.LogWarning($"Failed to initialize log mirroring: ({e.GetType()}) {e.Message}. No mirrored logs will be generated.");
         Logger.LogDebug(e);
     }
 }
Esempio n. 13
0
        public static Dictionary <string, string> GetTokens(string modName)
        {
            if (!tokenStore.ContainsKey(modName))
            {
                Log.LogWarning($"No translation tokens found for mod [{modName}]. Have you loaded them?");

                return(null);
            }

            tokenStore.TryGetValue(modName, out var tokens);

            return(tokens);
        }
Esempio n. 14
0
        private ModContainer LoadMod(string path)
        {
            if (!Directory.Exists(path))
            {
                return(null);
            }

            var infoPath = Path.Combine(path, "mod.json");

            if (!File.Exists(infoPath))
            {
                return(null);
            }

            var contents = File.ReadAllText(infoPath);
            var info     = JsonConvert.DeserializeObject <ModInfo>(contents);

            if (info == null)
            {
                _logger.LogWarning($"{infoPath} was not a valid ModInfo!");
                return(null);
            }

            _logger.LogInfo($"Loading {info.Name} [{info.Version}]");

            var container = new ModContainer
            {
                Info = info
            };

            if (!string.IsNullOrEmpty(info.EntryDLL))
            {
                container.Assembly = Assembly.LoadFrom(Path.Combine(path, info.EntryDLL));
            }

            var bundles = new List <AssetBundle>();

            foreach (var entry in info.Bundles)
            {
                var bundlePath = Path.Combine(path, entry);
                if (!File.Exists(bundlePath))
                {
                    _logger.LogWarning($"Couldn't find AssetBundle {bundlePath}!");
                    continue;
                }
                bundles.Add(AssetBundle.LoadFromFile(bundlePath));
            }
            container.Resources = new ModResources(bundles);

            return(container);
        }
Esempio n. 15
0
        private void LoadMods()
        {
            Logger.LogInfo("Loading mods...");
            var mods     = new List <Mod>();
            var modsPath = Path.Combine(Paths.GameRootPath, H3VR.Sideloader.Shared.Info.MODS_DIR);

            Directory.CreateDirectory(modsPath);
            var modIds = new HashSet <string>(); // TODO: Make more elaborate (check version, etc)

            void LoadMods(IEnumerable <string> paths, Func <string, Mod> loader)
            {
                foreach (var path in paths)
                {
                    try
                    {
                        var mod = loader(path);
                        if (modIds.Contains(mod.Manifest.Guid))
                        {
                            Logger.LogWarning(
                                $"Skipping [{mod.Name}] because a mod with same GUID ({mod.Manifest.Guid}) was already loaded (check logs)");
                            continue;
                        }

                        Logger.LogDebug($"Loading {mod.Name}");
                        modIds.Add(mod.Manifest.Guid);
                        mods.Add(mod);
                    }
                    catch (Exception e)
                    {
                        Logger.LogWarning($"Skipping {path} because: ({e.GetType()}) {e.Message}");
                    }
                }
            }

            LoadMods(Directory.GetDirectories(modsPath, "*", SearchOption.TopDirectoryOnly), Mod.LoadFromDir);
            LoadMods(Extensions.GetAllFiles(modsPath, H3VR.Sideloader.Shared.Info.ModExts.Select(s => $"*.{s}").ToArray()),
                     Mod.LoadFromZip);

            // TODO: Sanity checking etc

            foreach (var loader in loaders)
            {
                Logger.LogDebug($"Loading {loader}");
                loader.Initialize(mods);
            }


            Logger.LogInfo($"Loaded {mods.Count} mods!");
        }
Esempio n. 16
0
        private static Texture2D LoadPNG(string file)
        {
            byte[] array;

            using (var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read))
                using (var binaryReader = new BinaryReader(fileStream))
                {
                    try
                    {
                        array = binaryReader.ReadBytes((int)binaryReader.BaseStream.Length);
                    }
                    catch (Exception ex)
                    {
                        Logger.LogWarning(ex);
                        array = null;
                    }

                    binaryReader.Close();
                }

            if (array == null)
            {
                return(null);
            }

            var texture2D = new Texture2D(1, 1, TextureFormat.ARGB32, false);

            texture2D.LoadImage(array);
            return(texture2D);
        }
Esempio n. 17
0
        public HCSLoader()
        {
            Logger = base.Logger;

            var harmonyInstance = HarmonyWrapper.PatchAll();

            harmonyInstance.Patch(AccessTools.Constructor(typeof(Game), Type.EmptyTypes), postfix: new HarmonyMethod(typeof(HCSLoader), nameof(LoadGirlsHook)));

            string modsDirectory = Path.Combine(Paths.GameRootPath, "Mods");

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

            foreach (var subdir in Directory.GetDirectories(modsDirectory, "*", SearchOption.TopDirectoryOnly))
            {
                if (CharacterAdditionMod.TryLoad(subdir, out var addMod))
                {
                    CharacterAdditions.Add(addMod);
                }
                else if (CharacterModificationMod.TryLoad(subdir, out var editMod))
                {
                    CharacterModifications.Add(editMod);
                }
                else
                {
                    Logger.LogWarning($"Unknown mod type for folder '{Path.GetFileName(subdir)}', skipping");
                }
            }

            Logger.Log(LogLevel.Message, $"Found {CharacterAdditions.Count + CharacterModifications.Count} mods.");
        }
Esempio n. 18
0
        private IPALoader()
        {
            IPAPluginsPath = CfgFile.Bind(Metadata.ConfigSection, Metadata.ConfigKey, Metadata.ConfigDefaultValue, Metadata.ConfigDescription);
            Logger         = base.Logger;

            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                var name = assembly.GetName().Name;
                if (name == "IllusionInjector" || name == "IllusionPlugin")
                {
                    Logger.LogWarning($"Detected that IPA is already installed! Please either uninstall IPA or disable this loader.");
                    run = false;
                    return;
                }
            }

            // Redirect missing assembly requests to this assembly, since we have all the emulated code
            AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
            {
                var name = new AssemblyName(args.Name).Name;
                if (name == "IllusionPlugin" || name == "IllusionInjector")
                {
                    return(Assembly.GetExecutingAssembly());
                }

                return(null);
            };
        }
Esempio n. 19
0
        public void Awake()
        {
            Logger = base.Logger;
            Extension.Logger.logger = Logger;

            AddtionalFolder = Config.Bind <string>("Config", "Menu Addtional Text Folder", GetRelativePath(BepInEx.Paths.BepInExRootPath, Path.Combine(Path.GetDirectoryName(base.Info.Location), nameof(KK_StudioMenuScrollingText))));
            Speed           = Config.Bind <int>("Config", "Scrolling speed", 777, new ConfigDescription("σ`∀´)σ", new AcceptableValueRange <int>(666, 888)));
            if (!Directory.Exists(AddtionalFolder.Value))
            {
                Directory.CreateDirectory(AddtionalFolder.Value);
            }
            else
            {
                foreach (string path in Directory.GetFiles(AddtionalFolder.Value).ToList <string>().Where(s => s.EndsWith(".csv")))
                {
                    try {
                        File.ReadAllLines(path).Select(a => a.Split(',')).ToList().ForEach(s => {
                            if (s[0] == "Before")
                            {
                                HeaderDict[int.Parse(s[1])] = s[2];
                            }
                            else if (s[0] == "After")
                            {
                                FooterDict[int.Parse(s[1])] = s[2];
                            }
                        });
                    } catch (Exception) {
                        Logger.LogWarning($"Load addtional text faild in: {path}");
                        return;
                    };
                }
            }

            Harmony.CreateAndPatchAll(typeof(Patches));
        }
Esempio n. 20
0
        private void Init()
        {
            try
            {
                var methodField = UnhollowerUtils.GetIl2CppMethodInfoPointerFieldForGeneratedMethod(Original);

                if (methodField == null)
                {
                    throw new Exception($"No IL2CPP equivalent found for {Original.FullDescription()}. The target might have been automatically generated by Unhollower (e.g. field accessor).");
                }

                // Get the native MethodInfo struct for the target method
                originalNativeMethodInfo = (Il2CppMethodInfo *)(IntPtr)methodField.GetValue(null);

                // Create a trampoline from the original target method

                var trampolinePtr = DetourGenerator.CreateTrampolineFromFunction(originalNativeMethodInfo->methodPointer, out _, out _);

                // Create a modified native MethodInfo struct to point towards the trampoline

                modifiedNativeMethodInfo = (Il2CppMethodInfo *)Marshal.AllocHGlobal(Marshal.SizeOf <Il2CppMethodInfo>());
                Marshal.StructureToPtr(*originalNativeMethodInfo, (IntPtr)modifiedNativeMethodInfo, false);

                modifiedNativeMethodInfo->methodPointer = trampolinePtr;
                isValid = true;
            }
            catch (Exception e)
            {
                DetourLogger.LogWarning($"Failed to init IL2CPP patch backend for {Original.FullDescription()}, using normal patch handlers: {e.Message}");
            }
        }
Esempio n. 21
0
 public static void Warning(string str, params object[] args)
 {
     if (IsGlobalEnabled && IsWarnEnabled)
     {
         LogInstance?.LogWarning(string.Format(str, args));
     }
 }
Esempio n. 22
0
        /// <summary>
        /// 替換角色
        /// </summary>
        /// <param name="chaCtrl">目標chara</param>
        /// <param name="changeFace">是否替換臉部</param>
        /// <param name="changeBody">是否替換身體</param>
        public static void ChangeChara(ChaControl chaCtrl, bool changeFace = true, bool changeBody = true, bool disableDoubleChange = true)
        {
            if (Hooks.BlockChanging || null == chaCtrl || null == chaCtrl.chaFile)
            {
                return;
            }

            FBIOpenUp.SetCharaPath(null, null);

            if (chaCtrl.chaFile.parameter.sex != SampleChara.chaFile.parameter.sex)
            {
                Logger.LogWarning($"Skip changes that differ from Sample Chara's gender: {chaCtrl.fileParam.fullname}");
                return;
            }

            List <float> originalShapeValueFace;
            List <float> originalShapeValueBody;

            ChaFileCustom chaFileCustom = chaCtrl.chaFile.custom;

            originalShapeValueFace = chaFileCustom.face.shapeValueFace.ToList();
            originalShapeValueBody = chaFileCustom.body.shapeValueBody.ToList();

            //如果角色第一次替換,紀錄其原始數據至dict
            //如果在dict內有找到替換紀錄,以其原始數據來做替換
            //(不block掉是因為,即使在單次Loading Chara內,此function也會被trigger不止一次)
            if (chaFileCustomDict.TryGetValue(chaFileCustom, out List <float>[] chaFileCustomStored))
Esempio n. 23
0
        IEnumerator LoadAssetBundles(Action callback = null)
        {
            foreach (var bundleName in fileLoader.GetResourceFilenames("AssetBundle"))
            {
                var path = Path.Combine(m_bundleLoadDir, bundleName);

                m_bundleCreateRequest = AssetBundle.LoadFromFileAsync(path);
                yield return(m_bundleCreateRequest);

                AssetBundle bundle = m_bundleCreateRequest.assetBundle;
                if (bundle == null)
                {
                    Logger.LogWarning("Failed to load AssetBundle: " + bundleName);
                    yield return(bundle);
                }
                else
                {
                    Logger.LogInfo("Successfully loaded additional bundle named: " + bundle.name);
                    Bundles.Add(bundle);
                }
            }

            BundlesLoaded = true;
            StartCoroutine(LoadAllAssetsInBundle(callback));
        }
Esempio n. 24
0
 internal static byte[] MessagePackSerialize <T>(T obj)
 {
     try
     {
         return(MessagePackSerializer.Serialize(obj, StandardResolver.Instance));
     }
     catch (FormatterNotRegisteredException)
     {
         return(MessagePackSerializer.Serialize(obj, ContractlessStandardResolver.Instance));
     }
     catch (InvalidOperationException)
     {
         Logger.LogWarning("Only primitive types are supported. Serialize your data first.");
         throw;
     }
 }
Esempio n. 25
0
        private static void BepinexLog(object input, LogLevel level)
        {
            if (logger == null)
            {
                throw new System.NullReferenceException("Log Class in " + Assembly.GetExecutingAssembly().GetName().Name + " not initialized prior to message call!");
            }
            switch (level)
            {
            case LogLevel.Info:
                if (BepinexInfoAlwaysLogs || DebugConvar.value)
                {
                    logger.LogInfo(input);
                }
                break;

            case LogLevel.Message:
                logger.LogMessage(input);
                break;

            case LogLevel.Warning:
                logger.LogWarning(input);
                break;

            case LogLevel.Error:
                logger.LogError(input);
                break;
            }
        }
Esempio n. 26
0
        public static void MechaDroneLogic_ReloadStates_Postfix()
        {
            Texture2D newTexture = new Texture2D(512, 512);

            // Original GameMain.mainPlayer.mecha.droneRenderer.mat_0.color = (0.175, 0.461, 1.000, 1.000) = 45, 118, 255

            string filePath = $"{BepInEx.Paths.ConfigPath}/{pluginGuid}.png";

            if (System.IO.File.Exists(filePath))
            {
                byte[] fileData = System.IO.File.ReadAllBytes(filePath);
                newTexture.LoadImage(fileData);
                Logger.LogInfo($"Successfully loaded drone skin {filePath}");

                for (int x = 0; x < newTexture.width; x++)
                {
                    for (int y = 0; y < newTexture.height; y++)
                    {
                        Color pixel = newTexture.GetPixel(x, y);
                        newTexture.SetPixel(x, y, new Color(pixel.r, pixel.g, pixel.b, 0));
                    }
                }
                newTexture.Apply();

                // Original made up of 512x512 construction-drone-a.png, construction-drone-n.png, construction-drone-s.png
                // Changing this changes all drones simultaneously.
                // The change takes effect when MechaDroneRenderer.Draw is called which is called constantly.
                GameMain.mainPlayer.mecha.droneRenderer.mat_0.mainTexture = newTexture;
            }
            else
            {
                string cwd = System.IO.Directory.GetCurrentDirectory();
                Logger.LogWarning($"Unable to find drone skin at {cwd}/{filePath}");
            }
        }
Esempio n. 27
0
        public R2API()
        {
            Logger     = base.Logger;
            ModManager = new DetourModManager();
            AddHookLogging();
            CheckForIncompatibleAssemblies();
            CheckR2APIMonomodPatch();

            Environment.SetEnvironmentVariable("MONOMOD_DMD_TYPE", "Cecil");

            On.RoR2.RoR2Application.UnitySystemConsoleRedirector.Redirect += orig => { };
            var submoduleHandler = new APISubmoduleHandler(GameBuild, Logger);

            submoduleHandler.LoadRequested();

            RoR2Application.isModded = true;

            //This needs to always be enabled, regardless of module dependency, or it is useless
            ModListAPI.Init();

            On.RoR2.DisableIfGameModded.OnEnable += (orig, self) => {
                // TODO: If we can enable quick play without regrets, uncomment.
                //if (self.name == "Button, QP")
                //    return;

                self.gameObject.SetActive(false);
            };

            SteamworksClientManager.onLoaded += () => {
                var buildId =
                    SteamworksClientManager.instance.GetFieldValue <Client>("steamworksClient").BuildId;

                if (GameBuild == buildId)
                {
                    return;
                }

                Logger.LogWarning($"This version of R2API was built for build id \"{GameBuild}\", you are running \"{buildId}\".");
                Logger.LogWarning("Should any problems arise, please check for a new version before reporting issues.");
            };

            On.RoR2.SteamworksServerManager.UpdateHostName += (orig, self, hostname) => {
                orig(self, $"[MOD] {hostname}");
                var server = ((SteamworksServerManager)self).GetFieldValue <Server>("steamworksServer");
                server.GameTags = "mod," + server.GameTags;
            };
        }
Esempio n. 28
0
 /// <summary>
 /// Disables Multiplayer Testing.
 /// </summary>
 /// <param name="logger">BepInEx logger instance</param>
 /// <param name="message">Message to display when Multiplayer Testing is disabled</param>
 public static void Disable(ManualLogSource logger, string message = defaultDisableMessage)
 {
     if (logger != null)
     {
         logger.LogWarning(message);
     }
     Disable();
 }
Esempio n. 29
0
        public void Awake()
        {
            harmony = new Harmony(PluginId);
            logger  = base.Logger;
            logger.LogWarning($"This mod will Remove some DIY Ammor Data");

            harmony.PatchAll(typeof(Patch));
        }
Esempio n. 30
0
        static HookgenPreloader()
        {
            Logging.LogMessage($"BepInEx-Partiality-Wrapper initializing HOOKS...");

            if (!File.Exists(AsmCSharpFilePath))
            {
                Logging.LogMessage($"Could not find 'Assembly-CSharp.dll' file, aborting HOOKS generatiion.");
                return;
            }

            if (File.Exists(HooksAsmFilePath))
            {
                // if HOOKS file is older than the Assembly-Csharp file...
                if (File.GetLastWriteTime(HooksAsmFilePath) < File.GetLastWriteTime(AsmCSharpFilePath))
                {
                    Logging.LogMessage($"HOOKS file is outdated, deleting...");
                    File.Delete(HooksAsmFilePath);
                }
                else
                {
                    Logging.LogMessage($"HOOKS file is up to date!");
                    return;
                }
            }

            Logging.LogMessage("Generating new HOOKS file...");

            try
            {
                using (var modder = new MonoModder
                {
                    InputPath = AsmCSharpFilePath,
                    OutputPath = HooksAsmFilePath,
                    PublicEverything = true,
                    DependencyDirs = new List <string> {
                        Paths.ManagedPath, HookgenPatcherFolder
                    }
                })
                {
                    modder.Read();
                    modder.MapDependencies();
                    var generator = new HookGenerator(modder, Path.GetFileName(HooksAsmFilePath));
                    using (ModuleDefinition module = generator.OutputModule)
                    {
                        generator.HookPrivate = true;
                        generator.Generate();
                        module.Write(HooksAsmFilePath);
                    }
                }

                Logging.LogMessage("Done!");
            }
            catch (Exception ex)
            {
                Logging.LogWarning($"Exception running HOOKS generation!");
                Logging.LogMessage(ex);
            }
        }