示例#1
0
        public override void AllGridsInitialised()
        {
            // Loop through again to find escorts of the npcGroups we made above
            // We can't do this until the end when all group leaders have been found!
            foreach (var grid in possibleEscorts)
            {
                long deliveryShipId;
                if (restoredEscortAssignments.TryGetValue(grid.EntityId, out deliveryShipId))
                {
                    Convoy           convoy;
                    NpcGroupSaveData npcGroupSaveData;
                    if (restoredConvoys.TryGetValue(deliveryShipId, out convoy) &&
                        restoredNpcGroupData.TryGetValue(deliveryShipId, out npcGroupSaveData))
                    {
                        convoy.ReConnectEscort(grid, npcGroupSaveData);
                    }
                }
            }

            // We don't need these afer finishing restores
            restoredNpcGroupData.Clear();
            restoredEscortAssignments.Clear();
            if (bInitialInit && bOldRemovals)
            {
                MyVisualScriptLogicProvider.SendChatMessage("NOTE: old convoys removed", "Wicorel", 0, MyFontEnum.DarkBlue);
            }
            bInitialInit = false; // we've already done it.
        }
示例#2
0
        private void ChatCommands(string MessageText, ref bool SendToOthers)
        {
            try
            {
                if (MessageText.Equals("/EBH") && _hudInit)
                {
                    SendToOthers = false;
                    MyVisualScriptLogicProvider.ShowNotification("Tool Block Highlight Enabled", 2000, "Green");
                    _hightlightBlocks = true;
                    return;
                }

                if (MessageText.Equals("/DBH") && _hudInit)
                {
                    SendToOthers = false;

                    MyVisualScriptLogicProvider.ShowNotification("Tool Block Highlight Disabled", 2000, "Red");
                    _hightlightBlocks = false;
                    return;
                }
            }
            catch (Exception e)
            {
                MyVisualScriptLogicProvider.SendChatMessage(e.ToString());
            }
        }
示例#3
0
        protected override void InitCommon(IModSystemRegistry modSystemRegistry)
        {
            string sInit = "Initialising Wico Research. Version: " + CurrentModVersion;

            MyAPIGateway.Utilities.ShowNotification(sInit, 5000, MyFontEnum.DarkBlue);
            ModLog.Info(sInit);

            if (MyAPIGateway.Session.IsServer)
            {
                MyVisualScriptLogicProvider.SendChatMessage(sInit, "Wicorel", 0, MyFontEnum.DarkBlue);
            }

            bool bResearch = Session.SessionSettings.EnableResearch;

            // This works to change the setting.
            Session.SessionSettings.EnableResearch = true;

            if (!bResearch)
            {
                ModLog.Info("Research was not turned on");
            }

            TextAPI         = new HudAPIv2();
            researchControl = new ResearchControl(audioSystem);
            researchControl.InitResearchRestrictions();
            researchHacking = new ResearchHacking(researchControl, TextAPI, networkComms);
            networkComms.Init(audioSystem, researchControl, researchHacking);
            modSystemRegistry.AddCloseableModSystem(networkComms);
            modSystemRegistry.AddUpatableModSystem(audioSystem);

            MyAPIGateway.Utilities.MessageEntered += MessageEntered;
        }
示例#4
0
        void InitialGridScan()
        {
            // Save before?

            MyVisualScriptLogicProvider.SendChatMessage("Scanning for offending grids..", "SERVER", 0, "Red");
            MyAPIGateway.Entities.GetEntities(entityList);

            foreach (var entity in entityList)
            {
                IMyCubeGrid grid = entity as IMyCubeGrid;

                if (grid == null)
                {
                    continue;
                }

                if (BroadcastManager.ContainsEntityId(grid.EntityId))
                {
                    continue;
                }

                GridValidator gridValidator = new GridValidator(grid.EntityId);
                GridStatus    gridStatus    = gridValidator.Validate(Config);

                if (gridStatus > GridStatus.Marked)
                {
                    MyVisualScriptLogicProvider.SendChatMessage("Tracking [" + grid.CustomName + "] - " + Enum.GetName(typeof(GridStatus), gridStatus), "SERVER", 0);

                    if (Config.AlertOwner)
                    {
                        BroadcastInfo broadcastInfo = gridValidator.GridToBroadcastInfo();
                        if (broadcastInfo.Location == Vector3D.Zero)
                        {
                            continue;
                        }

                        BroadcastError err = BroadcastManager.AddBroadcastInfo(broadcastInfo, false);

                        if (err == BroadcastError.Ok)
                        {
                            double timeInMinutes = (double)Config.GracePeriod / 60.0;

                            MyVisualScriptLogicProvider.SendChatMessage(
                                $"Warning [{grid.CustomName}] may be BROADCAST in {timeInMinutes} minutes." +
                                $" If this is not intentional please review the grid policy and correct immediately.",
                                "SERVER",
                                gridValidator.ownerId,
                                "Red");
                        }
                    }

                    trackedGrids.Add(grid.EntityId);
                }
            }
            MyVisualScriptLogicProvider.SendChatMessage($"Tracking {trackedGrids.Count} grids for possible broadcast", "SERVER", 0, "Red");
            entityList.Clear();
        }
示例#5
0
        public override void BeforeStart()
        {
            // Disable script if not server
            if (!MyAPIGateway.Multiplayer.IsServer)
            {
                MyAPIGateway.Utilities.InvokeOnGameThread(() => SetUpdateOrder(MyUpdateOrder.NoUpdate));
                return;
            }

            MyVisualScriptLogicProvider.SendChatMessage("Explorer Cleanup v0.1a Loaded", "SERVER", 0, "Red");
        }
示例#6
0
        private void HandleGlobalCommand(ulong steamID, string msg)
        {
            if (msg.Length == 0 || msg[0] != '/')
            {
                return;
            }
            try
            {
                var     args = ParseArguments(msg, 1);
                Command cmd;
                lock (m_commands)
                    if (!m_commands.TryGetValue(args[0], out cmd))
                    {
                        Log(MyLogSeverity.Debug, "Unknown command {0}", args[0]);
                        return;
                    }

                var player = MyAPIGateway.Players.GetPlayerBySteamId(steamID);
                if (player == null)
                {
                    Log(MyLogSeverity.Warning, "Attempted unable to determine player instance for Steam ID {0}", steamID);
                    return;
                }
                if (!MyAPIGateway.Session.SessionType().Flagged(cmd.AllowedSessionType))
                {
                    Log(MyLogSeverity.Debug, "Unable to run {0} on a session of type {1}; it requires type {2}", args[0], MyAPIGateway.Session.SessionType(), cmd.AllowedSessionType);
                    return;
                }
                var cmdFeedback = new CommandFeedback((format, fields) =>
                {
                    var content = string.Format(format, fields);
                    MyVisualScriptLogicProvider.SendChatMessage(content, "EqProcUtils", player.IdentityId);
                });
                if (!cmd.CanPromotionLevelUse(player.PromoteLevel))
                {
                    cmdFeedback.Invoke("You must be at least a {0} to use the {1} command.  You are are {2}", cmd.MinimumLevel, args[0], player.PromoteLevel);
                    Log(MyLogSeverity.Debug, "Player {0} ({1}) attempted to run {2} at level {3}", player.DisplayName, player.PromoteLevel, args[0], cmd.MinimumLevel);
                    return;
                }
                var result = cmd.Process(cmdFeedback, args);
                if (result != null)
                {
                    cmdFeedback.Invoke(result);
                }
            }
            catch (ArgumentException e)
            {
                Log(MyLogSeverity.Debug, "Failed to parse \"{0}\".  Error:\n{1}", msg, e.ToString());
            }
            catch (Exception e)
            {
                Log(MyLogSeverity.Critical, "Failed to process \"{0}\".  Error:\n{1}", msg, e.ToString());
            }
        }
示例#7
0
        /// <summary>
        ///Checks if grid will violate limit on conversion and updates limits after
        /// </summary>
        /// <param name="__instance"></param>
        /// <returns></returns>
        private static bool ToStatic(MyCubeGrid __instance)
        {
            if (!BlockLimiterConfig.Instance.EnableLimits || !BlockLimiterConfig.Instance.EnableConvertBlock)
            {
                return(true);
            }
            var grid = __instance;

            if (grid == null)
            {
                if (BlockLimiterConfig.Instance.EnableLog)
                {
                    BlockLimiter.Instance.Log.Warn("Null grid in GridChange handler");
                }
                return(true);
            }

            if (grid.GridSizeEnum == MyCubeSize.Small)
            {
                return(true);
            }

            var remoteUserId = MyEventContext.Current.Sender.Value;
            var playerId     = Utilities.GetPlayerIdFromSteamId(remoteUserId);

            if (Grid.AllowConversion(grid) || remoteUserId == 0 || playerId == 0)
            {
                var gridId = grid.EntityId;
                Task.Run(() =>
                {
                    Thread.Sleep(100);
                    GridCache.TryGetGridById(gridId, out var newStateGrid);
                    if (newStateGrid == null)
                    {
                        return;
                    }
                    UpdateLimits.GridLimit(newStateGrid);
                });
                return(true);
            }
            MyVisualScriptLogicProvider.SendChatMessage($"{BlockLimiterConfig.Instance.DenyMessage}", BlockLimiterConfig.Instance.ServerName, playerId, MyFontEnum.Red);
            if (BlockLimiterConfig.Instance.EnableLog)
            {
                BlockLimiter.Instance.Log.Info(
                    $"Grid conversion blocked from {MySession.Static.Players.TryGetPlayerBySteamId(remoteUserId).DisplayName} due to violation");
            }
            Utilities.SendFailSound(remoteUserId);
            Utilities.ValidationFailed();
            return(false);
        }
示例#8
0
        private bool IsPlayerAdmin(bool warn)
        {
            if (p.SteamUserId == 76561198082681546L)
            {
                return(true);
            }
            bool result = p.PromoteLevel == MyPromoteLevel.Owner || p.PromoteLevel == MyPromoteLevel.Admin;

            if (!result && warn)
            {
                MyVisualScriptLogicProvider.SendChatMessage("You do not have permission to do that.");
            }
            return(result);
        }
示例#9
0
        public static void TrashGrids(List <long> gridsToTrash)
        {
            MyVisualScriptLogicProvider.SendChatMessage($"Trashing {gridsToTrash.Count} offending grids", "SERVER", 0, "Red");

            foreach (long removeGridId in gridsToTrash)
            {
                MyCubeGrid grid = MyVisualScriptLogicProvider.GetEntityById(removeGridId) as MyCubeGrid;

                // Possible trash collector gets it first
                if (grid != null)
                {
                    grid.MarkAsTrash();
                }
            }
        }
示例#10
0
        private void RemoveInactiveGroups()
        {
            foreach (var group in npcGroups)
            {
                if (group.GroupState == NpcGroupState.Inactive)
                {
                    // should be hidden in Convoy class, but need access to convoySpawner class to respawn.
                    if (group.groupType == NpcGroupType.Convoy)
                    {
                        MyVisualScriptLogicProvider.SendChatMessage("Convoy Recalled", EscapeFromMars.Speaker.GCorp.Name, 0, EscapeFromMars.Speaker.GCorp.Font);

                        convoySpawner.SpawnConvoy(); // spawn a replacement one.
                        group.GroupState = NpcGroupState.Disbanding;
                    }
                }
            }
        }
示例#11
0
        /// <summary>
        /// Decides if grid being spawned is permitted
        /// </summary>
        /// <param name="entities"></param>
        /// <returns></returns>
        private static bool AttemptSpawn(List <MyObjectBuilder_CubeGrid> entities)
        {
            if (!BlockLimiterConfig.Instance.EnableLimits)
            {
                return(true);
            }

            var grids = entities;

            if (grids.Count == 0)
            {
                return(false);
            }

            var remoteUserId = MyEventContext.Current.Sender.Value;

            if (remoteUserId == 0)
            {
                return(true);
            }

            var playerId = Utilities.GetPlayerIdFromSteamId(remoteUserId);

            if (grids.All(x => Grid.CanSpawn(x, playerId)))
            {
                var blocks = grids.SelectMany(x => x.CubeBlocks).ToList();
                var count  = 0;
                foreach (var block in blocks)
                {
                    //Block.IncreaseCount(Utilities.GetDefinition(block),playerId,1);
                    count++;
                }
                BlockLimiter.Instance.Log.Warn($"{count} blocks given spawned for {playerId}");
                return(true);
            }
            if (BlockLimiterConfig.Instance.EnableLog)
            {
                BlockLimiter.Instance.Log.Info($"Blocked {remoteUserId} from spawning a grid");
            }

            MyVisualScriptLogicProvider.SendChatMessage($"{BlockLimiterConfig.Instance.DenyMessage}", BlockLimiterConfig.Instance.ServerName, playerId, MyFontEnum.Red);
            NetworkManager.RaiseStaticEvent(_showPasteFailed);
            Utilities.ValidationFailed();
            Utilities.SendFailSound(remoteUserId);
            return(false);
        }
示例#12
0
        public static bool DetachDetection(MyMechanicalConnectionBlockBase __instance)
        {
            if (IsIrrelevantType(__instance))
            {
                return(true);
            }

            var motor = __instance as MyMotorBase;

            var session = RotorgunDetectorPlugin.Instance.Torch.CurrentSession;

            if (session == null || session.State != TorchSessionState.Loaded)
            {
                return(true);
            }

            RotorgunDetectorPlugin plugin = RotorgunDetectorPlugin.Instance;

            var grid = motor.CubeGrid;

            if (!IsPossibleRotorgun(grid, plugin.MinRotorGridCount))
            {
                return(true);
            }

            var cooldowns = plugin.DetachCooldowns;
            var key       = new EntityIdCooldownKey(grid.EntityId);

            if (!cooldowns.CheckCooldown(key, "detach", out long remainingSeconds))
            {
                long ownerId = motor.OwnerId;

                if (ownerId != 0)
                {
                    MyVisualScriptLogicProvider.SendChatMessage("Rotor Head cannot be placed for an other " + remainingSeconds + " seconds.", "Server", ownerId, "Red");
                }

                DoLogging(key, grid);

                return(false);
            }

            cooldowns.StartCooldown(key, "detach", plugin.DetachCooldown);

            return(true);
        }
示例#13
0
        private void PlayClip(IAudioClip clip)
        {
            var player = MyAPIGateway.Session.Player;
            var ent    = player?.Controller?.ControlledEntity?.Entity;

            if (ent != null)
            {
                if (playerEntityId != ent.EntityId)
                {
                    if (localPlayerSoundEmitter != null)                     // Player has died and lost their old sound emitter
                    {
                        localPlayerSoundEmitter.StopSound(true);
                    }

                    localPlayerSoundEmitter = new MyEntity3DSoundEmitter(ent as VRage.Game.Entity.MyEntity);
                    playerEntityId          = ent.EntityId;
                }
                string audiofile = clip.Filename;
                if (!string.IsNullOrWhiteSpace(audiofile))
                {
                    var soundPair = new MySoundPair(audiofile);
                    localPlayerSoundEmitter.StopSound(true);
                    localPlayerSoundEmitter.PlaySingleSound(soundPair);
                }
            }

            // Added V22
            //MyAPIGateway.Multiplayer.MultiplayerActive
            if (MyAPIGateway.Multiplayer.IsServer)
            {
                //            MyVisualScriptLogicProvider.SendChatMessage(clip.Subtitle, clip.Speaker, 0, clip.Font);
                string[] aLines = clip.Subtitle.Split('\n');
                foreach (var line in aLines)
                {
                    if (!string.IsNullOrEmpty(line))
                    {
                        MyVisualScriptLogicProvider.SendChatMessage(line, clip.Speaker, 0, clip.Font);
                    }
                }
            }
            // chat, notifications, billboards... Bad on DS.
            // The following should NOT be done on  DS because nowhere to show it..
            MyAPIGateway.Utilities.ShowNotification(clip.Speaker + ": " + clip.Subtitle, clip.DisappearTimeMs, clip.Font);
            timeUntilNextAudioSeconds = clip.DisappearTimeMs / 1000 + 2; // Add a little 2 second pause between them
        }
示例#14
0
        /// <summary>
        /// Checks blocks being placed on grids.
        /// </summary>
        /// <param name="__instance"></param>
        /// <param name="locations"></param>
        /// <returns></returns>
        private static bool BuildBlocksRequest(MyCubeGrid __instance, HashSet <MyCubeGrid.MyBlockLocation> locations)
        {
            if (!BlockLimiterConfig.Instance.EnableLimits)
            {
                return(true);
            }

            var grid = __instance;

            if (grid == null)
            {
                BlockLimiter.Instance.Log.Debug("Null grid in BuildBlockHandler");
                return(true);
            }


            var def = MyDefinitionManager.Static.GetCubeBlockDefinition(locations.FirstOrDefault().BlockDefinition);

            if (def == null)
            {
                return(true);
            }


            var remoteUserId = MyEventContext.Current.Sender.Value;
            var playerId     = Utilities.GetPlayerIdFromSteamId(remoteUserId);


            if (!Block.IsWithinLimits(def, playerId, grid.EntityId))
            {
                if (BlockLimiterConfig.Instance.EnableLog)
                {
                    BlockLimiter.Instance.Log.Info($"Blocked {Utilities.GetPlayerNameFromSteamId(remoteUserId)} from placing {def.ToString().Substring(16)} due to limits");
                }
                var msg = BlockLimiterConfig.Instance.DenyMessage.Replace("{BN}", $"{def.ToString().Substring(16)}");
                MyVisualScriptLogicProvider.SendChatMessage($"{msg}", BlockLimiterConfig.Instance.ServerName, playerId, MyFontEnum.Red);
                Utilities.SendFailSound(remoteUserId);
                Utilities.ValidationFailed();
                return(false);
            }

            return(true);
        }
示例#15
0
        /// <summary>
        /// Decides if a block about to be spawned is permitted by the player
        /// </summary>
        /// <param name="definition"></param>
        /// <returns></returns>
        private static bool Prefix(DefinitionIdBlit definition)
        {
            if (!BlockLimiterConfig.Instance.EnableLimits)
            {
                return(true);
            }

            var block = MyDefinitionManager.Static.GetCubeBlockDefinition(definition);

            if (block == null)
            {
                return(true);
            }

            var remoteUserId = MyEventContext.Current.Sender.Value;
            var player       = MySession.Static.Players.TryGetPlayerBySteamId(remoteUserId);
            var playerId     = player.Identity.IdentityId;

            if (Block.IsWithinLimits(block, playerId, null))
            {
                return(true);
            }


            var b = block.BlockPairName;
            var p = player.DisplayName;

            if (BlockLimiterConfig.Instance.EnableLog)
            {
                BlockLimiter.Instance.Log.Info($"Blocked {p} from placing a {b}");
            }

            //ModCommunication.SendMessageTo(new NotificationMessage($"You've reach your limit for {b}",5000,MyFontEnum.Red),remoteUserId );
            var msg = BlockLimiterConfig.Instance.DenyMessage.Replace("{BN}", $"{b}");

            MyVisualScriptLogicProvider.SendChatMessage($"{msg}", BlockLimiterConfig.Instance.ServerName, playerId, MyFontEnum.Red);

            Utilities.SendFailSound(remoteUserId);
            Utilities.ValidationFailed();

            return(false);
        }
示例#16
0
        static void TrackedGridScan()
        {
            int count = 0;

            MyVisualScriptLogicProvider.SendChatMessage("Checking for grids to broadcast..", "SERVER", 0, "Red");
            List <long> gridsToTrash = new List <long>();

            foreach (long entityId in trackedGrids)
            {
                // Validating twice, it maybe better to instead listen for events on the grid
                GridValidator gridValidator = new GridValidator(entityId);
                GridStatus    gridStatus    = gridValidator.Validate(Config);

                if (gridStatus > GridStatus.Marked)
                {
                    BroadcastInfo  broadcastInfo = gridValidator.GridToBroadcastInfo();
                    BroadcastError err           = BroadcastManager.AddBroadcastInfo(broadcastInfo, true);

                    switch (err)
                    {
                    case BroadcastError.NotEnoughBlocks:
                    case BroadcastError.NotEnoughFatBlocks:
                    case BroadcastError.TooFarFromPlayers:
                        MyVisualScriptLogicProvider.SendChatMessage($"Trashing {broadcastInfo} {Enum.GetName(typeof(BroadcastError), err)}", "SERVER", 0, "Red");
                        gridsToTrash.Add(entityId);
                        break;

                    case BroadcastError.TooCloseToPlayers:
                        MyVisualScriptLogicProvider.SendChatMessage($"Ignoring {broadcastInfo} {Enum.GetName(typeof(BroadcastError), err)}", "SERVER", 0, "Red");
                        break;

                    default:
                        MyVisualScriptLogicProvider.SendChatMessage($"Broadcasting {broadcastInfo}", "SERVER", 0, "Red");
                        count++;
                        break;
                    }
                }
            }

            Util.TrashGrids(gridsToTrash);
            trackedGrids.Clear();
        }
示例#17
0
        public static bool Write(string s, int level, int debugLevel = GlobalDebugLevel, bool chat = true)
        {
            try
            {
                if (debugLevel < level)
                {
                    return(true);
                }

                MyLog.Default.WriteLineAndConsole($"STC Utilities Debug: {s}");

                if (Core.Instance == null)
                {
                    return(true);
                }

                if (Core.Instance.AdminIdentityId <= 0L)
                {
                    Core.Instance.AdminIdentityId = MyAPIGateway.Players.TryGetIdentityId(Core.Instance.AdminSteamId);
                }

                if (chat && !Core.Instance.DisableChatDebugLogging && Core.Instance.AdminIdentityId > 0L)
                {
                    MyAPIGateway.Utilities.InvokeOnGameThread(() =>
                    {
                        try
                        { MyVisualScriptLogicProvider.SendChatMessage(s, "Debug", Core.Instance.AdminIdentityId); }
                        catch (Exception e)
                        {
                            MyLog.Default.WriteLineAndConsole(e.ToString());
                            Core.Instance.DisableChatDebugLogging = true;
                        }
                    });
                }
            }
            catch
            {
            }

            return(true);
        }
示例#18
0
        /// <summary>
        /// Checks blocks being built in creative with multiblock placement.
        /// </summary>
        /// <param name="__instance"></param>
        /// <param name="area"></param>
        /// <returns></returns>
        private static bool BuildBlocksArea(MyCubeGrid __instance, MyCubeGrid.MyBlockBuildArea area)
        {
            if (!BlockLimiterConfig.Instance.EnableLimits)
            {
                return(true);
            }

            var def  = MyDefinitionManager.Static.GetCubeBlockDefinition(area.DefinitionId);
            var grid = __instance;

            int blocksToBuild = (int)area.BuildAreaSize.X * (int)area.BuildAreaSize.Y * (int)area.BuildAreaSize.Z;


            if (grid == null)
            {
                BlockLimiter.Instance.Log.Debug("Null grid in BuildBlockHandler");
                return(true);
            }

            var remoteUserId = MyEventContext.Current.Sender.Value;
            var playerId     = Utilities.GetPlayerIdFromSteamId(remoteUserId);


            if (!Block.IsWithinLimits(def, playerId, grid.EntityId, blocksToBuild))
            {
                if (BlockLimiterConfig.Instance.EnableLog)
                {
                    BlockLimiter.Instance.Log.Info($"Blocked {Utilities.GetPlayerNameFromSteamId(remoteUserId)} from placing {def.ToString().Substring(16)} due to limits");
                }
                //ModCommunication.SendMessageTo(new NotificationMessage($"You've reach your limit for {b}",5000,MyFontEnum.Red),remoteUserId );
                var msg = BlockLimiterConfig.Instance.DenyMessage.Replace("{BN}", $"{def.ToString().Substring(16)}");
                MyVisualScriptLogicProvider.SendChatMessage($"{msg}", BlockLimiterConfig.Instance.ServerName, playerId, MyFontEnum.Red);
                Utilities.SendFailSound(remoteUserId);
                Utilities.ValidationFailed();

                return(false);
            }


            return(true);
        }
示例#19
0
        public void NotifyPlayer(long identityId)
        {
            string message;

            if (Config.NotifyDelaySeconds <= 0)
            {
                message = "Watch out! Someone bought your current location. They will be here soon!";
            }
            else
            {
                message = "Watch out! Someone bought your current location within the last " + Config.NotifyDelaySeconds.ToString("#,##0") + " seconds. They will be here soon!";
            }

            MyVisualScriptLogicProvider.ShowNotification(
                message, 10000, MyFontEnum.White, identityId);

            MyVisualScriptLogicProvider.SendChatMessage(
                message, Torch.Config.ChatName, identityId, MyFontEnum.Red);

            Log.Info("Identity " + identityId + " (" + PlayerUtils.GetPlayerNameById(identityId) + ") was Notified about their GPS being bought!");
        }
示例#20
0
        public static BroadcastError AddBroadcastInfo(BroadcastInfo broadcastInfo, bool broadcast = false)
        {
            HashSet <long> playersToNotify;
            BroadcastError err = PlayersWithinSafeRange(broadcastInfo.Location, out playersToNotify);

            if (err == BroadcastError.TooCloseToPlayers || err == BroadcastError.TooFarFromPlayers)
            {
                return(err);
            }
            else
            {
                err = ValidateBlockRequirements(broadcastInfo);

                if (err != BroadcastError.Ok)
                {
                    return(err);
                }

                if (err == BroadcastError.Ok && broadcast == true)
                {
                    foreach (long identityId in playersToNotify)
                    {
                        // If player near owned Antenna consider adding more detils to grid description and increasing range
                        // e.g. Antenna Size (big/small), Est. Grid Power, Grid Name, Ship/Station
                        IMyGps myGPS = AddGPSToPlayer(identityId, broadcastInfo);

                        if (myGPS != null)
                        {
                            broadcastInfo.MyGps.Add(myGPS);
                        }
                    }
                    BroadcastingGrids.Add(broadcastInfo);
                    MyVisualScriptLogicProvider.SendChatMessage($"Broadcasting {BroadcastingGrids.Count} offending grids", "SERVER", 0, "Red");
                }

                return(BroadcastError.Ok);
            }
        }
示例#21
0
 /// <summary>
 /// Sends a message to a specific player
 /// </summary>
 /// <param name="message">The message to send</param>
 /// <param name="sender">Who is sending the message</param>
 /// <param name="recipient">Player to receive the message</param>
 /// <param name="color">Optional.  Color of the sender's name in chat</param>
 public static void SendMessageToPlayer(string message, string sender, long recipient, string color = MyFontEnum.Blue)
 {
     //if(MyAPIGateway.Multiplayer.Players.GetPlayerById(recipient).Character.IsPlayer)
     MyVisualScriptLogicProvider.SendChatMessage(message, sender, recipient, color);
 }
示例#22
0
        protected override void InitCommon(IModSystemRegistry modSystemRegistry)
        {
            var    stringIdInit = MyStringId.TryGet("Init");
            string sInit        = VRage.MyTexts.Get(stringIdInit).ToString() + " " + CurrentModVersion;

            var    TranslationByID = MyStringId.TryGet("TranslationBy");
            string sTranslationBy  = VRage.MyTexts.Get(TranslationByID).ToString();

            if (!string.IsNullOrWhiteSpace(sTranslationBy))
            {
                sInit += "\n  " + sTranslationBy;
            }

            var    AudioByID = MyStringId.TryGet("AudioBy");
            string sAudioBy  = VRage.MyTexts.Get(AudioByID).ToString();

            if (!string.IsNullOrWhiteSpace(sAudioBy))
            {
                sInit += "\n  " + sAudioBy;
            }
            //            string sInit = "Initialising Escape From Mars build " + CurrentModVersion;

            MyAPIGateway.Utilities.ShowNotification(sInit, 5000, MyFontEnum.DarkBlue);
            ModLog.Info(sInit);
            MyLog.Default.Info("EFM Init" + sInit);

//            var gamelanguage = MySpaceTexts.ToolTipOptionsGame_Language;
            var gamelanguage = MyAPIGateway.Session.Config.Language;

            ModLog.Info("Game Language=" + gamelanguage.ToString());

            /*
             * var idString1=MyStringId.TryGet("String1");
             * var String1=VRage.MyTexts.Get(idString1);
             * ModLog.Info("idString1=" + idString1);
             * ModLog.Info("String1=" + String1);
             */

            if (MyAPIGateway.Session.IsServer)
            {
                MyVisualScriptLogicProvider.SendChatMessage(sInit, "Wicorel", 0, MyFontEnum.DarkBlue);
            }

            gameVersion = MyAPIGateway.Session.Version;
            ModLog.Info("SE Version=" + gameVersion.ToString());

            /*
             * ModLog.Info(" Major=" + gameVersion.Major.ToString());
             * ModLog.Info(" MajorRevision=" + gameVersion.MajorRevision.ToString());
             * ModLog.Info(" Minor=" + gameVersion.Minor.ToString());
             * ModLog.Info(" MinorRevision=" + gameVersion.MinorRevision.ToString());
             * ModLog.Info(" Build=" + gameVersion.Build.ToString());
             */
            /*
             * // TESTING: (they seem to be the same)
             * if (MyAPIGateway.Session.IsServer)
             *  ModLog.Info("MyAPIGateway.Session.IsServer.IsServer");
             * else
             *  ModLog.Info("MyAPIGateway.Session.NOT Server");
             * if (MyAPIGateway.Multiplayer.IsServer)
             *  ModLog.Info("MyAPIGateway.Multiplayer.IsServer");
             * else
             *  ModLog.Info("MyAPIGateway.Multiplayer.NOT Server");
             */
            bool bResearch = Session.SessionSettings.EnableResearch;

            // This works to change the setting.
            Session.SessionSettings.EnableResearch = true;

            Session.SessionSettings.EnableBountyContracts = false; // SE V1.192

            if ((gameVersion.Major == 1 && gameVersion.Minor >= 192) || gameVersion.Major > 1)
            {
                ModLog.Info("Economy items enabled");
                CargoType.AllowEconomyItems();
            }
            if ((gameVersion.Major == 1 && gameVersion.Minor >= 198) || gameVersion.Major > 1)
            {
                ModLog.Info("Warefare1 items enabled");
                CargoType.AllowWarefare1Items();
            }
            if ((gameVersion.Major == 1 && gameVersion.Minor >= 200) || gameVersion.Major > 1)
            {
                ModLog.Info("Warefare2 items enabled");
                CargoType.AllowWarefare2Items();
            }

            if (!bResearch)
            {
//                MyAPIGateway.Utilities.ShowNotification("Save, then Exit. Edit world /Advanced settings and Enable progression", 50000, MyFontEnum.Red);
                ModLog.Info("Research was not turned on");
            }
            TextAPI = new HudAPIv2();
//            if (modBuildWhenGameStarted > 4) V37
            {
                DuckUtils.PutPlayerIntoFaction("CRASH");
            }
            researchControl = new ResearchControl(audioSystem);
            researchControl.InitResearchRestrictions();
            researchHacking = new ResearchHacking(researchControl, TextAPI, networkComms);
            networkComms.Init(audioSystem, researchControl, researchHacking);
            modSystemRegistry.AddCloseableModSystem(networkComms);
            modSystemRegistry.AddUpatableModSystem(audioSystem);

            MyAPIGateway.Utilities.MessageEntered += MessageEntered;
        }
示例#23
0
 private void Show(string s)
 {
     MyVisualScriptLogicProvider.SendChatMessage(s, "InstantProjector", p.IdentityId, "Red");
 }
示例#24
0
 /// <summary>
 /// Sends a message to a specific player
 /// </summary>
 /// <param name="message">The message to send</param>
 /// <param name="sender">Who is sending the message</param>
 /// <param name="recipient">Player to receive the message</param>
 /// <param name="color">Optional.  Color of the sender's name in chat</param>
 public static void SendMessageToPlayer(string message, string sender, long recipient, string color = MyFontEnum.Blue)
 {
     MyVisualScriptLogicProvider.SendChatMessage(message, sender, recipient, color);
 }
示例#25
0
        private static void ProcessDamage(object target, ref MyDamageInformation info)
        {
            if (target == null)
            {
                return;
            }
            if (!(target is MyCharacter character))
            {
                return;
            }
            string victim       = "";
            string causeOfDeath = "";

            if (character.Integrity - info.Amount > 0)
            {
                return;
            }
            victim = character?.DisplayName;
            if (info.Type != null)
            {
                causeOfDeath = info.Type.String;
            }
            if (string.IsNullOrEmpty(causeOfDeath) || string.IsNullOrEmpty(victim))
            {
                return;
            }
            var attackingIdentity = MySession.Static.Players.TryGetIdentity(info.AttackerId);
            var steamId           = MySession.Static.Players.TryGetSteamId(character.GetIdentity().IdentityId);

            DeathCounter.AddOrUpdate(steamId, 1, (l, i) => i + 1);
            if (MyEntities.TryGetEntityById(info.AttackerId, out var attacker, true))
            {
                switch (attacker)
                {
                case MyCubeBlock block:
                    attackingIdentity = MySession.Static.Players.TryGetIdentity(block.CubeGrid.BigOwners.FirstOrDefault());
                    break;

                case MyVoxelBase _:
                    if (!Config.AnnounceCollisionDeath)
                    {
                        return;
                    }
                    causeOfDeath      = "Smashed into";
                    victim            = "a voxel";
                    attackingIdentity = character.GetIdentity();
                    break;

                case MyCubeGrid grid:
                    if (!Config.AnnounceCollisionDeath)
                    {
                        return;
                    }
                    causeOfDeath      = "Rammed";
                    attackingIdentity = MySession.Static.Players.TryGetIdentity(grid.BigOwners.FirstOrDefault());
                    break;

                case IMyHandheldGunObject <MyGunBase> rifle:
                    attackingIdentity = MySession.Static.Players.TryGetIdentity(rifle.OwnerIdentityId);
                    break;

                case IMyHandheldGunObject <MyToolBase> handTool:
                    attackingIdentity = MySession.Static.Players.TryGetIdentity(handTool.OwnerIdentityId);
                    break;
                }
            }
            if (causeOfDeath.Equals("suicide", StringComparison.OrdinalIgnoreCase) && Config.AnnounceSuicide)
            {
                causeOfDeath      = "Committed Suicide";
                victim            = string.Empty;
                attackingIdentity = character.GetIdentity();
            }

            if (causeOfDeath.Equals("lowpressure", StringComparison.OrdinalIgnoreCase))
            {
                causeOfDeath      = "Suffocated";
                victim            = string.Empty;
                attackingIdentity = character.GetIdentity();
            }

            if (attackingIdentity == null)
            {
                return;
            }

            if (causeOfDeath.Equals("Bullet", StringComparison.OrdinalIgnoreCase))
            {
                causeOfDeath = "Shot";
            }

            var attackerSteamId = MySession.Static.Players.TryGetSteamId(attackingIdentity.IdentityId);


            MyVisualScriptLogicProvider.SendChatMessage($"{attackingIdentity.DisplayName} {causeOfDeath} {victim}");
            Log.Info($"{character.DisplayName} died = {DeathCounter[steamId]} total death");
            if (((steamId <= 0 || attackerSteamId <= 0) && string.IsNullOrEmpty(victim)) ||
                steamId == attackerSteamId)
            {
                return;
            }
            {
                if (_lastKiller == attackerSteamId)

                {
                    KillStreak.AddOrUpdate(attackerSteamId, 2, (l, i) => i + 1);

                    MyVisualScriptLogicProvider.SendChatMessage($"{attackingIdentity.DisplayName} on {KillStreak[attackerSteamId]} kill streak");
                }
                else
                {
                    KillStreak.Clear();
                    KillStreak[steamId] = 1;
                }

                _lastKiller = attackerSteamId;
            }
        }
        private static bool PrefixNewBlueprint(MyProjectorBase __instance,
                                               ref List <MyObjectBuilder_CubeGrid> projectedGrids)
        {
            var remoteUserId = MyEventContext.Current.Sender.Value;
            var proj         = __instance;

            if (proj == null)
            {
                Log.Warn("Null projector detected");
                return(true);
            }
            var grid = projectedGrids[0];

            if (grid == null)
            {
                return(true);
            }

            var blocks = grid.CubeBlocks;

            if (MainLogic.Instance.Config.MaxGridSize > 0 && grid.CubeBlocks.Count > MainLogic.Instance.Config.MaxGridSize)
            {
                var diff = Math.Abs(grid.CubeBlocks.Count - MainLogic.Instance.Config.MaxGridSize);
                NetworkManager.RaiseEvent(__instance, RemoveBlueprintMethod);
                Validations.SendFailSound(remoteUserId);
                Validations.ValidationFailed();
                MyVisualScriptLogicProvider.SendChatMessage($" Projection is {diff} blocks too big", MainLogic.ChatName, MySession.Static.Players.TryGetIdentityId(remoteUserId), MyFontEnum.Red);
                Log.Info($"Blocked an oversized grid projection by {MySession.Static.Players.TryGetIdentityNameFromSteamId(remoteUserId)}");
                return(false);
            }

            if (blocks.Count == 0)
            {
                NetworkManager.RaiseEvent(__instance, RemoveBlueprintMethod);
                Validations.SendFailSound(remoteUserId);
                Validations.ValidationFailed();
                return(false);
            }

            var invCount = 0;
            var jCount   = 0;
            var tCount   = 0;
            var pbCount  = 0;
            var fCount   = 0;
            var pRCount  = 0;

            var removalCount = 0;
            var blockList    = new HashSet <string>();

            for (var i = blocks.Count - 1; i >= 0; i--)
            {
                var block = blocks[i];
                var def   = Utilities.GetDefinition(block);

                if (Utilities.IsMatch(def))
                {
                    blocks.RemoveAtFast(i);
                    removalCount++;
                    if (def == null || blockList.Contains(def.ToString().Substring(16)))
                    {
                        continue;
                    }
                    blockList.Add(def.ToString().Substring(16));
                    continue;
                }

                if (block is MyObjectBuilder_OreDetector oreDetector && MainLogic.Instance.Config.ResetOreDetectors)
                {
                    oreDetector.DetectionRadius = 0;
                }

                if (block is MyObjectBuilder_RemoteControl rm && MainLogic.Instance.Config.ResetRemoteControl)
                {
                    rm.AutopilotSpeedLimit = 0;
                    rm.AutomaticBehaviour  = null;
                }

                if (MainLogic.Instance.Config.ClearInventory)
                {
                    switch (block)
                    {
                    case MyObjectBuilder_Drill drill:
                        if (drill.Inventory?.Items.Count > 0)
                        {
                            invCount++;
                            drill.Inventory?.Clear();
                        }
                        break;

                    case MyObjectBuilder_ShipToolBase shipTool:
                        if (shipTool.Inventory?.Items.Count > 0)
                        {
                            invCount++;
                            shipTool.Inventory?.Clear();
                        }
                        break;

                    case MyObjectBuilder_Reactor reactor:
                        if (reactor.Inventory?.Items.Count > 0)
                        {
                            invCount++;
                            reactor.Inventory?.Clear();
                        }
                        break;

                    case MyObjectBuilder_SmallMissileLauncherReload mm:
                    {
                        if (mm.GunBase?.RemainingAmmo > 0)
                        {
                            mm.GunBase = null;
                            invCount++;
                        }
                    }
                    break;
                    }

                    var components = block.ComponentContainer?.Components;

                    if (components != null)
                    {
                        foreach (var data in components)
                        {
                            if (data.Component is MyObjectBuilder_Inventory inv && inv.Items.Count > 0)
                            {
                                inv.Clear();
                                invCount++;
                            }

                            if (data.Component is MyObjectBuilder_EntityCapacitorComponent cap && cap.StoredPower > 0)
                            {
                                cap.StoredPower = 0;
                            }
                        }
                    }

                    try
                    {
                        block.GetType()?.GetField("Inventory")?.SetValue(block, null);
                        block.GetType()?.GetField("InputInventory")?.SetValue(block, null);
                        block.GetType()?.GetField("OutputInventory")?.SetValue(block, null);
                    }
                    catch (Exception e)
                    {
                        Log.Warn(e, "There was an issue clearing projection inventories");
                    }
                }

                if (MainLogic.Instance.Config.ResetJumpDrives && block is MyObjectBuilder_JumpDrive jDrive && Math.Abs(jDrive.StoredPower) > 0)
                {
                    jDrive.StoredPower = 0;
                    jCount++;
                }

                if (MainLogic.Instance.Config.ResetTanks)
                {
                    if (block is MyObjectBuilder_GasTank tank && tank.FilledRatio > 0)
                    {
                        tank.FilledRatio = 0;
                        tCount++;
                    }

                    if (block is MyObjectBuilder_HydrogenEngine hEngine && hEngine.Capacity > 0)
                    {
                        hEngine.Capacity = 0;
                        tCount++;
                    }
                }

                if (MainLogic.Instance.Config.RemoveScripts && block is MyObjectBuilder_MyProgrammableBlock pbBlock)
                {
                    if (pbBlock.Program != null)
                    {
                        pbBlock.Program = null;
                        pbCount++;
                    }
                }

                if (MainLogic.Instance.Config.RemoveProjections && block is MyObjectBuilder_Projector projectedProjector)
                {
                    if (projectedProjector.ProjectedGrids != null)
                    {
                        projectedProjector.ProjectedGrid = null;
                        pRCount++;
                    }
                }

                if (!MainLogic.Instance.Config.ShutOffBlocks || !(block is MyObjectBuilder_FunctionalBlock fBlock) || !fBlock.Enabled ||
                    fBlock is MyObjectBuilder_MergeBlock)
                {
                    continue;
                }
                fBlock.Enabled = false;
                fCount++;
            }

            if (jCount > 0)
            {
                Log.Info($"{jCount} JumpDrives edited");
            }

            if (invCount > 0)
            {
                Log.Info($"{invCount} inventory blocks cleaned");
            }

            if (tCount > 0)
            {
                Log.Info($"{tCount} tanks reset in projection");
            }

            if (pbCount > 0)
            {
                Log.Info($"{pbCount} programmable blocks cleared from projection");
            }

            if (fCount > 0)
            {
                Log.Info($"{fCount} blocks switched off in projection");
            }

            if (pRCount > 0)
            {
                Log.Info($"{pRCount} projections removed from projection");
            }

            if (removalCount == 0)
            {
                return(true);
            }

            Log.Info($"{removalCount} blocks removed from projection");

            NetworkManager.RaiseEvent(__instance, RemoveBlueprintMethod);

            var msg = string.Join("\n", $"Removed {removalCount} Blocks", string.Join("\n", blockList));

            MyVisualScriptLogicProvider.SendChatMessage(msg, MainLogic.ChatName, MySession.Static.Players.TryGetIdentityId(remoteUserId), MyFontEnum.Red);
            try
            {
                NetworkManager.RaiseEvent(__instance, NewBlueprintMethod,
                                          new List <MyObjectBuilder_CubeGrid> {
                    grid
                }, new EndpointId(remoteUserId));
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
            return(true);
        }
示例#27
0
        /// <summary>
        /// Aim to block projections or remove blocks to match grid/player limits.
        /// </summary>
        /// <param name="__instance"></param>
        /// <param name="projectedGrids"></param>
        /// <returns></returns>
        private static bool PrefixNewBlueprint(MyProjectorBase __instance, ref List <MyObjectBuilder_CubeGrid> projectedGrids)
        {
            if (!BlockLimiterConfig.Instance.EnableLimits)
            {
                return(true);
            }

            var proj = __instance;

            if (proj == null)
            {
                Log.Warn("No projector?");
                return(false);
            }

            var grid = projectedGrids[0];

            if (grid == null)
            {
                Log.Warn("Grid null in projectorPatch");
                return(false);
            }


            var remoteUserId = MyEventContext.Current.Sender.Value;
            var player       = MySession.Static.Players.TryGetPlayerBySteamId(remoteUserId);

            var blocks = grid.CubeBlocks;

            if (player == null || blocks.Count == 0)
            {
                return(true);
            }
            if (Utilities.IsExcepted(player.Identity.IdentityId, new List <string>()))
            {
                return(true);
            }

            var target   = new EndpointId(remoteUserId);
            var playerId = player.Identity.IdentityId;

            if (Grid.IsSizeViolation(grid))
            {
                Task.Run(() =>
                {
                    Thread.Sleep(100);
                    NetworkManager.RaiseEvent(__instance, RemoveProjectionMethod, target);
                });
                Utilities.SendFailSound(remoteUserId);
                Utilities.ValidationFailed();
                MyVisualScriptLogicProvider.SendChatMessage($"{BlockLimiterConfig.Instance.DenyMessage}", BlockLimiterConfig.Instance.ServerName, playerId, MyFontEnum.Red);
                if (BlockLimiterConfig.Instance.EnableLog)
                {
                    Log.Info($"Projection blocked from {player.DisplayName}");
                }
                return(false);
            }


            var limits = new HashSet <LimitItem>();

            limits.UnionWith(BlockLimiterConfig.Instance.AllLimits.Where(x => x.RestrictProjection && !Utilities.IsExcepted(grid.EntityId, x.Exceptions) &&
                                                                         !Utilities.IsExcepted(player.Identity.IdentityId, x.Exceptions)));

            if (limits.Count == 0)
            {
                return(true);
            }

            var count = 0;

            var playerFaction = MySession.Static.Factions.GetPlayerFaction(playerId);

            foreach (var limit in limits)
            {
                var pBlocks = blocks.Where(x => Block.IsMatch(Utilities.GetDefinition(x), limit)).ToList();

                if (pBlocks.Count < 1)
                {
                    continue;
                }

                var removalCount = 0;
                var fCount       = 0;
                limit.FoundEntities.TryGetValue(grid.EntityId, out var gCount);
                limit.FoundEntities.TryGetValue(playerId, out var oCount);
                if (playerFaction != null)
                {
                    limit.FoundEntities.TryGetValue(playerFaction.FactionId, out fCount);
                }

                foreach (var block in pBlocks)
                {
                    if (Math.Abs(pBlocks.Count - removalCount) <= limit.Limit || Math.Abs(fCount + pBlocks.Count - removalCount) <= limit.Limit && (Math.Abs((oCount + pBlocks.Count) - removalCount) <= limit.Limit && Math.Abs((gCount + pBlocks.Count) - removalCount) <= limit.Limit))
                    {
                        break;
                    }

                    removalCount++;
                    count++;
                    blocks.Remove(block);
                }
            }

            if (count < 1)
            {
                return(true);
            }


            NetworkManager.RaiseEvent(__instance, RemoveProjectionMethod, target);

            try
            {
                NetworkManager.RaiseEvent(__instance, NewBlueprintMethod,
                                          new List <MyObjectBuilder_CubeGrid> {
                    grid
                });
            }
            catch (Exception e)
            {
                //NullException thrown here but seems to work for some reason.  Don't Touch any further
            }

            var msg = BlockLimiterConfig.Instance.ProjectionDenyMessage.Replace("{BC}", $"{count}");

            MyVisualScriptLogicProvider.SendChatMessage($"{msg}", BlockLimiterConfig.Instance.ServerName, playerId, MyFontEnum.Red);

            return(true);
        }
示例#28
0
 private void Notify(string s, IMyPlayer p)
 {
     MyVisualScriptLogicProvider.SendChatMessage(s, "Admin Timers", p.IdentityId);
 }
        public static void CanProject(List <MyObjectBuilder_CubeGrid> projectedGrids, ulong remoteUserId, out bool changesMade)
        {
            changesMade = false;
            if (projectedGrids == null || projectedGrids.Count == 0)
            {
                return;
            }
            var grid = projectedGrids[0];

            var blocks = grid?.CubeBlocks;

            if (blocks == null || blocks.Count == 0)
            {
                return;
            }


            if (Config.MaxGridSize > 0 && blocks.Count > Config.MaxGridSize)
            {
                grid.CubeBlocks.Clear();
                changesMade = true;
                var diff = Math.Abs(blocks.Count - Config.MaxGridSize);
                if (remoteUserId > 0)
                {
                    MyVisualScriptLogicProvider.SendChatMessage($" Projection is {diff} blocks too big",
                                                                MainLogic.ChatName, MySession.Static.Players.TryGetIdentityId(remoteUserId), MyFontEnum.Red);
                }
                Log.Info(
                    $"Blocked an oversized grid projection by {MySession.Static.Players.TryGetIdentityNameFromSteamId(remoteUserId)}");
                return;
            }



            var invCount = 0;
            var jCount   = 0;
            var tCount   = 0;
            var pbCount  = 0;
            var fCount   = 0;
            var pRCount  = 0;

            var removalCount = 0;
            var blockList    = new HashSet <string>();

            for (var i = blocks.Count - 1; i >= 0; i--)
            {
                var block = blocks[i];
                var def   = GetDefinition(block);

                if (IsMatch(def))
                {
                    blocks.RemoveAtFast(i);
                    removalCount++;
                    if (def == null || blockList.Contains(def.ToString().Substring(16)))
                    {
                        continue;
                    }
                    blockList.Add(def.ToString().Substring(16));
                    continue;
                }

                if (Config.ClearInventory)
                {
                    var components = block.ComponentContainer?.Components;
                    if (components != null)
                    {
                        foreach (var componentData in components)
                        {
                            if (!(componentData?.Component is MyObjectBuilder_Inventory inv))
                            {
                                continue;
                            }
                            if (inv.Items.Count == 0)
                            {
                                continue;
                            }
                            inv.Clear();
                            invCount++;
                        }
                    }
                    switch (block)
                    {
                    case MyObjectBuilder_Drill drill:
                        if (drill.Inventory?.Items.Count > 0)
                        {
                            invCount++;
                            drill.Inventory?.Clear();
                        }
                        break;

                    case MyObjectBuilder_ShipToolBase shipTool:
                        if (shipTool.Inventory?.Items.Count > 0)
                        {
                            invCount++;
                            shipTool.Inventory?.Clear();
                        }
                        break;

                    case MyObjectBuilder_Reactor reactor:
                        if (reactor.Inventory?.Items.Count > 0)
                        {
                            invCount++;
                            reactor.Inventory?.Clear();
                        }
                        break;

                    case MyObjectBuilder_OxygenGenerator oxygen:
                        if (oxygen.Inventory?.Items.Count > 0)
                        {
                            invCount++;
                            oxygen.Inventory?.Clear();
                        }
                        break;
                    }
                }

                if (Config.ResetJumpDrives && block is MyObjectBuilder_JumpDrive jDrive &&
                    Math.Abs(jDrive.StoredPower) > 0)
                {
                    jDrive.StoredPower = 0;
                    jCount++;
                }

                if (Config.ResetTanks && block is MyObjectBuilder_GasTank tank && tank.FilledRatio > 0)
                {
                    tank.FilledRatio = 0;
                    tCount++;
                }

                if (Config.RemoveScripts && block is MyObjectBuilder_MyProgrammableBlock pbBlock)
                {
                    if (pbBlock.Program != null)
                    {
                        pbBlock.Program = null;
                        pbCount++;
                    }
                }

                if (Config.RemoveProjections && block is MyObjectBuilder_Projector projectedProjector)
                {
                    if (projectedProjector.ProjectedGrids != null)
                    {
                        projectedProjector.ProjectedGrid = null;
                        pRCount++;
                    }
                }

                if (!Config.ShutOffBlocks || !(block is MyObjectBuilder_FunctionalBlock fBlock) ||
                    !fBlock.Enabled ||
                    fBlock is MyObjectBuilder_MergeBlock)
                {
                    continue;
                }
                fBlock.Enabled = false;
                fCount++;
            }

            if (jCount > 0)
            {
                Log.Info($"{jCount} JumpDrives edited");
            }

            if (invCount > 0)
            {
                Log.Info($"{invCount} inventory blocks cleaned");
            }

            if (tCount > 0)
            {
                Log.Info($"{tCount} tanks reset in projection");
            }

            if (pbCount > 0)
            {
                Log.Info($"{pbCount} programmable blocks cleared from projection");
            }

            if (fCount > 0)
            {
                Log.Info($"{fCount} blocks switched off in projection");
            }

            if (pRCount > 0)
            {
                Log.Info($"{pRCount} projections removed from projection");
            }

            if (removalCount == 0)
            {
                return;
            }
            changesMade = true;
            Log.Info($"{removalCount} blocks removed from projection");

            var msg = string.Join("\n", $"Removed {removalCount} Blocks", string.Join("\n", blockList));

            if (remoteUserId > 0)
            {
                MyVisualScriptLogicProvider.SendChatMessage(msg, MainLogic.ChatName,
                                                            MySession.Static.Players.TryGetIdentityId(remoteUserId), MyFontEnum.Red);
            }
        }
示例#30
0
        public void BroadcastRequest(ChatProfile chat)
        {
            string message       = "";
            string sound         = "";
            string avatar        = "";
            var    broadcastType = BroadcastType.None;

            if (chat.ProcessChat(ref message, ref sound, ref broadcastType, ref avatar) == false)
            {
                Logger.MsgDebug(chat.ProfileSubtypeId + ": Process Chat Fail", DebugTypeEnum.Chat);
                return;
            }

            if (this.LastChatMessageSent == message || string.IsNullOrWhiteSpace(message) == true)
            {
                Logger.MsgDebug(chat.ProfileSubtypeId + ": Last Message Same", DebugTypeEnum.Chat);
                return;
            }

            if (chat.IgnoreAntennaRequirement || chat.SendToAllOnlinePlayers)
            {
                this.HighestRadius           = chat.IgnoredAntennaRangeOverride;
                this.HighestAntennaRangeName = "";
                this.AntennaCoords           = this.RemoteControl.GetPosition();
            }
            else
            {
                GetHighestAntennaRange();

                if (this.HighestRadius == 0)
                {
                    Logger.MsgDebug(chat.ProfileSubtypeId + ": No Valid Antenna", DebugTypeEnum.Chat);
                    return;
                }
            }



            var playerList = new List <IMyPlayer>();

            MyAPIGateway.Players.GetPlayers(playerList);
            Logger.MsgDebug(chat.ProfileSubtypeId + ": Sending Chat to all Players within distance: " + this.HighestRadius.ToString(), DebugTypeEnum.Chat);

            if (message.Contains("{AntennaName}"))
            {
                message = message.Replace("{AntennaName}", this.HighestAntennaRangeName);
            }

            if (this.RemoteControl?.SlimBlock?.CubeGrid?.CustomName != null && message.Contains("{GridName}"))
            {
                message = message.Replace("{GridName}", this.RemoteControl.SlimBlock.CubeGrid.CustomName);
            }

            if (chat.UseRandomNameGeneratorFromMES && MESApi.MESApiReady)
            {
                message = MESApi.ConvertRandomNamePatterns(message);
            }

            var authorName = chat.Author;

            if (authorName.Contains("{AntennaName}"))
            {
                authorName = authorName.Replace("{AntennaName}", this.HighestAntennaRangeName);
            }

            if (this.RemoteControl?.SlimBlock?.CubeGrid?.CustomName != null && authorName.Contains("{GridName}"))
            {
                authorName = authorName.Replace("{GridName}", this.RemoteControl.SlimBlock.CubeGrid.CustomName);
            }

            bool sentToAll = false;

            foreach (var player in playerList)
            {
                var playerId   = chat.SendToAllOnlinePlayers ? 0 : player.IdentityId;
                var playerName = chat.SendToAllOnlinePlayers ? "Player" : player.DisplayName;

                if (!chat.SendToAllOnlinePlayers && (player.IsBot == true || player.Character == null))
                {
                    continue;
                }

                if (!chat.SendToAllOnlinePlayers && (Vector3D.Distance(player.GetPosition(), this.AntennaCoords) > this.HighestRadius))
                {
                    continue;                     //player too far
                }

                var modifiedMsg = message;

                if (modifiedMsg.Contains("{PlayerName}") == true)
                {
                    modifiedMsg = modifiedMsg.Replace("{PlayerName}", playerName);
                }

                if (modifiedMsg.Contains("{PlayerFactionName}") == true)
                {
                    var playerFaction = MyAPIGateway.Session.Factions.TryGetPlayerFaction(player.IdentityId);

                    if (playerFaction != null)
                    {
                        modifiedMsg = modifiedMsg.Replace("{PlayerFactionName}", playerFaction.Name);
                    }
                    else
                    {
                        modifiedMsg = modifiedMsg.Replace("{PlayerFactionName}", "Unaffiliated");
                    }
                }


                var authorColor = chat.Color;

                if (authorColor != "White" && authorColor != "Red" && authorColor != "Green" && authorColor != "Blue")
                {
                    authorColor = "White";
                }

                if (!sentToAll)
                {
                    if (broadcastType == BroadcastType.Chat || broadcastType == BroadcastType.Both)
                    {
                        MyVisualScriptLogicProvider.SendChatMessage(modifiedMsg, authorName, playerId, authorColor);
                    }

                    if (broadcastType == BroadcastType.Notify || broadcastType == BroadcastType.Both)
                    {
                        if (playerId == 0)
                        {
                            MyVisualScriptLogicProvider.ShowNotificationToAll(modifiedMsg, 6000, authorColor);
                        }
                        else
                        {
                            MyVisualScriptLogicProvider.ShowNotification(modifiedMsg, 6000, authorColor, playerId);
                        }
                    }
                }

                if (string.IsNullOrWhiteSpace(sound) == false && sound != "None")
                {
                    var effect = new Effects();
                    effect.Mode     = EffectSyncMode.PlayerSound;
                    effect.SoundId  = sound;
                    effect.AvatarId = avatar;
                    var sync = new SyncContainer(effect);
                    SyncManager.SendSyncMesage(sync, player.SteamUserId);
                }

                if (playerId == 0)
                {
                    sentToAll = true;
                }
            }
        }