private void Start()
        {
            onStartingServerPanel.gameObject.SetActive(false);

            //First, clear the maps dropdown
            mapsDropdown.ClearOptions();

            //Then get all online scenes
            onlineTCScenes = TCScenesManager.GetAllOnlineScenes().ToList();

            //And all the scenes to the map dropdown
            List <string> scenes = onlineTCScenes.Select(scene => scene.DisplayNameLocalized).ToList();

            mapsDropdown.AddOptions(scenes);
            mapsDropdown.RefreshShownValue();

            //Get active network manager
            netManager = TCNetworkManager.Instance;

            //Get the images that are in the input fields
            gameNameImage = gameNameText.GetComponent <Image>();

            //Get the existing colors of the input fields
            gameNameImageColor   = gameNameImage.color;
            maxPlayersImageColor = maxPlayersImage.color;

            menuController = GetComponentInParent <MenuController>();

            string[] names = Enum.GetNames(typeof(UserProvider));
            authModeDropdown.ClearOptions();
            authModeDropdown.AddOptions(names.ToList());
            authModeDropdown.RefreshShownValue();
        }
Exemple #2
0
        /// <summary>
        ///		Called after the client changes scenes
        /// </summary>
        internal static void OnClientSceneChanged()
        {
            Object.Instantiate(netManager.gameMangerPrefab);
            Logger.Info("The scene has been loaded to {Scene}", TCScenesManager.GetActiveScene().scene);

            DisplayMotdAndOrCreatePlayer().Forget();
        }
        protected override TCServerResponse ProcessRequest(TCServerRequest request, IPEndPoint endpoint)
        {
            Logger.Debug("Processing discovery request from `{Address}`...", endpoint.Address);

            try
            {
                if (request.ApplicationVersion != Application.version)
                {
                    return(null);
                }

                return(new TCServerResponse
                {
                    GameName = TCNetworkManager.Instance.serverConfig.gameName,
                    MaxPlayers = netManager.maxConnections,
                    CurrentAmountOfPlayers = netManager.numPlayers,
                    SceneName = TCScenesManager.GetActiveScene().name
                });
            }
            catch (NotImplementedException)
            {
                Logger.Error("Current transport does not support network discovery!");
                throw;
            }
        }
Exemple #4
0
        private void Start()
        {
            onStartingServerPanel.gameObject.SetActive(false);

            //First, clear the maps dropdown
            mapsDropdown.ClearOptions();

            //Then get all online scenes
            onlineTCScenes = TCScenesManager.GetAllEnabledOnlineScenesInfo().ToList();

            //And all the scenes to the map dropdown
            List <string> scenes = onlineTCScenes.Select(scene => scene.DisplayNameLocalized).ToList();

            mapsDropdown.AddOptions(scenes);
            mapsDropdown.RefreshShownValue();

            //Get active network manager
            netManager = TCNetworkManager.Instance;

            //Get the images that are in the input fields
            gameNameImage   = gameNameText.GetComponent <Image>();
            maxPlayersImage = maxPlayersText.GetComponent <Image>();

            //Get the existing colors of the input fields
            gameNameImageColor   = gameNameImage.color;
            maxPlayersImageColor = maxPlayersImage.color;
        }
 private static void ListAllEnabledScenes()
 {
     Debug.Log($"Online {nameof(TCScene)}s found:");
     foreach (TCScene tcScene in TCScenesManager.GetAllOnlineScenes())
     {
         Debug.Log($"{tcScene.scene} ({tcScene.SceneFileName})");
     }
 }
 private static void ListAllTCScenes()
 {
     Debug.Log($"{nameof(TCScene)}s found:");
     foreach (TCScene tcScene in TCScenesManager.GetAllTCScenesInfo())
     {
         Debug.Log($"{tcScene.scene} ({tcScene.DisplayNameLocalized})");
     }
 }
Exemple #7
0
        private void Initialize()
        {
            if (client != null)
            {
                Logger.Error("The discord client is already running!");
                return;
            }

            try
            {
                client = new global::Discord.GameSDK.Discord(long.Parse(settings.clientId), CreateFlags.NoRequireDiscord);
                client.Init();
            }
            catch (ResultException ex)
            {
                Logger.Error("Failed to connect with Discord! {@Message} {@ResultCode}", ex.Message, ex.Result);
                client = null;
                Destroy(gameObject);
                return;
            }

            client?.SetLogHook(settings.logLevel, (level, message) =>
            {
                switch (level)
                {
                case LogLevel.Error:
                    Logger.Error(message);
                    break;

                case LogLevel.Warn:
                    Logger.Warn(message);
                    break;

                case LogLevel.Info:
                    Logger.Info(message);
                    break;

                case LogLevel.Debug:
                    Logger.Debug(message);
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(level), level, null);
                }
            });
            activityManager = client?.GetActivityManager();
            userManager     = client?.GetUserManager();
            userManager.OnCurrentUserUpdate += UpdateUserAccountInfo;

            TCScenesManager.PreparingSceneLoadEvent += PreparingSceneLoad;
            TCScenesManager.OnSceneLoadedEvent      += SceneLoaded;

            SceneLoaded(TCScenesManager.GetActiveScene());
        }
        private void SceneLoaded(TCScene scene)
        {
            if (client != null)
            {
                Activity presence = new()
                {
                    Assets = new ActivityAssets
                    {
                        LargeImage = scene.largeImageKey,
                        LargeText  = scene.LargeImageKeyText
                    }
                };

                if (scene.showStartTime)
                {
                    presence.Timestamps = new ActivityTimestamps
                    {
                        Start = TimeHelper.UnixTimeNow()
                    }
                }
                ;

                if (scene.isOnlineScene)
                {
                    presence.Details = TCScenesManager.GetActiveScene().DisplayNameLocalized;
                    presence.State   = "Team Capture";
                }
                else if (scene.isMainMenu)
                {
                    presence.Details = "Main Menu";
                }
                else if (!scene.isMainMenu && !scene.isOnlineScene)
                {
                    presence.Details = "Loading...";
                }
                else
                {
                    Logger.Error("You CANNOT have an online scene and a main menu scene!");
                }

                UpdateActivity(presence);
            }
        }

        #endregion
    }
}
        public static void StartServerCommand(string[] args)
        {
            NetworkManager networkManager = NetworkManager.singleton;
            string         scene          = args[0];
            TCScene        tcScene        = TCScenesManager.FindSceneInfo(scene);

            if (tcScene == null)
            {
                Logger.Error("That scene doesn't exist!");
                return;
            }

            Scene = tcScene.SceneFileName;
            networkManager.onlineScene = tcScene.scene;

            networkManager.StartServer();
        }
Exemple #10
0
        private void Setup()
        {
            scene = TCScenesManager.GetActiveScene();
            if (scene == null)
            {
                Logger.Error("The scene '{@Scene}' doesn't have a TCScene assigned to it!",
                             SceneManager.GetActiveScene().name);
                return;
            }

            sceneCamera = GameObject.FindWithTag(SceneCameraTag);
            if (sceneCamera == null)
            {
                Logger.Error(
                    "The scene {@Scene} doesn't have a Camera with the tag `{@SceneCameraTag}` assigned to it!",
                    scene.scene, SceneCameraTag);
            }
        }
Exemple #11
0
 /// <summary>
 ///		Called after the client changes scenes
 /// </summary>
 internal static void OnClientSceneChanged(NetworkConnection conn)
 {
     Object.Instantiate(netManager.gameMangerPrefab);
     Logger.Info("The scene has been loaded to {Scene}", TCScenesManager.GetActiveScene().scene);
 }
 private void OnBeginSceneLoading(AsyncOperation operation, string sceneName)
 {
     StartCoroutine(OnStartSceneLoadAsync(operation, TCScenesManager.FindSceneInfo(sceneName)));
 }
        private static void OnDraw()
        {
            EditorGUILayout.BeginVertical(GUIStyles.DropdownContentStyle);
            Color defaultGUIBackgroundColor = GUI.backgroundColor;

            GUILayout.Label("Quick Start", GUIStyles.DropdownHeaderStyle);

            string tcFolder = $"{GameBuilder.GetBuildDirectory()}/Team-Capture-Quick/";

#if UNITY_EDITOR_WIN
            const string appName = "Team-Capture.exe";
#else
            const string appName = "Team-Capture";
#endif
            string tcFullPath = $"{tcFolder}{appName}";

            if (!File.Exists(tcFullPath))
            {
                EditorGUILayout.HelpBox("You need to build Team-Capture first before being able to use quick start!", MessageType.Error);
            }
            else
            {
                //Get all TC scenes
                IReadOnlyList <TCScene> scenes = TCScenesManager.GetAllOnlineScenes();

                EditorGUILayout.BeginHorizontal();
                {
                    GUI.backgroundColor = Color.green;
                    if (GUILayout.Button("Start"))
                    {
                        //Start each process
                        for (int i = 0; i < quickstartData.entries.Count; i++)
                        {
                            QuickStartEntry entry = quickstartData.entries[i];

                            //Build arguments
                            string arguments = $"-scene {scenes[quickstartData.selectedSceneIndex].SceneFileName} -auth-method {quickstartData.authMode.ToString()} ";
                            if (entry.server)
                            {
                                arguments += "-batchmode -nographics ";
                            }
                            arguments += entry.additionalArguments;

#if UNITY_EDITOR_LINUX
                            if (entry.server)
                            {
                                ProcessHelper.LaunchLinuxTerminalAndLaunchProcess(tcFullPath, arguments);
                                continue;
                            }
#endif

                            //Setup and start the process
                            Process newProcess = new Process
                            {
                                StartInfo = new ProcessStartInfo(tcFullPath, arguments)
                            };
                            newProcess.Start();
                            StartedProcesses.Add(newProcess);
                            Thread.Sleep(200);
                        }

                        Debug.Log(quickstartData.entries.Count > 1
                            ? $"Started {quickstartData.entries.Count} processes..."
                            : "Started 1 process...");
                    }
                    GUI.backgroundColor = defaultGUIBackgroundColor;

                    GUI.backgroundColor = Color.red;
                    if (GUILayout.Button("Stop All"))
                    {
                        //Kill each started process
                        for (int i = 0; i < StartedProcesses.Count; i++)
                        {
                            Process process = StartedProcesses[i];
                            if (process.HasExited)
                            {
                                continue;
                            }

                            process.Kill();
                        }
                        StartedProcesses.Clear();

                        Debug.Log("Stopped processes.");
                    }
                    GUI.backgroundColor = defaultGUIBackgroundColor;
                }
                EditorGUILayout.EndHorizontal();

                //Make sure there are online scenes
                if (scenes.Count == 0)
                {
                    EditorGUILayout.HelpBox("There are no available scenes!", MessageType.Error);
                }
                else
                {
                    //Check that all scenes still exist
                    if (quickstartData.selectedSceneIndex > scenes.Count)
                    {
                        quickstartData.selectedSceneIndex = 0;
                    }

                    //Display the scenes in a popup (aka a dropdown)
                    string[] names = scenes.Select(scene => scene.SceneFileName).ToArray();
                    quickstartData.selectedSceneIndex =
                        EditorGUILayout.Popup("Scene", quickstartData.selectedSceneIndex, names);
                }

                quickstartData.authMode = (UserProvider)EditorGUILayout.EnumPopup("Auth-Mode", quickstartData.authMode);

                GUILayout.Space(10f);
                GUILayout.Label("Processes", GUIStyles.DropdownHeaderStyle);

                if (quickstartData.entries.Count == 0)
                {
                    EditorGUILayout.HelpBox("There are no processes!", MessageType.Error);
                }
                else
                {
                    for (int i = 0; i < quickstartData.entries.Count; i++)
                    {
                        QuickStartEntry entry = quickstartData.entries[i];

                        GUILayout.BeginVertical();
                        {
                            GUILayout.BeginHorizontal();
                            {
                                GUILayout.Space(10);
                                entry.server = EditorGUILayout.Toggle("Server?", entry.server);
                            }
                            GUILayout.EndHorizontal();

                            GUILayout.BeginHorizontal();
                            {
                                GUILayout.Space(10);
                                entry.additionalArguments = EditorGUILayout.TextField("Additional Arguments", entry.additionalArguments);
                            }
                            GUILayout.EndHorizontal();

                            GUILayout.BeginHorizontal();
                            {
                                GUILayout.Space(10);
                                if (GUILayout.Button("Remove", new GUIStyle(EditorStyles.miniButtonMid)))
                                {
                                    quickstartData.entries.RemoveAt(i);
                                }
                            }
                            GUILayout.EndHorizontal();

                            GUILayout.Space(8f);
                        }
                        GUILayout.EndVertical();
                    }
                }

                if (GUILayout.Button("Add Process"))
                {
                    quickstartData.entries.Add(new QuickStartEntry
                    {
                        additionalArguments = string.Empty
                    });
                }
                if (EditorGUI.EndChangeCheck())
                {
                    string json = JsonUtility.ToJson(quickstartData);
                    EditorPrefs.SetString(QuickStartDataKey, json);
                }
            }

            EditorGUILayout.EndVertical();
        }
        /// <summary>
        ///     Call this when the server is started
        /// </summary>
        internal static void OnStartServer(TCNetworkManager workingNetManager)
        {
            serverOnlineFilePath = $"{Game.GetGameExecutePath()}/{ServerOnlineFile}";

            if (File.Exists(serverOnlineFilePath))
            {
                throw new Exception("Server is already online!");
            }

            netManager = workingNetManager;

            Logger.Info("Starting server...");

            //Get the online scene
            TCScene onlineScene = TCScenesManager.FindSceneInfo(Scene);

            if (onlineScene == null)
            {
                Logger.Error($"Failed to find scene {Scene}!");
                throw new FileNotFoundException($"Scene {Scene} not found!");
            }

            //Setup the server's config
            SetupServerConfig();
            Application.targetFrameRate = netManager.serverTickRate;

            //Make some adjustments to scenes config if we are running headless
            if (Game.IsHeadless)
            {
                netManager.offlineScene = null;
                netManager.onlineScene  = onlineScene.scene;
                TCScenesManager.LoadScene(onlineScene);
            }

            //Set what network address to use and start to advertise the server on lan
            netManager.networkAddress = NetHelper.LocalIpAddress();
            netManager.gameDiscovery.AdvertiseServer();

            //Setup ping related stuff
            PingManager.ServerSetup();
            LagCompensationManager.ServerSetup();

            //Run the server autoexec config
            ConsoleBackend.ExecuteFile("server-autoexec");

            //Server chat
            NetworkServer.RegisterHandler <ChatMessage>(ServerChat.ReceivedChatMessage);

            //Create server online file
            try
            {
                serverOnlineFileStream = File.Create(serverOnlineFilePath, 128, FileOptions.DeleteOnClose);
                serverOnlineFileStream.Write(ServerOnlineFileMessage, 0, ServerOnlineFileMessage.Length);
                serverOnlineFileStream.Flush();
                File.SetAttributes(serverOnlineFilePath, FileAttributes.Hidden);
            }
            catch (IOException ex)
            {
                Logger.Error(ex, "An error occurred while setting up the server!");
                netManager.StopHost();

                return;
            }

            Logger.Info("Server has started and is running on '{Address}' with max connections of {MaxPlayers}!",
                        netManager.networkAddress, netManager.maxConnections);
        }
        public override void OnBoot()
        {
            TCScene scene = sceneToLoadTo.LoadAssetAsync <TCScene>().WaitForCompletion();

            TCScenesManager.LoadScene(scene);
        }
 public override void OnBoot()
 {
     TCScenesManager.LoadScene(sceneToLoadTo);
 }
Exemple #17
0
 private void ChangeScene()
 {
     TCScenesManager.LoadScene(nextScene);
 }