Пример #1
0
        public static bool Prefix(AlphaWarheadController __instance, GameObject disabler)
        {
            try
            {
                ServerLogs.AddLog(ServerLogs.Modules.Warhead, "Detonation cancelled.", ServerLogs.ServerLogType.GameEvent);

                if (!__instance.inProgress || __instance.timeToDetonation <= 10.0)
                {
                    return(false);
                }

                if (__instance.timeToDetonation <= 15.0 && disabler != null)
                {
                    __instance.GetComponent <PlayerStats>().TargetAchieve(disabler.GetComponent <NetworkIdentity>().connectionToClient, "thatwasclose");
                }

                bool allow = true;

                Events.InvokeWarheadCancel(disabler, ref allow);

                return(allow && !EventPlugin.WarheadLocked);
            }
            catch (Exception exception)
            {
                Log.Error($"WarheadCancelledEvent error: {exception}");
                return(true);
            }
        }
Пример #2
0
        private static bool Prefix(AlphaWarheadController __instance)
        {
            if (Recontainer079.isLocked)
            {
                return(false);
            }

            __instance.doorsOpen = false;

            ServerLogs.AddLog(ServerLogs.Modules.Warhead, "Countdown started.", ServerLogs.ServerLogType.GameEvent);

            if ((AlphaWarheadController._resumeScenario != -1 || __instance.scenarios_start[AlphaWarheadController._startScenario].SumTime() != (double)__instance.timeToDetonation) && (AlphaWarheadController._resumeScenario == -1 || __instance.scenarios_resume[AlphaWarheadController._resumeScenario].SumTime() != (double)__instance.timeToDetonation))
            {
                return(false);
            }

            var ev = new StartingEventArgs(API.Features.Server.Host);

            Warhead.OnStarting(ev);

            if (!ev.IsAllowed)
            {
                return(false);
            }

            __instance.NetworkinProgress = true;

            return(false);
        }
Пример #3
0
        public static bool Prefix(FlashGrenade __instance, ref bool __result)
        {
            Exiled.API.Features.Log.Debug($"Flash grenade explosion", Subclass.Instance.Config.Debug);
            foreach (GameObject obj2 in PlayerManager.players)
            {
                Player       target   = Player.Get(obj2);
                Vector3      position = ((EffectGrenade)__instance).transform.position;
                ReferenceHub hub      = ReferenceHub.GetHub(obj2);
                Flashed      effect   = hub.playerEffectsController.GetEffect <Flashed>();
                Deafened     deafened = hub.playerEffectsController.GetEffect <Deafened>();
                Exiled.API.Features.Log.Debug($"Flash target is: {target?.Nickname}", Subclass.Instance.Config.Debug);
                if ((effect != null) &&
                    ((((EffectGrenade)__instance).thrower != null) &&
                     (__instance._friendlyFlash ||
                      effect.Flashable(ReferenceHub.GetHub(((EffectGrenade)__instance).thrower.gameObject), position, __instance._ignoredLayers))))
                {
                    if (!Tracking.PlayersWithSubclasses.ContainsKey(target) ||
                        !Tracking.PlayersWithSubclasses[target].Abilities.Contains(AbilityType.FlashImmune))
                    {
                        float num       = __instance.powerOverDistance.Evaluate((float)(Vector3.Distance(obj2.transform.position, position) / ((position.y > 900f) ? __instance.distanceMultiplierSurface : __instance.distanceMultiplierFacility))) * __instance.powerOverDot.Evaluate(Vector3.Dot(hub.PlayerCameraReference.forward, (hub.PlayerCameraReference.position - position).normalized));
                        byte  intensity = (byte)Mathf.Clamp(Mathf.RoundToInt((float)((num * 10f) * __instance.maximumDuration)), 1, 0xff);
                        if ((intensity >= effect.Intensity) && (num > 0f))
                        {
                            hub.playerEffectsController.ChangeEffectIntensity <Flashed>(intensity);
                            if (deafened != null)
                            {
                                hub.playerEffectsController.EnableEffect(deafened, num * __instance.maximumDuration, true);
                            }
                        }
                    }
                    else
                    {
                        Concussed concussedEffect = hub.playerEffectsController.GetEffect <Concussed>();
                        concussedEffect.Intensity = 3;
                        hub.playerEffectsController.EnableEffect(concussedEffect, 5);
                        Disabled disabledEffect = hub.playerEffectsController.GetEffect <Disabled>();
                        disabledEffect.Intensity = 2;
                        hub.playerEffectsController.EnableEffect(disabledEffect, 5);
                    }
                }
            }

            if (((EffectGrenade)__instance).serverGrenadeEffect != null)
            {
                Transform transform = ((Grenade)__instance).transform;
                Object.Instantiate <GameObject>(((EffectGrenade)__instance).serverGrenadeEffect, transform.position, transform.rotation);
            }

            string str = (((Grenade)__instance).thrower != null) ? ((Grenade)__instance).thrower.hub.LoggedNameFromRefHub() : ((string)"(UNKNOWN)");

            string[] textArray1 = new string[] { "Player ", (string)str, "'s ", (string)((Grenade)__instance).logName, " grenade exploded." };
            ServerLogs.AddLog(ServerLogs.Modules.Logger, string.Concat((string[])textArray1), ServerLogs.ServerLogType.GameEvent, false);

            __result = true;
            return(false);
        }
Пример #4
0
        public static bool Prefix(PlayerInteract __instance)
        {
            if (EventPlugin.WarheadStartEventPatchDisable)
            {
                return(true);
            }

            try
            {
                if (!__instance._playerInteractRateLimit.CanExecute(true) || (__instance._hc.CufferId > 0 && !__instance.CanDisarmedInteract))
                {
                    return(false);
                }

                GameObject gameObject = GameObject.Find("OutsitePanelScript");

                if (!__instance.ChckDis(gameObject.transform.position) || !AlphaWarheadOutsitePanel.nukeside.enabled)
                {
                    return(false);
                }

                if (!gameObject.GetComponent <AlphaWarheadOutsitePanel>().keycardEntered || Recontainer079.isLocked)
                {
                    return(false);
                }

                AlphaWarheadController.Host.doorsOpen = false;

                ServerLogs.AddLog(ServerLogs.Modules.Warhead, "Countdown started.", ServerLogs.ServerLogType.GameEvent);
                if ((AlphaWarheadController._resumeScenario == -1 && AlphaWarheadController.Host.scenarios_start[AlphaWarheadController._startScenario].SumTime() == AlphaWarheadController.Host.timeToDetonation) ||
                    (AlphaWarheadController._resumeScenario != -1 && AlphaWarheadController.Host.scenarios_resume[AlphaWarheadController._resumeScenario].SumTime() == AlphaWarheadController.Host.timeToDetonation))
                {
                    bool allow = true;

                    Events.InvokeWarheadStart(__instance.gameObject, ref allow);

                    if (!allow)
                    {
                        return(false);
                    }

                    AlphaWarheadController.Host.NetworkinProgress = true;
                }

                ServerLogs.AddLog(ServerLogs.Modules.Warhead, __instance.GetComponent <NicknameSync>().MyNick + " (" + __instance.GetComponent <CharacterClassManager>().UserId + ") started the Alpha Warhead detonation.", ServerLogs.ServerLogType.GameEvent);

                __instance.OnInteract();

                return(false);
            }
            catch (Exception exception)
            {
                Log.Error($"WarheadStartEvent error: {exception}");
                return(true);
            }
        }
Пример #5
0
 public static bool Prefix(Grenades.Grenade __instance, ref bool __result)
 {
     try
     {
         if (__instance.thrower?.name != "Host")
         {
             string text = (__instance.thrower != null) ? (__instance.thrower.ccm.UserId + " (" + __instance.thrower.nick.MyNick + ")") : "(UNKNOWN)";
             ServerLogs.AddLog(ServerLogs.Modules.Logger, "Player " + text + "'s " + __instance.logName + " grenade exploded.", ServerLogs.ServerLogType.GameEvent);
         }
         __result = true;
         return(false);
     }
     catch (Exception)
     {
         return(true);
     }
 }
Пример #6
0
        //
        // GET: /Reports/
        public ActionResult ServerLog(int?Id)
        {
            var loggedUser = UsersUtilities.GetLoggedUser();

            if (loggedUser == null)
            {
                return(Redirect("~/User/Login"));
            }
            ServerLogs logs = new ServerLogs(loggedUser);

            if (Id != null)
            {
                logs.SelectServer(Id.Value);
            }


            return(View(logs));
        }
Пример #7
0
        private static bool Prefix(PlayerInteract __instance)
        {
            if (!__instance._playerInteractRateLimit.CanExecute(true) || (__instance._hc.CufferId > 0 && !PlayerInteract.CanDisarmedInteract))
            {
                return(false);
            }

            GameObject gameObject = GameObject.Find("OutsitePanelScript");

            if (!__instance.ChckDis(gameObject.transform.position) || !AlphaWarheadOutsitePanel.nukeside.enabled)
            {
                return(false);
            }

            if (!gameObject.GetComponent <AlphaWarheadOutsitePanel>().keycardEntered || Recontainer079.isLocked)
            {
                return(false);
            }

            AlphaWarheadController.Host.doorsOpen = false;

            ServerLogs.AddLog(ServerLogs.Modules.Warhead, "Countdown started.", ServerLogs.ServerLogType.GameEvent);
            if ((AlphaWarheadController._resumeScenario == -1 && AlphaWarheadController.Host.scenarios_start[AlphaWarheadController._startScenario].SumTime() == AlphaWarheadController.Host.timeToDetonation) ||
                (AlphaWarheadController._resumeScenario != -1 && AlphaWarheadController.Host.scenarios_resume[AlphaWarheadController._resumeScenario].SumTime() == AlphaWarheadController.Host.timeToDetonation))
            {
                var ev = new StartingEventArgs(API.Features.Player.Get(__instance.gameObject) ?? API.Features.Server.Host);

                Warhead.OnStarting(ev);

                if (!ev.IsAllowed)
                {
                    return(false);
                }

                AlphaWarheadController.Host.NetworkinProgress = true;
            }

            ServerLogs.AddLog(ServerLogs.Modules.Warhead, __instance.GetComponent <NicknameSync>().MyNick + " (" + __instance.GetComponent <CharacterClassManager>().UserId + ") started the Alpha Warhead detonation.", ServerLogs.ServerLogType.GameEvent);

            __instance.OnInteract();

            return(false);
        }
Пример #8
0
        private static bool Prefix(AlphaWarheadController __instance, GameObject disabler)
        {
            ServerLogs.AddLog(ServerLogs.Modules.Warhead, "Detonation cancelled.", ServerLogs.ServerLogType.GameEvent);

            if (!__instance.inProgress || __instance.timeToDetonation <= 10.0)
            {
                return(false);
            }

            if (__instance.timeToDetonation <= 15.0 && disabler != null)
            {
                __instance.GetComponent <PlayerStats>().TargetAchieve(disabler.GetComponent <NetworkIdentity>().connectionToClient, "thatwasclose");
            }

            var ev = new StoppingEventArgs(API.Features.Player.Get(disabler) ?? API.Features.Server.Host);

            Warhead.OnStopping(ev);

            return(ev.IsAllowed && !API.Features.Warhead.IsWarheadLocked);
        }
Пример #9
0
            public static bool Prefix(AlphaWarheadController __instance)
            {
                if (EventPlugin.WarheadStartEventPatchDisable)
                {
                    return(true);
                }

                try
                {
                    if (Recontainer079.isLocked)
                    {
                        return(false);
                    }

                    __instance.doorsOpen = false;

                    ServerLogs.AddLog(ServerLogs.Modules.Warhead, "Countdown started.", ServerLogs.ServerLogType.GameEvent);

                    if ((AlphaWarheadController._resumeScenario != -1 || __instance.scenarios_start[AlphaWarheadController._startScenario].SumTime() != (double)__instance.timeToDetonation) && (AlphaWarheadController._resumeScenario == -1 || __instance.scenarios_resume[AlphaWarheadController._resumeScenario].SumTime() != (double)__instance.timeToDetonation))
                    {
                        return(false);
                    }

                    bool allow = true;

                    Events.InvokeWarheadStart(null, ref allow);

                    if (allow)
                    {
                        __instance.NetworkinProgress = true;
                    }

                    return(false);
                }
                catch (Exception exception)
                {
                    Log.Error($"WarheadStartEvent error: {exception}");
                    return(true);
                }
            }
Пример #10
0
 private void KeyPressed()
 {
     if (TabSelected == 0)
     {
         _blitzmodel.ManualLog(new BlitzEventArgs("Socket.IO Újrakapcsolódás", "Socket.IO-hozzáférés",
                                                  BlitzEventArgs.EventMood.COMMAND));
         _blitzmodel.ForwardGeocodingQuery(ProbeAddress);
     }
     else if (TabSelected == 1)
     {
         _blitzmodel.ManualLog(new BlitzEventArgs("Darabszám-grafikon manuális frissítése F5-tel",
                                                  "Villám darabszám-grafikon", BlitzEventArgs.EventMood.COMMAND));
         _blitzmodel.countProcess();
     }
     else if (TabSelected == 2)
     {
         _blitzmodel.ManualLog(new BlitzEventArgs("10 perces statisztikák manuális frissítése F5-tel",
                                                  "10 perces statisztika", BlitzEventArgs.EventMood.COMMAND));
         _blitzmodel.countProcess();
     }
     else if (TabSelected == 3)
     {
         _blitzmodel.ManualLog(new BlitzEventArgs("Hosszútávú statisztika manuális frissítése F5-tel",
                                                  "Hosszútávú statisztika", BlitzEventArgs.EventMood.COMMAND));
         _blitzmodel.OverallStatUpdate();
     }
     else if (TabSelected == 4)
     {
         _blitzmodel.ManualLog(new BlitzEventArgs("Összes állomásadat manuális frissítése F5-tel",
                                                  "Összes állomásadat", BlitzEventArgs.EventMood.COMMAND));
         _blitzmodel.StationsOverallStatUpdate();
     }
     else if (TabSelected == 5)
     {
         _blitzmodel.ManualLog(new BlitzEventArgs("Socket.IO Újrakapcsolódás", "Socket.IO-hozzáférés",
                                                  BlitzEventArgs.EventMood.COMMAND));
         _blitzmodel.ForwardGeocodingQuery(ProbeAddress);
         ServerLogs.Clear();
     }
 }
Пример #11
0
        public static bool Prefix(RespawnManager __instance)
        {
            try
            {
                if (!RespawnWaveGenerator.SpawnableTeams.TryGetValue(__instance.NextKnownTeam, out var spawnableTeam) || __instance.NextKnownTeam == SpawnableTeamType.None)
                {
                    ServerConsole.AddLog("Fatal error. Team '" + __instance.NextKnownTeam.ToString() + "' is undefined.", (ConsoleColor)12);
                    return(false);
                }
                var list = ReferenceHub.GetAllHubs().Values.Where((item) => item.characterClassManager.CurClass == RoleType.Spectator && !item.serverRoles.OverwatchEnabled).ToList();
                if (__instance._prioritySpawn)
                {
                    list = list.OrderBy((item) => item.characterClassManager.DeathTime).ToList();
                }
                else
                {
                    list.ShuffleList();
                }
                var singleton = RespawnTickets.Singleton;
                var num       = singleton.GetAvailableTickets(__instance.NextKnownTeam);
                if (num == 0)
                {
                    num = singleton.DefaultTeamAmount;
                    RespawnTickets.Singleton.GrantTickets(singleton.DefaultTeam, singleton.DefaultTeamAmount, true);
                }
                var num2 = Mathf.Min(num, spawnableTeam.MaxWaveSize);
                while (list.Count > num2)
                {
                    list.RemoveAt(list.Count - 1);
                }
                list.ShuffleList();
                var list2 = ListPool <ReferenceHub> .Shared.Rent();

                var playerList = list.Select(hub => hub.GetPlayer()).ToList();

                Events.InvokeTeamRespawnEvent(ref playerList, ref __instance.NextKnownTeam);

                if (__instance.NextKnownTeam == SpawnableTeamType.None)
                {
                    return(false);
                }

                foreach (var player in playerList)
                {
                    try
                    {
                        var classId = spawnableTeam.ClassQueue[Mathf.Min(list2.Count, spawnableTeam.ClassQueue.Length - 1)];
                        player.ClassManager.SetPlayersClass(classId, player.gameObject);
                        list2.Add(player.Hub);
                        ServerLogs.AddLog(ServerLogs.Modules.ClassChange, string.Concat(new string[]
                        {
                            "Player ",
                            player.Hub.LoggedNameFromRefHub(),
                            " respawned as ",
                            classId.ToString(),
                            "."
                        }), ServerLogs.ServerLogType.GameEvent);
                    }
                    catch (Exception ex)
                    {
                        if (player != null)
                        {
                            ServerLogs.AddLog(ServerLogs.Modules.ClassChange, "Player " + player.Hub.LoggedNameFromRefHub() + " couldn't be spawned. Err msg: " + ex.Message, ServerLogs.ServerLogType.GameEvent);
                        }
                        else
                        {
                            ServerLogs.AddLog(ServerLogs.Modules.ClassChange, "Couldn't spawn a player - target's ReferenceHub is null.", ServerLogs.ServerLogType.GameEvent);
                        }
                    }
                }
                if (list2.Count > 0)
                {
                    ServerLogs.AddLog(ServerLogs.Modules.ClassChange, string.Concat(new object[]
                    {
                        "RespawnManager has successfully spawned ",
                        list2.Count,
                        " players as ",
                        __instance.NextKnownTeam.ToString(),
                        "!"
                    }), ServerLogs.ServerLogType.GameEvent);
                    RespawnTickets.Singleton.GrantTickets(__instance.NextKnownTeam, -list2.Count * spawnableTeam.TicketRespawnCost);
                    if (UnitNamingRules.TryGetNamingRule(__instance.NextKnownTeam, out var unitNamingRule))
                    {
                        unitNamingRule.GenerateNew(__instance.NextKnownTeam, out var text);
                        foreach (ReferenceHub referenceHub2 in list2)
                        {
                            referenceHub2.characterClassManager.NetworkCurSpawnableTeamType = (byte)__instance.NextKnownTeam;
                            referenceHub2.characterClassManager.NetworkCurUnitName          = text;
                        }
                        unitNamingRule.PlayEntranceAnnouncement(text);
                    }
                    RespawnEffectsController.ExecuteAllEffects(RespawnEffectsController.EffectType.UponRespawn, __instance.NextKnownTeam);
                }
                __instance.NextKnownTeam = SpawnableTeamType.None;

                return(false);
            }
            catch (Exception e)
            {
                Log.Error($"TeamRespawnEvent Error: {e}");
                return(true);
            }
        }
Пример #12
0
        private static bool Spawn(RespawnManager __instance)
        {
            try
            {
                if (!RespawnWaveGenerator.SpawnableTeams.TryGetValue(__instance.NextKnownTeam, out var spawnableTeam) || __instance.NextKnownTeam == SpawnableTeamType.None)
                {
                    ServerConsole.AddLog("Fatal error. Team '" + __instance.NextKnownTeam + "' is undefined.", ConsoleColor.Red);
                    return(false);
                }
                List <ReferenceHub> list = (from item in ReferenceHub.GetAllHubs().Values
                                            where item.characterClassManager.CurClass == RoleType.Spectator && !item.serverRoles.OverwatchEnabled
                                            select item).ToList <ReferenceHub>();

                if (__instance._prioritySpawn)
                {
                    list = (from item in list
                            orderby item.characterClassManager.DeathTime
                            select item).ToList <ReferenceHub>();
                }
                else
                {
                    list.ShuffleList <ReferenceHub>();
                }

                var num = RespawnTickets.Singleton.GetAvailableTickets(__instance.NextKnownTeam);

                if (RespawnTickets.Singleton.IsFirstWave)
                {
                    RespawnTickets.Singleton.IsFirstWave = false;
                }

                if (num == 0)
                {
                    num = 5;
                    RespawnTickets.Singleton.GrantTickets(SpawnableTeamType.ChaosInsurgency, 5, true);
                }
                var num2 = Mathf.Min(num, spawnableTeam.MaxWaveSize);

                while (list.Count > num2)
                {
                    list.RemoveAt(list.Count - 1);
                }

                list.ShuffleList();

                var list2 = ListPool <ReferenceHub> .Shared.Rent();

                var players = list.Select(x => x.GetPlayer()).ToList();
                var team    = __instance.NextKnownTeam;

                SynapseController.Server.Events.Round.InvokeTeamRespawn(ref players, ref team, out var allow, out var id);

                if (!allow)
                {
                    return(false);
                }

                if (team == SpawnableTeamType.None)
                {
                    Server.Get.TeamManager.SpawnTeam(id, players);
                    return(false);
                }

                list = players.Select(x => x.Hub).ToList();
                __instance.NextKnownTeam = team;

                var que = new Queue <RoleType>();
                spawnableTeam.GenerateQueue(que, list.Count);

                foreach (ReferenceHub referenceHub in list)
                {
                    try
                    {
                        RoleType classid = que.Dequeue();
                        referenceHub.characterClassManager.SetPlayersClass(classid, referenceHub.gameObject, CharacterClassManager.SpawnReason.Respawn, false);
                        list2.Add(referenceHub);
                        ServerLogs.AddLog(ServerLogs.Modules.ClassChange, string.Concat(new string[]
                        {
                            "Player ",
                            referenceHub.LoggedNameFromRefHub(),
                            " respawned as ",
                            classid.ToString(),
                            "."
                        }), ServerLogs.ServerLogType.GameEvent, false);
                    }
                    catch (Exception ex)
                    {
                        if (referenceHub != null)
                        {
                            ServerLogs.AddLog(ServerLogs.Modules.ClassChange, "Player " + referenceHub.LoggedNameFromRefHub() + " couldn't be spawned. Err msg: " + ex.Message, ServerLogs.ServerLogType.GameEvent, false);
                        }
                        else
                        {
                            ServerLogs.AddLog(ServerLogs.Modules.ClassChange, "Couldn't spawn a player - target's ReferenceHub is null.", ServerLogs.ServerLogType.GameEvent, false);
                        }
                    }
                }
                if (list2.Count > 0)
                {
                    ServerLogs.AddLog(ServerLogs.Modules.ClassChange, string.Concat(new object[]
                    {
                        "RespawnManager has successfully spawned ",
                        list2.Count,
                        " players as ",
                        __instance.NextKnownTeam.ToString(),
                        "!"
                    }), ServerLogs.ServerLogType.GameEvent, false);
                    RespawnTickets.Singleton.GrantTickets(__instance.NextKnownTeam, -list2.Count * spawnableTeam.TicketRespawnCost, false);
                    if (Respawning.NamingRules.UnitNamingRules.TryGetNamingRule(__instance.NextKnownTeam, out var unitNamingRule))
                    {
                        unitNamingRule.GenerateNew(__instance.NextKnownTeam, out string text);
                        foreach (ReferenceHub referenceHub2 in list2)
                        {
                            referenceHub2.characterClassManager.NetworkCurSpawnableTeamType = (byte)__instance.NextKnownTeam;
                            referenceHub2.characterClassManager.NetworkCurUnitName          = text;
                        }
                        unitNamingRule.PlayEntranceAnnouncement(text);
                    }
                    RespawnEffectsController.ExecuteAllEffects(RespawnEffectsController.EffectType.UponRespawn, __instance.NextKnownTeam);
                }
                ListPool <ReferenceHub> .Shared.Return(list2);

                __instance.NextKnownTeam = SpawnableTeamType.None;

                return(false);
            }
            catch (Exception e)
            {
                SynapseController.Server.Logger.Error($"Synapse-Event: TeamRespawn failed!!\n{e}");
                return(true);
            }
        }
Пример #13
0
        public static bool Prefix(CharacterClassManager __instance)
        {
            try
            {
                Dictionary <GameObject, RoleType> roles = new Dictionary <GameObject, RoleType>();
                RoleType     forcedClass = NonFacilityCompatibility.currentSceneSettings.forcedClass;
                GameObject[] array       = __instance.GetShuffledPlayerList().ToArray();
                RoundSummary.SumInfo_ClassList startClassList = default;
                bool    flag   = false;
                int     num    = 0;
                float[] array2 = new float[] { 0f, 0.4f, 0.6f, 0.5f };
                __instance.laterJoinNextIndex = 0;
                for (int i = 0; i < array.Length; i++)
                {
                    RoleType roleType = (RoleType)((__instance.ForceClass < RoleType.Scp173)
                                                ? __instance.FindRandomIdUsingDefinedTeam(__instance.ClassTeamQueue[i])
                                                : ((int)__instance.ForceClass));
                    __instance.laterJoinNextIndex++;
                    if (__instance.Classes.CheckBounds(forcedClass))
                    {
                        roleType = forcedClass;
                    }

                    switch (__instance.Classes.SafeGet(roleType).team)
                    {
                    case Team.SCP:
                        startClassList.scps_except_zombies++;
                        break;

                    case Team.MTF:
                        startClassList.mtf_and_guards++;
                        break;

                    case Team.CHI:
                        startClassList.chaos_insurgents++;
                        break;

                    case Team.RSC:
                        startClassList.scientists++;
                        break;

                    case Team.CDP:
                        startClassList.class_ds++;
                        break;
                    }

                    if (__instance.Classes.SafeGet(roleType).team == Team.SCP && !flag)
                    {
                        if (array2[Mathf.Clamp(num, 0, array2.Length)] > Random.value)
                        {
                            flag = true;
                            __instance.Classes.Get(roleType).banClass = false;
                            roleType = RoleType.Scp079;
                        }

                        num++;
                    }

                    if (TutorialManager.status)
                    {
                        __instance.SetPlayersClass(RoleType.Tutorial, __instance.gameObject);
                    }
                    else
                    {
                        if (!roles.ContainsKey(array[i]))
                        {
                            roles.Add(array[i], roleType);
                        }
                        else
                        {
                            roles[array[i]] = roleType;
                        }

                        ServerLogs.AddLog(ServerLogs.Modules.ClassChange,
                                          string.Concat(array[i].GetComponent <NicknameSync>().MyNick, " (",
                                                        array[i].GetComponent <CharacterClassManager>().UserId, ") spawned as ",
                                                        __instance.Classes.SafeGet(roleType).fullName.Replace("\n", ""), "."),
                                          ServerLogs.ServerLogType.GameEvent);
                    }
                }

                Object.FindObjectOfType <PlayerList>().NetworkRoundStartTime = (int)Time.realtimeSinceStartup;
                startClassList.time          = (int)Time.realtimeSinceStartup;
                startClassList.warhead_kills = -1;
                Object.FindObjectOfType <RoundSummary>().SetStartClassList(startClassList);
                if (ConfigFile.ServerConfig.GetBool("smart_class_picker", true))
                {
                    string str = "Before Starting";
                    try
                    {
                        str = "Setting Initial Value";
                        if (ConfigFile.smBalancedPicker == null)
                        {
                            ConfigFile.smBalancedPicker = new Dictionary <string, int[]>();
                        }

                        str = "Valid Players List Error";
                        List <GameObject> shuffledPlayerList = __instance.GetShuffledPlayerList();
                        str = "Copying Balanced Picker List";
                        Dictionary <string, int[]> dictionary =
                            new Dictionary <string, int[]>(ConfigFile.smBalancedPicker);
                        str = "Clearing Balanced Picker List";
                        ConfigFile.smBalancedPicker.Clear();
                        str = "Re-building Balanced Picker List";
                        foreach (GameObject gameObject in shuffledPlayerList)
                        {
                            if (!(gameObject == null))
                            {
                                CharacterClassManager component         = gameObject.GetComponent <CharacterClassManager>();
                                NetworkConnection     networkConnection = null;
                                if (component != null)
                                {
                                    networkConnection = (component.connectionToClient ?? component.connectionToServer);
                                }

                                str = "Getting Player ID";
                                if (networkConnection == null && component == null)
                                {
                                    shuffledPlayerList.Remove(gameObject);
                                    break;
                                }

                                if (__instance.SrvRoles.DoNotTrack)
                                {
                                    shuffledPlayerList.Remove(gameObject);
                                }
                                else
                                {
                                    string str4 = (networkConnection != null) ? networkConnection.address : "";
                                    string str2 = (component != null) ? component.UserId : "";
                                    string text = str4 + str2;
                                    str = "Setting up Player \"" + text + "\"";
                                    if (!dictionary.ContainsKey(text))
                                    {
                                        str = "Adding Player \"" + text + "\" to smBalancedPicker";
                                        int[] arra = new int[__instance.Classes.Length];
                                        for (int j = 0; j < arra.Length; j++)
                                        {
                                            arra[j] = ConfigFile.ServerConfig.GetInt("smart_cp_starting_weight", 6);
                                        }

                                        ConfigFile.smBalancedPicker.Add(text, arra);
                                    }
                                    else
                                    {
                                        str = "Updating Player \"" + text + "\" in smBalancedPicker";
                                        int[] value;
                                        if (dictionary.TryGetValue(text, out value))
                                        {
                                            ConfigFile.smBalancedPicker.Add(text, value);
                                        }
                                    }
                                }
                            }
                        }

                        str = "Clearing Copied Balanced Picker List";
                        dictionary.Clear();
                        List <RoleType> list = new List <RoleType>();
                        str = "Getting Available Roles";
                        if (shuffledPlayerList.Contains(null))
                        {
                            shuffledPlayerList.Remove(null);
                        }

                        foreach (GameObject gameObject2 in shuffledPlayerList)
                        {
                            if (!(gameObject2 == null))
                            {
                                RoleType rt = RoleType.None;
                                roles.TryGetValue(gameObject2, out rt);
                                if (rt != RoleType.None)
                                {
                                    list.Add(rt);
                                }
                                else
                                {
                                    shuffledPlayerList.Remove(gameObject2);
                                }
                            }
                        }

                        List <GameObject> list2 = new List <GameObject>();
                        str = "Setting Roles";
                        foreach (GameObject gameObject3 in shuffledPlayerList)
                        {
                            if (!(gameObject3 == null))
                            {
                                CharacterClassManager component2         = gameObject3.GetComponent <CharacterClassManager>();
                                NetworkConnection     networkConnection2 = null;
                                if (component2 != null)
                                {
                                    networkConnection2 =
                                        (component2.connectionToClient ?? component2.connectionToServer);
                                }

                                if (networkConnection2 == null && component2 == null)
                                {
                                    shuffledPlayerList.Remove(gameObject3);
                                    break;
                                }

                                string str5  = (networkConnection2 != null) ? networkConnection2.address : "";
                                string str3  = (component2 != null) ? component2.UserId : "";
                                string text2 = str5 + str3;
                                str = "Setting Player \"" + text2 + "\"'s Class";
                                RoleType mostLikelyClass = __instance.GetMostLikelyClass(text2, list);
                                if (mostLikelyClass != RoleType.None)
                                {
                                    if (!roles.ContainsKey(gameObject3))
                                    {
                                        roles.Add(gameObject3, mostLikelyClass);
                                    }
                                    else
                                    {
                                        roles[gameObject3] = mostLikelyClass;
                                    }

                                    ServerLogs.AddLog(ServerLogs.Modules.ClassChange,
                                                      string.Concat(gameObject3.GetComponent <NicknameSync>().MyNick, " (",
                                                                    gameObject3.GetComponent <CharacterClassManager>().UserId, ") class set to ",
                                                                    __instance.Classes.SafeGet(mostLikelyClass).fullName.Replace("\n", ""),
                                                                    " by Smart Class Picker."), ServerLogs.ServerLogType.GameEvent);
                                    list.Remove(mostLikelyClass);
                                }
                                else
                                {
                                    list2.Add(gameObject3);
                                }
                            }
                        }

                        str = "Reversing Additional Classes List";
                        list.Reverse();
                        str = "Setting Unknown Players Classes";
                        foreach (GameObject gameObject4 in list2)
                        {
                            if (gameObject4 == null)
                            {
                                continue;
                            }
                            if (list.Count > 0)
                            {
                                RoleType roleType2 = list[0];
                                if (!roles.ContainsKey(gameObject4))
                                {
                                    roles.Add(gameObject4, roleType2);
                                }
                                else
                                {
                                    roles[gameObject4] = roleType2;
                                }

                                ServerLogs.AddLog(ServerLogs.Modules.ClassChange,
                                                  string.Concat(gameObject4.GetComponent <NicknameSync>().MyNick, " (",
                                                                gameObject4.GetComponent <CharacterClassManager>().UserId, ") class set to ",
                                                                __instance.Classes.SafeGet(roleType2).fullName.Replace("\n", ""),
                                                                " by Smart Class Picker."), ServerLogs.ServerLogType.GameEvent);
                                list.Remove(roleType2);
                            }
                            else
                            {
                                roles.Add(gameObject4, RoleType.Spectator);
                                ServerLogs.AddLog(ServerLogs.Modules.ClassChange,
                                                  gameObject4.GetComponent <NicknameSync>().MyNick + " (" +
                                                  gameObject4.GetComponent <CharacterClassManager>().UserId +
                                                  ") class set to SPECTATOR by Smart Class Picker.",
                                                  ServerLogs.ServerLogType.GameEvent);
                            }
                        }

                        str = "Clearing Unknown Players List";
                        list2.Clear();
                        str = "Clearing Available Classes List";
                        list.Clear();
                    }
                    catch (Exception ex)
                    {
                        Console.AddLog("Smart Class Picker Failed: " + str + ", " + ex.Message,
                                       new Color32(byte.MaxValue, 180, 0, byte.MaxValue));
                        return(true);
                    }
                }

                foreach (KeyValuePair <GameObject, RoleType> rtr in roles)
                {
                    __instance.SetPlayersClass(rtr.Value, rtr.Key);
                }

                return(false);
            }
            catch (Exception e)
            {
                Log.Error($"StupidClassPicked: {e}");
                return(true);
            }
        }
Пример #14
0
 protected internal override void RaiseLog(string message)
 {
     ServerLogs?.Invoke(message);
 }
Пример #15
0
        private static IEnumerator <float> Process(RoundSummary roundSummary)
        {
            while (roundSummary != null)
            {
                while (RoundSummary.RoundLock || !RoundSummary.RoundInProgress() || (roundSummary._keepRoundOnOne && PlayerManager.players.Count < 2))
                {
                    yield return(0.0f);
                }
                yield return(0.0f);

                RoundSummary.SumInfo_ClassList newList = default;
                foreach (GameObject player in PlayerManager.players)
                {
                    if (!(player == null))
                    {
                        CharacterClassManager component = player.GetComponent <CharacterClassManager>();
                        if (component.Classes.CheckBounds(component.CurClass))
                        {
                            switch (component.Classes.SafeGet(component.CurClass).team)
                            {
                            case Team.SCP:
                                if (component.CurClass == RoleType.Scp0492)
                                {
                                    ++newList.zombies;
                                    continue;
                                }

                                ++newList.scps_except_zombies;
                                continue;

                            case Team.MTF:
                                ++newList.mtf_and_guards;
                                continue;

                            case Team.CHI:
                                ++newList.chaos_insurgents;
                                continue;

                            case Team.RSC:
                                ++newList.scientists;
                                continue;

                            case Team.CDP:
                                ++newList.class_ds;
                                continue;

                            default:
                                continue;
                            }
                        }
                    }
                }

                newList.warhead_kills = AlphaWarheadController.Host.detonated ? AlphaWarheadController.Host.warheadKills : -1;
                yield return(float.NegativeInfinity);

                newList.time = (int)Time.realtimeSinceStartup;
                yield return(float.NegativeInfinity);

                RoundSummary.roundTime = newList.time - roundSummary.classlistStart.time;
                int   num1 = newList.mtf_and_guards + newList.scientists;
                int   num2 = newList.chaos_insurgents + newList.class_ds;
                int   num3 = newList.scps_except_zombies + newList.zombies;
                float num4 = roundSummary.classlistStart.class_ds == 0 ? 0.0f : (RoundSummary.escaped_ds + newList.class_ds) / roundSummary.classlistStart.class_ds;
                float num5 = roundSummary.classlistStart.scientists == 0 ? 1f : (RoundSummary.escaped_scientists + newList.scientists) / roundSummary.classlistStart.scientists;

                if (newList.class_ds == 0 && num1 == 0)
                {
                    roundSummary._roundEnded = true;
                }
                else
                {
                    int num6 = 0;
                    if (num1 > 0)
                    {
                        ++num6;
                    }
                    if (num2 > 0)
                    {
                        ++num6;
                    }
                    if (num3 > 0)
                    {
                        ++num6;
                    }
                    if (num6 <= 1)
                    {
                        roundSummary._roundEnded = true;
                    }
                }

                var endingRoundEventArgs = new EndingRoundEventArgs(LeadingTeam.Draw, newList, roundSummary._roundEnded);

                if (num1 > 0)
                {
                    if (RoundSummary.escaped_ds == 0 && RoundSummary.escaped_scientists != 0)
                    {
                        endingRoundEventArgs.LeadingTeam = LeadingTeam.FacilityForces;
                    }
                }
                else
                {
                    endingRoundEventArgs.LeadingTeam = RoundSummary.escaped_ds != 0 ? LeadingTeam.ChaosInsurgency : LeadingTeam.Anomalies;
                }

                Server.OnEndingRound(endingRoundEventArgs);

                roundSummary._roundEnded = endingRoundEventArgs.IsRoundEnded && endingRoundEventArgs.IsAllowed;

                if (roundSummary._roundEnded)
                {
                    FriendlyFireConfig.PauseDetector = true;
                    string str = "Round finished! Anomalies: " + num3 + " | Chaos: " + num2 + " | Facility Forces: " + num1 + " | D escaped percentage: " + num4 + " | S escaped percentage: : " + num5;
                    Console.AddLog(str, Color.gray, false);
                    ServerLogs.AddLog(ServerLogs.Modules.Logger, str, ServerLogs.ServerLogType.GameEvent);
                    byte i1;
                    for (i1 = 0; i1 < 75; ++i1)
                    {
                        yield return(0.0f);
                    }
                    int timeToRoundRestart = Mathf.Clamp(ConfigFile.ServerConfig.GetInt("auto_round_restart_time", 10), 5, 1000);

                    if (roundSummary != null)
                    {
                        newList.scps_except_zombies -= newList.zombies;

                        var roundEndedEventArgs = new RoundEndedEventArgs(endingRoundEventArgs.LeadingTeam, newList, timeToRoundRestart);

                        Server.OnRoundEnded(roundEndedEventArgs);

                        roundSummary.RpcShowRoundSummary(roundSummary.classlistStart, roundEndedEventArgs.ClassList, (RoundSummary.LeadingTeam)roundEndedEventArgs.LeadingTeam, RoundSummary.escaped_ds, RoundSummary.escaped_scientists, RoundSummary.kills_by_scp, roundEndedEventArgs.TimeToRestart);
                    }

                    for (int i2 = 0; i2 < 50 * (timeToRoundRestart - 1); ++i2)
                    {
                        yield return(0.0f);
                    }
                    roundSummary.RpcDimScreen();
                    for (i1 = 0; i1 < 50; ++i1)
                    {
                        yield return(0.0f);
                    }
                    PlayerManager.localPlayer.GetComponent <PlayerStats>().Roundrestart();
                    yield break;
                }
            }
        }
Пример #16
0
        private static bool Prefix(RespawnManager __instance)
        {
            try
            {
                if (!RespawnWaveGenerator.SpawnableTeams.TryGetValue(__instance.NextKnownTeam, out SpawnableTeam spawnableTeam) ||
                    __instance.NextKnownTeam == SpawnableTeamType.None)
                {
                    ServerConsole.AddLog("Fatal error. Team '" + __instance.NextKnownTeam + "' is undefined.", ConsoleColor.Red);
                }
                else
                {
                    List <API.Features.Player> list = ListPool <API.Features.Player> .Shared.Rent(API.Features.Player.List.Where(player => player.IsDead && !player.IsOverwatchEnabled));

                    if (__instance._prioritySpawn)
                    {
                        var tempList = ListPool <API.Features.Player> .Shared.Rent();

                        tempList.AddRange(list.OrderBy(item => item.ReferenceHub.characterClassManager.DeathTime));

                        ListPool <API.Features.Player> .Shared.Return(list);

                        list = tempList;
                    }
                    else
                    {
                        list.ShuffleList();
                    }

                    // Code that should be here is in RespawningTeamEventArgs::ReissueNextKnownTeam
                    var ev = new RespawningTeamEventArgs(list, __instance.NextKnownTeam);

                    Handlers.Server.OnRespawningTeam(ev);

                    if (ev.IsAllowed && ev.SpawnableTeam != null)
                    {
                        while (list.Count > ev.MaximumRespawnAmount)
                        {
                            list.RemoveAt(list.Count - 1);
                        }

                        list.ShuffleList();

                        List <ReferenceHub> referenceHubList = ListPool <ReferenceHub> .Shared.Rent();

                        foreach (API.Features.Player me in list)
                        {
                            try
                            {
                                RoleType classid = ev.SpawnableTeam.Value.ClassQueue[Mathf.Min(referenceHubList.Count, spawnableTeam.ClassQueue.Length - 1)];

                                me.ReferenceHub.characterClassManager.SetPlayersClass(classid, me.ReferenceHub.gameObject);

                                referenceHubList.Add(me.ReferenceHub);

                                ServerLogs.AddLog(ServerLogs.Modules.ClassChange, "Player " + me.ReferenceHub.LoggedNameFromRefHub() + " respawned as " + classid + ".", ServerLogs.ServerLogType.GameEvent);
                            }
                            catch (Exception ex)
                            {
                                if (me != null)
                                {
                                    ServerLogs.AddLog(ServerLogs.Modules.ClassChange, "Player " + me.ReferenceHub.LoggedNameFromRefHub() + " couldn't be spawned. Err msg: " + ex.Message, ServerLogs.ServerLogType.GameEvent);
                                }
                                else
                                {
                                    ServerLogs.AddLog(ServerLogs.Modules.ClassChange, "Couldn't spawn a player - target's ReferenceHub is null.", ServerLogs.ServerLogType.GameEvent);
                                }
                            }
                        }

                        if (referenceHubList.Count > 0)
                        {
                            ServerLogs.AddLog(ServerLogs.Modules.ClassChange, $"RespawnManager has successfully spawned {referenceHubList.Count} players as {__instance.NextKnownTeam}!", ServerLogs.ServerLogType.GameEvent);
                            RespawnTickets.Singleton.GrantTickets(__instance.NextKnownTeam, -referenceHubList.Count * spawnableTeam.TicketRespawnCost);

                            if (UnitNamingRules.TryGetNamingRule(__instance.NextKnownTeam, out UnitNamingRule rule))
                            {
                                rule.GenerateNew(__instance.NextKnownTeam, out string regular);
                                foreach (ReferenceHub referenceHub in referenceHubList)
                                {
                                    referenceHub.characterClassManager.NetworkCurSpawnableTeamType =
                                        (byte)__instance.NextKnownTeam;
                                    referenceHub.characterClassManager.NetworkCurUnitName = regular;
                                }

                                rule.PlayEntranceAnnouncement(regular);
                            }

                            RespawnEffectsController.ExecuteAllEffects(RespawnEffectsController.EffectType.UponRespawn, __instance.NextKnownTeam);
                        }

                        ListPool <ReferenceHub> .Shared.Return(referenceHubList);
                    }

                    ListPool <API.Features.Player> .Shared.Return(list);

                    __instance.NextKnownTeam = SpawnableTeamType.None;
                }

                return(false);
            }
            catch (Exception e)
            {
                Exiled.API.Features.Log.Error($"Exiled.Events.Patches.Events.Server.RespawningTeam: {e}\n{e.StackTrace}");

                return(true);
            }
        }
Пример #17
0
        public static bool Prefix(FragGrenade __instance, ref bool __result)
        {
            Player thrower = Player.Get(__instance.thrower.gameObject);

            Dictionary <Player, float> damages = new Dictionary <Player, float>();

            Vector3 position = ((EffectGrenade)__instance).transform.position;
            int     num      = 0;

            Collider[] colliderArray = Physics.OverlapSphere(position, __instance.chainTriggerRadius, (int)__instance.damageLayerMask);
            int        index         = 0;

            foreach (GameObject obj2 in PlayerManager.players)
            {
                if (!ServerConsole.FriendlyFire && ((obj2 != ((EffectGrenade)__instance).thrower.gameObject) &&
                                                    (!obj2.GetComponent <WeaponManager>().GetShootPermission(((EffectGrenade)__instance).throwerTeam, false))))
                {
                    continue;
                }
                PlayerStats component = obj2.GetComponent <PlayerStats>();
                if ((component != null) && component.ccm.InWorld)
                {
                    float amount = (float)(__instance.damageOverDistance.Evaluate(Vector3.Distance(position, component.transform.position)) * (component.ccm.IsHuman() ? ConfigFile.ServerConfig.GetFloat("human_grenade_multiplier", 0.7f) : ConfigFile.ServerConfig.GetFloat("scp_grenade_multiplier", 1f)));
                    damages.Add(Player.Get(obj2), amount);
                }
            }

            var ev = new ExplodingGrenadeEventArgs(thrower, damages, true, __instance.gameObject);

            Exiled.Events.Handlers.Map.OnExplodingGrenade(ev);

            if (!ev.IsAllowed)
            {
                return(false);
            }

            while (index < colliderArray.Length)
            {
                Collider        collider  = colliderArray[index];
                BreakableWindow component = collider.GetComponent <BreakableWindow>();
                if (component != null)
                {
                    if ((component.transform.position - position).sqrMagnitude <= __instance.sqrChainTriggerRadius)
                    {
                        component.ServerDamageWindow(500f);
                    }
                }
                else
                {
                    DoorVariant componentInParent = collider.GetComponentInParent <DoorVariant>();
                    if (componentInParent != null && componentInParent is IDamageableDoor damageableDoor)
                    {
                        damageableDoor.ServerDamage(__instance.damageOverDistance.Evaluate(Vector3.Distance(position, componentInParent.transform.position)), DoorDamageType.Grenade);
                    }
                    else if (((__instance.chainLengthLimit == -1) || (__instance.chainLengthLimit > ((EffectGrenade)__instance).currentChainLength)) && ((__instance.chainConcurrencyLimit == -1) || (__instance.chainConcurrencyLimit > num)))
                    {
                        Pickup componentInChildren = collider.GetComponentInChildren <Pickup>();
                        if ((componentInChildren != null) && __instance.ChangeIntoGrenade(componentInChildren))
                        {
                            num = (int)(num + 1);
                        }
                    }
                }
                index = (int)(index + 1);
            }

            foreach (var item in damages)
            {
                if (item.Value > __instance.absoluteDamageFalloff)
                {
                    PlayerStats component     = item.Key.GameObject.GetComponent <PlayerStats>();
                    Transform[] grenadePoints = component.grenadePoints;
                    index = 0;
                    while (true)
                    {
                        if (index < grenadePoints.Length)
                        {
                            Transform transform = grenadePoints[index];
                            if (Physics.Linecast(position, transform.position, (int)__instance.hurtLayerMask))
                            {
                                index = (int)(index + 1);
                                continue;
                            }
                            component.HurtPlayer(new PlayerStats.HitInfo(item.Value, (((EffectGrenade)__instance).thrower != null) ? ((EffectGrenade)__instance).thrower.hub.LoggedNameFromRefHub() : ((string)"(UNKNOWN)"), DamageTypes.Grenade, ((EffectGrenade)__instance).thrower.hub.queryProcessor.PlayerId), item.Key.GameObject, false);
                        }
                        if (!component.ccm.IsAnyScp())
                        {
                            ReferenceHub hub      = item.Key.ReferenceHub;
                            float        duration = __instance.statusDurationOverDistance.Evaluate(Vector3.Distance(position, component.transform.position));
                            hub.playerEffectsController.EnableEffect(hub.playerEffectsController.GetEffect <Burned>(), duration, false);
                            hub.playerEffectsController.EnableEffect(hub.playerEffectsController.GetEffect <Concussed>(), duration, false);
                        }
                        break;
                    }
                }
            }

            //if (Tracking.PlayersWithSubclasses.ContainsKey(thrower) && Tracking.PlayersWithSubclasses[thrower].Abilities.Contains(AbilityType.HealGrenadeFrag))
            //{
            //	if (!Tracking.CanUseAbility(thrower, AbilityType.HealGrenadeFrag, Tracking.PlayersWithSubclasses[thrower]))
            //	{
            //		Tracking.DisplayCantUseAbility(thrower, AbilityType.HealGrenadeFrag, Tracking.PlayersWithSubclasses[thrower], "heal frag");
            //	}
            //	else
            //	{
            //		Tracking.UseAbility(thrower, AbilityType.HealGrenadeFrag, Tracking.PlayersWithSubclasses[thrower]);
            //		UnityEngine.Collider[] colliders = UnityEngine.Physics.OverlapSphere(__instance.transform.position, 4);
            //		Subclass.Instance.map.UpdateHealths(colliders, thrower, "HealGrenadeFragHealAmount");
            //		return false;
            //	}
            //}

            string str = (((Grenade)((EffectGrenade)__instance)).thrower != null) ? ((Grenade)((EffectGrenade)__instance)).thrower.hub.LoggedNameFromRefHub() : ((string)"(UNKNOWN)");

            string[] textArray1 = new string[] { "Player ", (string)str, "'s ", (string)((Grenade)((EffectGrenade)__instance)).logName, " grenade exploded." };
            ServerLogs.AddLog(ServerLogs.Modules.Logger, string.Concat((string[])textArray1), ServerLogs.ServerLogType.GameEvent, false);

            if (((EffectGrenade)__instance).serverGrenadeEffect != null)
            {
                Transform transform = ((Grenade)((EffectGrenade)__instance)).transform;
                Object.Instantiate <GameObject>(((EffectGrenade)__instance).serverGrenadeEffect, transform.position, transform.rotation);
            }

            __result = true;
            return(false);
        }
Пример #18
0
        private static bool Prefix(RespawnManager __instance)
        {
            SpawnableTeam spawnableTeam;

            if (!RespawnWaveGenerator.SpawnableTeams.TryGetValue(__instance.NextKnownTeam, out spawnableTeam) || __instance.NextKnownTeam == SpawnableTeamType.None)
            {
                ServerConsole.AddLog("Fatal error. Team '" + __instance.NextKnownTeam + "' is undefined.", ConsoleColor.Red);
            }
            else
            {
                List <API.Features.Player> list = API.Features.Player.List.Where(p => p.IsDead && !p.IsOverwatchEnabled).ToList();

                if (__instance._prioritySpawn)
                {
                    list = list.OrderBy(item => item.ReferenceHub.characterClassManager.DeathTime).ToList();
                }
                else
                {
                    list.ShuffleList();
                }

                RespawnTickets singleton = RespawnTickets.Singleton;
                int            a         = singleton.GetAvailableTickets(__instance.NextKnownTeam);
                if (a == 0)
                {
                    a = singleton.DefaultTeamAmount;
                    RespawnTickets.Singleton.GrantTickets(singleton.DefaultTeam, singleton.DefaultTeamAmount, true);
                }

                int num = Mathf.Min(a, spawnableTeam.MaxWaveSize);

                List <ReferenceHub> referenceHubList = ListPool <ReferenceHub> .Rent();

                var ev = new RespawningTeamEventArgs(list, num, __instance.NextKnownTeam);
                Handlers.Server.OnRespawningTeam(ev);

                while (list.Count > num)
                {
                    list.RemoveAt(list.Count - 1);
                }
                list.ShuffleList();

                foreach (API.Features.Player me in list)
                {
                    try
                    {
                        RoleType classid = spawnableTeam.ClassQueue[Mathf.Min(referenceHubList.Count, spawnableTeam.ClassQueue.Length - 1)];
                        me.ReferenceHub.characterClassManager.SetPlayersClass(classid, me.ReferenceHub.gameObject);
                        referenceHubList.Add(me.ReferenceHub);
                        ServerLogs.AddLog(ServerLogs.Modules.ClassChange, "Player " + me.ReferenceHub.LoggedNameFromRefHub() + " respawned as " + classid + ".", ServerLogs.ServerLogType.GameEvent);
                    }
                    catch (Exception ex)
                    {
                        if (me != null)
                        {
                            ServerLogs.AddLog(ServerLogs.Modules.ClassChange, "Player " + me.ReferenceHub.LoggedNameFromRefHub() + " couldn't be spawned. Err msg: " + ex.Message, ServerLogs.ServerLogType.GameEvent);
                        }
                        else
                        {
                            ServerLogs.AddLog(ServerLogs.Modules.ClassChange, "Couldn't spawn a player - target's ReferenceHub is null.", ServerLogs.ServerLogType.GameEvent);
                        }
                    }
                }

                if (referenceHubList.Count > 0)
                {
                    ServerLogs.AddLog(ServerLogs.Modules.ClassChange, $"RespawnManager has successfully spawned {referenceHubList.Count} players as {__instance.NextKnownTeam}!", ServerLogs.ServerLogType.GameEvent);
                    RespawnTickets.Singleton.GrantTickets(__instance.NextKnownTeam, -referenceHubList.Count * spawnableTeam.TicketRespawnCost);
                    UnitNamingRule rule;
                    if (UnitNamingRules.TryGetNamingRule(__instance.NextKnownTeam, out rule))
                    {
                        string regular;
                        rule.GenerateNew(__instance.NextKnownTeam, out regular);
                        foreach (ReferenceHub referenceHub in referenceHubList)
                        {
                            referenceHub.characterClassManager.NetworkCurSpawnableTeamType = (byte)__instance.NextKnownTeam;
                            referenceHub.characterClassManager.NetworkCurUnitName          = regular;
                        }

                        rule.PlayEntranceAnnouncement(regular);
                    }

                    RespawnEffectsController.ExecuteAllEffects(RespawnEffectsController.EffectType.UponRespawn, __instance.NextKnownTeam);
                }

                __instance.NextKnownTeam = SpawnableTeamType.None;
            }

            return(false);
        }
Пример #19
0
        private static void HandleConnection(ConnectionRequest request)
        {
            NetDataWriter rejectData = new NetDataWriter();

            try
            {
                byte result1;
                byte result2;
                if (!request.Data.TryGetByte(out result1) || !request.Data.TryGetByte(out result2) || result1 != CustomNetworkManager.Major || result2 != CustomNetworkManager.Minor)
                {
                    rejectData.Reset();
                    rejectData.Put(3);
                    request.Reject(rejectData);
                }
                else
                {
                    if (CustomLiteNetLib4MirrorTransport.IpRateLimiting)
                    {
                        if (CustomLiteNetLib4MirrorTransport.IpRateLimit.Contains(request.RemoteEndPoint.Address.ToString()))
                        {
                            ServerConsole.AddLog(string.Format("Connexion entrante à partir de l'IP {0} rejetée en raison d'un dépassement du taux limite.", request.RemoteEndPoint));
                            ServerLogs.AddLog(ServerLogs.Modules.Networking, string.Format("Connexion entrante à partir de l'IP {0} rejetée en raison d'un dépassement du taux limite.", request.RemoteEndPoint), ServerLogs.ServerLogType.RateLimit);
                            rejectData.Reset();
                            rejectData.Put(12);
                            request.Reject(rejectData);
                            return;
                        }
                        CustomLiteNetLib4MirrorTransport.IpRateLimit.Add(request.RemoteEndPoint.Address.ToString());
                    }

                    string result3;
                    if (!request.Data.TryGetString(out result3) || result3 == string.Empty)
                    {
                        rejectData.Reset();
                        rejectData.Put(5);
                        request.Reject(rejectData);
                    }
                    else
                    {
                        ulong  result4;
                        byte   result5;
                        string result6;
                        byte[] result7;
                        if (!request.Data.TryGetULong(out result4) || !request.Data.TryGetByte(out result5) || !request.Data.TryGetString(out result6) || !request.Data.TryGetBytesWithLength(out result7))
                        {
                            rejectData.Reset();
                            rejectData.Put(4);
                            request.Reject(rejectData);
                        }
                        else
                        {
                            CentralAuthPreauthFlags flags = (CentralAuthPreauthFlags)result5;
                            try
                            {
                                String steamID   = result3;
                                Login  LoginJSON = new Login();
                                LoginJSON.Steamid64 = steamID;
                                LoginJSON.Ip        = request.RemoteEndPoint.Address.ToString();
                                String JSON         = Serialize.ToJson(LoginJSON);
                                String JsonResponse = Methods.Post(Plugin.LoginURL, JSON);

                                try
                                {
                                    JSON.Success.SuccessResponseJSON APIResponse = AtlasUserAPI.JSON.Success.SuccessResponseJSON.FromJson(JsonResponse);

                                    if (!ECDSA.VerifyBytes(string.Format("{0};{1};{2};{3}", result3, result5, result6, result4), result7, ServerConsole.PublicKey))
                                    {
                                        ServerConsole.AddLog(string.Format("Joueur avec l'IP {0} a envoyé un jeton de préauthentification avec une signature numérique non valide.", request.RemoteEndPoint));
                                        rejectData.Reset();
                                        rejectData.Put(2);
                                        request.Reject(rejectData);
                                    }
                                    else if (TimeBehaviour.CurrentUnixTimestamp > result4)
                                    {
                                        ServerConsole.AddLog(string.Format("Joueur avec l'IP {0} a envoyé un jeton de préauthentification périmé.", request.RemoteEndPoint));
                                        ServerConsole.AddLog("Assurez-vous que l'heure et le fuseau horaire définis sur le serveur sont corrects. Nous recommandons de synchroniser l'heure.");
                                        rejectData.Reset();
                                        rejectData.Put(11);
                                        request.Reject(rejectData);
                                    }
                                    else
                                    {
                                        if (CustomLiteNetLib4MirrorTransport.UserRateLimiting)
                                        {
                                            if (CustomLiteNetLib4MirrorTransport.UserRateLimit.Contains(result3))
                                            {
                                                ServerConsole.AddLog(string.Format("Connexion entrante de {0} ({1}) rejetée en raison d'un dépassement du taux limite.", result3, request.RemoteEndPoint));
                                                ServerLogs.AddLog(ServerLogs.Modules.Networking, string.Format("Connexion entrante à partir de l'IP {0} ({1}) rejetée en raison d'un dépassement du taux limite.", result3, request.RemoteEndPoint), ServerLogs.ServerLogType.RateLimit);
                                                rejectData.Reset();
                                                rejectData.Put(12);
                                                request.Reject(rejectData);
                                                return;
                                            }
                                            CustomLiteNetLib4MirrorTransport.UserRateLimit.Add(result3);
                                        }
                                        if (!flags.HasFlagFast(CentralAuthPreauthFlags.IgnoreBans) || !ServerStatic.GetPermissionsHandler().IsVerified)
                                        {
                                            // API Check BAN.
                                            if (APIResponse.IsBanned)
                                            {
                                                ServerConsole.AddLog(string.Format("Le joueur {0} a essayé de se connecter avec l'IP {1}, mais l'API répond qu'il est banni.", result3, request.RemoteEndPoint));
                                                ServerLogs.AddLog(ServerLogs.Modules.Networking, string.Format("Le joueur {0} a essayé de se connecter avec l'IP {1}, mais l'API répond qu'il est banni.", result3, request.RemoteEndPoint), ServerLogs.ServerLogType.ConnectionUpdate);

                                                rejectData.Reset();
                                                rejectData.Put(6);
                                                request.Reject(rejectData);
                                                return;
                                            }
                                        }
                                        if (flags.HasFlagFast(CentralAuthPreauthFlags.GloballyBanned) && !ServerStatic.GetPermissionsHandler().IsVerified)
                                        {
                                            bool useGlobalBans = CustomLiteNetLib4MirrorTransport.UseGlobalBans;
                                        }
                                        if ((!flags.HasFlagFast(CentralAuthPreauthFlags.IgnoreWhitelist) || !ServerStatic.GetPermissionsHandler().IsVerified) && !WhiteList.IsWhitelisted(result3))
                                        {
                                            ServerConsole.AddLog(string.Format("Le joueur {0} a essayé de joindre à partir de l'IP {1}, mais n'est pas sur la liste blanche.", result3, request.RemoteEndPoint));
                                            rejectData.Reset();
                                            rejectData.Put(7);
                                            request.Reject(rejectData);
                                        }
                                        else if (CustomLiteNetLib4MirrorTransport.Geoblocking != GeoblockingMode.None && (!flags.HasFlagFast(CentralAuthPreauthFlags.IgnoreGeoblock) || !ServerStatic.GetPermissionsHandler().BanTeamBypassGeo) && (!CustomLiteNetLib4MirrorTransport.GeoblockIgnoreWhitelisted || !WhiteList.IsOnWhitelist(result3)) && (CustomLiteNetLib4MirrorTransport.Geoblocking == GeoblockingMode.Whitelist && !CustomLiteNetLib4MirrorTransport.GeoblockingList.Contains(result6.ToUpper()) || CustomLiteNetLib4MirrorTransport.Geoblocking == GeoblockingMode.Blacklist && CustomLiteNetLib4MirrorTransport.GeoblockingList.Contains(result6.ToUpper())))
                                        {
                                            ServerConsole.AddLog(string.Format("Le joueur {0} ({1}) a tenté de rejoindre depuis le pays bloqué {2}.", result3, request.RemoteEndPoint, result6.ToUpper()));
                                            rejectData.Reset();
                                            rejectData.Put(9);
                                            request.Reject(rejectData);
                                        }
                                        else
                                        {
                                            // API Role & Slots
                                            string role;
                                            if (Plugin.role.TryGetValue(steamID, out role))
                                            {
                                                Plugin.role.Remove(steamID);
                                            }
                                            if (!String.IsNullOrEmpty(APIResponse.Role))
                                            {
                                                Plugin.role.Add(steamID, APIResponse.Role);
                                            }
                                            else
                                            {
                                                if (ServerStatic.GetPermissionsHandler()._members.ContainsKey(steamID))
                                                {
                                                    ServerStatic.GetPermissionsHandler()._members.Remove(steamID);
                                                }
                                            }

                                            int num = CustomNetworkManager.slots;
                                            if (flags.HasFlagFast(CentralAuthPreauthFlags.ReservedSlot) && ServerStatic.GetPermissionsHandler().BanTeamSlots)
                                            {
                                                num = LiteNetLib4MirrorNetworkManager.singleton.maxConnections;
                                            }
                                            else if (ConfigFile.ServerConfig.GetBool("use_reserved_slots", true))
                                            {
                                                // API Slots
                                                if (!String.IsNullOrEmpty(APIResponse.Role))
                                                {
                                                    List <string> RoleRSRead = File.ReadAllLines(Plugin.RoleRSFilePath).ToList();
                                                    if (RoleRSRead.Contains(APIResponse.Role))
                                                    {
                                                        num = CustomNetworkManager.singleton.maxConnections;
                                                    }
                                                }
                                            }
                                            if (LiteNetLib4MirrorCore.Host.PeersCount < num)
                                            {
                                                if (CustomLiteNetLib4MirrorTransport.UserIds.ContainsKey(request.RemoteEndPoint))
                                                {
                                                    CustomLiteNetLib4MirrorTransport.UserIds[request.RemoteEndPoint].SetUserId(result3);
                                                }
                                                else
                                                {
                                                    CustomLiteNetLib4MirrorTransport.UserIds.Add(request.RemoteEndPoint, new PreauthItem(result3));
                                                }
                                                bool allow = true;
                                                Events.InvokePreAuth(ref result3, request, ref allow);
                                                if (allow)
                                                {
                                                    request.Accept();
                                                    ServerConsole.AddLog(string.Format("Le joueur {0} est préauthentifié à partir de l'IP {1}.", result3, request.RemoteEndPoint));
                                                    ServerLogs.AddLog(ServerLogs.Modules.Networking, string.Format("{0} préauthentifié à partir de l'IP {1}.", result3, request.RemoteEndPoint), ServerLogs.ServerLogType.ConnectionUpdate);
                                                }
                                            }
                                            else
                                            {
                                                ServerConsole.AddLog(string.Format("Le joueur {0} ({1}) a essayé de se connecter, mais le serveur est plein.", result3, request.RemoteEndPoint));
                                                rejectData.Reset();
                                                rejectData.Put(1);
                                                request.Reject(rejectData);
                                            }
                                        }
                                    }
                                }
                                catch (Exception exception)
                                {
                                    ServerConsole.AddLog(string.Format("Le joueur avec l'IP {0} a envoyé un jeton de préauthentification non valable. {1}", request.RemoteEndPoint, exception.Message));
                                    rejectData.Reset();
                                    rejectData.Put(2);
                                    request.Reject(rejectData);
                                }
                            }
                            catch (Exception exception)
                            {
                                ServerConsole.AddLog(string.Format("Le joueur avec l'IP {0} a subi une erreur avec l'API. {1}", request.RemoteEndPoint, exception.Message));
                                rejectData.Reset();
                                rejectData.Put(2);
                                request.Reject(rejectData);
                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                ServerConsole.AddLog(string.Format("Joueur avec l'IP {0} n'a pas réussi à se préauthentifier : {1}", request.RemoteEndPoint, exception.Message));
                rejectData.Reset();
                rejectData.Put(4);
                request.Reject(rejectData);
            }
        }
Пример #20
0
        public static bool Prefix(CharacterClassManager __instance)
        {
            try
            {
                Dictionary <GameObject, RoleType> roles = new Dictionary <GameObject, RoleType>();
                RoleType     forcedClass = NonFacilityCompatibility.currentSceneSettings.forcedClass;
                GameObject[] array       = __instance.GetShuffledPlayerList().ToArray();
                RoundSummary.SumInfo_ClassList startClassList = default;
                bool    flag   = false;
                int     num    = 0;
                float[] array2 = new float[] { 0f, 0.4f, 0.6f, 0.5f };
                __instance.laterJoinNextIndex = 0;
                int r = EventPlugin.Gen.Next(1, 100);

                for (int i = 0; i < array.Length; i++)
                {
                    RoleType roleType = (RoleType)((__instance.ForceClass < RoleType.Scp173)
                                                ? __instance.FindRandomIdUsingDefinedTeam(__instance.ClassTeamQueue[i])
                                                : ((int)__instance.ForceClass));
                    __instance.laterJoinNextIndex++;
                    if (__instance.Classes.CheckBounds(forcedClass))
                    {
                        roleType = forcedClass;
                    }

                    if (r <= __instance.CiPercentage && roleType == RoleType.FacilityGuard)
                    {
                        roleType = RoleType.ChaosInsurgency;
                    }

                    switch (__instance.Classes.SafeGet(roleType).team)
                    {
                    case Team.SCP:
                        startClassList.scps_except_zombies++;
                        break;

                    case Team.MTF:
                        startClassList.mtf_and_guards++;
                        break;

                    case Team.CHI:
                        startClassList.chaos_insurgents++;
                        break;

                    case Team.RSC:
                        startClassList.scientists++;
                        break;

                    case Team.CDP:
                        startClassList.class_ds++;
                        break;
                    }

                    if (__instance.Classes.SafeGet(roleType).team == Team.SCP && !flag)
                    {
                        if (array2[Mathf.Clamp(num, 0, array2.Length)] > Random.value)
                        {
                            flag = true;
                            __instance.Classes.Get(roleType).banClass = false;
                            roleType = RoleType.Scp079;
                        }

                        num++;
                    }

                    if (TutorialManager.status)
                    {
                        __instance.SetPlayersClass(RoleType.Tutorial, __instance.gameObject);
                    }
                    else
                    {
                        if (!roles.ContainsKey(array[i]))
                        {
                            roles.Add(array[i], roleType);
                        }
                        else
                        {
                            roles[array[i]] = roleType;
                        }

                        ServerLogs.AddLog(ServerLogs.Modules.ClassChange,
                                          string.Concat(array[i].GetComponent <NicknameSync>().MyNick, " (",
                                                        array[i].GetComponent <CharacterClassManager>().UserId, ") spawned as ",
                                                        __instance.Classes.SafeGet(roleType).fullName.Replace("\n", ""), "."),
                                          ServerLogs.ServerLogType.GameEvent);
                    }
                }

                Object.FindObjectOfType <PlayerList>().NetworkRoundStartTime = (int)Time.realtimeSinceStartup;
                startClassList.time          = (int)Time.realtimeSinceStartup;
                startClassList.warhead_kills = -1;
                Object.FindObjectOfType <RoundSummary>().SetStartClassList(startClassList);
                if (ConfigFile.ServerConfig.GetBool("smart_class_picker", true))
                {
                    string str = "Before Starting";
                    try
                    {
                        str = "Setting Initial Value";
                        if (ConfigFile.smBalancedPicker == null)
                        {
                            ConfigFile.smBalancedPicker = new Dictionary <string, int[]>();
                        }

                        str = "Valid Players List Error";
                        List <GameObject> shuffledPlayerList = __instance.GetShuffledPlayerList();
                        str = "Copying Balanced Picker List";
                        Dictionary <string, int[]> dictionary =
                            new Dictionary <string, int[]>(ConfigFile.smBalancedPicker);
                        str = "Clearing Balanced Picker List";
                        ConfigFile.smBalancedPicker.Clear();
                        str = "Re-building Balanced Picker List";
                        foreach (GameObject gameObject in shuffledPlayerList)
                        {
                            if (!(gameObject == null))
                            {
                                CharacterClassManager component         = gameObject.GetComponent <CharacterClassManager>();
                                NetworkConnection     networkConnection = null;
                                if (component != null)
                                {
                                    networkConnection = (component.connectionToClient ?? component.connectionToServer);
                                }

                                str = "Getting Player ID";
                                if (networkConnection == null && component == null)
                                {
                                    shuffledPlayerList.Remove(gameObject);
                                    break;
                                }

                                if (__instance.SrvRoles.DoNotTrack)
                                {
                                    shuffledPlayerList.Remove(gameObject);
                                }
                                else
                                {
                                    string str4 = (networkConnection != null) ? networkConnection.address : "";
                                    string str2 = (component != null) ? component.UserId : "";
                                    string text = str4 + str2;
                                    str = "Setting up Player \"" + text + "\"";
                                    if (!dictionary.ContainsKey(text))
                                    {
                                        str = "Adding Player \"" + text + "\" to smBalancedPicker";
                                        int[] arra = new int[__instance.Classes.Length];
                                        for (int j = 0; j < arra.Length; j++)
                                        {
                                            arra[j] = ConfigFile.ServerConfig.GetInt("smart_cp_starting_weight", 6);
                                        }

                                        ConfigFile.smBalancedPicker.Add(text, arra);
                                    }
                                    else
                                    {
                                        str = "Updating Player \"" + text + "\" in smBalancedPicker";

                                        if (dictionary.TryGetValue(text, out int[] value))
                                        {
                                            ConfigFile.smBalancedPicker.Add(text, value);
                                        }
                                    }
Пример #21
0
        private static bool Prefix(PlayerStats __instance, out bool __result, PlayerStats.HitInfo info, GameObject go, bool noTeamDamage = false, bool IsValidDamage = true)
        {
            try
            {
                __result = false;
                var player = go?.GetPlayer();
                var killer = __instance?.GetPlayer();
                if (player == null)
                {
                    return(false);
                }

                if (info.GetDamageType() == DamageTypes.Grenade)
                {
                    killer = SynapseController.Server.GetPlayer(info.PlayerId);
                }
                else if (info.GetDamageType() == DamageTypes.Pocket)
                {
                    killer = Server.Get.Players.FirstOrDefault(x => x.Scp106Controller.PocketPlayers.Contains(player));

                    if (SynapseExtensions.CanNotHurtByScp(player))
                    {
                        return(false);
                    }
                }

                bool         flag         = false;
                bool         flag2        = false;
                bool         flag3        = go == null;
                ReferenceHub referenceHub = flag3 ? null : ReferenceHub.GetHub(go);

                if (info.Amount < 0f)
                {
                    if (flag3)
                    {
                        info.Amount = Mathf.Abs(999999f);
                    }
                    else
                    {
                        info.Amount = ((referenceHub.playerStats != null) ? Mathf.Abs(referenceHub.playerStats.Health + referenceHub.playerStats.syncArtificialHealth + 10f) : Mathf.Abs(999999f));
                    }
                }

                if (__instance._burned.Enabled)
                {
                    info.Amount *= __instance._burned.DamageMult;
                }

                if (info.Amount > 2.14748365E+09f)
                {
                    info.Amount = 2.14748365E+09f;
                }

                if (info.GetDamageType().isWeapon&& referenceHub.characterClassManager.IsAnyScp() && info.GetDamageType() != DamageTypes.MicroHid)
                {
                    info.Amount *= __instance.weaponManager.weapons[(int)__instance.weaponManager.curWeapon].scpDamageMultiplier;
                }

                if (flag3)
                {
                    __result = false;
                    return(false);
                }

                PlayerStats           playerStats           = referenceHub.playerStats;
                CharacterClassManager characterClassManager = referenceHub.characterClassManager;

                if (playerStats == null || characterClassManager == null)
                {
                    __result = false;
                    return(false);
                }

                if (characterClassManager.GodMode)
                {
                    __result = false;
                    return(false);
                }

                if (__instance.ccm.CurRole.team == Team.SCP && __instance.ccm.Classes.SafeGet(characterClassManager.CurClass).team == Team.SCP && __instance.ccm != characterClassManager)
                {
                    __result = false;
                    return(false);
                }

                if (characterClassManager.SpawnProtected && !__instance._allowSPDmg)
                {
                    __result = false;
                    return(false);
                }

                bool flag4 = !noTeamDamage && info.IsPlayer && referenceHub != info.RHub && referenceHub.characterClassManager.Fraction == info.RHub.characterClassManager.Fraction;

                if (flag4)
                {
                    info.Amount *= PlayerStats.FriendlyFireFactor;
                }

                float health = playerStats.Health;

                if (__instance.lastHitInfo.Attacker == "ARTIFICIALDEGEN")
                {
                    playerStats.unsyncedArtificialHealth -= info.Amount;
                    if (playerStats.unsyncedArtificialHealth < 0f)
                    {
                        playerStats.unsyncedArtificialHealth = 0f;
                    }
                }
                else
                {
                    var allow = true;
                    try
                    {
                        Server.Get.Events.Player.InvokePlayerDamageEvent(player, killer, ref info, out allow);
                    }
                    catch (Exception e)
                    {
                        SynapseController.Server.Logger.Error($"Synapse-Event: PlayerDamage Event failed!!\n{e}\nStackTrace:\n{e.StackTrace}");
                    }

                    if (!allow)
                    {
                        __result = false;
                        return(false);
                    }

                    if (playerStats.unsyncedArtificialHealth > 0f)
                    {
                        float num  = info.Amount * playerStats.artificialNormalRatio;
                        float num2 = info.Amount - num;
                        playerStats.unsyncedArtificialHealth -= num;
                        if (playerStats.unsyncedArtificialHealth < 0f)
                        {
                            num2 += Mathf.Abs(playerStats.unsyncedArtificialHealth);
                            playerStats.unsyncedArtificialHealth = 0f;
                        }
                        playerStats.Health -= num2;
                        if (playerStats.Health > 0f && playerStats.Health - num <= 0f && characterClassManager.CurRole.team != Team.SCP)
                        {
                            __instance.TargetAchieve(characterClassManager.connectionToClient, "didntevenfeelthat");
                        }
                    }
                    else
                    {
                        playerStats.Health -= info.Amount;
                    }

                    if (playerStats.Health < 0f)
                    {
                        playerStats.Health = 0f;
                    }

                    playerStats.lastHitInfo = info;
                }
                PlayableScpsController component = go.GetComponent <PlayableScpsController>();
                if (component != null && (object)component.CurrentScp is PlayableScps.Interfaces.IDamagable damagable)
                {
                    damagable.OnDamage(info);
                }

                if (playerStats.Health < 1f && characterClassManager.CurClass != RoleType.Spectator)
                {
                    if (component != null && (object)component.CurrentScp is PlayableScps.Interfaces.IImmortalScp immortalScp && !immortalScp.OnDeath(info, __instance.gameObject))
                    {
                        __result = false;
                        return(false);
                    }
                    foreach (Scp079PlayerScript scp079PlayerScript in Scp079PlayerScript.instances)
                    {
                        Scp079Interactable.ZoneAndRoom otherRoom = go.GetComponent <Scp079PlayerScript>().GetOtherRoom();
                        bool flag5 = false;
                        foreach (Scp079Interaction scp079Interaction in scp079PlayerScript.ReturnRecentHistory(12f, __instance._filters))
                        {
                            foreach (Scp079Interactable.ZoneAndRoom zoneAndRoom in scp079Interaction.interactable.currentZonesAndRooms)
                            {
                                if (zoneAndRoom.currentZone == otherRoom.currentZone && zoneAndRoom.currentRoom == otherRoom.currentRoom)
                                {
                                    flag5 = true;
                                }
                            }
                        }

                        if (flag5)
                        {
                            scp079PlayerScript.RpcGainExp(ExpGainType.KillAssist, characterClassManager.CurClass);
                        }
                    }

                    if (RoundSummary.RoundInProgress() && RoundSummary.roundTime < 60 && IsValidDamage)
                    {
                        __instance.TargetAchieve(characterClassManager.connectionToClient, "wowreally");
                    }

                    if (__instance.isLocalPlayer && info.PlayerId != referenceHub.queryProcessor.PlayerId)
                    {
                        RoundSummary.Kills++;
                    }

                    flag = true;

                    if (characterClassManager.CurClass == RoleType.Scp096)
                    {
                        ReferenceHub hub = ReferenceHub.GetHub(go);

                        if (hub != null && hub.scpsController.CurrentScp is PlayableScps.Scp096 && (hub.scpsController.CurrentScp as PlayableScps.Scp096).PlayerState == PlayableScps.Scp096PlayerState.Enraging)
                        {
                            __instance.TargetAchieve(characterClassManager.connectionToClient, "unvoluntaryragequit");
                        }
                    }
                    else if (info.GetDamageType() == DamageTypes.Pocket)
                    {
                        __instance.TargetAchieve(characterClassManager.connectionToClient, "newb");
                    }
                    else if (info.GetDamageType() == DamageTypes.Scp173)
                    {
                        __instance.TargetAchieve(characterClassManager.connectionToClient, "firsttime");
                    }
                    else if (info.GetDamageType() == DamageTypes.Grenade && info.PlayerId == referenceHub.queryProcessor.PlayerId)
                    {
                        __instance.TargetAchieve(characterClassManager.connectionToClient, "iwanttobearocket");
                    }
                    else if (info.GetDamageType().isWeapon)
                    {
                        Inventory inventory = referenceHub.inventory;
                        if (characterClassManager.CurClass == RoleType.Scientist)
                        {
                            Item itemByID = inventory.GetItemByID(inventory.curItem);
                            if (itemByID != null && itemByID.itemCategory == ItemCategory.Keycard && __instance.GetComponent <CharacterClassManager>().CurClass == RoleType.ClassD)
                            {
                                __instance.TargetAchieve(__instance.connectionToClient, "betrayal");
                            }
                        }

                        if (Time.realtimeSinceStartup - __instance._killStreakTime > 30f || __instance._killStreak == 0)
                        {
                            __instance._killStreak     = 0;
                            __instance._killStreakTime = Time.realtimeSinceStartup;
                        }

                        if (__instance.GetComponent <WeaponManager>().GetShootPermission(characterClassManager, true))
                        {
                            __instance._killStreak++;
                        }

                        if (__instance._killStreak >= 5)
                        {
                            __instance.TargetAchieve(__instance.connectionToClient, "pewpew");
                        }

                        if ((__instance.ccm.CurRole.team == Team.MTF || __instance.ccm.Classes.SafeGet(__instance.ccm.CurClass).team == Team.RSC) && characterClassManager.CurClass == RoleType.ClassD)
                        {
                            __instance.TargetStats(__instance.connectionToClient, "dboys_killed", "justresources", 50);
                        }
                    }
                    else if (__instance.ccm.CurRole.team == Team.SCP && go.GetComponent <MicroHID>().CurrentHidState != MicroHID.MicroHidState.Idle)
                    {
                        __instance.TargetAchieve(__instance.connectionToClient, "illpassthanks");
                    }

                    if (player.RealTeam == Team.RSC && player.RealTeam == Team.SCP)
                    {
                        __instance.TargetAchieve(__instance.connectionToClient, "timetodoitmyself");
                    }

                    bool flag6 = info.IsPlayer && referenceHub == info.RHub;
                    flag2 = flag4;

                    if (flag6)
                    {
                        ServerLogs.AddLog(ServerLogs.Modules.ClassChange, string.Concat(new string[]
                        {
                            referenceHub.LoggedNameFromRefHub(),
                            " playing as ",
                            referenceHub.characterClassManager.CurRole.fullName,
                            " committed a suicide using ",
                            info.GetDamageName(),
                            "."
                        }), ServerLogs.ServerLogType.Suicide, false);
                    }
                    else
                    {
                        ServerLogs.AddLog(ServerLogs.Modules.ClassChange, string.Concat(new string[]
                        {
                            referenceHub.LoggedNameFromRefHub(),
                            " playing as ",
                            referenceHub.characterClassManager.CurRole.fullName,
                            " has been killed by ",
                            info.Attacker,
                            " using ",
                            info.GetDamageName(),
                            info.IsPlayer ? (" playing as " + info.RHub.characterClassManager.CurRole.fullName + ".") : "."
                        }), flag2 ? ServerLogs.ServerLogType.Teamkill : ServerLogs.ServerLogType.KillLog, false);
                    }

                    if (info.GetDamageType().isScp || info.GetDamageType() == DamageTypes.Pocket)
                    {
                        RoundSummary.kills_by_scp++;
                    }

                    else if (info.GetDamageType() == DamageTypes.Grenade)
                    {
                        RoundSummary.kills_by_frag++;
                    }

                    try
                    {
                        Server.Get.Events.Player.InvokePlayerDeathEvent(player, killer, info);
                    }

                    catch (Exception e)
                    {
                        SynapseController.Server.Logger.Error($"Synapse-Event: PlayerDeath Event failed!!\n{e}\nStackTrace:\n{e.StackTrace}");
                    }

                    if (!__instance._pocketCleanup || info.GetDamageType() != DamageTypes.Pocket)
                    {
                        referenceHub.inventory.ServerDropAll();
                        PlayerMovementSync playerMovementSync = referenceHub.playerMovementSync;
                        if (characterClassManager.Classes.CheckBounds(characterClassManager.CurClass) && info.GetDamageType() != DamageTypes.RagdollLess)
                        {
                            __instance.GetComponent <RagdollManager>().SpawnRagdoll(go.transform.position, go.transform.rotation, (playerMovementSync == null) ? Vector3.zero : playerMovementSync.PlayerVelocity, (int)characterClassManager.CurClass, info, characterClassManager.CurRole.team > Team.SCP, go.GetComponent <Dissonance.Integrations.MirrorIgnorance.MirrorIgnorancePlayer>().PlayerId, referenceHub.nicknameSync.DisplayName, referenceHub.queryProcessor.PlayerId);
                        }
                    }
                    else
                    {
                        referenceHub.inventory.Clear();
                    }

                    characterClassManager.NetworkDeathPosition = go.transform.position;

                    if (characterClassManager.CurRole.team == Team.SCP)
                    {
                        if (characterClassManager.CurClass == RoleType.Scp0492)
                        {
                            NineTailedFoxAnnouncer.CheckForZombies(go);
                        }
                        else
                        {
                            GameObject x = null;
                            foreach (GameObject gameObject in PlayerManager.players)
                            {
                                if (gameObject.GetComponent <RemoteAdmin.QueryProcessor>().PlayerId == info.PlayerId)
                                {
                                    x = gameObject;
                                }
                            }
                            if (x != null)
                            {
                                NineTailedFoxAnnouncer.AnnounceScpTermination(characterClassManager.CurRole, info, string.Empty);
                            }
                            else
                            {
                                DamageTypes.DamageType damageType = info.GetDamageType();
                                if (damageType == DamageTypes.Tesla)
                                {
                                    NineTailedFoxAnnouncer.AnnounceScpTermination(characterClassManager.CurRole, info, "TESLA");
                                }
                                else if (damageType == DamageTypes.Nuke)
                                {
                                    NineTailedFoxAnnouncer.AnnounceScpTermination(characterClassManager.CurRole, info, "WARHEAD");
                                }
                                else if (damageType == DamageTypes.Decont)
                                {
                                    NineTailedFoxAnnouncer.AnnounceScpTermination(characterClassManager.CurRole, info, "DECONTAMINATION");
                                }
                                else if (characterClassManager.CurClass != RoleType.Scp079)
                                {
                                    NineTailedFoxAnnouncer.AnnounceScpTermination(characterClassManager.CurRole, info, "UNKNOWN");
                                }
                            }
                        }
                    }

                    playerStats.SetHPAmount(100);
                    characterClassManager.SetClassID(RoleType.Spectator);

                    player.CustomRole = null;
                    foreach (var larry in Server.Get.Players.Where(x => x.Scp106Controller.PocketPlayers.Contains(player)))
                    {
                        larry.Scp106Controller.PocketPlayers.Remove(player);
                    }
                }
                else
                {
                    Vector3 pos  = Vector3.zero;
                    float   num3 = 40f;
                    if (info.GetDamageType().isWeapon)
                    {
                        GameObject playerOfID = __instance.GetPlayerOfID(info.PlayerId);
                        if (playerOfID != null)
                        {
                            pos  = go.transform.InverseTransformPoint(playerOfID.transform.position).normalized;
                            num3 = 100f;
                        }
                    }
                    else if (info.GetDamageType() == DamageTypes.Pocket)
                    {
                        PlayerMovementSync component2 = __instance.ccm.GetComponent <PlayerMovementSync>();
                        if (component2.RealModelPosition.y > -1900f)
                        {
                            component2.OverridePosition(Vector3.down * 1998.5f, 0f, true);
                        }
                    }
                    __instance.TargetBloodEffect(go.GetComponent <NetworkIdentity>().connectionToClient, pos, Mathf.Clamp01(info.Amount / num3));
                }
                Respawning.RespawnTickets singleton = Respawning.RespawnTickets.Singleton;
                Team team = characterClassManager.CurRole.team;
                byte b    = (byte)team;
                if (b != 0)
                {
                    if (b == 3)
                    {
                        if (flag)
                        {
                            Team team2 = __instance.ccm.Classes.SafeGet(characterClassManager.CurClass).team;
                            if (team2 == Team.CDP && team2 == Team.CHI)
                            {
                                singleton.GrantTickets(Respawning.SpawnableTeamType.ChaosInsurgency, __instance._respawn_tickets_ci_scientist_died_count, false);
                            }
                        }
                    }
                }
                else if (characterClassManager.CurClass != RoleType.Scp0492)
                {
                    for (float num4 = 1f; num4 > 0f; num4 -= __instance._respawn_tickets_mtf_scp_hurt_interval)
                    {
                        float num5 = (float)playerStats.maxHP * num4;
                        if (health > num5 && playerStats.Health < num5)
                        {
                            singleton.GrantTickets(Respawning.SpawnableTeamType.NineTailedFox, __instance._respawn_tickets_mtf_scp_hurt_count, false);
                        }
                    }
                }

                if (component != null && (object)component.CurrentScp is PlayableScps.Interfaces.IDamagable damagable2)
                {
                    damagable2.OnDamage(info);
                }

                if (!flag4 || FriendlyFireConfig.PauseDetector || PermissionsHandler.IsPermitted(info.RHub.serverRoles.Permissions, PlayerPermissions.FriendlyFireDetectorImmunity))
                {
                    __result = flag;
                    return(false);
                }

                if (FriendlyFireConfig.IgnoreClassDTeamkills && referenceHub.characterClassManager.CurRole.team == Team.CDP && info.RHub.characterClassManager.CurRole.team == Team.CDP)
                {
                    __result = flag;
                    return(false);
                }

                if (flag2)
                {
                    if (info.RHub.FriendlyFireHandler.Respawn.RegisterKill())
                    {
                        __result = flag;
                        return(false);
                    }
                    if (info.RHub.FriendlyFireHandler.Window.RegisterKill())
                    {
                        __result = flag;
                        return(false);
                    }
                    if (info.RHub.FriendlyFireHandler.Life.RegisterKill())
                    {
                        __result = flag;
                        return(false);
                    }
                    if (info.RHub.FriendlyFireHandler.Round.RegisterKill())
                    {
                        __result = flag;
                        return(false);
                    }
                }

                if (info.RHub.FriendlyFireHandler.Respawn.RegisterDamage(info.Amount))
                {
                    __result = flag;
                    return(false);
                }

                if (info.RHub.FriendlyFireHandler.Window.RegisterDamage(info.Amount))
                {
                    __result = flag;
                    return(false);
                }

                if (info.RHub.FriendlyFireHandler.Life.RegisterDamage(info.Amount))
                {
                    __result = flag;
                    return(false);
                }

                info.RHub.FriendlyFireHandler.Round.RegisterDamage(info.Amount);
                __result = flag;
                return(false);
            }
            catch (Exception e)
            {
                SynapseController.Server.Logger.Error($"Synapse-Event: PlayerDamage Patch failed!!\n{e}\nStackTrace:\n{e.StackTrace}");
                __result = false;
                return(true);
            }
        }
Пример #22
0
        protected internal override void RaiseLog(Exception ex)
        {
            var str = ex.Message + Environment.NewLine + "stacktrace: " + ex.StackTrace;

            ServerLogs?.Invoke(str);
        }
Пример #23
0
        private static bool Prefix(CharacterClassManager __instance, bool first)
        {
            try
            {
                if (__instance.isLocalPlayer && __instance.isServer)
                {
                    __instance.RunDefaultClassPicker(first, out var roleList, out var dictionary);

                    ServerLogs.AddLog(ServerLogs.Modules.Logger, "Random classes have been assigned by DCP.", ServerLogs.ServerLogType.GameEvent, false);

                    if (first && GameCore.ConfigFile.ServerConfig.GetBool("smart_class_picker", true) && GameCore.Console.EnableSCP)
                    {
                        __instance.RunSmartClassPicker(roleList, out dictionary);

                        ServerLogs.AddLog(ServerLogs.Modules.Logger, "Smart class picking has been performed.", ServerLogs.ServerLogType.GameEvent, false);
                    }

                    var newDictionary = new Dictionary <Player, int>();
                    var flag          = UnityEngine.Random.Range(1f, 100f) <= GameCore.ConfigFile.ServerConfig.GetFloat("ci_on_start_percent");
                    foreach (var pair in dictionary)
                    {
                        var player = pair.Key.GetPlayer();
                        if (player == Server.Get.Host)
                        {
                            continue;
                        }

                        //This fix the Bug that Overwatch Players get spawned in for a sec and then get sets to Spectator again which results in many bugs
                        if (player.OverWatch)
                        {
                            player.RoleID = (int)RoleType.Spectator;
                            continue;
                        }

                        if (flag && pair.Value == RoleType.FacilityGuard)
                        {
                            newDictionary.Add(player, (int)RoleType.ChaosInsurgency);
                        }
                        else
                        {
                            newDictionary.Add(player, (int)pair.Value);
                        }
                    }

                    var allow = true;
                    try
                    {
                        Server.Get.Events.Round.InvokeSpawnPlayersEvent(ref newDictionary, out allow);
                    }
                    catch (Exception e)
                    {
                        Logger.Get.Error($"Synapse-Event: SpawnPlayersEvent failed!!\n{e}");
                    }

                    if (allow)
                    {
                        var builder = StringBuilderPool.Shared.Rent();
                        foreach (var pair in newDictionary)
                        {
                            pair.Key.RoleID = pair.Value;

                            builder.Append((RoleType)pair.Value + " | ");
                        }

                        ServerLogs.AddLog(ServerLogs.Modules.Logger, "Class Picker Result: " + builder, ServerLogs.ServerLogType.GameEvent, false);
                        StringBuilderPool.Shared.Return(builder);
                    }
                }
                if (NetworkServer.active)
                {
                    Timing.RunCoroutine(__instance.MakeSureToSetHPAndStamina(), Segment.FixedUpdate);
                }

                return(false);
            }
            catch (Exception e)
            {
                SynapseController.Server.Logger.Error($"Synapse-Event: SpawnPlayers failed!!\n{e}\nStackTrace:\n{e.StackTrace}");
                return(true);
            }
        }
Пример #24
0
        public static IEnumerator <float> ProcessServerSide(RoundSummary instance)
        {
            while (instance != null)
            {
                while (Map.Get.Round.RoundLock || !RoundSummary.RoundInProgress() || (instance._keepRoundOnOne && Server.Get.Players.Count < 2) || Map.Get.Round.RoundLength.TotalSeconds <= 3)
                {
                    yield return(Timing.WaitForOneFrame);
                }

                var teams = new List <Team>();

                var customroles = new List <Synapse.Api.Roles.IRole>();

                var teamAmounts = 0;

                var leadingTeam = RoundSummary.LeadingTeam.Draw;

                var result = default(RoundSummary.SumInfo_ClassList);

                bool endround;

                foreach (var player in Server.Get.Players)
                {
                    if (player.CustomRole != null)
                    {
                        customroles.Add(player.CustomRole);
                    }

                    teams.Add(player.RealTeam);

                    switch (player.RealTeam)
                    {
                    case Team.SCP:
                        if (player.RoleID == (int)RoleType.Scp0492)
                        {
                            result.zombies++;
                        }
                        else
                        {
                            result.scps_except_zombies++;
                        }
                        break;

                    case Team.MTF:
                        result.mtf_and_guards++;
                        break;

                    case Team.CHI:
                        result.chaos_insurgents++;
                        break;

                    case Team.RSC:
                        result.scientists++;
                        break;

                    case Team.CDP:
                        result.class_ds++;
                        break;
                    }
                }

                if (teams.Contains(Team.MTF))
                {
                    teamAmounts++;
                }
                if (teams.Contains(Team.RSC))
                {
                    teamAmounts++;
                }
                if (teams.Contains(Team.CHI))
                {
                    teamAmounts++;
                }
                if (teams.Contains(Team.CDP))
                {
                    teamAmounts++;
                }
                if (teams.Contains(Team.SCP))
                {
                    teamAmounts++;
                }

                result.warhead_kills = Map.Get.Nuke.Detonated ? Map.Get.Nuke.NukeKills : -1;

                yield return(Timing.WaitForOneFrame);

                result.time = (int)Time.realtimeSinceStartup;

                yield return(Timing.WaitForOneFrame);

                RoundSummary.roundTime = result.time - instance.classlistStart.time;

                switch (teamAmounts)
                {
                case 0:
                case 1:
                    endround = true;
                    break;

                case 2:
                    if (teams.Contains(Team.CHI) && teams.Contains(Team.SCP))
                    {
                        endround = Server.Get.Configs.SynapseConfiguration.ChaosScpEnd;
                    }

                    else if (teams.Contains(Team.CHI) && teams.Contains(Team.CDP))
                    {
                        endround = true;
                    }

                    else if (teams.Contains(Team.MTF) && teams.Contains(Team.RSC))
                    {
                        endround = true;
                    }
                    else
                    {
                        endround = false;
                    }
                    break;

                default:
                    endround = false;
                    break;
                }

                foreach (var role in customroles)
                {
                    if (role.GetEnemys().Any(x => teams.Contains(x)))
                    {
                        endround = false;
                    }
                }

                if (RoundSummary.escaped_ds + teams.Count(x => x == Team.CDP) > 0)
                {
                    if (teams.Contains(Team.SCP) || teams.Contains(Team.CHI) || teams.Contains(Team.CHI))
                    {
                        leadingTeam = RoundSummary.LeadingTeam.ChaosInsurgency;
                    }
                }
                else
                {
                    if (teams.Contains(Team.MTF) || teams.Contains(Team.RSC))
                    {
                        if (RoundSummary.escaped_scientists + teams.Count(x => x == Team.RSC) > 0)
                        {
                            leadingTeam = RoundSummary.LeadingTeam.FacilityForces;
                        }
                    }
                    else
                    {
                        leadingTeam = RoundSummary.LeadingTeam.Anomalies;
                    }
                }

                try
                {
                    Server.Get.Events.Round.InvokeRoundCheckEvent(ref endround, ref leadingTeam);
                }
                catch (Exception e)
                {
                    Logger.Get.Error($"Synapse-Event: RoundCheckEvent failed!!\n{e}\nStackTrace:\n{e.StackTrace}");
                }


                if (endround || Map.Get.Round.Forceend)
                {
                    instance._roundEnded             = true;
                    Map.Get.Round.Forceend           = false;
                    FriendlyFireConfig.PauseDetector = true;

                    var dpercentage = (float)instance.classlistStart.class_ds == 0 ? 0 : RoundSummary.escaped_ds + result.class_ds / instance.classlistStart.class_ds;
                    var spercentage = (float)instance.classlistStart.scientists == 0 ? 0 : RoundSummary.escaped_scientists + result.scientists / instance.classlistStart.scientists;
                    var text        = $"Round finished! Anomalies: {teams.Where(x => x == Team.SCP).Count()} | Chaos: {teams.Where(x => x == Team.CHI || x == Team.CDP).Count()}" +
                                      $" | Facility Forces: {teams.Where(x => x == Team.MTF || x == Team.RSC).Count()} | D escaped percentage: {dpercentage} | S escaped percentage : {spercentage}";
                    GameCore.Console.AddLog(text, Color.gray, false);
                    ServerLogs.AddLog(ServerLogs.Modules.Logger, text, ServerLogs.ServerLogType.GameEvent, false);

                    for (byte i = 0; i < 75; i++)
                    {
                        yield return(0f);
                    }

                    var timeToRoundRestart = Mathf.Clamp(GameCore.ConfigFile.ServerConfig.GetInt("auto_round_restart_time", 10), 5, 1000);

                    Map.Get.Round.ShowRoundSummary(result, leadingTeam);

                    for (int j = 0; j < 50 * timeToRoundRestart; j++)
                    {
                        yield return(0f);
                    }

                    Map.Get.Round.DimScreens();

                    for (byte i = 0; i < 50; i++)
                    {
                        yield return(0f);
                    }

                    Map.Get.Round.RestartRound();
                }
            }
        }
Пример #25
0
        private static void HandleConnection(ConnectionRequest request)
        {
            NetDataWriter rejectData = new NetDataWriter();

            try
            {
                byte result1;
                byte result2;
                int  position = request.Data.Position;
                if (!request.Data.TryGetByte(out result1) || !request.Data.TryGetByte(out result2) || result1 != CustomNetworkManager.Major || result2 != CustomNetworkManager.Minor)
                {
                    rejectData.Reset();
                    rejectData.Put(3);
                    request.Reject(rejectData);
                }
                else
                {
                    if (CustomLiteNetLib4MirrorTransport.IpRateLimiting)
                    {
                        if (CustomLiteNetLib4MirrorTransport.IpRateLimit.Contains(request.RemoteEndPoint.Address.ToString()))
                        {
                            ServerConsole.AddLog(string.Format("Incoming connection from endpoint {0} rejected due to exceeding the rate limit.", request.RemoteEndPoint));
                            ServerLogs.AddLog(ServerLogs.Modules.Networking, string.Format("Incoming connection from endpoint {0} rejected due to exceeding the rate limit.", request.RemoteEndPoint), ServerLogs.ServerLogType.RateLimit);
                            rejectData.Reset();
                            rejectData.Put(12);
                            request.Reject(rejectData);
                            return;
                        }
                        CustomLiteNetLib4MirrorTransport.IpRateLimit.Add(request.RemoteEndPoint.Address.ToString());
                    }
                    if (!CharacterClassManager.OnlineMode)
                    {
                        KeyValuePair <BanDetails, BanDetails> keyValuePair = BanHandler.QueryBan(null, request.RemoteEndPoint.Address.ToString());
                        if (keyValuePair.Value != null)
                        {
                            ServerConsole.AddLog(string.Format("Player tried to connect from banned endpoint {0}.", request.RemoteEndPoint));
                            rejectData.Reset();
                            rejectData.Put(6);
                            rejectData.Put(keyValuePair.Value.Expires);
                            rejectData.Put(keyValuePair.Value?.Reason ?? string.Empty);
                            request.Reject(rejectData);
                        }
                        else
                        {
                            request.Accept();
                        }
                    }
                    else
                    {
                        string result3;
                        if (!request.Data.TryGetString(out result3) || result3 == string.Empty)
                        {
                            rejectData.Reset();
                            rejectData.Put(5);
                            request.Reject(rejectData);
                        }
                        else
                        {
                            ulong  result4;
                            byte   result5;
                            string result6;
                            byte[] result7;
                            if (!request.Data.TryGetULong(out result4) || !request.Data.TryGetByte(out result5) || !request.Data.TryGetString(out result6) || !request.Data.TryGetBytesWithLength(out result7))
                            {
                                rejectData.Reset();
                                rejectData.Put(4);
                                request.Reject(rejectData);
                            }
                            else
                            {
                                CentralAuthPreauthFlags flags = (CentralAuthPreauthFlags)result5;
                                try
                                {
                                    if (!ECDSA.VerifyBytes(string.Format("{0};{1};{2};{3}", result3, result5, result6, result4), result7, ServerConsole.PublicKey))
                                    {
                                        ServerConsole.AddLog(string.Format("Player from endpoint {0} sent preauthentication token with invalid digital signature.", request.RemoteEndPoint));
                                        rejectData.Reset();
                                        rejectData.Put(2);
                                        request.Reject(rejectData);
                                    }
                                    else if (TimeBehaviour.CurrentUnixTimestamp > result4)
                                    {
                                        ServerConsole.AddLog(string.Format("Player from endpoint {0} sent expired preauthentication token.", request.RemoteEndPoint));
                                        ServerConsole.AddLog("Make sure that time and timezone set on server is correct. We recommend synchronizing the time.");
                                        rejectData.Reset();
                                        rejectData.Put(11);
                                        request.Reject(rejectData);
                                    }
                                    else
                                    {
                                        if (CustomLiteNetLib4MirrorTransport.UserRateLimiting)
                                        {
                                            if (CustomLiteNetLib4MirrorTransport.UserRateLimit.Contains(result3))
                                            {
                                                ServerConsole.AddLog(string.Format("Incoming connection from {0} ({1}) rejected due to exceeding the rate limit.", result3, request.RemoteEndPoint));
                                                ServerLogs.AddLog(ServerLogs.Modules.Networking, string.Format("Incoming connection from endpoint {0} ({1}) rejected due to exceeding the rate limit.", result3, request.RemoteEndPoint), ServerLogs.ServerLogType.RateLimit);
                                                rejectData.Reset();
                                                rejectData.Put(12);
                                                request.Reject(rejectData);
                                                return;
                                            }
                                            CustomLiteNetLib4MirrorTransport.UserRateLimit.Add(result3);
                                        }
                                        if (!flags.HasFlagFast(CentralAuthPreauthFlags.IgnoreBans) || !ServerStatic.GetPermissionsHandler().IsVerified)
                                        {
                                            KeyValuePair <BanDetails, BanDetails> keyValuePair = BanHandler.QueryBan(result3, request.RemoteEndPoint.Address.ToString());
                                            if (keyValuePair.Key != null || keyValuePair.Value != null)
                                            {
                                                ServerConsole.AddLog(string.Format("{0} {1} tried to connect from {2} endpoint {3}.", keyValuePair.Key == null ? "Player" : "Banned player", result3, keyValuePair.Value == null ? "" : "banned ", request.RemoteEndPoint));
                                                ServerLogs.AddLog(ServerLogs.Modules.Networking, string.Format("{0} {1} tried to connect from {2} endpoint {3}.", keyValuePair.Key == null ? "Player" : "Banned player", result3, keyValuePair.Value == null ? "" : "banned ", request.RemoteEndPoint), ServerLogs.ServerLogType.ConnectionUpdate);
                                                rejectData.Reset();
                                                rejectData.Put(6);
                                                NetDataWriter netDataWriter1 = rejectData;
                                                BanDetails    key            = keyValuePair.Key;
                                                netDataWriter1.Put(key != null ? key.Expires : keyValuePair.Value.Expires);
                                                NetDataWriter netDataWriter2 = rejectData;
                                                string        str;
                                                if ((str = keyValuePair.Key?.Reason) == null)
                                                {
                                                    str = keyValuePair.Value?.Reason ?? string.Empty;
                                                }
                                                netDataWriter2.Put(str);
                                                request.Reject(rejectData);
                                                return;
                                            }
                                        }
                                        if (flags.HasFlagFast(CentralAuthPreauthFlags.GloballyBanned) && !ServerStatic.GetPermissionsHandler().IsVerified)
                                        {
                                            bool useGlobalBans = CustomLiteNetLib4MirrorTransport.UseGlobalBans;
                                        }
                                        if ((!flags.HasFlagFast(CentralAuthPreauthFlags.IgnoreWhitelist) || !ServerStatic.GetPermissionsHandler().IsVerified) && !WhiteList.IsWhitelisted(result3))
                                        {
                                            ServerConsole.AddLog(string.Format("Player {0} tried joined from endpoint {1}, but is not whitelisted.", result3, request.RemoteEndPoint));
                                            rejectData.Reset();
                                            rejectData.Put(7);
                                            request.Reject(rejectData);
                                        }
                                        else if (CustomLiteNetLib4MirrorTransport.Geoblocking != GeoblockingMode.None && (!flags.HasFlagFast(CentralAuthPreauthFlags.IgnoreGeoblock) || !ServerStatic.GetPermissionsHandler().BanTeamBypassGeo) && (!CustomLiteNetLib4MirrorTransport.GeoblockIgnoreWhitelisted || !WhiteList.IsOnWhitelist(result3)) && (CustomLiteNetLib4MirrorTransport.Geoblocking == GeoblockingMode.Whitelist && !CustomLiteNetLib4MirrorTransport.GeoblockingList.Contains(result6.ToUpper()) || CustomLiteNetLib4MirrorTransport.Geoblocking == GeoblockingMode.Blacklist && CustomLiteNetLib4MirrorTransport.GeoblockingList.Contains(result6.ToUpper())))
                                        {
                                            ServerConsole.AddLog(string.Format("Player {0} ({1}) tried joined from blocked country {2}.", result3, request.RemoteEndPoint, result6.ToUpper()));
                                            rejectData.Reset();
                                            rejectData.Put(9);
                                            request.Reject(rejectData);
                                        }
                                        else
                                        {
                                            int num = CustomNetworkManager.slots;
                                            if (flags.HasFlagFast(CentralAuthPreauthFlags.ReservedSlot) && ServerStatic.GetPermissionsHandler().BanTeamSlots)
                                            {
                                                num = LiteNetLib4MirrorNetworkManager.singleton.maxConnections;
                                            }
                                            else if (ConfigFile.ServerConfig.GetBool("use_reserved_slots", true) && ReservedSlot.HasReservedSlot(result3))
                                            {
                                                num += CustomNetworkManager.reservedSlots;
                                            }
                                            if (LiteNetLib4MirrorCore.Host.PeersCount < num)
                                            {
                                                if (CustomLiteNetLib4MirrorTransport.UserIds.ContainsKey(request.RemoteEndPoint))
                                                {
                                                    CustomLiteNetLib4MirrorTransport.UserIds[request.RemoteEndPoint].SetUserId(result3);
                                                }
                                                else
                                                {
                                                    CustomLiteNetLib4MirrorTransport.UserIds.Add(request.RemoteEndPoint, new PreauthItem(result3));
                                                }
                                                bool allow = true;
                                                Events.InvokePreAuth(result3, request, position, result5, result6, ref allow);
                                                if (allow)
                                                {
                                                    request.Accept();
                                                    ServerConsole.AddLog(string.Format("Player {0} preauthenticated from endpoint {1}.", result3, request.RemoteEndPoint));
                                                    ServerLogs.AddLog(ServerLogs.Modules.Networking, string.Format("{0} preauthenticated from endpoint {1}.", result3, request.RemoteEndPoint), ServerLogs.ServerLogType.ConnectionUpdate);
                                                }
                                                else
                                                {
                                                    ServerConsole.AddLog(string.Format("Player {0} tried to preauthenticate from endpoint {1}, but the request has been rejected by a plugin.", result3, request.RemoteEndPoint));
                                                    ServerLogs.AddLog(ServerLogs.Modules.Networking, string.Format("{0} tried to preauthenticate from endpoint {1}, but the request has been rejected by a plugin.", result3, request.RemoteEndPoint), ServerLogs.ServerLogType.ConnectionUpdate);
                                                }
                                            }
                                            else
                                            {
                                                rejectData.Reset();
                                                rejectData.Put(1);
                                                request.Reject(rejectData);
                                            }
                                        }
                                    }
                                }
                                catch (Exception exception)
                                {
                                    ServerConsole.AddLog(string.Format("Player from endpoint {0} sent an invalid preauthentication token. {1}", request.RemoteEndPoint, exception.Message));
                                    rejectData.Reset();
                                    rejectData.Put(2);
                                    request.Reject(rejectData);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                ServerConsole.AddLog(string.Format("Player from endpoint {0} failed to preauthenticate: {1}", request.RemoteEndPoint, exception.Message));
                rejectData.Reset();
                rejectData.Put(4);
                request.Reject(rejectData);
            }
        }
Пример #26
0
        private static bool SetRandomRoles(CharacterClassManager __instance, bool first)
        {
            try
            {
                __instance.RunDefaultClassPicker(first, out var roleList, out var dictionary);

                ServerLogs.AddLog(ServerLogs.Modules.Logger, "Random classes have been assigned by DCP.", ServerLogs.ServerLogType.GameEvent, false);

                if (first && GameCore.ConfigFile.ServerConfig.GetBool("smart_class_picker", true) && GameCore.Console.EnableSCP)
                {
                    __instance.RunSmartClassPicker(roleList, out dictionary);

                    ServerLogs.AddLog(ServerLogs.Modules.Logger, "Smart class picking has been performed.", ServerLogs.ServerLogType.GameEvent, false);
                }

                var newDictionary = new Dictionary <Player, int>();
                foreach (var pair in dictionary)
                {
                    var player = pair.Key.GetPlayer();
                    if (player == Server.Get.Host)
                    {
                        continue;
                    }

                    //This fix the Bug that Overwatch Players get spawned in for a sec and then get sets to Spectator again which results in many bugs
                    if (player.OverWatch)
                    {
                        player.RoleID = (int)RoleType.Spectator;
                        continue;
                    }

                    if (__instance.IsCIOnStart && pair.Value == RoleType.FacilityGuard)
                    {
                        newDictionary.Add(player, (int)RoleType.ChaosRifleman);
                    }
                    else
                    {
                        newDictionary.Add(player, (int)pair.Value);
                    }
                }

                var allow = true;
                try
                {
                    Server.Get.Events.Round.InvokeSpawnPlayersEvent(ref newDictionary, out allow);
                }
                catch (Exception e)
                {
                    Logger.Get.Error($"Synapse-Event: SpawnPlayersEvent failed!!\n{e}");
                }

                if (allow)
                {
                    var builder = StringBuilderPool.Shared.Rent();
                    foreach (var pair in newDictionary)
                    {
                        pair.Key.RoleID = pair.Value;

                        builder.Append((RoleType)pair.Value + " | ");
                    }

                    ServerLogs.AddLog(ServerLogs.Modules.Logger, "Class Picker Result: " + builder, ServerLogs.ServerLogType.GameEvent, false);
                    StringBuilderPool.Shared.Return(builder);
                }

                return(false);
            }
            catch (Exception e)
            {
                SynapseController.Server.Logger.Error($"Synapse-Event: SpawnPlayers failed!!\n{e}");
                return(true);
            }
        }
Пример #27
0
        public static bool Prefix(MTFRespawn __instance)
        {
            if (EventPlugin.RespawnPatchDisable)
            {
                return(true);
            }

            try
            {
                int num = 0;
                __instance.playersToNTF.Clear();

                Log.Debug($"Respawn: Got players: {EventPlugin.DeadPlayers.Count}");

                foreach (ReferenceHub player in EventPlugin.DeadPlayers.ToArray())
                {
                    if (player.GetOverwatch() || player.GetRole() != RoleType.Spectator)
                    {
                        Log.Debug($"Removing {player.GetNickname()} -- Overwatch true or not spectator");
                        EventPlugin.DeadPlayers.Remove(player);
                    }
                }

                if (Plugin.Config.GetBool("exiled_random_respawns"))
                {
                    EventPlugin.DeadPlayers.ShuffleList();
                }

                bool isChaos    = __instance.nextWaveIsCI;
                int  maxRespawn = isChaos ? __instance.maxCIRespawnAmount : __instance.maxMTFRespawnAmount;

                List <ReferenceHub> playersToRespawn = EventPlugin.DeadPlayers.Take(maxRespawn).ToList();
                Log.Debug($"Respawn: pre-vent list: {playersToRespawn.Count}");
                Events.InvokeTeamRespawn(ref isChaos, ref maxRespawn, ref playersToRespawn);

                if (maxRespawn <= 0 || playersToRespawn == null || playersToRespawn.Count == 0)
                {
                    return(false);
                }

                foreach (ReferenceHub player in playersToRespawn)
                {
                    if (num >= maxRespawn)
                    {
                        break;
                    }

                    if (player != null)
                    {
                        ++num;
                        if (isChaos)
                        {
                            __instance.GetComponent <CharacterClassManager>().SetPlayersClass(RoleType.ChaosInsurgency, player.gameObject);
                            ServerLogs.AddLog(ServerLogs.Modules.ClassChange, player.GetNickname() + " (" + player.GetUserId() +
                                              ") respawned as Chaos Insurgency agent.", ServerLogs.ServerLogType.GameEvent);
                        }
                        else
                        {
                            __instance.playersToNTF.Add(player.gameObject);
                        }

                        EventPlugin.DeadPlayers.Remove(player);
                    }
                }

                if (num > 0)
                {
                    ServerLogs.AddLog(ServerLogs.Modules.ClassChange,
                                      (__instance.nextWaveIsCI ? "Chaos Insurgency" : "MTF") + " respawned!", ServerLogs.ServerLogType.GameEvent);
                    if (__instance.nextWaveIsCI)
                    {
                        __instance.Invoke("CmdDelayCIAnnounc", 1f);
                    }
                }

                __instance.SummonNTF();
                return(false);
            }
            catch (Exception exception)
            {
                Log.Error($"RespawnEvent error: {exception}");
                return(true);
            }
        }
Пример #28
0
        public static bool Prefix(FragGrenade __instance, ref bool __result)
        {
            Player thrower = Player.Get(__instance.thrower.gameObject);

            if (Tracking.PlayersWithSubclasses.ContainsKey(thrower) && Tracking.PlayersWithSubclasses[thrower].Abilities.Contains(AbilityType.HealGrenadeFrag))
            {
                UnityEngine.Collider[] colliders = UnityEngine.Physics.OverlapSphere(__instance.transform.position, 4);
                Subclass.Instance.map.UpdateHealths(colliders, thrower, "HealGrenadeFragHealAmount");
                return(false);
            }

            string str = (((Grenade)((EffectGrenade)__instance)).thrower != null) ? ((Grenade)((EffectGrenade)__instance)).thrower.hub.LoggedNameFromRefHub() : ((string)"(UNKNOWN)");

            string[] textArray1 = new string[] { "Player ", (string)str, "'s ", (string)((Grenade)((EffectGrenade)__instance)).logName, " grenade exploded." };
            ServerLogs.AddLog(ServerLogs.Modules.Logger, string.Concat((string[])textArray1), ServerLogs.ServerLogType.GameEvent, false);

            if (((EffectGrenade)__instance).serverGrenadeEffect != null)
            {
                Transform transform = ((Grenade)((EffectGrenade)__instance)).transform;
                Object.Instantiate <GameObject>(((EffectGrenade)__instance).serverGrenadeEffect, transform.position, transform.rotation);
            }

            Vector3 position = ((EffectGrenade)__instance).transform.position;
            int     num      = 0;

            Collider[] colliderArray = Physics.OverlapSphere(position, __instance.chainTriggerRadius, (int)__instance.damageLayerMask);
            int        index         = 0;

            while (index < colliderArray.Length)
            {
                Collider        collider  = colliderArray[index];
                BreakableWindow component = collider.GetComponent <BreakableWindow>();
                if (component != null)
                {
                    if ((component.transform.position - position).sqrMagnitude <= __instance.sqrChainTriggerRadius)
                    {
                        component.ServerDamageWindow(500f);
                    }
                }
                else
                {
                    Door componentInParent = collider.GetComponentInParent <Door>();
                    if (componentInParent != null)
                    {
                        if ((!componentInParent.GrenadesResistant && (!componentInParent.commandlock && (!componentInParent.decontlock && !componentInParent.lockdown))) && ((componentInParent.transform.position - position).sqrMagnitude <= __instance.sqrChainTriggerRadius))
                        {
                            componentInParent.DestroyDoor(true);
                        }
                    }
                    else if (((__instance.chainLengthLimit == -1) || (__instance.chainLengthLimit > ((EffectGrenade)__instance).currentChainLength)) && ((__instance.chainConcurrencyLimit == -1) || (__instance.chainConcurrencyLimit > num)))
                    {
                        Pickup componentInChildren = collider.GetComponentInChildren <Pickup>();
                        if ((componentInChildren != null) && __instance.ChangeIntoGrenade(componentInChildren))
                        {
                            num = (int)(num + 1);
                        }
                    }
                }
                index = (int)(index + 1);
            }
            Player pthrower = Player.Get(((EffectGrenade)__instance).thrower.gameObject);

            foreach (GameObject obj2 in PlayerManager.players)
            {
                if (!ServerConsole.FriendlyFire && ((obj2 != ((EffectGrenade)__instance).thrower.gameObject) &&
                                                    (!obj2.GetComponent <WeaponManager>().GetShootPermission(((EffectGrenade)__instance).throwerTeam, false))) &&
                    !Tracking.PlayerHasFFToPlayer(pthrower, Player.Get(obj2)))
                {
                    Exiled.API.Features.Log.Debug($"Player {Player.Get(obj2)?.Nickname} could not be hurt from a grenade. Thrower has ff to player: {Tracking.PlayerHasFFToPlayer(pthrower, Player.Get(obj2))}", Subclass.Instance.Config.Debug);
                    continue;
                }
                PlayerStats component = obj2.GetComponent <PlayerStats>();
                if ((component != null) && component.ccm.InWorld)
                {
                    float amount = (float)(__instance.damageOverDistance.Evaluate(Vector3.Distance(position, component.transform.position)) * (component.ccm.IsHuman() ? ConfigFile.ServerConfig.GetFloat("human_grenade_multiplier", 0.7f) : ConfigFile.ServerConfig.GetFloat("scp_grenade_multiplier", 1f)));
                    if (amount > __instance.absoluteDamageFalloff)
                    {
                        Exiled.API.Features.Log.Debug($"Attempting to hurt player {Player.Get(obj2)?.Nickname} with a grenade", Subclass.Instance.Config.Debug);
                        Transform[] grenadePoints = component.grenadePoints;
                        index = 0;
                        while (true)
                        {
                            if (index < grenadePoints.Length)
                            {
                                Transform transform = grenadePoints[index];
                                if (Physics.Linecast(position, transform.position, (int)__instance.hurtLayerMask))
                                {
                                    index = (int)(index + 1);
                                    continue;
                                }
                                component.HurtPlayer(new PlayerStats.HitInfo(amount, (((EffectGrenade)__instance).thrower != null) ? ((EffectGrenade)__instance).thrower.hub.LoggedNameFromRefHub() : ((string)"(UNKNOWN)"), DamageTypes.Grenade, ((EffectGrenade)__instance).thrower.hub.queryProcessor.PlayerId), obj2, false);
                            }
                            if (!component.ccm.IsAnyScp())
                            {
                                ReferenceHub hub      = ReferenceHub.GetHub(obj2);
                                float        duration = __instance.statusDurationOverDistance.Evaluate(Vector3.Distance(position, component.transform.position));
                                hub.playerEffectsController.EnableEffect(hub.playerEffectsController.GetEffect <Burned>(), duration, false);
                                hub.playerEffectsController.EnableEffect(hub.playerEffectsController.GetEffect <Concussed>(), duration, false);
                            }
                            break;
                        }
                    }
                }
            }

            __result = true;
            return(false);
        }
Пример #29
0
        public static IEnumerator <float> ProcessServerSide(RoundSummary instance)
        {
            var roundSummary = instance;

            while (roundSummary != null)
            {
                while (RoundSummary.RoundLock || !RoundSummary.RoundInProgress() ||
                       roundSummary._keepRoundOnOne && PlayerManager.players.Count < 2)
                {
                    yield return(0.0f);
                }

                var newList = new RoundSummary.SumInfo_ClassList();

                foreach (var chrClassManager in PlayerManager.players.Where(gameObject => gameObject != null).Select(gameObject => gameObject.GetComponent <CharacterClassManager>()).Where(chrClassManager => chrClassManager.Classes.CheckBounds(chrClassManager.CurClass)))
                {
                    // ReSharper disable once SwitchStatementHandlesSomeKnownEnumValuesWithDefault
                    switch (chrClassManager.Classes.SafeGet(chrClassManager.CurClass).team)
                    {
                    case Team.SCP:
                        if (chrClassManager.CurClass == RoleType.Scp0492)
                        {
                            newList.zombies++;
                            continue;
                        }

                        newList.scps_except_zombies++;
                        continue;

                    case Team.MTF:
                        newList.mtf_and_guards++;
                        continue;

                    case Team.CHI:
                        newList.chaos_insurgents++;
                        continue;

                    case Team.RSC:
                        newList.scientists++;
                        continue;

                    case Team.CDP:
                        newList.class_ds++;
                        continue;

                    default:
                        continue;
                    }
                }

                newList.warhead_kills =
                    AlphaWarheadController.Host.detonated ? AlphaWarheadController.Host.warheadKills : -1;

                yield return(float.NegativeInfinity);

                newList.time = (int)Time.realtimeSinceStartup;
                yield return(float.NegativeInfinity);

                RoundSummary.roundTime = newList.time - roundSummary.classlistStart.time;

                var mtfSum   = newList.mtf_and_guards + newList.scientists;
                var chaosSum = newList.chaos_insurgents + newList.class_ds;
                var scpSum   = newList.scps_except_zombies + newList.zombies;

                var escapedDs         = (float)(roundSummary.classlistStart.class_ds == 0 ? 0 : (RoundSummary.escaped_ds + newList.class_ds) / roundSummary.classlistStart.class_ds);
                var escapedScientists = (float)(roundSummary.classlistStart.scientists == 0 ? 1 : (RoundSummary.escaped_scientists + newList.scientists) / roundSummary.classlistStart.scientists);

                var allow       = true;
                var forceEnd    = false;
                var teamChanged = false;
                var team        = RoundSummary.LeadingTeam.Draw;

                try
                {
                    Events.InvokeCheckRoundEnd(ref forceEnd, ref allow, ref team, ref teamChanged);
                }
                catch (Exception e)
                {
                    Log.Error($"CheckRoundEnd err: {e}");
                    continue;
                }

                if (forceEnd)
                {
                    roundSummary._roundEnded = true;
                }

                if (!allow)
                {
                    continue;
                }

                if (newList.class_ds == 0 && mtfSum == 0)
                {
                    roundSummary._roundEnded = true;
                }

                else if (mtfSum == 0 && Respawning.RespawnTickets.Singleton.GetAvailableTickets(Respawning.SpawnableTeamType.NineTailedFox) == 0)
                {
                    roundSummary._roundEnded = true;
                }

                else
                {
                    //Okay. SCP hat hier einfach wirklich nur Staub gefressen oder so.
                    var checkVar = 0;

                    if (mtfSum > 0)
                    {
                        checkVar++;
                    }
                    if (chaosSum > 0)
                    {
                        checkVar++;
                    }
                    if (scpSum > 0)
                    {
                        checkVar++;
                    }

                    if (checkVar <= 1)
                    {
                        roundSummary._roundEnded = true;
                    }
                }


                if (!roundSummary._roundEnded)
                {
                    continue;
                }
                var leadingTeam = RoundSummary.LeadingTeam.Draw;

                if (mtfSum > 0)
                {
                    if (RoundSummary.escaped_ds == 0 && RoundSummary.escaped_scientists != 0)
                    {
                        leadingTeam = RoundSummary.LeadingTeam.FacilityForces;
                    }
                }
                else
                {
                    leadingTeam = RoundSummary.escaped_ds != 0
                        ? RoundSummary.LeadingTeam.ChaosInsurgency
                        : RoundSummary.LeadingTeam.Anomalies;
                }

                if (teamChanged)
                {
                    leadingTeam = team;
                }

                var text = $"Round finished! Anomalies:{scpSum} | Chaos: {chaosSum} | Facility Forces: {mtfSum} | D escaped percentage: {escapedDs} | S escaped percentage: {escapedScientists}";

                GameCore.Console.AddLog(text, Color.gray);
                ServerLogs.AddLog(ServerLogs.Modules.Logger, text, ServerLogs.ServerLogType.GameEvent);

                for (byte i = 0; i < 75; i += 1)
                {
                    yield return(0f);
                }
                var timeToRoundRestart = Mathf.Clamp(ConfigFile.ServerConfig.GetInt("auto_round_restart_time", 10), 5, 1000);
                if (roundSummary != null)
                {
                    roundSummary.RpcShowRoundSummary(roundSummary.classlistStart, newList, leadingTeam, RoundSummary.escaped_ds, RoundSummary.escaped_scientists, RoundSummary.kills_by_scp, timeToRoundRestart);
                }
                int num7;
                for (var j = 0; j < 50 * (timeToRoundRestart - 1); j = num7 + 1)
                {
                    yield return(0f);

                    num7 = j;
                }
                roundSummary.RpcDimScreen();
                for (byte i = 0; i < 50; i += 1)
                {
                    yield return(0f);
                }
                PlayerManager.localPlayer.GetComponent <PlayerStats>().Roundrestart();
            }
        }
Пример #30
0
        private static IEnumerator<float> Process(RoundSummary roundSummary)
        {
            float time = Time.unscaledTime;
            while (roundSummary is not null)
            {
                yield return Timing.WaitForSeconds(2.5f);

                while (RoundSummary.RoundLock || !RoundSummary.RoundInProgress() || Time.unscaledTime - time < 15f || (roundSummary._keepRoundOnOne && PlayerManager.players.Count < 2))
                    yield return Timing.WaitForOneFrame;

                RoundSummary.SumInfo_ClassList newList = default;
                foreach (KeyValuePair<GameObject, ReferenceHub> keyValuePair in ReferenceHub.GetAllHubs())
                {
                    if (keyValuePair.Value is null)
                        continue;

                    CharacterClassManager component = keyValuePair.Value.characterClassManager;
                    if (component.Classes.CheckBounds(component.CurClass))
                    {
                        switch (component.CurRole.team)
                        {
                            case Team.SCP:
                                if (component.CurClass == RoleType.Scp0492)
                                    newList.zombies++;
                                else
                                    newList.scps_except_zombies++;
                                continue;
                            case Team.MTF:
                                newList.mtf_and_guards++;
                                continue;
                            case Team.CHI:
                                newList.chaos_insurgents++;
                                continue;
                            case Team.RSC:
                                newList.scientists++;
                                continue;
                            case Team.CDP:
                                newList.class_ds++;
                                continue;
                            default:
                                continue;
                        }
                    }
                }

                yield return Timing.WaitForOneFrame;
                newList.warhead_kills = AlphaWarheadController.Host.detonated ? AlphaWarheadController.Host.warheadKills : -1;
                yield return Timing.WaitForOneFrame;
                newList.time = (int)Time.realtimeSinceStartup;
                yield return Timing.WaitForOneFrame;
                RoundSummary.roundTime = newList.time - roundSummary.classlistStart.time;
                int num1 = newList.mtf_and_guards + newList.scientists;
                int num2 = newList.chaos_insurgents + newList.class_ds;
                int num3 = newList.scps_except_zombies + newList.zombies;
                int num4 = newList.class_ds + RoundSummary.EscapedClassD;
                int num5 = newList.scientists + RoundSummary.EscapedScientists;
                float num6 = (roundSummary.classlistStart.class_ds == 0) ? 0f : (num4 / roundSummary.classlistStart.class_ds);
                float num7 = (roundSummary.classlistStart.scientists == 0) ? 1f : (num5 / roundSummary.classlistStart.scientists);

                RoundSummary.SurvivingSCPs = newList.scps_except_zombies;

                if (newList.class_ds <= 0 && num1 <= 0)
                {
                    roundSummary.RoundEnded = true;
                }
                else
                {
                    int num8 = 0;
                    if (num1 > 0)
                        num8++;
                    if (num2 > 0)
                        num8++;
                    if (num3 > 0)
                        num8++;
                    if (num8 <= 1)
                        roundSummary.RoundEnded = true;
                }

                EndingRoundEventArgs endingRoundEventArgs = new(LeadingTeam.Draw, newList, roundSummary.RoundEnded);

                if (num1 > 0)
                    endingRoundEventArgs.LeadingTeam = RoundSummary.EscapedScientists >= RoundSummary.EscapedClassD ? LeadingTeam.FacilityForces : LeadingTeam.Draw;
                else if (num3 > 0)
                    endingRoundEventArgs.LeadingTeam = RoundSummary.EscapedClassD > RoundSummary.SurvivingSCPs ? LeadingTeam.ChaosInsurgency : (RoundSummary.SurvivingSCPs > RoundSummary.EscapedScientists ? LeadingTeam.Anomalies : LeadingTeam.Draw);
                else if (num2 > 0)
                    endingRoundEventArgs.LeadingTeam = RoundSummary.EscapedClassD >= RoundSummary.EscapedScientists ? LeadingTeam.ChaosInsurgency : LeadingTeam.Draw;

                Server.OnEndingRound(endingRoundEventArgs);

                roundSummary.RoundEnded = endingRoundEventArgs.IsRoundEnded && endingRoundEventArgs.IsAllowed;

                if (roundSummary.RoundEnded)
                {
                    FriendlyFireConfig.PauseDetector = true;
                    string str = "Round finished! Anomalies: " + num3 + " | Chaos: " + num2 + " | Facility Forces: " + num1 + " | D escaped percentage: " + num6 + " | S escaped percentage: : " + num7;
                    Console.AddLog(str, Color.gray, false);
                    ServerLogs.AddLog(ServerLogs.Modules.Logger, str, ServerLogs.ServerLogType.GameEvent);
                    yield return Timing.WaitForSeconds(1.5f);
                    int timeToRoundRestart = Mathf.Clamp(ConfigFile.ServerConfig.GetInt("auto_round_restart_time", 10), 5, 1000);

                    if (roundSummary is not null)
                    {
                        RoundEndedEventArgs roundEndedEventArgs = new(endingRoundEventArgs.LeadingTeam, newList, timeToRoundRestart);

                        Server.OnRoundEnded(roundEndedEventArgs);

                        roundSummary.RpcShowRoundSummary(roundSummary.classlistStart, roundEndedEventArgs.ClassList, (RoundSummary.LeadingTeam)roundEndedEventArgs.LeadingTeam, RoundSummary.EscapedClassD, RoundSummary.EscapedScientists, RoundSummary.KilledBySCPs, roundEndedEventArgs.TimeToRestart);
                    }

                    yield return Timing.WaitForSeconds(timeToRoundRestart - 1);
                    roundSummary.RpcDimScreen();
                    yield return Timing.WaitForSeconds(1f);
                    RoundRestart.InitiateRoundRestart();
                    yield break;
                }
            }
        }