Ejemplo n.º 1
0
    public void Awake()
    {
        // TODO: LZ:
        //      to be removed
        PlayerPrefs.SetInt("Unity.Colletions.NativeLeakDetection.Mode", 0);

        ClientServerSystemManager.CollectAllSystems();

        GameDebug.Assert(game == null);
        DontDestroyOnLoad(gameObject);
        game = this;

        m_StopwatchFrequency = System.Diagnostics.Stopwatch.Frequency;
        m_Clock = new System.Diagnostics.Stopwatch();
        m_Clock.Start();

        var buildInfo = FindObjectOfType <BuildInfo>();

        if (buildInfo != null)
        {
            _buildId = buildInfo.buildId;
        }

        var commandLineArgs = new List <string>(System.Environment.GetCommandLineArgs());

#if UNITY_STANDALONE_LINUX
        m_isHeadless = true;
#else
        m_isHeadless = commandLineArgs.Contains("-batchmode");
#endif
        var consoleRestoreFocus = commandLineArgs.Contains("-consolerestorefocus");

        if (m_isHeadless)
        {
#if UNITY_STANDALONE_WIN
            string consoleTitle;

            var overrideTitle = ArgumentForOption(commandLineArgs, "-title");
            if (overrideTitle != null)
            {
                consoleTitle = overrideTitle;
            }
            else
            {
                consoleTitle = Application.productName + " Console";
            }

            consoleTitle += " [" + System.Diagnostics.Process.GetCurrentProcess().Id + "]";

            var consoleUI = new ConsoleTextWin(consoleTitle, consoleRestoreFocus);
#elif UNITY_STANDALONE_LINUX
            var consoleUI = new ConsoleTextLinux();
#else
            UnityEngine.Debug.Log("WARNING: starting without a console");
            var consoleUI = new ConsoleNullUI();
#endif
            Console.Init(consoleUI);
        }
        else
        {
            var consoleUI = Instantiate(Resources.Load <ConsoleGUI>("Prefabs/ConsoleGUI"));
            DontDestroyOnLoad(consoleUI);
            Console.Init(consoleUI);

            m_DebugOverlay = Instantiate(Resources.Load <DebugOverlay>("DebugOverlay"));
            DontDestroyOnLoad(m_DebugOverlay);
            m_DebugOverlay.Init();

            var hdpipe = RenderPipelineManager.currentPipeline as HDRenderPipeline;
            if (hdpipe != null)
            {
                // TODO: LZ:
                //      fix me
                //hdpipe.DebugLayer2DCallback = DebugOverlay.Render;
                //hdpipe.DebugLayer3DCallback = DebugOverlay.Render3D;
            }

            m_GameStatistics = new GameStatistics();
        }

        // If -logfile was passed, we try to put our own logs next to the engine's logfile
        var engineLogFileLocation = ".";
        var logfileArgIdx         = commandLineArgs.IndexOf("-logfile");
        if (logfileArgIdx >= 0 && commandLineArgs.Count >= logfileArgIdx)
        {
            engineLogFileLocation = System.IO.Path.GetDirectoryName(commandLineArgs[logfileArgIdx + 1]);
        }

        var logName = m_isHeadless ? "game_" + DateTime.UtcNow.ToString("yyyyMMdd_HHmmss_fff") : "game";
        GameDebug.Init(engineLogFileLocation, logName);

        ConfigVar.Init();

        // Support -port and -query_port as per Multiplay standard
        var serverPort = ArgumentForOption(commandLineArgs, "-port");
        if (serverPort != null)
        {
            Console.EnqueueCommandNoHistory("server.port " + serverPort);
        }

        var sqpPort = ArgumentForOption(commandLineArgs, "-query_port");
        if (sqpPort != null)
        {
            Console.EnqueueCommandNoHistory("server.sqp_port " + sqpPort);
        }

        Console.EnqueueCommandNoHistory("exec -s " + k_UserConfigFilename);

        // Default is to allow no frame cap, i.e. as fast as possible if vsync is disabled
        Application.targetFrameRate = -1;

        if (m_isHeadless)
        {
            Application.targetFrameRate = serverTickRate.IntValue;
            QualitySettings.vSyncCount  = 0; // Needed to make targetFramerate work; even in headless mode

#if !UNITY_STANDALONE_LINUX
            if (!commandLineArgs.Contains("-nographics"))
            {
                GameDebug.Log("WARNING: running -batchmod without -nographics");
            }
#endif
        }
        else
        {
            RenderSettings.Init();
        }

        // Out of the box game behaviour is driven by boot.cfg unless you ask it not to
        if (!commandLineArgs.Contains("-noboot"))
        {
            Console.EnqueueCommandNoHistory("exec -s " + k_BootConfigFilename);
        }


        if (m_isHeadless)
        {
            m_SoundSystem = new SoundSystemNull();
        }
        else
        {
            m_SoundSystem = new SoundSystem();
            m_SoundSystem.Init(audioMixer);
            m_SoundSystem.MountBank(defaultBank);

            GameObject go = (GameObject)GameObject.Instantiate(Resources.Load("Prefabs/ClientFrontend", typeof(GameObject)));
            UnityEngine.Object.DontDestroyOnLoad(go);
            clientFrontend = go.GetComponentInChildren <ClientFrontend>();
        }

        sqpClient = new SQP.SQPClient();

        GameDebug.Log("FPS Sample initialized");
#if UNITY_EDITOR
        GameDebug.Log("Build type: editor");
#elif DEVELOPMENT_BUILD
        GameDebug.Log("Build type: development");
#else
        GameDebug.Log("Build type: release");
#endif
        GameDebug.Log("BuildID: " + buildId);
        GameDebug.Log("Cwd: " + System.IO.Directory.GetCurrentDirectory());

        SimpleBundleManager.Init();
        GameDebug.Log("SimpleBundleManager initialized");

        levelManager = new LevelManager();
        levelManager.Init();
        GameDebug.Log("LevelManager initialized");

        inputSystem = new InputSystem();
        GameDebug.Log("InputSystem initialized");

        // TODO (petera) added Instantiate here to avoid making changes to asset file.
        // Feels like maybe SO is not really the right tool here.
        config = Instantiate((GameConfiguration)Resources.Load("GameConfiguration"));
        GameDebug.Log("Loaded game config");

        // Game loops
        Console.AddCommand("preview", CmdPreview, "Start preview mode");
        Console.AddCommand("serve", CmdServe, "Start server listening");
        Console.AddCommand("client", CmdClient, "client: Enter client mode.");
        Console.AddCommand("thinclient", CmdThinClient, "client: Enter thin client mode.");
        Console.AddCommand("boot", CmdBoot, "Go back to boot loop");
        Console.AddCommand("connect", CmdConnect, "connect <ip>: Connect to server on ip (default: localhost)");

        Console.AddCommand("menu", CmdMenu, "show the main menu");
        Console.AddCommand("load", CmdLoad, "Load level");
        Console.AddCommand("quit", CmdQuit, "Quits");
        Console.AddCommand("screenshot", CmdScreenshot, "Capture screenshot. Optional argument is destination folder or filename.");
        Console.AddCommand("crashme", (string[] args) => { GameDebug.Assert(false); }, "Crashes the game next frame ");
        Console.AddCommand("saveconfig", CmdSaveConfig, "Save the user config variables");
        Console.AddCommand("loadconfig", CmdLoadConfig, "Load the user config variables");

#if UNITY_STANDALONE_WIN
        Console.AddCommand("windowpos", CmdWindowPosition, "Position of window. e.g. windowpos 100,100");
#endif

        Console.SetOpen(true);
        Console.ProcessCommandLineArguments(commandLineArgs.ToArray());

        PushCamera(bootCamera);
    }
Ejemplo n.º 2
0
    public bool Init(string[] args)
    {
        m_StateMachine = new StateMachine <ClientState>();
        m_StateMachine.Add(ClientState.Browsing, EnterBrowsingState, UpdateBrowsingState, LeaveBrowsingState);
        m_StateMachine.Add(ClientState.Connecting, EnterConnectingState, UpdateConnectingState, null);
        m_StateMachine.Add(ClientState.Loading, EnterLoadingState, UpdateLoadingState, null);
        m_StateMachine.Add(ClientState.Playing, EnterPlayingState, UpdatePlayingState, LeavePlayingState);

#if UNITY_EDITOR
        Game.game.levelManager.UnloadLevel();
#endif
        m_GameWorld = new GameWorld("ClientWorld");

        m_NetworkTransport = new SocketTransport();
        m_NetworkClient    = new NetworkClient(m_NetworkTransport);

        if (Application.isEditor || Game.game.buildId == "AutoBuild")
        {
            NetworkClient.clientVerifyProtocol.Value = "0";
        }

        m_NetworkClient.UpdateClientConfig();
        m_NetworkStatistics = new NetworkStatisticsClient(m_NetworkClient);
        m_ChatSystem        = new ChatSystemClient(m_NetworkClient);

        GameDebug.Log("Network client initialized");

        m_requestedPlayerSettings.playerName = clientPlayerName.Value;
        m_requestedPlayerSettings.teamId     = -1;

        Console.AddCommand("disconnect", CmdDisconnect, "Disconnect from server if connected", this.GetHashCode());
        Console.AddCommand("prediction", CmdTogglePrediction, "Toggle prediction", this.GetHashCode());
        Console.AddCommand("runatserver", CmdRunAtServer, "Run command at server", this.GetHashCode());
        Console.AddCommand("respawn", CmdRespawn, "Force a respawn", this.GetHashCode());
        Console.AddCommand("nextchar", CmdNextChar, "Select next character", this.GetHashCode());
        Console.AddCommand("nextteam", CmdNextTeam, "Select next character", this.GetHashCode());
        Console.AddCommand("spectator", CmdSpectator, "Select spectator cam", this.GetHashCode());
        Console.AddCommand("matchmake", CmdMatchmake, "matchmake <hostname[:port]/{projectid}>: Find and join a server", this.GetHashCode());

        if (args.Length > 0)
        {
            targetServer = args[0];
            m_StateMachine.SwitchTo(ClientState.Connecting);
        }
        else
        {
            m_StateMachine.SwitchTo(ClientState.Browsing);
        }

        ReplicatedPrefabMgr.Initialize();

        ClientServerSystemManager.InitClientSystems();
        World.Active.GetExistingSystem <TickClientSimulationSystem>().Enabled   = true;
        World.Active.GetExistingSystem <TickClientPresentationSystem>().Enabled = true;
        Unity.Networking.Transport.NetworkEndPoint ep = Unity.Networking.Transport.NetworkEndPoint.Parse(targetServer, (ushort)NetworkConfig.netcodeServerPort);
        World         clientWorld = ClientServerSystemManager.clientWorld;
        EntityManager em          = clientWorld.EntityManager;
        Entity        ent         = clientWorld.GetExistingSystem <NetworkStreamReceiveSystem>().Connect(ep);
        em.AddComponentData(ent, new NetworkStreamInGame());

        GameDebug.Log("Client initialized");

        return(true);
    }
Ejemplo n.º 3
0
    public bool Init(string[] args)
    {
        ReplicatedPrefabMgr.Initialize();

        ClientServerSystemManager.InitServerSystems();
        World.Active.GetExistingSystem <TickServerSimulationSystem>().Enabled = true;
        Unity.Networking.Transport.NetworkEndPoint ep = Unity.Networking.Transport.NetworkEndPoint.AnyIpv4;
        ep.Port = (ushort)NetworkConfig.netcodeServerPort;
        World serverWorld = ClientServerSystemManager.serverWorld;

        serverWorld.GetExistingSystem <NetworkStreamReceiveSystem>().Listen(ep);

        // Set up statemachine for ServerGame
        m_StateMachine = new StateMachine <ServerState>();
        m_StateMachine.Add(ServerState.Idle, null, UpdateIdleState, null);
        m_StateMachine.Add(ServerState.Loading, null, UpdateLoadingState, null);
        m_StateMachine.Add(ServerState.Active, EnterActiveState, UpdateActiveState, LeaveActiveState);

        m_StateMachine.SwitchTo(ServerState.Idle);

        m_NetworkTransport = new SocketTransport(NetworkConfig.serverPort.IntValue, serverMaxClients.IntValue);
        var listenAddresses = NetworkUtils.GetLocalInterfaceAddresses();

        if (listenAddresses.Count > 0)
        {
            Console.SetPrompt(listenAddresses[0] + ":" + NetworkConfig.serverPort.Value + "> ");
        }
        GameDebug.Log("Listening on " + string.Join(", ", NetworkUtils.GetLocalInterfaceAddresses()) + " on port " + NetworkConfig.serverPort.IntValue);
        m_NetworkServer = new NetworkServer(m_NetworkTransport);

        if (Game.game.clientFrontend != null)
        {
            var serverPanel = Game.game.clientFrontend.serverPanel;
            serverPanel.SetPanelActive(true);
            serverPanel.serverInfo.text += "Listening on:\n";
            foreach (var a in NetworkUtils.GetLocalInterfaceAddresses())
            {
                serverPanel.serverInfo.text += a + ":" + NetworkConfig.serverPort.IntValue + "\n";
            }
        }

        m_NetworkServer.UpdateClientInfo();
        m_NetworkServer.serverInfo.compressionModel = m_Model;

        if (serverServerName.Value == "")
        {
            serverServerName.Value = MakeServername();
        }

#if false
        m_ServerQueryProtocolServer = new SQP.SQPServer(NetworkConfig.serverSQPPort.IntValue > 0? NetworkConfig.serverSQPPort.IntValue : NetworkConfig.serverPort.IntValue + NetworkConfig.sqpPortOffset);
#endif


#if UNITY_EDITOR
        Game.game.levelManager.UnloadLevel();
#endif
        m_GameWorld = new GameWorld("ServerWorld");

        m_NetworkStatistics = new NetworkStatisticsServer(m_NetworkServer);

        m_ChatSystem = new ChatSystemServer(m_Clients, m_NetworkServer);

        GameDebug.Log("Network server initialized");

        Console.AddCommand("load", CmdLoad, "Load a named scene", this.GetHashCode());
        Console.AddCommand("unload", CmdUnload, "Unload current scene", this.GetHashCode());
        Console.AddCommand("respawn", CmdRespawn, "Respawn character (usage : respawn playername|playerId)", this.GetHashCode());
        Console.AddCommand("servername", CmdSetServerName, "Set name of the server", this.GetHashCode());
        Console.AddCommand("beginnetworkprofile", CmdBeginNetworkProfile, "begins a network profile", this.GetHashCode());
        Console.AddCommand("endnetworkprofile", CmdEndNetworkProfile, "Ends a network profile and analyzes. [optional] filepath for model data", this.GetHashCode());
        Console.AddCommand("loadcompressionmodel", CmdLoadNetworkCompressionModel, "Loads a network compression model from a filepath", this.GetHashCode());
        Console.AddCommand("list", CmdList, "List clients", this.GetHashCode());

        CmdLoad(args);
        Game.SetMousePointerLock(false);

        m_ServerStartTime = Time.time;

        GameDebug.Log("Server initialized");
        Console.SetOpen(false);
        return(true);
    }