Example #1
0
        public void TestCommandLine()
        {
            CommandLine cmdline = new CommandLine(new string[] { "-batchmode", "+server.hostname", "My", "Server", "Name", "+server.port", "28015", "+server.identity", "facepunchdev", "+server.seed", "6738" });

            Assert.AreEqual(true, cmdline.HasVariable("batchmode"), "Failed cmdline.HasFlag");
            Assert.AreEqual(false, cmdline.HasVariable("random"), "Failed cmdline.HasFlag");
            Assert.AreEqual(false, cmdline.HasVariable("server.hostname"), "Failed cmdline.HasFlag");

            Assert.AreEqual(true, cmdline.HasVariable("server.hostname"), "Failed cmdline.HasVariable");
            Assert.AreEqual(true, cmdline.HasVariable("server.port"), "Failed cmdline.HasVariable");
            Assert.AreEqual(true, cmdline.HasVariable("server.identity"), "Failed cmdline.HasVariable");
            Assert.AreEqual(true, cmdline.HasVariable("server.seed"), "Failed cmdline.HasVariable");
            Assert.AreEqual(false, cmdline.HasVariable("server.random"), "Failed cmdline.HasVariable");
            Assert.AreEqual(false, cmdline.HasVariable("batchmode"), "Failed cmdline.HasVariable");

            Assert.AreEqual("My Server Name", cmdline.GetVariable("server.hostname"), "Failed cmdline.GetVariable");
            Assert.AreEqual("28015", cmdline.GetVariable("server.port"), "Failed cmdline.GetVariable");
            Assert.AreEqual("facepunchdev", cmdline.GetVariable("server.identity"), "Failed cmdline.GetVariable");
            Assert.AreEqual("6738", cmdline.GetVariable("server.seed"), "Failed cmdline.GetVariable");
            Assert.AreEqual(null, cmdline.GetVariable("server.random"), "Failed cmdline.GetVariable");
            Assert.AreEqual(null, cmdline.GetVariable("batchmode"), "Failed cmdline.GetVariable");
        }
Example #2
0
        /// <summary>
        /// Initializes a new instance of the OxideMod class
        /// </summary>
        public void Load()
        {
            RootDirectory = Environment.CurrentDirectory;
            if (RootDirectory.StartsWith(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)))
            {
                RootDirectory = AppDomain.CurrentDomain.BaseDirectory;
            }

            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
            JsonConvert.DefaultSettings         = () => new JsonSerializerSettings {
                Culture = CultureInfo.InvariantCulture
            };

            // Create the commandline
            CommandLine = new CommandLine(Environment.GetCommandLineArgs());

            // Load the config
            var oxideConfig = Path.Combine(RootDirectory, "oxide.config.json");

            if (!File.Exists(oxideConfig))
            {
                throw new FileNotFoundException("Could not load the Oxide configuration file", oxideConfig);
            }
            Config = ConfigFile.Load <OxideConfig>(oxideConfig);
            Config.Save();

            // Work out the instance directory
            for (var i = 0; i < Config.InstanceCommandLines.Length; i++)
            {
                string varname, format;
                Config.GetInstanceCommandLineArg(i, out varname, out format);
                if (string.IsNullOrEmpty(varname) || CommandLine.HasVariable(varname))
                {
                    InstanceDirectory = Path.Combine(RootDirectory, Utility.CleanPath(string.Format(format, CommandLine.GetVariable(varname))));
                    break;
                }
            }
            if (InstanceDirectory == null)
            {
                throw new Exception("Could not identify instance directory");
            }

            // Clean and set directory paths
            ExtensionDirectory = Path.Combine(RootDirectory, Utility.CleanPath(Config.ExtensionDirectory));
            PluginDirectory    = Path.Combine(InstanceDirectory, Utility.CleanPath("plugins"));
            DataDirectory      = Path.Combine(InstanceDirectory, Utility.CleanPath("data"));
            LangDirectory      = Path.Combine(InstanceDirectory, Utility.CleanPath("lang"));
            LogDirectory       = Path.Combine(InstanceDirectory, Utility.CleanPath("logs"));
            ConfigDirectory    = Path.Combine(InstanceDirectory, Utility.CleanPath(Config.ConfigDirectory));

            // Create directories if needed
            if (!Directory.Exists(ExtensionDirectory))
            {
                throw new Exception("Could not identify extension directory");
            }
            if (!Directory.Exists(InstanceDirectory))
            {
                Directory.CreateDirectory(InstanceDirectory);
            }
            if (!Directory.Exists(PluginDirectory))
            {
                Directory.CreateDirectory(PluginDirectory);
            }
            if (!Directory.Exists(DataDirectory))
            {
                Directory.CreateDirectory(DataDirectory);
            }
            if (!Directory.Exists(LangDirectory))
            {
                Directory.CreateDirectory(LangDirectory);
            }
            if (!Directory.Exists(LogDirectory))
            {
                Directory.CreateDirectory(LogDirectory);
            }
            if (!Directory.Exists(ConfigDirectory))
            {
                Directory.CreateDirectory(ConfigDirectory);
            }

            // Register the library path
            RegisterLibrarySearchPath(Path.Combine(ExtensionDirectory, IntPtr.Size == 8 ? "x64" : "x86"));

            // Set the default group
            DefaultGroup = Config.DefaultGroup;

            // Create the loggers
            RootLogger = new CompoundLogger();
            RootLogger.AddLogger(new RotatingFileLogger {
                Directory = LogDirectory
            });
            if (debugCallback != null)
            {
                RootLogger.AddLogger(new CallbackLogger(debugCallback));
            }

            // Log Oxide core loading
            LogInfo("Loading Oxide Core v{0}...", Version);

            // Create the managers
            RootPluginManager = new PluginManager(RootLogger)
            {
                ConfigPath = ConfigDirectory
            };
            extensionManager = new ExtensionManager(RootLogger);

            // Initialize other things
            DataFileSystem = new DataFileSystem(DataDirectory);

            // Register core libraries
            extensionManager.RegisterLibrary("Covalence", covalence = new Covalence());
            extensionManager.RegisterLibrary("Global", new Global());
            extensionManager.RegisterLibrary("Lang", new Lang());
            extensionManager.RegisterLibrary("Permission", new Permission());
            extensionManager.RegisterLibrary("Plugins", new Libraries.Plugins(RootPluginManager));
            extensionManager.RegisterLibrary("Time", new Time());
            extensionManager.RegisterLibrary("Timer", libtimer = new Timer());
            extensionManager.RegisterLibrary("WebRequests", new WebRequests());

            // Load all extensions
            LogInfo("Loading extensions...");
            extensionManager.LoadAllExtensions(ExtensionDirectory);

            // Initialize covalence library after extensions (as it depends on things from within an ext)
            covalence.Initialize();

            // Remove old files
            Cleanup.Add(Path.Combine(Interface.Oxide.RootDirectory, "oxide.root.json"));
            Cleanup.Run();

            // If no clock has been defined, make our own unreliable clock
            if (getTimeSinceStartup == null)
            {
                timer = new Stopwatch();
                timer.Start();
                getTimeSinceStartup = () => (float)timer.Elapsed.TotalSeconds;
                LogWarning("A reliable clock is not available, falling back to a clock which may be unreliable on certain hardware");
            }

            // Load all watchers
            foreach (var ext in extensionManager.GetAllExtensions())
            {
                ext.LoadPluginWatchers(PluginDirectory);
            }

            // Load all plugins
            LogInfo("Loading plugins...");
            LoadAllPlugins(true);

            // Hook all watchers
            foreach (var watcher in extensionManager.GetPluginChangeWatchers())
            {
                watcher.OnPluginSourceChanged += watcher_OnPluginSourceChanged;
                watcher.OnPluginAdded         += watcher_OnPluginAdded;
                watcher.OnPluginRemoved       += watcher_OnPluginRemoved;
            }

            // Check for 'load' variable and warn
            if (CommandLine.HasVariable("load"))
            {
                LogWarning("The 'load' variable is unused and can be removed");
            }

            // Check for 'nolog' variable and warn
            if (CommandLine.HasVariable("nolog"))
            {
                LogWarning("Usage of the 'nolog' variable will prevent logging");
            }
        }
Example #3
0
        /// <summary>
        /// Initialises a new instance of the OxideMod class
        /// </summary>
        public void Load()
        {
            // Create the commandline
            commandline = new CommandLine(Environment.CommandLine);

            // Load the config
            if (!File.Exists("oxide.root.json"))
            {
                throw new FileNotFoundException("Could not load Oxide root configuration", "oxide.root.json");
            }
            rootconfig = ConfigFile.Load <OxideConfig>("oxide.root.json");

            // Work out the instance directory
            for (int i = 0; i < rootconfig.InstanceCommandLines.Length; i++)
            {
                string varname, format;
                rootconfig.GetInstanceCommandLineArg(i, out varname, out format);
                if (string.IsNullOrEmpty(varname) || commandline.HasVariable(varname))
                {
                    InstanceDirectory = Path.Combine(Environment.CurrentDirectory, string.Format(format, commandline.GetVariable(varname)));
                    break;
                }
            }
            if (InstanceDirectory == null)
            {
                throw new Exception("Could not identify instance directory");
            }
            ExtensionDirectory = Path.Combine(Environment.CurrentDirectory, rootconfig.ExtensionDirectory);
            PluginDirectory    = Path.Combine(InstanceDirectory, rootconfig.PluginDirectory);
            DataDirectory      = Path.Combine(InstanceDirectory, rootconfig.DataDirectory);
            LogDirectory       = Path.Combine(InstanceDirectory, rootconfig.LogDirectory);
            ConfigDirectory    = Path.Combine(InstanceDirectory, rootconfig.ConfigDirectory);
            TempDirectory      = Path.Combine(InstanceDirectory, rootconfig.TempDirectory);
            if (!Directory.Exists(ExtensionDirectory))
            {
                throw new Exception("Could not identify extension directory");
            }
            if (!Directory.Exists(InstanceDirectory))
            {
                Directory.CreateDirectory(InstanceDirectory);
            }
            if (!Directory.Exists(PluginDirectory))
            {
                Directory.CreateDirectory(PluginDirectory);
            }
            if (!Directory.Exists(DataDirectory))
            {
                Directory.CreateDirectory(DataDirectory);
            }
            if (!Directory.Exists(LogDirectory))
            {
                Directory.CreateDirectory(LogDirectory);
            }
            if (!Directory.Exists(ConfigDirectory))
            {
                Directory.CreateDirectory(ConfigDirectory);
            }
            if (!Directory.Exists(TempDirectory))
            {
                Directory.CreateDirectory(TempDirectory);
            }

            // Create the loggers
            filelogger           = new RotatingFileLogger();
            filelogger.Directory = LogDirectory;
            rootlogger           = new CompoundLogger();
            rootlogger.AddLogger(filelogger);

            // Log Oxide core loading
            rootlogger.Write(LogType.Info, "Loading Oxide core v{0}...", Version);

            // Create the managers
            pluginmanager = new PluginManager(rootlogger)
            {
                ConfigPath = ConfigDirectory
            };
            extensionmanager = new ExtensionManager(rootlogger);

            // Register core libraries
            libglobal = new Global();
            extensionmanager.RegisterLibrary("Global", libglobal);
            libtimer = new Timer();
            extensionmanager.RegisterLibrary("Timer", libtimer);
            libtime = new Time();
            extensionmanager.RegisterLibrary("Time", libtime);
            libplugins = new Libraries.Plugins(pluginmanager);
            extensionmanager.RegisterLibrary("Plugins", libplugins);
            libwebrequests = new WebRequests();
            extensionmanager.RegisterLibrary("WebRequests", libwebrequests);

            // Initialise other things
            DataFileSystem = new DataFileSystem(DataDirectory);

            // Load all extensions
            rootlogger.Write(LogType.Info, "Loading extensions...");
            extensionmanager.LoadAllExtensions(ExtensionDirectory);

            // Load all watchers
            foreach (Extension ext in extensionmanager.GetAllExtensions())
            {
                ext.LoadPluginWatchers(PluginDirectory);
            }

            // Load all plugins
            rootlogger.Write(LogType.Info, "Loading plugins...");
            LoadAllPlugins();

            // Hook all watchers
            foreach (PluginChangeWatcher watcher in extensionmanager.GetPluginChangeWatchers())
            {
                watcher.OnPluginSourceChanged += watcher_OnPluginSourceChanged;
                watcher.OnPluginAdded         += watcher_OnPluginAdded;
                watcher.OnPluginRemoved       += watcher_OnPluginRemoved;
            }
        }
Example #4
0
        /// <summary>
        /// Initializes a new instance of the OxideMod class
        /// </summary>
        public void Load()
        {
            RootDirectory = Environment.CurrentDirectory;
            if (RootDirectory.StartsWith(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)))
            {
                RootDirectory = AppDomain.CurrentDomain.BaseDirectory;
            }

            if (RootDirectory == null)
            {
                throw new Exception("RootDirectory is null");
            }

            InstanceDirectory = Path.Combine(RootDirectory, "oxide");
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
            JsonConvert.DefaultSettings         = () => new JsonSerializerSettings {
                Culture = CultureInfo.InvariantCulture
            };
            CommandLine = new CommandLine(Environment.GetCommandLineArgs());

            if (CommandLine.HasVariable("oxide.directory"))
            {
                CommandLine.GetArgument("oxide.directory", out string var, out string format);
                if (string.IsNullOrEmpty(var) || CommandLine.HasVariable(var))
                {
                    InstanceDirectory = Path.Combine(RootDirectory, Utility.CleanPath(string.Format(format, CommandLine.GetVariable(var))));
                }
            }

            ExtensionDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            if (ExtensionDirectory == null || !Directory.Exists(ExtensionDirectory))
            {
                throw new Exception("Could not identify extension directory");
            }

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

            ConfigDirectory = Path.Combine(InstanceDirectory, Utility.CleanPath("config"));
            if (!Directory.Exists(ConfigDirectory))
            {
                Directory.CreateDirectory(ConfigDirectory);
            }

            DataDirectory = Path.Combine(InstanceDirectory, Utility.CleanPath("data"));
            if (!Directory.Exists(DataDirectory))
            {
                Directory.CreateDirectory(DataDirectory);
            }

            LangDirectory = Path.Combine(InstanceDirectory, Utility.CleanPath("lang"));
            if (!Directory.Exists(LangDirectory))
            {
                Directory.CreateDirectory(LangDirectory);
            }

            LogDirectory = Path.Combine(InstanceDirectory, Utility.CleanPath("logs"));
            if (!Directory.Exists(LogDirectory))
            {
                Directory.CreateDirectory(LogDirectory);
            }

            PluginDirectory = Path.Combine(InstanceDirectory, Utility.CleanPath("plugins"));
            if (!Directory.Exists(PluginDirectory))
            {
                Directory.CreateDirectory(PluginDirectory);
            }

            RegisterLibrarySearchPath(Path.Combine(ExtensionDirectory, IntPtr.Size == 8 ? "x64" : "x86"));

            string config = Path.Combine(InstanceDirectory, "oxide.config.json");

            if (File.Exists(config))
            {
                Config = ConfigFile.Load <OxideConfig>(config);
            }
            else
            {
                Config = new OxideConfig(config);
                Config.Save();
            }

            if (CommandLine.HasVariable("web.ip"))
            {
                Config.Options.WebRequestIP = CommandLine.GetVariable("web.ip");
            }

            if (CommandLine.HasVariable("rcon.port"))
            {
                Config.Rcon.Port = Utility.GetNumbers(CommandLine.GetVariable("rcon.port"));
            }

            if (CommandLine.HasVariable("rcon.password"))
            {
                Config.Rcon.Password = CommandLine.GetVariable("rcon.password");
            }

            RootLogger = new CompoundLogger();
            RootLogger.AddLogger(new RotatingFileLogger {
                Directory = LogDirectory
            });
            if (debugCallback != null)
            {
                RootLogger.AddLogger(new CallbackLogger(debugCallback));
            }

            if (CommandLine.HasVariable("nolog"))
            {
                LogWarning("Usage of the 'nolog' variable will prevent logging");
            }

            LogInfo("Loading Oxide Core v{0}...", Version);

            RootPluginManager = new PluginManager(RootLogger)
            {
                ConfigPath = ConfigDirectory
            };
            extensionManager = new ExtensionManager(RootLogger);
            DataFileSystem   = new DataFileSystem(DataDirectory);

            extensionManager.RegisterLibrary("Covalence", covalence = new Covalence());
            extensionManager.RegisterLibrary("Global", new Global());
            extensionManager.RegisterLibrary("Lang", new Lang());
            extensionManager.RegisterLibrary("Permission", libperm = new Permission());
            extensionManager.RegisterLibrary("Plugins", new Libraries.Plugins(RootPluginManager));
            extensionManager.RegisterLibrary("Time", new Time());
            extensionManager.RegisterLibrary("Timer", libtimer = new Timer());
            extensionManager.RegisterLibrary("WebRequests", new WebRequests());

            LogInfo("Loading extensions...");
            extensionManager.LoadAllExtensions(ExtensionDirectory);

            Cleanup.Run();
            covalence.Initialize();
            RemoteConsole = new RemoteConsole.RemoteConsole();
            RemoteConsole?.Initalize();

            if (getTimeSinceStartup == null)
            {
                timer = new Stopwatch();
                timer.Start();
                getTimeSinceStartup = () => (float)timer.Elapsed.TotalSeconds;
                LogWarning("A reliable clock is not available, falling back to a clock which may be unreliable on certain hardware");
            }

            foreach (Extension ext in extensionManager.GetAllExtensions())
            {
                ext.LoadPluginWatchers(PluginDirectory);
            }

            LogInfo("Loading plugins...");
            LoadAllPlugins(true);

            foreach (PluginChangeWatcher watcher in extensionManager.GetPluginChangeWatchers())
            {
                watcher.OnPluginSourceChanged += watcher_OnPluginSourceChanged;
                watcher.OnPluginAdded         += watcher_OnPluginAdded;
                watcher.OnPluginRemoved       += watcher_OnPluginRemoved;
            }
        }
Example #5
0
        /// <summary>
        /// Called when all other extensions have been loaded
        /// </summary>
        public override void OnModLoad()
        {
            if (!Interface.Oxide.EnableConsole()) return;

            if (File.Exists(LogFileName)) File.Delete(LogFileName);
            var logStream = File.AppendText(LogFileName);
            logStream.AutoFlush = true;
            logWriter = TextWriter.Synchronized(logStream);

            Application.logMessageReceivedThreaded += HandleLog;
            Interface.Oxide.ServerConsole.Input += ServerConsoleOnInput;

            // Override default server settings
            //var boltInit = UnityEngine.Object.FindObjectOfType<BoltInit>();
            //var serverAddress = typeof(BoltInit).GetField("serverAddress", BindingFlags.NonPublic | BindingFlags.Instance);
            //var serverPort = typeof(BoltInit).GetField("serverPort", BindingFlags.NonPublic | BindingFlags.Instance);
            var commandLine = new CommandLine(Environment.GetCommandLineArgs());
            //if (commandLine.HasVariable("ip")) serverAddress?.SetValue(boltInit, commandLine.GetVariable("ip"));
            //if (commandLine.HasVariable("port")) serverPort?.SetValue(boltInit, commandLine.GetVariable("port"));
            if (commandLine.HasVariable("maxplayers")) PlayerPrefs.SetInt("MpGamePlayerCount", int.Parse(commandLine.GetVariable("maxplayers")));
            if (commandLine.HasVariable("hostname")) PlayerPrefs.SetString("MpGameName", commandLine.GetVariable("hostname"));
            if (commandLine.HasVariable("friendsonly"))  PlayerPrefs.SetInt("MpGameFriendsOnly", int.Parse(commandLine.GetVariable("friendsonly")));
            if (commandLine.HasVariable("saveslot")) TitleScreen.StartGameSetup.Slot = (TitleScreen.GameSetup.Slots) int.Parse(commandLine.GetVariable("saveslot"));
            //if (commandLine.HasVariable("saveinterval")) /* TODO */

            // Disable client audio for server
            TheForestCore.DisableAudio();

            // Limit FPS to reduce CPU usage
            PlayerPreferences.MaxFrameRate = 60;

            Interface.Oxide.ServerConsole.Title = () =>
            {
                if (CoopLobby.Instance == null) return string.Empty;
                var players = CoopLobby.Instance.MemberCount;
                var hostname = CoopLobby.Instance.Info.Name;
                return string.Concat(players, " | ", hostname);
            };

            Interface.Oxide.ServerConsole.Status1Left = () =>
            {
                if (CoopLobby.Instance == null) return string.Empty;
                var hostname = CoopLobby.Instance.Info.Name;
                return string.Concat(" ", hostname);
            };
            Interface.Oxide.ServerConsole.Status1Right = () =>
            {
                var fps = Mathf.RoundToInt(1f / Time.smoothDeltaTime);
                var seconds = TimeSpan.FromSeconds(Time.realtimeSinceStartup);
                var uptime = $"{seconds.TotalHours:00}h{seconds.Minutes:00}m{seconds.Seconds:00}s".TrimStart(' ', 'd', 'h', 'm', 's', '0');
                return string.Concat(fps, "fps, ", uptime);
            };

            Interface.Oxide.ServerConsole.Status2Left = () =>
            {
                if (CoopLobby.Instance == null) return string.Empty;
                var players = CoopLobby.Instance.MemberCount;
                var playerLimit = CoopLobby.Instance.Info.MemberLimit;
                return string.Concat(" ", players, "/", playerLimit, " players");
            };
            Interface.Oxide.ServerConsole.Status2Right = () =>
            {
                // TODO: Network in/out
                return string.Empty;
            };

            Interface.Oxide.ServerConsole.Status3Left = () =>
            {
                //var gameTime = TheForestAtmosphere.Instance?.TimeOfDay; // TODO: Fix NRE and format
                return string.Concat(string.Empty/*, gameTime*/);
            };
            Interface.Oxide.ServerConsole.Status3Right = () =>
            {
                var gameVersion = "0.30b"; // TODO: Grab version
                var oxideVersion = OxideMod.Version.ToString();
                return string.Concat("Oxide ", oxideVersion, " for ", gameVersion);
            };
            Interface.Oxide.ServerConsole.Status3RightColor = ConsoleColor.Yellow;
        }
Example #6
0
        /// <summary>
        /// Initializes a new instance of the OxideMod class
        /// </summary>
        public void Load()
        {
            RootDirectory = Environment.CurrentDirectory;
            if (RootDirectory.StartsWith(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)))
            {
                RootDirectory = AppDomain.CurrentDomain.BaseDirectory;
            }

            // Create the commandline
            commandline = new CommandLine(Environment.GetCommandLineArgs());

            // Load the config
            var oxideConfig = Path.Combine(RootDirectory, "oxide.root.json");

            if (!File.Exists(oxideConfig))
            {
                throw new FileNotFoundException("Could not load Oxide root configuration", oxideConfig);
            }
            rootconfig = ConfigFile.Load <OxideConfig>(oxideConfig);

            // Work out the instance directory
            for (int i = 0; i < rootconfig.InstanceCommandLines.Length; i++)
            {
                string varname, format;
                rootconfig.GetInstanceCommandLineArg(i, out varname, out format);
                if (string.IsNullOrEmpty(varname) || commandline.HasVariable(varname))
                {
                    InstanceDirectory = Path.Combine(RootDirectory, CleanPath(string.Format(format, commandline.GetVariable(varname))));
                    break;
                }
            }
            if (InstanceDirectory == null)
            {
                throw new Exception("Could not identify instance directory");
            }
            ExtensionDirectory = Path.Combine(RootDirectory, CleanPath(rootconfig.ExtensionDirectory));
            PluginDirectory    = Path.Combine(InstanceDirectory, CleanPath(rootconfig.PluginDirectory));
            DataDirectory      = Path.Combine(InstanceDirectory, CleanPath(rootconfig.DataDirectory));
            LangDirectory      = Path.Combine(InstanceDirectory, CleanPath(rootconfig.LangDirectory));
            LogDirectory       = Path.Combine(InstanceDirectory, CleanPath(rootconfig.LogDirectory));
            ConfigDirectory    = Path.Combine(InstanceDirectory, CleanPath(rootconfig.ConfigDirectory));
            if (!Directory.Exists(ExtensionDirectory))
            {
                throw new Exception("Could not identify extension directory");
            }
            if (!Directory.Exists(InstanceDirectory))
            {
                Directory.CreateDirectory(InstanceDirectory);
            }
            if (!Directory.Exists(PluginDirectory))
            {
                Directory.CreateDirectory(PluginDirectory);
            }
            if (!Directory.Exists(DataDirectory))
            {
                Directory.CreateDirectory(DataDirectory);
            }
            if (!Directory.Exists(LangDirectory))
            {
                Directory.CreateDirectory(LangDirectory);
            }
            if (!Directory.Exists(LogDirectory))
            {
                Directory.CreateDirectory(LogDirectory);
            }
            if (!Directory.Exists(ConfigDirectory))
            {
                Directory.CreateDirectory(ConfigDirectory);
            }

            RegisterLibrarySearchPath(Path.Combine(ExtensionDirectory, IntPtr.Size == 8 ? "x64" : "x86"));

            // Create the loggers
            RootLogger = new CompoundLogger();
            RootLogger.AddLogger(new RotatingFileLogger {
                Directory = LogDirectory
            });
            if (debugCallback != null)
            {
                RootLogger.AddLogger(new CallbackLogger(debugCallback));
            }

            // Log Oxide core loading
            LogInfo("Loading Oxide Core v{0}...", Version);

            // Create the managers
            RootPluginManager = new PluginManager(RootLogger)
            {
                ConfigPath = ConfigDirectory
            };
            extensionmanager = new ExtensionManager(RootLogger);

            // Initialize other things
            DataFileSystem = new DataFileSystem(DataDirectory);

            // Register core libraries
            extensionmanager.RegisterLibrary("Global", new Global());
            extensionmanager.RegisterLibrary("Time", new Time());
            extensionmanager.RegisterLibrary("Timer", libtimer = new Timer());
            extensionmanager.RegisterLibrary("Permission", new Permission());
            extensionmanager.RegisterLibrary("Plugins", new Libraries.Plugins(RootPluginManager));
            extensionmanager.RegisterLibrary("WebRequests", new WebRequests());
            extensionmanager.RegisterLibrary("Lang", new Lang());
            extensionmanager.RegisterLibrary("Covalence", covalence = new Covalence());

            // Load all extensions
            LogInfo("Loading extensions...");
            extensionmanager.LoadAllExtensions(ExtensionDirectory);

            // Remove old files
            Cleanup.Run();

            // Initialize covalence library after extensions (as it depends on things from within an ext)
            covalence.Initialize();

            // If no clock has been defined, make our own
            if (getTimeSinceStartup == null)
            {
                timer = new Stopwatch();
                timer.Start();
                getTimeSinceStartup = () => (float)timer.Elapsed.TotalSeconds;
            }

            // Load all watchers
            foreach (var ext in extensionmanager.GetAllExtensions())
            {
                ext.LoadPluginWatchers(PluginDirectory);
            }

            // Load all plugins
            LogInfo("Loading plugins...");
            LoadAllPlugins();

            // Hook all watchers
            foreach (var watcher in extensionmanager.GetPluginChangeWatchers())
            {
                watcher.OnPluginSourceChanged += watcher_OnPluginSourceChanged;
                watcher.OnPluginAdded         += watcher_OnPluginAdded;
                watcher.OnPluginRemoved       += watcher_OnPluginRemoved;
            }
        }
Example #7
0
        /// <summary>
        /// Called when all other extensions have been loaded
        /// </summary>
        public override void OnModLoad()
        {
            // Get the game's version from mainData
            var regex = new Regex(@"Version v(\d+\.\d+[a-z]?)");
            using (var reader = new StreamReader(Path.Combine(Application.dataPath, "mainData")))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    var match = regex.Match(line);
                    if (!match.Success) continue;
                    GameVersion = match.Groups[1].Value;
                }
            }

            if (!Directory.Exists("logs")) Directory.CreateDirectory("logs");
            if (File.Exists(logFileName)) File.Delete(logFileName);
            var logStream = File.AppendText(logFileName);
            logStream.AutoFlush = true;
            logWriter = TextWriter.Synchronized(logStream);
            Application.logMessageReceivedThreaded += HandleLog;

            // Limit FPS to reduce CPU usage
            PlayerPreferences.MaxFrameRate = 60;

            // Override default server settings
            var commandLine = new CommandLine(Environment.GetCommandLineArgs());
            if (commandLine.HasVariable("maxplayers")) PlayerPrefs.SetInt("MpGamePlayerCount", int.Parse(commandLine.GetVariable("maxplayers")));
            if (commandLine.HasVariable("hostname")) PlayerPrefs.SetString("MpGameName", commandLine.GetVariable("hostname"));
            if (commandLine.HasVariable("friendsonly")) PlayerPrefs.SetInt("MpGameFriendsOnly", int.Parse(commandLine.GetVariable("friendsonly")));
            if (commandLine.HasVariable("saveslot")) PlayerPrefs.SetInt("MpGameSaveSlot", int.Parse(commandLine.GetVariable("saveslot")));
            //if (commandLine.HasVariable("saveinterval")) // TODO: Make this work
            //if (commandLine.HasVariable("gamemode")) // TODO: Make this work

            // Check if client should be disabled
            if (commandLine.HasVariable("batchmode") || commandLine.HasVariable("nographics"))
            {
                TheForestCore.DisableAudio();
                DisableClient = true;
            }

            if (Interface.Oxide.EnableConsole()) Interface.Oxide.ServerConsole.Input += ServerConsoleOnInput;
        }