Пример #1
0
        private static void Main(string[] args)
        {
            Log.SetLevel(Log.LogLevel.Info | Log.LogLevel.Debug);

            NitroxServiceLocator.InitializeDependencyContainer(new ServerAutoFacRegistrar());
            NitroxServiceLocator.BeginNewLifetimeScope();

            ConfigureCultureInfo();
            Server server;

            try
            {
                server = NitroxServiceLocator.LocateService <Server>();
                server.Start();
            }
            catch (Exception e)
            {
                Log.Error(e.ToString());
                return;
            }

            CatchExitEvent();

            ConsoleCommandProcessor cmdProcessor = NitroxServiceLocator.LocateService <ConsoleCommandProcessor>();

            while (server.IsRunning)
            {
                cmdProcessor.ProcessCommand(Console.ReadLine(), Optional <Player> .Empty(), Perms.CONSOLE);
            }
        }
Пример #2
0
        public void AllPacketsAreHandled()
        {
            List <Type> packetTypes = typeof(DefaultServerPacketProcessor).Assembly.GetTypes()
                                      .Where(p => typeof(PacketProcessor).IsAssignableFrom(p) && p.IsClass && !p.IsAbstract)
                                      .ToList();

            NitroxServiceLocator.InitializeDependencyContainer(new ClientAutoFacRegistrar(), new SubnauticaServerAutoFacRegistrar(), new TestAutoFacRegistrar());
            NitroxServiceLocator.BeginNewLifetimeScope();

            foreach (Type packet in typeof(Packet).Assembly.GetTypes()
                     .Where(p => typeof(Packet).IsAssignableFrom(p) && p.IsClass && !p.IsAbstract)
                     .ToList())
            {
                Type clientPacketProcessorType          = typeof(ClientPacketProcessor <>);
                Type authenticatedPacketProcessorType   = typeof(AuthenticatedPacketProcessor <>);
                Type unauthenticatedPacketProcessorType = typeof(UnauthenticatedPacketProcessor <>);

                Type clientProcessorType = clientPacketProcessorType.MakeGenericType(packet);
                Type authProcessorType   = authenticatedPacketProcessorType.MakeGenericType(packet);
                Type unauthProcessorType = unauthenticatedPacketProcessorType.MakeGenericType(packet);

                Console.WriteLine($@"Checking handler for packet {packet}...");
                (packetTypes.Contains(packet) ||
                 NitroxServiceLocator.LocateOptionalService(clientProcessorType).HasValue ||
                 NitroxServiceLocator.LocateOptionalService(authProcessorType).HasValue ||
                 NitroxServiceLocator.LocateOptionalService(unauthProcessorType).HasValue).Should()
                .BeTrue($"Packet of type '{packet}' should have at least one processor.");
            }
        }
Пример #3
0
        public void Setup()
        {
            NitroxServiceLocator.InitializeDependencyContainer(new SubnauticaServerAutoFacRegistrar(), new TestAutoFacRegistrar());
            NitroxServiceLocator.BeginNewLifetimeScope();

            tempSaveFilePath  = Path.Combine(Path.GetTempPath(), "NitroxTestTempDir");
            serverSerializers = NitroxServiceLocator.LocateService <IServerSerializer[]>();
            worldPersistence  = NitroxServiceLocator.LocateService <WorldPersistence>();
            serverConfig      = NitroxServiceLocator.LocateService <ServerConfig>();

            worldData = GeneratePersistedWorldData();
            world     = worldPersistence.CreateWorld(worldData, serverConfig.GameMode);

            worldsDataAfter = new PersistedWorldData[serverSerializers.Length];
            for (int index = 0; index < serverSerializers.Length; index++)
            {
                worldPersistence.UpdateSerializer(serverSerializers[index]);
                Assert.IsTrue(worldPersistence.Save(world, tempSaveFilePath));
                Assert.IsFalse(worldPersistence.Save(null, tempSaveFilePath));

                worldPersistence.UpdateSerializer(serverSerializers[index]);
                Optional <World> worldAfter = worldPersistence.LoadFromFile(tempSaveFilePath);
                Assert.IsTrue(worldAfter.HasValue);
                worldsDataAfter[index] = PersistedWorldData.From(worldAfter.Value);
            }
        }
Пример #4
0
        public static void BeforeAll(TestContext context)
        {
            TestAutoFacRegistrar registrar = new TestAutoFacRegistrar();

            NitroxServiceLocator.InitializeDependencyContainer(registrar);
            NitroxServiceLocator.BeginNewLifetimeScope();
        }
Пример #5
0
        static void Main(string[] args)
        {
            Log.SetLevel(Log.LogLevel.ConsoleInfo | Log.LogLevel.ConsoleDebug | Log.LogLevel.FileLog);

            NitroxServiceLocator.InitializeDependencyContainer(new ServerAutoFacRegistrar());
            NitroxServiceLocator.BeginNewLifetimeScope();

            configureCultureInfo();
            Server server;

            try
            {
                server = NitroxServiceLocator.LocateService <Server>();
                server.Start();
            }
            catch (Exception e)
            {
                Log.Error(e.ToString());
                return;
            }

            ConsoleCommandProcessor CmdProcessor = NitroxServiceLocator.LocateService <ConsoleCommandProcessor>();

            while (server.IsRunning)
            {
                CmdProcessor.ProcessCommand(Console.ReadLine());
            }
        }
Пример #6
0
        private static void Initialize()
        {
            Optional.ApplyHasValueCondition <UnityEngine.Object>(o => (bool)o);

            if (container != null)
            {
                throw new Exception($"Patches have already been detected! Call {nameof(Apply)} or {nameof(Restore)} instead.");
            }
            Log.Info("Registering dependencies");
            container = CreatePatchingContainer();
            try
            {
                NitroxServiceLocator.InitializeDependencyContainer(new ClientAutoFacRegistrar());
            }
            catch (ReflectionTypeLoadException ex)
            {
                Log.Error($"Failed to load one or more dependency types for Nitrox. Assembly: {ex.Types.FirstOrDefault()?.Assembly.FullName ?? "unknown"}");
                foreach (Exception loaderEx in ex.LoaderExceptions)
                {
                    Log.Error(loaderEx);
                }
                throw;
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Error while initializing and loading dependencies.");
                throw;
            }

            InitPatches();
            ApplyNitroxBehaviours();
        }
Пример #7
0
        private static void Main(string[] args)
        {
            ConfigureConsoleWindow();
            ConfigureCultureInfo();

            NitroxModel.Helper.Map.Main = new SubnauticaMap();

            NitroxServiceLocator.InitializeDependencyContainer(new SubnauticaServerAutoFacRegistrar());
            NitroxServiceLocator.BeginNewLifetimeScope();

            Server server;

            try
            {
                server = NitroxServiceLocator.LocateService <Server>();
                server.Start();
            }
            catch (Exception e)
            {
                Log.Error(e.ToString());
                return;
            }

            CatchExitEvent();

            ConsoleCommandProcessor cmdProcessor = NitroxServiceLocator.LocateService <ConsoleCommandProcessor>();

            while (server.IsRunning)
            {
                cmdProcessor.ProcessCommand(Console.ReadLine(), Optional.Empty, Perms.CONSOLE);
            }
        }
Пример #8
0
        public void RuntimeDetectsAllClientPacketProcessors()
        {
            ContainerBuilder       containerBuilder          = new ContainerBuilder();
            ClientAutoFacRegistrar clientDependencyRegistrar = new ClientAutoFacRegistrar();

            NitroxServiceLocator.InitializeDependencyContainer(clientDependencyRegistrar);
            NitroxServiceLocator.BeginNewLifetimeScope();

            // Check if every PacketProcessor has been detected:
            typeof(Multiplayer).Assembly.GetTypes()
            .Where(p => typeof(PacketProcessor).IsAssignableFrom(p) && p.IsClass && !p.IsAbstract)
            .ToList()
            .ForEach(processor =>
            {
                try
                {
                    Assert.IsTrue(NitroxServiceLocator.LocateOptionalService(processor.BaseType).IsPresent(),
                                  $"{processor} has not been discovered by the runtime code!");
                }
                catch (Autofac.Core.DependencyResolutionException ex)
                {
                    if (ex.InnerException.GetType() != typeof(System.Security.SecurityException))
                    {
                        throw ex;
                    }
                }
            }
                     );
        }
Пример #9
0
        public void AllPacketsAreHandled()
        {
            World                  world = new World();
            ContainerBuilder       serverContainerBuilder    = new ContainerBuilder();
            ServerAutoFacRegistrar serverDependencyRegistrar = new ServerAutoFacRegistrar();

            NitroxServiceLocator.InitializeDependencyContainer(serverDependencyRegistrar);
            NitroxServiceLocator.BeginNewLifetimeScope();

            List <Type> packetTypes = typeof(DefaultServerPacketProcessor).Assembly.GetTypes()
                                      .Where(p => typeof(PacketProcessor).IsAssignableFrom(p) && p.IsClass && !p.IsAbstract)
                                      .ToList();

            ContainerBuilder       containerBuilder          = new ContainerBuilder();
            ClientAutoFacRegistrar clientDependencyRegistrar = new ClientAutoFacRegistrar();

            NitroxServiceLocator.InitializeDependencyContainer(clientDependencyRegistrar);
            NitroxServiceLocator.BeginNewLifetimeScope();

            typeof(Packet).Assembly.GetTypes()
            .Where(p => typeof(Packet).IsAssignableFrom(p) && p.IsClass && !p.IsAbstract)
            .ToList()
            .ForEach(packet =>
            {
                Type clientPacketProcessorType = typeof(ClientPacketProcessor <>);
                Type clientProcessorType       = clientPacketProcessorType.MakeGenericType(packet);

                Console.WriteLine("Checking handler for packet {0}...", packet);
                Assert.IsTrue(packetTypes.Contains(packet) || NitroxServiceLocator.LocateOptionalService(clientProcessorType).IsPresent(),
                              $"Runtime has not detected a handler for {packet}!");
            }
                     );
        }
Пример #10
0
        public static void ClassInitialize(TestContext context)
        {
            NitroxServiceLocator.InitializeDependencyContainer(new SubnauticaServerAutoFacRegistrar(), new TestAutoFacRegistrar());
            NitroxServiceLocator.BeginNewLifetimeScope();

            WorldPersistence worldPersistence = NitroxServiceLocator.LocateService <WorldPersistence>();

            serverSerializers = NitroxServiceLocator.LocateService <IServerSerializer[]>();
            worldsDataAfter   = new PersistedWorldData[serverSerializers.Length];
            tempSaveFilePath  = Path.Combine(Path.GetTempPath(), "NitroxTestTempDir");

            worldData = GeneratePersistedWorldData();
            World world = worldPersistence.CreateWorld(worldData, ServerGameMode.CREATIVE);

            world.EventTriggerer.ResetWorldTime();

            for (int index = 0; index < serverSerializers.Length; index++)
            {
                //Checking saving
                worldPersistence.UpdateSerializer(serverSerializers[index]);
                Assert.IsTrue(worldPersistence.Save(world, tempSaveFilePath), $"Saving normal world failed while using {serverSerializers[index]}.");
                Assert.IsFalse(worldPersistence.Save(null, tempSaveFilePath), $"Saving null world worked while using {serverSerializers[index]}.");

                //Checking loading
                Optional <World> worldAfter = worldPersistence.LoadFromFile(tempSaveFilePath);
                Assert.IsTrue(worldAfter.HasValue, $"Loading saved world failed while using {serverSerializers[index]}.");
                worldAfter.Value.EventTriggerer.ResetWorldTime();
                worldsDataAfter[index] = PersistedWorldData.From(worldAfter.Value);
            }
        }
Пример #11
0
        private static void Main(string[] args)
        {
            ConfigureCultureInfo();
            Log.Setup();

            ConfigureConsoleWindow();

            // Allow game path to be given as command argument
            if (args.Length > 0 && Directory.Exists(args[0]) && File.Exists(Path.Combine(args[0], "Subnautica.exe")))
            {
                string gameDir = Path.GetFullPath(args[0]);
                Log.Info($"Using game files from: {gameDir}");
                gameInstallDir = new Lazy <string>(() => gameDir);
            }
            else
            {
                gameInstallDir = new Lazy <string>(() =>
                {
                    string gameDir = GameInstallationFinder.Instance.FindGame();
                    Log.Info($"Using game files from: {gameDir}");
                    return(gameDir);
                });
            }

            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomainOnAssemblyResolve;
            AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += CurrentDomainOnAssemblyResolve;

            NitroxModel.Helper.Map.Main = new SubnauticaMap();

            NitroxServiceLocator.InitializeDependencyContainer(new SubnauticaServerAutoFacRegistrar());
            NitroxServiceLocator.BeginNewLifetimeScope();

            Server server;

            try
            {
                server = NitroxServiceLocator.LocateService <Server>();
                Log.Info($"Loaded save\n{server.SaveSummary}");
                if (!server.Start())
                {
                    Log.Error("Unable to start server.");
                    Console.WriteLine("\nPress any key to continue..");
                    Console.ReadKey(true);
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return;
            }

            CatchExitEvent();

            ConsoleCommandProcessor cmdProcessor = NitroxServiceLocator.LocateService <ConsoleCommandProcessor>();

            while (server.IsRunning)
            {
                cmdProcessor.ProcessCommand(Console.ReadLine(), Optional.Empty, Perms.CONSOLE);
            }
        }
Пример #12
0
        public MultiplayerClient(ulong playerId)
        {
            Log.SetLevel(Log.LogLevel.ConsoleInfo | Log.LogLevel.ConsoleDebug);
            playerName = "Player" + playerId.ToString();

            NitroxServiceLocator.InitializeDependencyContainer(new ClientAutoFaqRegistrar());
            packetReceiver     = NitroxServiceLocator.LocateService <DeferringPacketReceiver>();
            multiplayerSession = NitroxServiceLocator.LocateService <IMultiplayerSession>();
        }
Пример #13
0
        public void TestInitialize()
        {
            NitroxServiceLocator.InitializeDependencyContainer(new ClientAutoFacRegistrar(), new TestAutoFacRegistrar());
            NitroxServiceLocator.BeginNewLifetimeScope();

            packetReceiver = NitroxServiceLocator.LocateService <PacketReceiver>();

            loadedCell   = new AbsoluteEntityCell(loadedActionPosition, CELL_LEVEL);
            unloadedCell = new AbsoluteEntityCell(unloadedActionPosition, CELL_LEVEL);

            visibleCells.Add(loadedCell);
        }
Пример #14
0
        public static void Execute()
        {
            Log.SetLevel(Log.LogLevel.ConsoleInfo | Log.LogLevel.ConsoleDebug | Log.LogLevel.InGameMessages | Log.LogLevel.FileLog);

            if (patches != null)
            {
                Log.Warn("Patches have already been detected! Call Apply or Restore instead.");
                return;
            }

            Log.Info("Registering Dependencies");

            // Our application's entry point. First, register client dependencies with AutoFac.
            NitroxServiceLocator.InitializeDependencyContainer(new ClientAutoFacRegistrar());

            Log.Info("Patching Subnautica...");

            // Enabling this creates a log file on your desktop (why there?), showing the emitted IL instructions.
            HarmonyInstance.DEBUG = false;

            IEnumerable <NitroxPatch> discoveredPatches = Assembly.GetExecutingAssembly()
                                                          .GetTypes()
                                                          .Where(p => typeof(NitroxPatch).IsAssignableFrom(p) &&
                                                                 p.IsClass && !p.IsAbstract
                                                                 )
                                                          .Select(Activator.CreateInstance)
                                                          .Cast <NitroxPatch>();

            IEnumerable <IGrouping <string, NitroxPatch> > splittedPatches = discoveredPatches.GroupBy(p => p.GetType().Namespace);

            splittedPatches.First(g => g.Key == "NitroxPatcher.Patches.Persistent").ForEach(p =>
            {
                Log.Info("Applying persistent patch " + p.GetType());
                p.Patch(harmony);
            });

            patches = splittedPatches.First(g => g.Key == "NitroxPatcher.Patches").ToArray();
            Multiplayer.OnBeforeMultiplayerStart += Apply;
            Multiplayer.OnAfterMultiplayerEnd    += Restore;
            Log.Info("Completed patching using " + Assembly.GetExecutingAssembly().FullName);

            Log.Info("Enabling developer console.");
            DevConsole.disableConsole   = false;
            Application.runInBackground = true;
            Log.Info($"Unity run in background set to {Application.runInBackground.ToString().ToUpperInvariant()}.");

            ApplyNitroxBehaviours();
        }
        public static void Execute()
        {
            Log.EnableInGameMessages();

            if (container != null)
            {
                Log.Warn("Patches have already been detected! Call Apply or Restore instead.");
                return;
            }

            Log.Info("Registering Dependencies");
            container = CreatePatchingContainer();
            NitroxServiceLocator.InitializeDependencyContainer(new ClientAutoFacRegistrar());

            InitPatches();
            ApplyNitroxBehaviours();
        }
Пример #16
0
        public static void Execute()
        {
            Log.Setup(true);
            Optional.ApplyHasValueCondition <Object>(o => (bool)o);

            if (container != null)
            {
                Log.Warn($"Patches have already been detected! Call {nameof(Apply)} or {nameof(Restore)} instead.");
                return;
            }

            Log.Info("Registering dependencies");
            container = CreatePatchingContainer();
            NitroxServiceLocator.InitializeDependencyContainer(new ClientAutoFacRegistrar());

            InitPatches();
            ApplyNitroxBehaviours();
        }
Пример #17
0
        public void RuntimeDetectsAllServerPacketProcessors()
        {
            World world = new World();

            ContainerBuilder       containerBuilder          = new ContainerBuilder();
            ServerAutoFacRegistrar serverDependencyRegistrar = new NitroxServer_Subnautica.SubnauticaServerAutoFacRegistrar();

            NitroxServiceLocator.InitializeDependencyContainer(serverDependencyRegistrar);
            NitroxServiceLocator.BeginNewLifetimeScope();

            // Check if every PacketProcessor has been detected:
            typeof(DefaultServerPacketProcessor).Assembly.GetTypes()
            .Where(p => typeof(PacketProcessor).IsAssignableFrom(p) && p.IsClass && !p.IsAbstract)
            .ToList()
            .ForEach(processor =>
                     Assert.IsTrue(NitroxServiceLocator.LocateOptionalService(processor.BaseType).IsPresent(),
                                   $"{processor} has not been discovered by the runtime code!")
                     );
        }
Пример #18
0
        public void SameAmountOfServerPacketProcessors()
        {
            IEnumerable <Type> processors = typeof(PacketHandler).Assembly.GetTypes()
                                            .Where(p => typeof(PacketProcessor).IsAssignableFrom(p) && p.IsClass && !p.IsAbstract);
            ServerAutoFacRegistrar serverDependencyRegistrar = new ServerAutoFacRegistrar();

            NitroxServiceLocator.InitializeDependencyContainer(serverDependencyRegistrar);
            NitroxServiceLocator.BeginNewLifetimeScope();

            List <Type> packetTypes = typeof(DefaultServerPacketProcessor).Assembly.GetTypes()
                                      .Where(p => typeof(PacketProcessor).IsAssignableFrom(p) && p.IsClass && !p.IsAbstract)
                                      .ToList();

            int both = packetTypes.Count;

            Assert.AreEqual(processors.Count(),
                            both,
                            "Not all(Un) AuthenticatedPacketProcessors have been discovered by the runtime code " +
                            $"(auth + unauth: {both} out of {processors.Count()}). " + // this is a small patch to keep this alive a little longer until its put out of its misery
                            "Perhaps the runtime matching code is too strict, or a processor does not derive from ClientPacketProcessor " +
                            "(and will hence not be detected).");
        }
Пример #19
0
        private static void Main(string[] args)
        {
            ConfigureConsoleWindow();
            ConfigureCultureInfo();

            NitroxModel.Helper.Map.Main = new SubnauticaMap();

            NitroxServiceLocator.InitializeDependencyContainer(new SubnauticaServerAutoFacRegistrar());
            NitroxServiceLocator.BeginNewLifetimeScope();

            Server server;

            try
            {
                server = NitroxServiceLocator.LocateService <Server>();
                Log.Info($"Loaded save\n{server.SaveSummary}");
                if (!server.Start())
                {
                    Log.Error("Unable to start server.");
                    Console.WriteLine("\nPress any key to continue..");
                    Console.ReadKey(true);
                }
            }
            catch (Exception e)
            {
                Log.Error(e.ToString());
                return;
            }

            CatchExitEvent();

            ConsoleCommandProcessor cmdProcessor = NitroxServiceLocator.LocateService <ConsoleCommandProcessor>();

            while (server.IsRunning)
            {
                cmdProcessor.ProcessCommand(Console.ReadLine(), Optional.Empty, Perms.CONSOLE);
            }
        }
Пример #20
0
 public static void BeforeAll(TestContext context)
 {
     NitroxServiceLocator.InitializeDependencyContainer(new DependencyInjectionTestsAutoFacRegistrar());
     NitroxServiceLocator.BeginNewLifetimeScope();
 }
Пример #21
0
        private static async Task Main(string[] args)
        {
            // The thread that writers to console is paused while selecting text in console. So console writer needs to be async.
            Log.Setup(asyncConsoleWriter: true, isConsoleApp: true);
            AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;

            ConfigureCultureInfo();

            AppMutex.Hold(() =>
            {
                Log.Info("Waiting for 30 seconds on other Nitrox servers to initialize before starting..");
            }, 30000);
            Server server;

            try
            {
                // Allow game path to be given as command argument
                if (args.Length > 0 && Directory.Exists(args[0]) && File.Exists(Path.Combine(args[0], "Subnautica.exe")))
                {
                    string gameDir = Path.GetFullPath(args[0]);
                    Log.Info($"Using game files from: {gameDir}");
                    gameInstallDir = new Lazy <string>(() => gameDir);
                }
                else
                {
                    gameInstallDir = new Lazy <string>(() =>
                    {
                        string gameDir = GameInstallationFinder.Instance.FindGame();
                        Log.Info($"Using game files from: {gameDir}");
                        return(gameDir);
                    });
                }

                AppDomain.CurrentDomain.AssemblyResolve += CurrentDomainOnAssemblyResolve;
                AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += CurrentDomainOnAssemblyResolve;

                Map.Main = new SubnauticaMap();

                NitroxServiceLocator.InitializeDependencyContainer(new SubnauticaServerAutoFacRegistrar());
                NitroxServiceLocator.BeginNewLifetimeScope();

                server = NitroxServiceLocator.LocateService <Server>();
                await WaitForAvailablePortAsync(server.Port);

                if (!server.Start())
                {
                    throw new Exception("Unable to start server.");
                }
                Log.Info("Server is waiting for players!");

                CatchExitEvent();
            }
            finally
            {
                // Allow other servers to start initializing.
                AppMutex.Release();
            }

            Log.Info("To get help for commands, run help in console or /help in chatbox");
            ConsoleCommandProcessor cmdProcessor = NitroxServiceLocator.LocateService <ConsoleCommandProcessor>();

            while (server.IsRunning)
            {
                cmdProcessor.ProcessCommand(Console.ReadLine(), Optional.Empty, Perms.CONSOLE);
            }
        }