public static void VignetteIntensityCommand(string[] args) { string stringAmount = args[0].ToLower(); if (float.TryParse(stringAmount, out float amount)) { //Vignette intensity doesn't go over 1.0 if (amount > 1.0f) { amount = 1.0f; } GameSettings.AdvSettings.VignetteIntensity = amount; GameSettings.Save(); return; } Logger.Error("Invalid input!"); }
public static void MotionBlurClampCommand(string[] args) { string stringAmount = args[0].ToLower(); if (float.TryParse(stringAmount, out float amount)) { //Motion blur clamp doesn't go over 0.2 if (amount > 0.2f) { amount = 0.2f; } GameSettings.AdvSettings.MotionBlurClamp = amount; GameSettings.Save(); return; } Logger.Error("Invalid input!"); }
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 static async UniTaskVoid WaitForServerOneFileAndConnect(string serverOnlinePath, Action onSuccessFullCompletion = null, Action onFailToStart = null) { float timeUntilCancel = Time.time + TimeOutServerTime; //Wait until the server online file exist while (!File.Exists(serverOnlinePath)) { //If we hit the timeout time, then fail it await UniTask.Delay(100); if (Time.time >= timeUntilCancel) { Logger.Error("Server process did not start for some reason! Not connecting."); onFailToStart?.Invoke(); return; } } onSuccessFullCompletion?.Invoke(); }
/// <summary> /// Call when a client connects /// </summary> /// <param name="conn"></param> internal static void OnServerAddClient(NetworkConnection conn) { //Sent to client the server config conn.Send(TCNetworkManager.Instance.serverConfig); //Lets just hope our transport never assigns the first connection max value of int if (closeServerOnFirstClientDisconnect && firstConnectionId == int.MaxValue) { firstConnectionId = conn.connectionId; } Logger.Info( "Client from '{Address}' connected with the connection ID of {ConnectionID}.", conn.address, conn.connectionId); IUser user = netManager.tcAuthenticator.GetAccount(conn.connectionId); if (user != null) { ServerChat.SendChatMessage("<b>Join</b>", user.UserName); } }
private void Start() { if (ConsoleUI != null) { Destroy(gameObject); Logger.Warn("You should only ever load this script on a bootloader scene!"); return; } //If we are headless we need to create a console UI using the OS's terminal //I really which Unity would have this included... if (Game.IsHeadless) { #if UNITY_STANDALONE_WIN ConsoleUI = new ConsoleWindows($"{Application.productName} Server"); #elif UNITY_STANDALONE_LINUX ConsoleUI = new ConsoleLinux($"{Application.productName} Server"); #elif UNITY_STANDALONE_OSX //TODO: Add console for OSX #endif } else { GameObject consoleUiPrefab = Addressables.LoadAssetAsync <GameObject>(ConsoleUiPrefabPath).WaitForCompletion(); //Create in-game console GUI ConsoleUI = Instantiate(consoleUiPrefab, transform).GetComponent <ConsoleGUI>(); } //Init the console ConsoleUI.Init(); //Init the backend of the console ConsoleBackend.InitConsoleBackend(); //Exec autoexec ConsoleBackend.ExecuteFileCommand(new[] { "autoexec" }); }
public void UpdateConsole() { //Return if there is no key available if (!System.Console.KeyAvailable) { return; } //Read the key ConsoleKeyInfo keyInfo = System.Console.ReadKey(); switch (keyInfo.Key) { //Enter in input case ConsoleKey.Enter: string value = System.Console.ReadLine(); Logger.Info($"cmd>: {value}"); ConsoleBackend.ExecuteCommand(value); break; } }
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); }
protected override void OnAdd() { nextTimeToFire = 0f; currentProjectileCount = maxWeaponProjectileCount; isReloading = false; if (isServer) { projectileObjectsPool = GameSceneManager.Instance.rocketsPool; } if (isLocalClient) { OnUIUpdate(new DefaultHudUpdateMessage(null, currentProjectileCount, isReloading)); } weaponGraphics = weaponObjectInstance.GetComponent <WeaponGraphics>(); if (weaponGraphics == null) { Logger.Error("Weapon model doesn't contain a weapon graphics!"); } }
public static void MotionBlurEnableCommand(string[] args) { string toggle = args[0].ToLower(); switch (toggle) { case "1": case "true": GameSettings.AdvSettings.MotionBlur = true; GameSettings.Save(); break; case "0": case "false": GameSettings.AdvSettings.MotionBlur = false; GameSettings.Save(); break; default: Logger.Error("Invalid argument!"); break; } }
/// <summary> /// Call when a client disconnects /// </summary> /// <param name="conn"></param> internal static void OnServerRemoveClient(NetworkConnection conn) { NetworkServer.DestroyPlayerForConnection(conn); if (netManager == null) { CloseServerIfNecessary(conn); return; } if (netManager.tcAuthenticator != null) { IUser user = netManager.tcAuthenticator.GetAccount(conn.connectionId); if (user != null) { ServerChat.SendChatMessage("<b>Disconnect</b>", user.UserName); } } netManager.tcAuthenticator.OnServerClientDisconnect(conn); Logger.Info("Client '{ConnectionId}' disconnected from the server.", conn.connectionId); CloseServerIfNecessary(conn); }
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); } }
/// <summary> /// Creates a new <see cref="Locale" /> instance /// </summary> /// <param name="fileLocation"></param> public Locale(string fileLocation) { //Try and load the locale for the native system language string systemLanguageLocaleLocation = fileLocation.Replace("%LANG%", Language.ToString()); if (!File.Exists(systemLanguageLocaleLocation)) //The locale doesn't exist for the system language { //Try and default to english (Should generally always exist, as Voltstro Studios is english...) systemLanguageLocaleLocation = fileLocation.Replace("%LANG%", "English"); if (!File.Exists(systemLanguageLocaleLocation)) { Logger.Error("No locale exists at {@LocalLocation}! The locale will not be loaded!", fileLocation); Tokens = new Dictionary <string, string>(); return; } Logger.Warn("No locale exists for system language {@Language}... defaulting to english!", Language.ToString()); } //Now to load the tokens Tokens = JsonConvert.DeserializeObject <Dictionary <string, string> >( File.ReadAllText(systemLanguageLocaleLocation)); }
public void TakeDamage(int damageAmount, string sourcePlayerId) { if (string.IsNullOrWhiteSpace(sourcePlayerId)) { Logger.Error("The {@ArgumentName} cannot be empty or null!", nameof(sourcePlayerId)); return; } //Can't do damage on a player if they are dead or just re-spawned if (IsDead || IsInvincible) { return; } Health -= damageAmount; if (Health > 0) { return; } //Player is dead ServerPlayerDie(sourcePlayerId); }
/// <summary> /// Called when the client disconnects from a server /// </summary> /// <param name="conn"></param> internal static void OnClientDisconnect(NetworkConnection conn) { netManager.StopClient(); Logger.Info($"Disconnected from server {conn.address}"); }
/// <summary> /// Called when the client is stopped /// </summary> internal static void OnClientStop() { PingManager.ClientShutdown(); Logger.Info("Stopped client."); }
/// <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); }
/// <summary> /// Adds all fields that have the <see cref="ConVar" /> attribute attached to it /// </summary> private static void RegisterConVars() { foreach (KeyValuePair <ConVar, FieldInfo> conVar in GetConVars()) { ConVar attribute = conVar.Key; FieldInfo fieldInfo = conVar.Value; if (attribute.GraphicsOnly && Game.IsHeadless) { continue; } Action action = null; try { //Create an action if the callback string is not null if (attribute.Callback != null) { action = (Action)Delegate.CreateDelegate(typeof(Action), fieldInfo.DeclaringType ?? throw new Exception("Field's declaring type was null!"), attribute.Callback); } } catch (Exception ex) { Logger.Error(ex, "An error occurred while adding the ConVar {@ConVar}'s callback method!", attribute.Name); continue; } //We add the ConVar as it was a normal command, but with a custom CommandMethod AddCommand(new ConsoleCommand { CommandSummary = attribute.Summary, RunPermission = CommandRunPermission.Both, MinArgs = 1, MaxArgs = 1, CommandMethod = args => { if (fieldInfo.FieldType.IsEnum) { object enumOption = Enum.Parse(fieldInfo.FieldType, args[0]); fieldInfo.SetValue(fieldInfo, enumOption); action?.Invoke(); Logger.Info("'{Name}' was set to {Value}", attribute.Name, enumOption); return; } //If we have an ITypeReader for the type, then read the arg using it if (typeReaders.TryGetValue(fieldInfo.FieldType, out ITypeReader reader)) { //Set the field and invoke the action (if not null) fieldInfo.SetValue(fieldInfo, reader.ReadType(args[0])); action?.Invoke(); Logger.Info("'{Name}' was set to '{Value}'", attribute.Name, reader.ReadType(args[0])); return; } Logger.Error("There is no {@TypeReaderNameOf} for the Type {@Type}!", nameof(ITypeReader), fieldInfo.FieldType.FullName); } }, attribute.Name);
public static void VersionCommand(string[] args) { Logger.Info($"You are running TC version {Application.version} using Unity {Application.unityVersion}"); }
public static void SetAddressCommand(string[] args) { NetworkManager.singleton.networkAddress = args[0]; Logger.Info("Server's address was set to {Address}", args[0]); }
private void WeaponRayCast() { //Next, get what weapon the player was using TCWeapon tcWeapon = weaponManager.GetActiveWeapon().GetTCWeapon(); if (tcWeapon == null) { return; } Stopwatch stopwatch = Stopwatch.StartNew(); //Get the direction the player was facing Transform playerFacingDirection = localPlayerCamera.transform; //Create a list here, so we know later where the bullets landed List <Vector3> targets = new List <Vector3>(); List <Vector3> targetsNormal = new List <Vector3>(); for (int i = 0; i < tcWeapon.bulletsPerShot; i++) { //Calculate random spread Vector3 direction = playerFacingDirection.forward; direction += playerFacingDirection.TransformDirection(new Vector3( Random.Range(-tcWeapon.spreadFactor, tcWeapon.spreadFactor), Random.Range(-tcWeapon.spreadFactor, tcWeapon.spreadFactor), Random.Range(-tcWeapon.spreadFactor, tcWeapon.spreadFactor))); //Now do our raycast // ReSharper disable once Unity.PreferNonAllocApi RaycastHit[] hits = RaycastHelper.RaycastAllSorted(playerFacingDirection.position, direction, tcWeapon.range, raycastLayerMask); foreach (RaycastHit hit in hits) { //Don't count if we hit the shooting player if (hit.collider.name == transform.name) { continue; } //Do impact effect on all clients targets.Add(hit.point); targetsNormal.Add(hit.normal); //So if we hit a player then do damage PlayerManager hitPlayer = hit.collider.GetComponent <PlayerManager>(); if (hitPlayer == null) { break; } hitPlayer.TakeDamage(tcWeapon.damage, transform.name); break; } } //Send where the bullets hit in one big message RpcDoWeaponShootEffects(new WeaponShootEffectsTargets { Targets = targets.ToArray(), TargetNormals = targetsNormal.ToArray() }); stopwatch.Stop(); Logger.Debug("Took {@Milliseconds}ms to fire {@Player}'s {@Weapon}", stopwatch.Elapsed.TotalMilliseconds, transform.name, tcWeapon.weapon); }
/// <summary> /// Called when the client is stopped /// </summary> internal static void OnClientStop() { Status = ClientStatus.Offline; PingManager.ClientShutdown(); Logger.Info("Stopped client."); }
public void ChangeUserData(IUser user) { Logger.Info($"Change username to {user.UserName}"); User = user; }
public static void EchoCommand(string[] args) { Logger.Info(string.Join(" ", args)); }
private static void Init() { weapons = Addressables.LoadAssetsAsync <WeaponBase>(WeaponLabel, null).WaitForCompletion(); Logger.Debug("Loaded {WeaponCount} weapons.", weapons.Count); }
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)); }
/// <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); }
public static void SetGameNameCommand(string[] args) { TCNetworkManager.Instance.serverConfig.gameName = string.Join(" ", args); Logger.Info("Game name was set to {Name}", TCNetworkManager.Instance.serverConfig.gameName); }