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(); TCScenesManager.PreparingSceneLoadEvent += PreparingSceneLoad; TCScenesManager.OnSceneLoadedEvent += SceneLoaded; SceneLoaded(TCScenesManager.GetActiveScene()); }
/// <summary> /// Called after the scene changes /// </summary> /// <param name="sceneName"></param> internal static void OnServerChangedScene(string sceneName) { //Instantiate the new game manager Object.Instantiate(netManager.gameMangerPrefab); Object.Instantiate(netManager.gameSceneManagerPrefab); Logger.Debug("Created GameManager object"); NetworkServer.SendToAll(TCNetworkManager.Instance.serverConfig); Logger.Info("Server changed scene to {SceneName}", sceneName); }
public void CmdSetWeapon(int index) { if (weapons.ElementAt(index) == null) { return; } Logger.Debug($"Player `{transform.name}` set their weapon index to `{index}`."); SetClientWeaponIndex(index); }
/// <summary> /// Generate the list from scratch /// <para>Should only need to do this when a player is added or removed, or when the panel is opened</para> /// </summary> private void SetPlayerList() { Stopwatch stopwatch = Stopwatch.StartNew(); players = GameManager.GetAllPlayers().ToList(); SortPlayerList(); SetScoreBoardPlayerItems(); UpdateUIPositions(); stopwatch.Stop(); Logger.Debug($"Took {stopwatch.Elapsed.TotalMilliseconds}ms to update scoreboard player items."); }
private static void RequestPlayerObject(NetworkConnection conn) { // Ready/AddPlayer is usually triggered by a scene load completing. if no scene was loaded, then Ready/AddPlayer it here instead. if (!ClientScene.ready) { ClientScene.Ready(conn); } ClientScene.AddPlayer(conn); clientHasPlayer = true; Logger.Debug("Client has requested player object."); }
internal static void Init() { accountProvidersPriority = new[] { AccountProvider.Steam, AccountProvider.Discord, AccountProvider.Offline }; accounts = new SortedList <AccountProvider, Account>(new AccountProviderComparer()); AddAccount(new Account { AccountProvider = AccountProvider.Offline, AccountName = PlayerName }); Logger.Debug("Initialized user account system."); }
private void Awake() { //Get our network manager netManager = GetComponent <TCNetworkManager>(); //Set the active game discovery to this discovery object netManager.gameDiscovery = this; if (!Game.IsGameQuitting) { Logger.Debug("Game discovery is ready!"); } }
private static void RequestPlayerObject() { // Ready/AddPlayer is usually triggered by a scene load completing. if no scene was loaded, then Ready/AddPlayer it here instead. if (!NetworkClient.ready) { NetworkClient.Ready(); } NetworkClient.AddPlayer(); clientHasPlayer = true; Logger.Debug("Client has requested player object."); }
private static void OnInit() { Physics.autoSimulation = false; Physics2D.simulationMode = SimulationMode2D.Script; adjustedFixedUpdate = Time.fixedDeltaTime; timingPerStep = Time.fixedDeltaTime * TimingStepPercent; timingRange = new[] { Time.fixedDeltaTime *(1f - MAXIMUM_OFFSET_PERCENT), Time.fixedDeltaTime *(1f + MAXIMUM_OFFSET_PERCENT) }; Logger.Debug("Init fixed update manager."); }
private void DoProjectile() { Transform projectileSpawnPoint = weaponGraphics.bulletTracerPosition; Transform playerFacingDirection = weaponManager.localPlayerCamera; //Figure out where the projectile should aim for RaycastHit[] hits = RaycastHelper.RaycastAllSorted(playerFacingDirection.position, playerFacingDirection.forward, float.MaxValue, weaponManager.raycastLayerMask); //We need to filter through each hit RaycastHit?raycastHit = null; foreach (RaycastHit hit in hits) { //Don't count if we hit the shooting player if (hit.collider.name == weaponManager.transform.name) { continue; } raycastHit = hit; } //Spawn the object GameObject newProjectile = projectileObjectsPool.GetPooledObject(); if (raycastHit.HasValue) { RaycastHit hit = raycastHit.Value; if (hit.distance > projectileAutoAimMinRange) { newProjectile.transform.LookAt(hit.point); Logger.Debug("Pointing player's projectile at cross-hair."); } } ProjectileBase projectile = newProjectile.GetComponent <ProjectileBase>(); if (projectile == null) { Logger.Error("Weapon projectile doesn't have a projectile base on it!"); return; } projectile.SetupOwner(weaponManager.playerManager); projectile.ServerEnable(projectileSpawnPoint.position, projectileSpawnPoint.rotation.eulerAngles); DoWeaponEffects(new ProjectileEffectsMessage()); }
/// <summary> /// Updates the active Discord activity that is shown (AkA the Rich Presence) /// </summary> /// <param name="activity"></param> public static void UpdateActivity(Activity activity) { if (Instance == null) { return; } if (Instance.client == null) { return; } Instance.activityManager.UpdateActivity(activity, result => { Logger.Debug($"[Discord Presence] Updated activity: {result}"); }); }
private static void Init() { try { if (setToHighPriority) { Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High; Logger.Debug("Process was set to high priority."); } } catch (Exception ex) { Logger.Error(ex, "Failed to set current process to high priority!"); } }
private void Start() { Stopwatch stopwatch = Stopwatch.StartNew(); //Create home/return button string backButtonText = "Menu_Home"; if (NetworkManager.singleton != null) { if (NetworkManager.singleton.isNetworkActive) { backButtonText = "Menu_Resume"; } } CreateButton(topButtonPrefab, topNavBar, backButtonText, CloseActivePanel, 69f); //Pre-create all panels and button foreach (MainMenuPanel menuPanel in menuPanels) { //Create the panel GameObject panel = Instantiate(menuPanel.panelPrefab, mainMenuPanel); panel.name = menuPanel.name; panel.SetActive(false); menuPanel.activePanel = panel; //If it has a PanelBase, set it cancel button's onClick event to toggle it self if (panel.GetComponent <PanelBase>() != null) { panel.GetComponent <PanelBase>().cancelButton.onClick .AddListener(delegate { TogglePanel(menuPanel.name); }); } //Create the button for it if (menuPanel.bottomNavBarButton) { CreateButton(bottomButtonPrefab, bottomNavBar, menuPanel.menuButtonText, delegate { TogglePanel(menuPanel.name); }); } else { CreateButton(topButtonPrefab, topNavBar, menuPanel.menuButtonText, delegate { TogglePanel(menuPanel.name); }); } } stopwatch.Stop(); Logger.Debug("Time taken to update menu UI: {@TotalMilliseconds}ms", stopwatch.ElapsedMilliseconds); }
private void OnDestroy() { if (Game.IsGameQuitting) { return; } Logger.Debug("Resetting all main menu events..."); //Reset all the main menu script-able objects foreach (MainMenuPanel menu in menuPanels) { menu.isOpen = false; menu.activePanel = null; } }
private static void ApplySettings() { if (Game.IsHeadless) { return; } VideoSettingsClass settings = GameSettings.VideoSettings; Screen.SetResolution(settings.Resolution.width, settings.Resolution.height, settings.ScreenMode, settings.Resolution.refreshRate); QualitySettings.masterTextureLimit = (int)settings.TextureQuality; QualitySettings.vSyncCount = (int)settings.VSync; Logger.Debug("Applied Video settings"); }
/// <summary> /// Sets up the UI /// </summary> /// <param name="playerManager"></param> public void SetupUI(PlayerManager playerManager) { //Reset this IsPauseMenuOpen = false; hud.Setup(this); PlayerManager = playerManager; WeaponManager = playerManager.GetComponent <WeaponManager>(); pauseMenu.gameObject.SetActive(false); scoreBoardObject.SetActive(false); scoreBoardObject.GetComponent <ScoreBoard.ScoreBoard>().clientPlayer = playerManager; Logger.Debug("The ClientUI is now ready."); }
/// <summary> /// <para> /// Sets the <see cref="GameObject" />s <see cref="Transform" /> position and rotation using the given frame index, /// and optional interpolation value. /// </para> /// <para> /// The <see cref="Transform" /> will not be changed back until a call to <see cref="ResetStateTransform" /> /// </para> /// </summary> /// <param name="secondsAgo"></param> public void SetStateTransform(double secondsAgo) { Transform objTransform = transform; //Save last state lastPosition = objTransform.position; lastRotation = objTransform.rotation; double currentTime = NetworkTime.time; double targetTime = currentTime - secondsAgo; double previousTime = 0f; double nextTime = 0f; for (int i = 0; i < frameKeys.Count; i++) { if (previousTime <= targetTime && frameKeys.ElementAt(i) >= targetTime) { nextTime = frameKeys.ElementAt(i); break; } else { previousTime = frameKeys.ElementAt(i); } } if (nextTime == 0) { nextTime = frameKeys.GetMostRecentElement(); } double timeBetweenFrames = nextTime - previousTime; double timeAwayFromPrevious = currentTime - previousTime; //We loose some accuracy here, but Unity's transforms are floats float lerpProgress = (float)(timeAwayFromPrevious / timeBetweenFrames); Logger.Debug("TimeAgo: {TimeAgo}, previousTime: {PreviousTime}, nextTime: {NextTime}, lerp: {Lerp}", secondsAgo, previousTime, nextTime, lerpProgress); objTransform.position = Vector3.Lerp(frameData[previousTime].Position, frameData[nextTime].Position, lerpProgress); objTransform.rotation = Quaternion.Slerp(frameData[previousTime].Rotation, frameData[nextTime].Rotation, lerpProgress); }
public static void HelpCommand(string[] args) { Stopwatch stopwatch = Stopwatch.StartNew(); List <string> helpList = new List <string>(); foreach (KeyValuePair <string, ConsoleCommand> command in ConsoleBackend.GetAllCommands()) { helpList.Add($"\n`{command.Key}` - {command.Value.CommandSummary}"); } helpList.Sort(string.Compare); Logger.Info(string.Join("", helpList)); stopwatch.Stop(); Logger.Debug("Took {Time}ms to build help menu.", stopwatch.Elapsed.TotalMilliseconds); }
private static void OnReceiveClientPingMessage(NetworkConnection conn, PingClientMessage message) { ExponentialMovingAverage rtt; if (clientsPing.ContainsKey(conn.connectionId)) { rtt = clientsPing[conn.connectionId]; } else { rtt = AddClient(conn); } double clientRttValue = NetworkTime.time - message.ClientTime; rtt.Add(clientRttValue); Logger.Debug("Got client {ClientConnectionId}'s rtt of {ClientRtt}ms", conn.connectionId, rtt.Value); }
internal IEnumerator ServerReloadPlayerWeapon() { Logger.Debug($"Reloading player `{transform.name}`'s active weapon"); //Get our players weapon NetworkedWeapon networkedWeapon = GetActiveWeapon(); networkedWeapon.IsReloading = true; networkedWeapon.CurrentBulletAmount = 0; TargetSendWeaponStatus(GetClientConnection, networkedWeapon); int weaponIndex = SelectedWeaponIndex; TCWeapon weapon = networkedWeapon.GetTCWeapon(); yield return(new WaitForSeconds(weapon.reloadTime)); FinishReload(networkedWeapon, weaponIndex); }
private void OpenPanel(MainMenuPanel panel, bool isSwitching = false) { Logger.Debug($"Opening {panel.name}"); if (!isSwitching) { if (panel.showTopBlackBar) { ActivateTopBlackBar(); } if (panel.darkenScreen) { ActivateBlackBackground(); } } panel.activePanel.SetActive(true); panel.isOpen = true; }
private async UniTaskVoid LoadSteamAvatarAsync() { Image?imageTask = await SteamFriends.GetLargeAvatarAsync(UserId).AsUniTask(); if (!imageTask.HasValue) { return; } Image image = imageTask.Value; Logger.Debug("Got Steam user profile image of {Height} x {Width}", image.Height, image.Width); if (userProfilePicture.width != image.Width || userProfilePicture.height != image.Height) { userProfilePicture.Reinitialize((int)image.Width, (int)image.Height); } userProfilePicture.LoadSteamworksImageIntoTexture2D(image); }
protected override void SingletonAwakened() { if (string.IsNullOrEmpty(SettingsPath)) { Logger.Error("Settings path cannot be empty or null!"); Destroy(this); return; } try { Settings = Addressables.LoadAssetAsync <TSettingsType>(SettingsPath).WaitForCompletion(); } catch (Exception ex) { Logger.Error(ex, "Failed to load settings!"); } Logger.Debug("Loaded settings from '{Path}'.", SettingsPath); }
private Camera FindMainCamera() { GameObject cameraObj = GameObject.FindWithTag(sceneCameraTag); //Fall back to main camera if we can't find the scene camera if (cameraObj == null) { Logger.Debug("Did not find scene camera! Falling back to Camera.main."); return(Camera.main); } Camera foundCam = cameraObj.GetComponent <Camera>(); if (foundCam == null) { Logger.Debug("Did not find scene camera! Falling back to Camera.main."); return(Camera.main); } Logger.Debug("Found SceneCamera"); return(foundCam); }
private void ApplyVolumeSettings() { //Get the advance settings AdvSettingsClass settings = GameSettings.AdvSettings; ActiveVolume.enabled = settings.PostProcessing; //No point in apply anything if we aren't using Post-Processing if (!settings.PostProcessing) { return; } //Motion Blur if (ActiveVolume.profile.TryGet(out MotionBlur blur)) { blur.active = settings.MotionBlur; blur.intensity.value = settings.MotionBlurIntensity; blur.clamp.value = settings.MotionBlurClamp; } //Bloom if (ActiveVolume.profile.TryGet(out Bloom bloom)) { bloom.active = settings.Bloom; bloom.threshold.value = settings.BloomThreshold; bloom.intensity.value = settings.BloomIntensity; } //Vignette if (ActiveVolume.profile.TryGet(out Vignette vignette)) { vignette.active = settings.Vignette; vignette.intensity.value = settings.VignetteIntensity; vignette.smoothness.value = settings.VignetteSmoothness; } Logger.Debug("Applied Volume(Post-Processing) settings"); }
/// <summary> /// Adds a <see cref="TCServerResponse" /> to the list of servers /// </summary> /// <param name="server"></param> public void AddServer(TCServerResponse server) { //We are connecting to a server... if (NetworkManager.singleton.mode == NetworkManagerMode.ClientOnly) { return; } //If the server already exists in the list then ignore it if (servers.Any(x => Equals(x.EndPoint, server.EndPoint))) { return; } //Add the server to the list servers.Add(server); AddServerItem(server); statusText.gameObject.SetActive(false); Logger.Debug("Found server at {Address}", server.EndPoint.Address); }
internal void AddWeapon(string weapon) { TCWeapon tcWeapon = WeaponsResourceManager.GetWeapon(weapon); if (tcWeapon == null) { return; } NetworkedWeapon netWeapon = new NetworkedWeapon(tcWeapon); weapons.Add(netWeapon); Logger.Debug($"Added weapon {weapon} for {transform.name} with {tcWeapon.maxBullets} bullets"); //Setup the new added weapon, and stop any reloading going on with the current weapon TargetSendWeaponStatus(GetClientConnection, netWeapon); if (weapons.Count > 1) { SetClientWeaponIndex(weapons.Count - 1); } }
private void CreateStringField(string val, FieldInfo field, OptionsMenu optionsMenu) { Logger.Debug($"\tCreating string field for {field.Name} in {optionsMenu.Name}. Current is {val}"); // new TMP_InputField().onValueChanged.AddListener(s => field.SetValue(GetSettingObject(field), s)); }
private static void Init() { weapons = Addressables.LoadAssetsAsync <WeaponBase>(WeaponLabel, null).WaitForCompletion(); Logger.Debug("Loaded {WeaponCount} weapons.", weapons.Count); }
/// <summary> /// Generates the settings menu /// </summary> //TODO: The sub-functions need to update the UI element based on the reflected value on startup/settings reload public void UpdateUI() { Stopwatch stopwatch = Stopwatch.StartNew(); optionsPanel.ClearPanels(); //TODO: Holy f*****g hell this is ugly //Loop over each setting menu and all the sub-settings foreach (PropertyInfo settingInfo in GameSettings.GetSettingClasses()) { //If it has the don't show attribute, then, well... don't show it if (settingInfo.DontShowObject()) { continue; } object settingGroupInstance = settingInfo.GetStaticValue <object>(); //Get display text string settingGroupName = settingInfo.GetObjectDisplayText(); //Create a menu module OptionsMenu optionOptionsMenu = new OptionsMenu(settingGroupName); GameObject panel = optionsPanel.AddPanel(optionOptionsMenu); //Get each property in the settings FieldInfo[] menuFields = settingInfo.PropertyType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (FieldInfo settingField in menuFields) { //If it has the don't show attribute, then, well... don't show it if (settingField.DontShowObject()) { continue; } Type fieldType = settingField.FieldType; if (fieldType == typeof(int)) { CreateIntSlider(settingField.GetValue <int>(settingGroupInstance), settingField, panel); } else if (fieldType == typeof(float)) { CreateFloatSlider(settingField.GetValue <float>(settingGroupInstance), settingField, panel); } else if (fieldType == typeof(bool)) { CreateBoolToggle(settingField.GetValue <bool>(settingGroupInstance), settingField, panel); } else if (fieldType == typeof(string)) { CreateStringField(settingField.GetValue <string>(settingGroupInstance), settingField, optionOptionsMenu); } else if (fieldType == typeof(Resolution)) { CreateResolutionDropdown(settingField.GetValue <Resolution>(settingGroupInstance), settingField, panel); } else if (fieldType.IsEnum) { CreateEnumDropdown(settingField.GetValue <int>(settingGroupInstance), settingField, panel); } else { Logger.Error("UI Element for setting of type {FullName} is not supported!", fieldType.FullName); } } } stopwatch.Stop(); Logger.Debug("Time taken to update settings UI: {TotalMilliseconds}ms", stopwatch.Elapsed.TotalMilliseconds); }