Example #1
0
        public Boolean CheckGrids(Vector3 Position, long PlayerIdentityId)
        {
            MyFaction       PlayersFaction = MySession.Static.Factions.GetPlayerFaction(PlayerIdentityId);
            BoundingSphereD sphere         = new BoundingSphereD(Position, 15000);

            foreach (MyCubeGrid grid in MyAPIGateway.Entities.GetEntitiesInSphere(ref sphere).OfType <MyCubeGrid>())
            {
                if (FacUtils.IsOwnerOrFactionOwned(grid, PlayerIdentityId, true))
                {
                    continue;
                }

                if (grid.Projector != null)
                {
                    continue;
                }

                MyFaction CheckFaction = MySession.Static.Factions.GetPlayerFaction(FacUtils.GetOwner(grid));
                if (PlayersFaction != null && CheckFaction != null)
                {
                    MyRelationsBetweenFactions Relation = MySession.Static.Factions.GetRelationBetweenFactions(PlayersFaction.FactionId, CheckFaction.FactionId).Item1;
                    if (Relation == MyRelationsBetweenFactions.Neutral || Relation == MyRelationsBetweenFactions.Friends)
                    {
                        continue;
                    }
                }

                if (Vector3D.Distance(Position, grid.PositionComp.GetPosition()) <= 15000)
                {
                    return(false);
                }
            }
            return(true);
        }
Example #2
0
        public long GetUpkeep()
        {
            float upkeep = 0;

            upkeep += AlliancePlugin.config.BaseUpkeepFee;
            foreach (long id in AllianceMembers)
            {
                MyFaction fac = MySession.Static.Factions.TryGetFactionById(id) as MyFaction;
                if (fac != null)
                {
                    upkeep += AlliancePlugin.config.BaseUpkeepFee * AlliancePlugin.config.PercentPerFac;
                    upkeep += AlliancePlugin.config.FeePerMember * fac.Members.Count;
                }
            }
            foreach (JumpGate gate in AlliancePlugin.AllGates.Values)
            {
                if (gate.OwnerAlliance == AllianceId && !gate.CanBeRented)
                {
                    upkeep += gate.upkeep;
                }
            }
            if (this.hasUnlockedHangar)
            {
                upkeep += AlliancePlugin.config.HangarUpkeep;
            }
            if (this.hasUnlockedShipyard)
            {
                upkeep += AlliancePlugin.config.ShipyardUpkeep;
            }
            return((long)upkeep);
        }
Example #3
0
        public virtual void Init(MyObjectBuilder_Bot botBuilder)
        {
            MyObjectBuilder_AgentBot bot = botBuilder as MyObjectBuilder_AgentBot;

            if (bot != null)
            {
                this.m_deathCountdownMs = bot.RespawnCounter;
                if (this.AgentDefinition.FactionTag != null)
                {
                    MyFaction faction = MySession.Static.Factions.TryGetOrCreateFactionByTag(this.AgentDefinition.FactionTag);
                    if (faction != null)
                    {
                        MyFactionCollection.SendJoinRequest(faction.FactionId, this.Player.Identity.IdentityId);
                        this.m_joinRequestSent = true;
                    }
                }
                if (bot.AiTarget != null)
                {
                    this.AgentActions.AiTargetBase.Init(bot.AiTarget);
                }
                if (botBuilder.BotMemory != null)
                {
                    this.m_botMemory.Init(botBuilder.BotMemory);
                }
                MyAIComponent.Static.BehaviorTrees.SetBehaviorName(this, bot.LastBehaviorTree);
            }
        }
Example #4
0
        private void grid_OnBlockOwnershipChanged(MyCubeGrid obj)
        {
            bool flag = false;

            foreach (long num in obj.BigOwners)
            {
                MyFaction playerFaction = MySession.Static.Factions.GetPlayerFaction(num);
                if ((playerFaction != null) && !playerFaction.IsEveryoneNpc())
                {
                    flag = true;
                    break;
                }
            }
            foreach (long num2 in obj.SmallOwners)
            {
                MyFaction playerFaction = MySession.Static.Factions.GetPlayerFaction(num2);
                if ((playerFaction != null) && !playerFaction.IsEveryoneNpc())
                {
                    flag = true;
                    break;
                }
            }
            if (flag)
            {
                obj.Components.Remove <MyUpdateTriggerComponent>();
                obj.OnBlockOwnershipChanged -= new Action <MyCubeGrid>(this.grid_OnBlockOwnershipChanged);
            }
        }
        public static void Login(IPlayer p)
        {
            if (p == null)
            {
                return;
            }

            MyIdentity id = AlliancePlugin.GetIdentityByNameOrId(p.SteamId.ToString());

            if (id == null)
            {
                return;
            }
            IMyFaction playerFac = MySession.Static.Factions.GetPlayerFaction(id.IdentityId);
            MyFaction  arrr      = MySession.Static.Factions.TryGetFactionByTag("arrr");

            if (arrr != null)
            {
                if (playerFac != null && !MySession.Static.Factions.AreFactionsEnemies(arrr.FactionId, FacUtils.GetPlayersFaction(id.IdentityId).FactionId))
                {
                    Sandbox.Game.Multiplayer.MyFactionCollection.DeclareWar(playerFac.FactionId, arrr.FactionId);
                }
            }

            MyFaction ACME = MySession.Static.Factions.TryGetFactionByTag("ACME");

            if (ACME != null)
            {
                MySession.Static.Factions.SetReputationBetweenPlayerAndFaction(id.IdentityId, ACME.FactionId, 0);
                MySession.Static.Factions.AddFactionPlayerReputation(id.IdentityId, ACME.FactionId, 0);
            }
            MyFaction GAIA = MySession.Static.Factions.TryGetFactionByTag("GAIA");

            if (GAIA != null)
            {
                MySession.Static.Factions.SetReputationBetweenPlayerAndFaction(id.IdentityId, GAIA.FactionId, 0);
                MySession.Static.Factions.AddFactionPlayerReputation(id.IdentityId, GAIA.FactionId, 0);
            }
            MyFaction wolf = MySession.Static.Factions.TryGetFactionByTag("WOLF");

            if (wolf != null)
            {
                if (playerFac != null && !MySession.Static.Factions.AreFactionsEnemies(wolf.FactionId, FacUtils.GetPlayersFaction(id.IdentityId).FactionId))
                {
                    Sandbox.Game.Multiplayer.MyFactionCollection.DeclareWar(playerFac.FactionId, wolf.FactionId);
                }
            }
            if (File.Exists(AlliancePlugin.path + "//PlayerData//" + p.SteamId + ".xml") && playerFac != null)
            {
                PlayerData data = utils.ReadFromXmlFile <PlayerData>(AlliancePlugin.path + "//PlayerData//" + p.SteamId + ".xml");
                if (data.InAllianceChat)
                {
                    if (AlliancePlugin.GetAllianceNoLoading(playerFac as MyFaction) != null)
                    {
                        PeopleInAllianceChat.Remove(p.SteamId);
                        PeopleInAllianceChat.Add(p.SteamId, AlliancePlugin.GetAllianceNoLoading(playerFac as MyFaction).AllianceId);
                    }
                }
            }
        }
 public MyEventSectorOwnerChanged(MyFaction oldOwner, MyFaction newOwner, MySector sector, ReasonEnum reason) : base(false)
 {
     OldOwner = oldOwner;
     NewOwner = newOwner ?? throw new ArgumentNullException(nameof(newOwner));
     Sector   = sector ?? throw new ArgumentNullException(nameof(sector));
     _reason  = reason;
 }
        private void RefreshFactionChatHistory(MyFaction faction)
        {
            m_chatHistory.Clear();

            var localFaction = MySession.Static.Factions.TryGetPlayerFaction(MySession.Static.LocalPlayerId);

            if (localFaction == null)
            {
                System.Diagnostics.Debug.Fail("Chat shouldn't be refreshed if local player is not a member of a faction!");
                return;
            }
            MyFactionChatHistory factionChat = MyChatSystem.FindFactionChatHistory(faction.FactionId, localFaction.FactionId);

            if (factionChat != null)
            {
                var chat = factionChat.Chat;
                foreach (var item in chat)
                {
                    bool alreadySentToMe;
                    if (item.IdentityId == MySession.Static.LocalPlayerId || (item.PlayersToSendTo.TryGetValue(MySession.Static.LocalPlayerId, out alreadySentToMe) && alreadySentToMe))
                    {
                        int alreadySentToCount = 0;
                        foreach (var keyValue in item.PlayersToSendTo)
                        {
                            if (keyValue.Value)
                            {
                                alreadySentToCount++;
                            }
                        }
                        var identity = MySession.Static.Players.TryGetIdentity(item.IdentityId);

                        if (identity == null)
                        {
                            continue;
                        }
                        bool isPlayer = identity.IdentityId == MySession.Static.LocalPlayerId;

                        m_chatHistory.AppendText(identity.DisplayName, isPlayer ? MyFontEnum.DarkBlue : MyFontEnum.Blue, m_chatHistory.TextScale, Vector4.One);
                        if (item.PlayersToSendTo != null && item.PlayersToSendTo.Count > 0 && alreadySentToCount < item.PlayersToSendTo.Count)
                        {
                            var pendingText = new StringBuilder();
                            pendingText.Append(" (");
                            pendingText.Append(alreadySentToCount.ToString());
                            pendingText.Append("/");
                            pendingText.Append(item.PlayersToSendTo.Count.ToString());
                            pendingText.Append(") ");
                            m_chatHistory.AppendText(pendingText, MyFontEnum.Red, m_chatHistory.TextScale, Vector4.One);
                        }
                        m_chatHistory.AppendText(": ", isPlayer ? MyFontEnum.DarkBlue : MyFontEnum.Blue, m_chatHistory.TextScale, Vector4.One);
                        m_chatHistory.AppendText(item.Text, MyFontEnum.White, m_chatHistory.TextScale, Vector4.One);
                        m_chatHistory.AppendLine();
                    }
                }
            }

            m_playerList.SelectedItems.Clear();
            m_chatHistory.ScrollbarOffset = 1.0f;
        }
Example #8
0
        //TODO: This should probably be moved into Torch base, but I honestly cannot be bothered
        /// <summary>
        /// Removes a faction from the server and all clients because Keen f****d up their own system.
        /// </summary>
        /// <param name="faction"></param>
        private static void RemoveFaction(MyFaction faction)
        {
            //bypass the check that says the server doesn't have permission to delete factions
            _applyFactionState(MySession.Static.Factions, MyFactionStateChange.RemoveFaction, faction.FactionId, faction.FactionId, 0, 0);
            var n = EssentialsPlugin.Instance.Torch.CurrentSession.Managers.GetManager <NetworkManager>();

            //send remove message to clients
            n.RaiseStaticEvent(_factionChangeSuccessInfo, MyFactionStateChange.RemoveFaction, faction.FactionId, faction.FactionId, 0L, 0L);
        }
        public static bool IsSomeoneNpc(this MyFaction self)
        {
            foreach (var(id, _) in self.Members)
            {
                if (Sync.Players.IdentityIsNpc(id))
                {
                    return(true);
                }
            }

            return(false);
        }
        public void distress(string reason = "")
        {
            if (Context.Player == null)
            {
                Context.Respond("no no console no distress");
                return;
            }


            IMyFaction playerFac = FacUtils.GetPlayersFaction(Context.Player.Identity.IdentityId);

            if (playerFac == null)
            {
                Context.Respond("You dont have a faction.");
                return;
            }
            if (reason != "")
            {
                reason = Context.RawArgs;
            }
            MyFaction fac = MySession.Static.Factions.GetPlayerFaction(Context.Player.IdentityId);

            if (fac == null)
            {
                Context.Respond("A faction is required to use alliance features.");
                return;
            }

            if (distressCooldowns.TryGetValue(Context.Player.IdentityId, out DateTime time))
            {
                if (DateTime.Now < time)
                {
                    Context.Respond(AllianceCommands.GetCooldownMessage(time));
                    return;
                }
                else
                {
                    distressCooldowns[Context.Player.IdentityId] = DateTime.Now.AddSeconds(30);
                }
            }
            else
            {
                distressCooldowns.Add(Context.Player.IdentityId, DateTime.Now.AddSeconds(30));
            }
            Alliance alliance = AlliancePlugin.GetAllianceNoLoading(fac);

            if (alliance != null)
            {
                distressCount++;
                AllianceChat.SendChatMessage(alliance.AllianceId, "Distress Signal", CreateGps(Context.Player.Character.GetPosition(), Color.Yellow, 600, distressCount.ToString(), reason).ToString(), true, 0);
            }
        }
Example #11
0
 //TODO: This should probably be moved into Torch base, but I honestly cannot be bothered
 /// <summary>
 /// Removes a faction from the server and all clients because Keen f****d up their own system.
 /// </summary>
 /// <param name="faction"></param>
 private static void RemoveFaction(MyFaction faction)
 {
     //bypass the check that says the server doesn't have permission to delete factions
     //_applyFactionState(MySession.Static.Factions, MyFactionStateChange.RemoveFaction, faction.FactionId, faction.FactionId, 0L, 0L);
     //MyMultiplayer.RaiseStaticEvent(s =>
     //        (Action<MyFactionStateChange, long, long, long, long>) Delegate.CreateDelegate(typeof(Action<MyFactionStateChange, long, long, long, long>), _factionStateChangeReq),
     //    MyFactionStateChange.RemoveFaction, faction.FactionId, faction.FactionId, faction.FounderId, faction.FounderId);
     NetworkManager.RaiseStaticEvent(_factionChangeSuccessInfo, MyFactionStateChange.RemoveFaction, faction.FactionId, faction.FactionId, 0L, 0L);
     if (!MyAPIGateway.Session.Factions.FactionTagExists(faction.Tag))
     {
         return;
     }
     MyAPIGateway.Session.Factions.RemoveFaction(faction.FactionId); //Added to remove factions that got through the crack
 }
        private static bool ResolveFaction(string name, out MyFaction faction)
        {
            foreach (var fac in MySession.Static.Factions)
            {
                if (fac.Value.Tag.Equals(name, StringComparison.OrdinalIgnoreCase) || fac.Value.Name.Equals(name, StringComparison.OrdinalIgnoreCase) ||
                    fac.Key.ToString().Equals(name, StringComparison.OrdinalIgnoreCase))
                {
                    faction = fac.Value;
                    return(true);
                }
            }

            faction = null;
            return(name.Equals("nil", StringComparison.OrdinalIgnoreCase) || name.Equals("null", StringComparison.OrdinalIgnoreCase) || name.Equals("0"));
        }
 internal MyBotFactionApi(MyPlayer sender)
 {
     Sender = sender;
     if (Sender is null)
     {
         throw new ArgumentNullException("Игрок не зарегистрирован", nameof(sender));
     }
     if (Sender.IsBanned)
     {
         throw new ArgumentException("Игрок заблокирован", nameof(sender));
     }
     Faction = MySave.Factions.Find(x => x.Tag == Sender.Tag);
     if (Faction is null || !Sender.IsFactionLeader)
     {
         throw new InvalidOperationException("Игрок не состоит во фракции или не является ее лидером");
     }
 }
        public void DoAllianceChat(string message = "")
        {
            MyFaction fac = MySession.Static.Factions.GetPlayerFaction(Context.Player.IdentityId);

            if (fac == null)
            {
                Context.Respond("Only factions can be in alliances.");
                return;
            }
            PlayerData data;

            if (File.Exists(AlliancePlugin.path + "//PlayerData//" + Context.Player.SteamUserId + ".xml"))
            {
                data = utils.ReadFromXmlFile <PlayerData>(AlliancePlugin.path + "//PlayerData//" + Context.Player.SteamUserId + ".xml");
            }
            else
            {
                data = new PlayerData();
            }
            Alliance alliance = AlliancePlugin.GetAlliance(fac);

            if (AllianceChat.PeopleInAllianceChat.ContainsKey(Context.Player.SteamUserId))
            {
                data.InAllianceChat = false;
                AllianceChat.IdentityIds.Remove(Context.Player.SteamUserId);
                AllianceChat.PeopleInAllianceChat.Remove(Context.Player.SteamUserId);
                Context.Respond("Leaving alliance chat.", Color.Red);
                utils.WriteToXmlFile <PlayerData>(AlliancePlugin.path + "//PlayerData//" + Context.Player.SteamUserId + ".xml", data);
                return;
            }
            if (alliance != null)
            {
                {
                    AllianceChat.IdentityIds.Remove(Context.Player.SteamUserId);
                    AllianceChat.IdentityIds.Add(Context.Player.SteamUserId, Context.Player.Identity.IdentityId);
                    data.InAllianceChat = true;
                    AllianceChat.PeopleInAllianceChat.Add(Context.Player.SteamUserId, alliance.AllianceId);
                    Context.Respond("Entering alliance chat.", Color.Cyan);
                    utils.WriteToXmlFile <PlayerData>(AlliancePlugin.path + "//PlayerData//" + Context.Player.SteamUserId + ".xml", data);
                }
            }
            else
            {
                Context.Respond("You must be in an alliance to use alliance chat.");
            }
        }
        public static void SendChatMessageFromDiscord(Guid allianceId, string prefix, string message, ulong discordId = 0)
        {
            log.Info(allianceId.ToString() + " : " + prefix + " " + message);
            Alliance     alliance     = AlliancePlugin.GetAllianceNoLoading(allianceId);
            List <ulong> OtherMembers = new List <ulong>();

            foreach (MyPlayer player in MySession.Static.Players.GetOnlinePlayers())
            {
                MyFaction fac = MySession.Static.Factions.TryGetPlayerFaction(player.Identity.IdentityId) as MyFaction;
                if (fac != null)
                {
                    if (alliance.AllianceMembers.Contains(fac.FactionId))
                    {
                        OtherMembers.Add(player.Id.SteamId);
                    }
                }
            }
            if (discordId > 0)
            {
                log.Info(allianceId.ToString() + " : " + alliance.name + " : " + prefix + " " + message + " discord id " + discordId);
            }
            else
            {
                log.Info(allianceId.ToString() + " : " + alliance.name + " : " + prefix + " " + message + " the bot");
            }
            foreach (ulong id in OtherMembers)
            {
                ShipyardCommands.SendMessage(prefix, message, new Color(alliance.r, alliance.g, alliance.b), (long)id);
                MyGpsCollection gpscol = (MyGpsCollection)MyAPIGateway.Session?.GPS;

                if (ScanChat(message, null) != null)
                {
                    MyGps gpsRef = ScanChat(message, null);
                    gpsRef.GPSColor      = Color.Yellow;
                    gpsRef.AlwaysVisible = true;
                    gpsRef.ShowOnHud     = true;

                    long idenId = MySession.Static.Players.TryGetIdentityId(id);
                    MyAPIGateway.Utilities.InvokeOnGameThread(() =>
                    {
                        gpscol.SendAddGps(idenId, ref gpsRef);
                    });
                }
            }
        }
Example #16
0
 protected virtual void UpdateInternal()
 {
     this.m_navigation.Update(this.m_botMemory.TickCounter);
     this.m_botLogic.Update();
     if ((!this.m_joinRequestSent && (this.m_botDefinition.FactionTag != null)) && (this.m_botDefinition.FactionTag.Length > 0))
     {
         string    tag     = this.m_botDefinition.FactionTag.ToUpperInvariant();
         MyFaction faction = MySession.Static.Factions.TryGetFactionByTag(tag, null);
         if (faction != null)
         {
             long controllingIdentityId = this.AgentEntity.ControllerInfo.ControllingIdentityId;
             if ((MySession.Static.Factions.TryGetPlayerFaction(controllingIdentityId) == null) && !this.m_joinRequestSent)
             {
                 MyFactionCollection.SendJoinRequest(faction.FactionId, controllingIdentityId);
                 this.m_joinRequestSent = true;
             }
         }
     }
 }
Example #17
0
 public Boolean JoinAlliance(MyFaction fac)
 {
     if (BlockedFactions.Contains(fac.FactionId))
     {
         return(false);
     }
     if (Invites.Contains(fac.FactionId))
     {
         Invites.Remove(fac.FactionId);
         AllianceMembers.Remove(fac.FactionId);
         AllianceMembers.Add(fac.FactionId);
         ForceFriendlies();
         return(true);
     }
     else
     {
         return(false);
     }
 }
Example #18
0
        public Boolean CheckCharacters(Vector3 Position, long PlayerIdentityId)
        {
            MyFaction PlayersFaction = MySession.Static.Factions.GetPlayerFaction(PlayerIdentityId);

            foreach (MyCharacter Player in MyEntities.GetEntities().OfType <MyCharacter>())
            {
                if (Player == null || Player.MarkedForClose)
                {
                    continue;
                }

                long PlayerID = Player.GetPlayerIdentityId();
                if (PlayerID == 0L || PlayerID == PlayerIdentityId)
                {
                    continue;
                }


                MyFaction CheckFaction = MySession.Static.Factions.GetPlayerFaction(PlayerID);
                if (PlayersFaction != null && CheckFaction != null)
                {
                    if (PlayersFaction.FactionId == CheckFaction.FactionId)
                    {
                        continue;
                    }

                    MyRelationsBetweenFactions Relation = MySession.Static.Factions.GetRelationBetweenFactions(PlayersFaction.FactionId, CheckFaction.FactionId).Item1;
                    if (Relation == MyRelationsBetweenFactions.Neutral || Relation == MyRelationsBetweenFactions.Friends)
                    {
                        continue;
                    }
                }

                if (Vector3D.Distance(Position, Player.PositionComp.GetPosition()) <= 15000)
                {
                    return(false);
                }
            }
            return(true);
        }
        public static void DoChatMessage(TorchChatMessage msg, ref bool consumed)
        {
            if (msg.AuthorSteamId == null)
            {
                return;
            }
            if (msg.Channel == Sandbox.Game.Gui.ChatChannel.Private || msg.Channel == Sandbox.Game.Gui.ChatChannel.Faction)
            {
                return;
            }
            if (msg.Message.StartsWith("!"))
            {
                return;
            }

            if (PeopleInAllianceChat.ContainsKey((ulong)msg.AuthorSteamId))
            {
                MyIdentity identity;
                if (IdentityIds.ContainsKey((ulong)msg.AuthorSteamId))
                {
                    identity = MySession.Static.Players.TryGetIdentity(IdentityIds[(ulong)msg.AuthorSteamId]);
                }
                else
                {
                    identity = AlliancePlugin.GetIdentityByNameOrId(msg.AuthorSteamId.ToString());
                }

                if (identity == null)
                {
                    return;
                }
                MyFaction fac = MySession.Static.Factions.GetPlayerFaction(identity.IdentityId);
                if (fac == null)
                {
                    bool noFac = true;
                    if (AlliancePlugin.GetIdentityByNameOrId(msg.Author) != null)
                    {
                        if (MySession.Static.Factions.GetPlayerFaction(AlliancePlugin.GetIdentityByNameOrId(msg.Author).IdentityId) != null)
                        {
                            noFac = false;
                            fac   = MySession.Static.Factions.GetPlayerFaction(AlliancePlugin.GetIdentityByNameOrId(msg.Author).IdentityId);
                        }
                    }

                    if (noFac)
                    {
                        PeopleInAllianceChat.Remove((ulong)msg.AuthorSteamId);
                        AlliancePlugin.SendChatMessage("Failsafe", "Faction null");
                    }
                    return;
                }
                if (AlliancePlugin.GetAllianceNoLoading(fac) == null)
                {
                    PeopleInAllianceChat.Remove((ulong)msg.AuthorSteamId);
                    AlliancePlugin.SendChatMessage("Failsafe", "Alliance null");
                    return;
                }
                consumed = true;
                Guid         allianceId   = PeopleInAllianceChat[(ulong)msg.AuthorSteamId];
                List <ulong> OtherMembers = new List <ulong>();

                Alliance alliance = AlliancePlugin.GetAllianceNoLoading(allianceId);
                // ShipyardCommands.SendMessage(msg.Author, "You are in alliance chat", Color.BlueViolet, (long)msg.AuthorSteamId);
                if (alliance.GetTitle((ulong)msg.AuthorSteamId).Equals(""))
                {
                    SendChatMessage(allianceId, msg.Author, msg.Message, true, identity.IdentityId);
                }
                else
                {
                    SendChatMessage(allianceId, alliance.GetTitle((ulong)msg.AuthorSteamId) + " | " + msg.Author, msg.Message, true, identity.IdentityId);
                }
            }
            else
            {
                //  PeopleInAllianceChat.Remove((ulong)msg.AuthorSteamId);
            }
        }
Example #20
0
 public FactionWrapper(MyFaction faction)
 {
     Faction = faction;
 }
        public static void SendChatMessage(Guid allianceId, string prefix, string message, bool toDiscord, long playerId)
        {
            prefix = prefix.Replace(":", "");
            Alliance     alliance     = AlliancePlugin.GetAllianceNoLoading(allianceId);
            List <ulong> OtherMembers = new List <ulong>();

            message = message.Replace("@", "");

            log.Info(allianceId.ToString() + " : " + alliance.name + " : " + prefix + " " + message);
            if (toDiscord && DiscordStuff.AllianceHasBot(allianceId))
            {
                try
                {
                    DiscordStuff.SendAllianceMessage(alliance, prefix, message);
                }
                catch (Exception ex)
                {
                    AlliancePlugin.Log.Error(ex);
                    if (DiscordStuff.debugMode)
                    {
                        if (MySession.Static.Players.GetPlayerByName("Crunch") != null)
                        {
                            MyPlayer player = MySession.Static.Players.GetPlayerByName("Crunch");
                            ShipyardCommands.SendMessage("Discord", "Bot not connected 1", Color.Blue, (long)player.Id.SteamId);
                        }
                    }
                }
            }
            else
            {
                if (DiscordStuff.debugMode)
                {
                    if (MySession.Static.Players.GetPlayerByName("Crunch") != null)
                    {
                        MyPlayer player = MySession.Static.Players.GetPlayerByName("Crunch");
                        ShipyardCommands.SendMessage("Discord", "Bot not connected 2", Color.Blue, (long)player.Id.SteamId);
                    }
                }
            }

            foreach (MyPlayer player in MySession.Static.Players.GetOnlinePlayers())
            {
                if (player.Identity.IdentityId == playerId)
                {
                    ShipyardCommands.SendMessage("Alliance chat", "You are in alliance chat.", new Color(alliance.r, alliance.g, alliance.b), (long)player.Id.SteamId);
                    continue;
                }
                MyFaction fac = MySession.Static.Factions.TryGetPlayerFaction(player.Identity.IdentityId) as MyFaction;
                if (fac != null)
                {
                    if (alliance.AllianceMembers.Contains(fac.FactionId))
                    {
                        OtherMembers.Add(player.Id.SteamId);
                    }
                }
            }

            foreach (ulong id in OtherMembers)
            {
                ShipyardCommands.SendMessage(prefix, message, new Color(alliance.r, alliance.g, alliance.b), (long)id);
                MyGpsCollection gpscol = (MyGpsCollection)MyAPIGateway.Session?.GPS;

                if (ScanChat(message, null) != null)
                {
                    MyGps gpsRef = ScanChat(message, null);
                    gpsRef.GPSColor      = Color.Yellow;
                    gpsRef.AlwaysVisible = true;
                    gpsRef.ShowOnHud     = true;

                    long idenId = MySession.Static.Players.TryGetIdentityId(id);
                    gpscol.SendAddGps(idenId, ref gpsRef);
                }
            }
        }
        public void RentGate(string name)
        {
            MyFaction fac = MySession.Static.Factions.GetPlayerFaction(Context.Player.IdentityId);

            if (fac == null)
            {
                Context.Respond("Only factions can be in alliances.");
                return;
            }
            Alliance alliance = AlliancePlugin.GetAlliance(fac);

            if (alliance == null)
            {
                Context.Respond("Only members of an alliance may rent a gate.");
                return;
            }
            if (alliance != null)
            {
                if (alliance.SupremeLeader == Context.Player.SteamUserId || alliance.HasAccess(Context.Player.SteamUserId, AccessLevel.PayFromBank))
                {
                    JumpGate gate1 = null;
                    JumpGate gate2 = null;
                    AlliancePlugin.LoadAllGates();
                    foreach (JumpGate gate in AlliancePlugin.AllGates.Values)
                    {
                        if (gate.GateName.Equals(name) && gate.CanBeRented && DateTime.Now >= gate.NextRentAvailable)
                        {
                            gate1 = gate;
                            gate2 = AlliancePlugin.AllGates[gate.TargetGateId];
                            break;
                        }
                    }
                    if (gate1 == null || gate2 == null)
                    {
                        Context.Respond("Could not find one of those gates.");
                        return;
                    }
                    if (alliance.CurrentMetaPoints >= gate1.MetaPointRentCost)
                    {
                        alliance.CurrentMetaPoints           -= gate1.MetaPointRentCost;
                        gate1.OwnerAlliance                   = alliance.AllianceId;
                        gate2.OwnerAlliance                   = alliance.AllianceId;
                        gate1.NextRentAvailable               = DateTime.Now.AddDays(gate1.DaysPerRent);
                        gate2.NextRentAvailable               = DateTime.Now.AddDays(gate1.DaysPerRent);
                        AlliancePlugin.AllGates[gate1.GateId] = gate1;
                        AlliancePlugin.AllGates[gate2.GateId] = gate2;
                        gate1.Save();
                        gate2.Save();
                        Context.Respond("Successfully rented gate for " + gate1.DaysPerRent + " Days. Fees can now be set with !jumpgate fee <gateName> <amount>");
                        Context.Respond("Gate names, " + gate1.GateName + ", " + gate2.GateName);
                        AlliancePlugin.SaveAllianceData(alliance);
                        return;
                    }
                    else
                    {
                        Context.Respond("Cannot afford the meta point cost of " + gate1.MetaPointRentCost);
                        return;
                    }
                }
                else
                {
                    Context.Respond("You dont have the rank to do this.");
                }
            }
        }
        public void SetFee(string name, string target, string inputAmount)
        {
            MyFaction fac = MySession.Static.Factions.GetPlayerFaction(Context.Player.IdentityId);

            if (fac == null)
            {
                Context.Respond("Only factions can be in alliances.");
                return;
            }
            Int64 amount;

            inputAmount = inputAmount.Replace(",", "");
            inputAmount = inputAmount.Replace(".", "");
            inputAmount = inputAmount.Replace(" ", "");
            try
            {
                amount = Int64.Parse(inputAmount);
            }
            catch (Exception)
            {
                Context.Respond("Error parsing amount", Color.Red, "Bank Man");
                return;
            }
            if (amount < 0 || amount == 0)
            {
                Context.Respond("Must be a positive amount", Color.Red, "Bank Man");
                return;
            }
            if (amount >= AlliancePlugin.config.MaximumGateFee)
            {
                Context.Respond("Amount exceeds the maximum of " + String.Format("{0:n0}", AlliancePlugin.config.MaximumGateFee) + " SC.");
                return;
            }
            Alliance alliance = AlliancePlugin.GetAlliance(fac);

            if (alliance == null)
            {
                Context.Respond("Only members of an alliance can set a gate fee.");
                return;
            }
            if (alliance != null)
            {
                if (alliance.SupremeLeader == Context.Player.SteamUserId || alliance.HasAccess(Context.Player.SteamUserId, AccessLevel.PayFromBank))
                {
                    JumpGate gate1 = null;
                    JumpGate gate2 = null;

                    foreach (JumpGate gate in AlliancePlugin.AllGates.Values)
                    {
                        if (gate.GateName.Equals(name) && gate.OwnerAlliance == alliance.AllianceId)
                        {
                            gate1 = gate;
                            continue;
                        }
                        if (gate.GateName.Equals(target) && gate.OwnerAlliance == alliance.AllianceId)
                        {
                            gate2 = gate;
                            continue;
                        }
                    }
                    if (gate1 == null || gate2 == null)
                    {
                        Context.Respond("Could not find one of those gates, does the alliance own it?.");
                        return;
                    }
                    Context.Respond("Fee updated.");
                    gate1.fee = amount;
                    gate2.fee = amount;
                    AlliancePlugin.AllGates[gate1.GateId] = gate1;
                    AlliancePlugin.AllGates[gate2.GateId] = gate2;
                    gate1.Save();
                    gate2.Save();
                }
                else
                {
                    Context.Respond("You dont have the rank to do this.");
                }
            }
        }
Example #24
0
        private bool CheckEnemyDistance(LoadType LoadingAtSavePoint, Vector3D Position = new Vector3D())
        {
            if (LoadingAtSavePoint == LoadType.ForceLoadMearPlayer)
            {
                Position = PlayerPosition;
            }

            MyFaction PlayersFaction = MySession.Static.Factions.GetPlayerFaction(IdentityID);
            bool      EnemyFoundFlag = false;



            if (Config.DistanceCheck > 0)
            {
                //Check enemy location! If under limit return!

                foreach (MyPlayer P in MySession.Static.Players.GetOnlinePlayers())
                {
                    if (P.Character == null || P.Character.MarkedForClose)
                    {
                        continue;
                    }

                    Vector3D Pos;
                    if (P.Character.IsUsing is MyCryoChamber || P.Character.IsUsing is MyCockpit)
                    {
                        Pos = (P.Character.IsUsing as MyCockpit).PositionComp.GetPosition();
                    }
                    else
                    {
                        Pos = P.GetPosition();
                    }


                    long PlayerID = P.Identity.IdentityId;
                    if (PlayerID == 0L)
                    {
                        continue;
                    }
                    if (PlayerID == IdentityID)
                    {
                        continue;
                    }

                    MyFaction TargetPlayerFaction = MySession.Static.Factions.GetPlayerFaction(PlayerID);
                    if (PlayersFaction != null && TargetPlayerFaction != null)
                    {
                        if (PlayersFaction.FactionId == TargetPlayerFaction.FactionId)
                        {
                            continue;
                        }

                        //Neutrals count as allies not friends for some reason
                        MyRelationsBetweenFactions Relation = MySession.Static.Factions.GetRelationBetweenFactions(PlayersFaction.FactionId, TargetPlayerFaction.FactionId).Item1;
                        if (Relation == MyRelationsBetweenFactions.Neutral || Relation == MyRelationsBetweenFactions.Friends)
                        {
                            continue;
                        }
                    }


                    if (Vector3D.Distance(Position, Pos) == 0)
                    {
                        continue;
                    }

                    if (Vector3D.Distance(Position, Pos) <= Config.DistanceCheck)
                    {
                        Chat?.Respond("Unable to load grid! Enemy within " + Config.DistanceCheck + "m!");
                        GpsSender.SendGps(Position, "Failed Hangar Load! (Enemy nearby)", IdentityID);
                        EnemyFoundFlag = true;
                        break;
                    }
                }
            }


            if (Config.GridDistanceCheck > 0 && Config.GridCheckMinBlock > 0 && EnemyFoundFlag == false)
            {
                BoundingSphereD SpawnSphere = new BoundingSphereD(Position, Config.GridDistanceCheck);

                List <MyEntity> entities = new List <MyEntity>();
                MyGamePruningStructure.GetAllTopMostEntitiesInSphere(ref SpawnSphere, entities);



                //This is looping through all grids in the specified range. If we find an enemy, we need to break and return/deny spawning
                foreach (MyCubeGrid Grid in entities.OfType <MyCubeGrid>())
                {
                    if (Grid == null || Grid.MarkedForClose)
                    {
                        continue;
                    }

                    if (Grid.BigOwners.Count <= 0 || Grid.CubeBlocks.Count < Config.GridCheckMinBlock)
                    {
                        continue;
                    }

                    if (Grid.BigOwners.Contains(IdentityID))
                    {
                        continue;
                    }



                    //if the player isnt big owner, we need to scan for faction mates
                    bool FoundAlly = true;
                    foreach (long Owner in Grid.BigOwners)
                    {
                        MyFaction TargetPlayerFaction = MySession.Static.Factions.GetPlayerFaction(Owner);


                        if (PlayersFaction != null && TargetPlayerFaction != null)
                        {
                            if (PlayersFaction.FactionId == TargetPlayerFaction.FactionId)
                            {
                                continue;
                            }

                            MyRelationsBetweenFactions Relation = MySession.Static.Factions.GetRelationBetweenFactions(PlayersFaction.FactionId, TargetPlayerFaction.FactionId).Item1;
                            if (Relation == MyRelationsBetweenFactions.Enemies)
                            {
                                FoundAlly = false;
                                break;
                            }
                        }
                        else
                        {
                            FoundAlly = false;
                            break;
                        }
                    }


                    if (!FoundAlly)
                    {
                        //Stop loop
                        Chat?.Respond("Unable to load grid! Enemy within " + Config.GridDistanceCheck + "m!");
                        GpsSender.SendGps(Position, "Failed Hangar Load! (Enemy nearby)", IdentityID);
                        EnemyFoundFlag = true;
                        break;
                    }
                }
            }
            return(!EnemyFoundFlag);
        }
Example #25
0
        public Boolean SaveGridToHangar(String gridName, ulong steamid, Alliance alliance, Vector3D position, MyFaction faction, List <MyCubeGrid> gridsToSave, long IdentityId)
        {
            if (!CheckGrids(position, IdentityId))
            {
                AlliancePlugin.Log.Info("Failed grid check");
                return(false);
            }

            if (!CheckCharacters(position, IdentityId))
            {
                AlliancePlugin.Log.Info("Failed character check");
                return(false);
            }
            HangarLog     log  = GetHangarLog(alliance);
            HangarLogItem item = new HangarLogItem();

            item.action   = "Saved";
            item.steamid  = steamid;
            item.GridName = gridName;
            item.time     = DateTime.Now;
            log.log.Add(item);
            utils.WriteToJsonFile <HangarLog>(AlliancePlugin.path + "//HangarData//" + alliance.AllianceId + "//log.json", log);
            HangarItem hangItem = new HangarItem();

            hangItem.name     = gridName;
            hangItem.steamid  = steamid;
            hangItem.position = position;
            ItemsInHangar.Add(getAvailableSlot(), hangItem);
            GridManager.SaveGridNoDelete(System.IO.Path.Combine(AlliancePlugin.path + "//HangarData//" + alliance.AllianceId + "//" + gridName + ".xml"), gridName, true, false, gridsToSave);
            if (AlliancePlugin.GridBackupInstalled)
            {
                List <MyObjectBuilder_CubeGrid> obBuilders = new List <MyObjectBuilder_CubeGrid>();
                foreach (MyCubeGrid grid in gridsToSave)
                {
                    obBuilders.Add(grid.GetObjectBuilder() as MyObjectBuilder_CubeGrid);
                }
                AlliancePlugin.BackupGridMethod(obBuilders, IdentityId);
            }
            utils.WriteToJsonFile <HangarData>(AlliancePlugin.path + "//HangarData//" + alliance.AllianceId + "//hangar.json", this);
            return(true);
        }
        public override bool HandleCommand(ulong userId, string[] words)
        {
            Essentials.Log.Info("Faction cleanup");
            MyFactionCollection factionCollection = MySession.Static.Factions;

            if (factionCollection == null)
            {
                Essentials.Log.Info("Fail");
                return(true);
            }
            HashSet <MyFaction> toDelete = new HashSet <MyFaction>( );
            bool verbose = words.Any( ) && words[0].ToLower( ) == "verbose";

            foreach (KeyValuePair <long, MyFaction> item in factionCollection)
            {
                MyFaction faction = item.Value;
                if (faction == null)
                {
                    continue;
                }

                //get factions with one or fewer members
                if (faction.Members.Count( ) <= 1)
                {
                    MyPlayer.PlayerId playerId;

                    //check if the member is a valid player
                    MyPlayer member;
                    if (!MySession.Static.Players.TryGetPlayerId(faction.Members.First( ).Value.PlayerId, out playerId))
                    {
                        toDelete.Add(faction);
                        continue;
                    }
                    //check if the player is online
                    //I'm not sure what happens if we delete a faction with a member logged in
                    //probably nothing, but maybe Clang
                    member = MySession.Static.Players.GetPlayerById(playerId);
                    if (member == null || member.Identity.IsDead)
                    {
                        toDelete.Add(faction);
                    }
                }
            }

            Essentials.Log.Info($"Found {toDelete.Count} factions to delete.");
            if (verbose)
            {
                Communication.SendPrivateInformation(userId, $"Found {toDelete.Count} factions to delete.");
            }
            int count = 0;

            foreach (MyFaction faction in toDelete)
            {
                if (faction == null)
                {
                    continue;
                }

                //make sure the faction still exists
                if (!factionCollection.Contains(faction.FactionId))
                {
                    continue;
                }

                //NPC factions
                if (faction.IsEveryoneNpc(  ))
                {
                    continue;
                }

                count++;
                if (verbose)
                {
                    Communication.SendPrivateInformation(userId, $"Removing faction {faction.Tag}: {faction.Name}");
                }

                if (DateTime.Now.Millisecond < 10)
                {
                    Communication.SendPrivateInformation(userId, $"Removed {count} of {toDelete.Count} factions.");
                }

                //delete the faction
                Wrapper.GameAction(() => MyFactionCollection.RemoveFaction(faction.FactionId));
            }

            Communication.SendPrivateInformation(userId, $"Removed {count} factions with one or fewer members.");

            return(true);
        }
Example #27
0
        public virtual bool CheckIfGridsAreRelevant(List <MyCubeGrid> grids, int distance, bool filterOffline, bool ignoreNpcs)
        {
            foreach (MyCubeGrid grid in grids)
            {
                var gridOwnerList = grid.BigOwners;
                var ownerCnt      = gridOwnerList.Count;
                var gridOwner     = 0L;

                if (ownerCnt > 0 && gridOwnerList[0] != 0)
                {
                    gridOwner = gridOwnerList[0];
                }
                else if (ownerCnt > 1)
                {
                    gridOwner = gridOwnerList[1];
                }

                if (gridOwner == 0)
                {
                    continue;
                }

                if (ignoreNpcs && MySession.Static.Players.IdentityIsNpc(gridOwner))
                {
                    continue;
                }

                MyFaction faction = MySession.Static.Factions.GetPlayerFaction(gridOwner);

                Vector3D gridPosition = grid.PositionComp.GetPosition();

                if (faction != null)
                {
                    bool allOffline = true;

                    foreach (long factionMember in faction.Members.Keys)
                    {
                        MyPlayer member = GetPlayerById(factionMember);

                        /* if member is not online and we filter offlines ignore. */
                        if (filterOffline && member == null)
                        {
                            continue;
                        }

                        /* If member is online we need to remember that not all players are offline. */
                        if (member != null)
                        {
                            allOffline = false;

                            Vector3D position = member.GetPosition();

                            /* If player is close by grid is relevant */
                            if (Vector3D.Distance(gridPosition, position) <= distance)
                            {
                                return(true);
                            }
                        }
                    }

                    /* If all players of that faction are offline. And we dont want to filter offlines grid is relevant. */
                    if (allOffline && !filterOffline)
                    {
                        return(true);
                    }
                }
                else
                {
                    MyPlayer owner = GetPlayerById(gridOwner);

                    /* If owner is offline and we dont want to see offlines continue */
                    if (filterOffline && owner == null)
                    {
                        continue;
                    }

                    if (owner != null)
                    {
                        /* If player is online check distance */

                        Vector3D position = owner.GetPosition();

                        if (Vector3D.Distance(gridPosition, position) <= distance)
                        {
                            return(true);
                        }
                    }
                    else if (!filterOffline)
                    {
                        /* if player is offline and we want to see offlines mark as relevant */
                        return(true);
                    }
                }
            }

            return(false);
        }
Example #28
0
        public static bool IsExcepted(object target, LimitItem limit = null)
        {
            if (target == null)
            {
                return(false);
            }

            HashSet <string> allExceptions = new HashSet <string>();

            if (limit != null)
            {
                allExceptions = new HashSet <string>(limit.Exceptions);
            }
            allExceptions.UnionWith(BlockLimiterConfig.Instance.GeneralException);

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

            MyIdentity     identity      = null;
            MyFaction      faction       = null;
            long           identityId    = 0;
            ulong          playerSteamId = 0;
            string         displayName   = "";
            HashSet <long> gridOwners    = new HashSet <long>();

            switch (target)
            {
            case HashSet <long> owners:
                gridOwners.UnionWith(owners);
                break;

            case ulong steamId:
                if (steamId == 0)
                {
                    return(false);
                }
                playerSteamId = steamId;
                identityId    = GetPlayerIdFromSteamId(steamId);
                identity      = MySession.Static.Players.TryGetIdentity(identityId);
                displayName   = identity.DisplayName;
                faction       = MySession.Static.Factions.GetPlayerFaction(identityId);
                break;

            case string name:
                if (allExceptions.Contains(name))
                {
                    return(true);
                }
                if (TryGetPlayerByNameOrId(name, out identity))
                {
                    identityId    = identity.IdentityId;
                    faction       = MySession.Static.Factions.GetPlayerFaction(identityId);
                    displayName   = identity.DisplayName;
                    playerSteamId = GetSteamIdFromPlayerId(identityId);
                }
                break;

            case long id:
                if (id == 0)
                {
                    return(false);
                }
                identityId = id;
                identity   = MySession.Static.Players.TryGetIdentity(id);
                if (identity != null)
                {
                    faction       = MySession.Static.Factions.GetPlayerFaction(id);
                    displayName   = identity.DisplayName;
                    playerSteamId = GetSteamIdFromPlayerId(id);
                }
                else
                {
                    faction = (MyFaction)MySession.Static.Factions.TryGetFactionById(id);
                }
                if (MyEntities.TryGetEntityById(id, out var entity))
                {
                    if (allExceptions.Contains(entity.DisplayName))
                    {
                        return(true);
                    }
                }

                if (GridCache.TryGetGridById(id, out var foundGrid))
                {
                    gridOwners.UnionWith(GridCache.GetOwners(foundGrid));
                    if (allExceptions.Contains(foundGrid.DisplayName))
                    {
                        return(true);
                    }
                }
                break;

            case MyFaction targetFaction:
                if (allExceptions.Contains(targetFaction.Tag) ||
                    allExceptions.Contains(targetFaction.FactionId.ToString()))
                {
                    return(true);
                }
                break;

            case MyPlayer player:
                playerSteamId = player.Character.ControlSteamId;
                if (playerSteamId == 0)
                {
                    return(false);
                }
                if (allExceptions.Contains(playerSteamId.ToString()))
                {
                    return(true);
                }
                identityId = GetPlayerIdFromSteamId(playerSteamId);
                if (identityId > 0)
                {
                    if (allExceptions.Contains(identityId.ToString()))
                    {
                        return(true);
                    }
                    identity    = MySession.Static.Players.TryGetIdentity(identityId);
                    displayName = identity.DisplayName;
                }
                break;

            case MyCubeGrid grid:
            {
                if (allExceptions.Contains(grid.DisplayName) || allExceptions.Contains(grid.EntityId.ToString()))
                {
                    return(true);
                }
                var owners = GridCache.GetOwners(grid);
                if (owners.Count == 0)
                {
                    break;
                }
                gridOwners.UnionWith(owners);
                break;
            }
            }

            foreach (var owner in gridOwners)
            {
                if (owner == 0)
                {
                    continue;
                }
                if (allExceptions.Contains(owner.ToString()))
                {
                    return(true);
                }
                identity      = MySession.Static.Players.TryGetIdentity(owner);
                playerSteamId = GetSteamIdFromPlayerId(owner);
                if (playerSteamId > 0 && allExceptions.Contains(playerSteamId.ToString()))
                {
                    return(true);
                }
                if (identity != null)
                {
                    if (allExceptions.Contains(identity.DisplayName))
                    {
                        return(true);
                    }
                }
                faction = MySession.Static.Factions.GetPlayerFaction(owner);
                if (faction != null && (allExceptions.Contains(faction.Tag) ||
                                        allExceptions.Contains(faction.FactionId.ToString())))
                {
                    return(true);
                }
            }

            if (playerSteamId > 0 && allExceptions.Contains(playerSteamId.ToString()))
            {
                return(true);
            }
            if (identityId > 0 && allExceptions.Contains(identityId.ToString()))
            {
                return(true);
            }
            if (identity != null && allExceptions.Contains(identity.DisplayName))
            {
                return(true);
            }
            if (faction != null && (allExceptions.Contains(faction.Tag) || allExceptions.Contains(faction.FactionId.ToString())))
            {
                return(true);
            }
            if (!string.IsNullOrEmpty(displayName) && allExceptions.Contains(displayName))
            {
                return(true);
            }
            return(false);
        }
        internal MyTradeShipAttackResult AttackTradeShip(string tag, TimeSpan time, out MyTradeShipFight fight)
        {
            fight = null;
            if (!Faction.Attack)
            {
                return(MyTradeShipAttackResult.NoAttack);
            }
            if (Faction.Tag == tag)
            {
                return(MyTradeShipAttackResult.YourShip);
            }
            string factionTag = GetTradeShips().Find(x => x == tag);

            if (string.IsNullOrWhiteSpace(factionTag))
            {
                return(MyTradeShipAttackResult.NotFound);
            }
            MyFaction enemy = MySave.Factions.Find(x => x.Tag == tag);

            if (enemy is null)
            {
                return(MyTradeShipAttackResult.NotFound);
            }
            MyPolitic policits = MySave.Politics.Find(x => x.Factions.Item1 == Faction.Tag && (x.Factions.Item2 == enemy.Tag) ^ (x.Factions.Item2 == Faction.Tag) && x.Factions.Item1 == enemy.Tag) ?? throw new ArgumentException("Данные отношений не найдены", nameof(Faction));

            if (!(policits.Status == MyPoliticStatus.War || Faction.FactionType == FactionType.Pirate))
            {
                return(MyTradeShipAttackResult.NotInWar);
            }

            if (MySave.BotSettings.ActivityTime.Item1 > time || MySave.BotSettings.ActivityTime.Item2 < time)
            {
                return(MyTradeShipAttackResult.InvalidAdminTime);
            }
            if (Faction.ActiveInterval.start > time || Faction.ActiveInterval.finish < time)
            {
                return(MyTradeShipAttackResult.InvalidYourTime);
            }
            if (enemy.ActiveInterval.start > time || enemy.ActiveInterval.finish < time)
            {
                return(MyTradeShipAttackResult.InvalidEnemyTime);
            }

            if (enemy.Ships.Values.Sum() == 0)
            {
                enemy.TradeShipStatus = TradeShipStatus.None;
                Faction.Resourses    %= Faction.FactionType == FactionType.Pirate ? 250 : 125;
                Faction.Attack        = false;
                return(MyTradeShipAttackResult.OkNoFight);
            }

            enemy.TradeShipStatus = TradeShipStatus.Attacked;
            DateTime date = DateTime.UtcNow.Date.AddDays(1.0) + time;

            if (date < DateTime.UtcNow)
            {
                date = date.AddDays(1.0);
            }
            fight         = new MyTradeShipFight(Faction.Tag, enemy.Tag, date);
            MySave.Fights = MySave.Fights.Add(fight);
            return(MyTradeShipAttackResult.Ok);
        }
Example #30
0
        public Boolean LoadGridFromHangar(int slotNum, ulong steamid, Alliance alliance, MyIdentity identity, MyFaction faction)
        {
            HangarItem hangItem = ItemsInHangar[slotNum];

            if (!CheckGrids(hangItem.position, identity.IdentityId))
            {
                return(false);
            }

            if (!CheckCharacters(hangItem.position, identity.IdentityId))
            {
                return(false);
            }

            if (!GridManager.LoadGrid(System.IO.Path.Combine(AlliancePlugin.path + "//HangarData//" + alliance.AllianceId + "//" + ItemsInHangar[slotNum].name + ".xml"), ItemsInHangar[slotNum].position, true, steamid, ItemsInHangar[slotNum].name))
            {
                if (!GridManager.LoadGrid(System.IO.Path.Combine(AlliancePlugin.path + "//HangarData//" + alliance.AllianceId + "//" + ItemsInHangar[slotNum].name + ".xml"), ItemsInHangar[slotNum].position, false, steamid, ItemsInHangar[slotNum].name))
                {
                    return(false);
                }
            }

            HangarLog     log  = GetHangarLog(alliance);
            HangarLogItem item = new HangarLogItem();

            item.action   = "Loaded";
            item.steamid  = steamid;
            item.GridName = ItemsInHangar[slotNum].name;
            item.time     = DateTime.Now;
            log.log.Add(item);
            utils.WriteToJsonFile <HangarLog>(AlliancePlugin.path + "//HangarData//" + alliance.AllianceId + "//log.json", log);


            if (AlliancePlugin.GridBackupInstalled)
            {
                List <MyObjectBuilder_CubeGrid> obBuilders = new List <MyObjectBuilder_CubeGrid>();
                obBuilders = GridManager.GetObjectBuilders(AlliancePlugin.path + "//HangarData//" + alliance.AllianceId + "//" + ItemsInHangar[slotNum].name + ".xml");
                if (obBuilders != null)
                {
                    AlliancePlugin.BackupGridMethod(obBuilders, identity.IdentityId);
                }
                else
                {
                    AlliancePlugin.Log.Error("Error saving a backup when loading this grid");
                }
            }

            File.Delete(AlliancePlugin.path + "//HangarData//" + alliance.AllianceId + "//" + ItemsInHangar[slotNum].name + ".xml");
            ItemsInHangar.Remove(slotNum);
            List <HangarItem> temp = new List <HangarItem>();

            foreach (HangarItem hangitem in ItemsInHangar.Values)
            {
                temp.Add(hangitem);
            }
            ItemsInHangar.Clear();
            int i = 1;

            foreach (HangarItem hangitem in temp)
            {
                ItemsInHangar.Add(i, hangitem);
                i++;
            }
            utils.WriteToJsonFile <HangarData>(AlliancePlugin.path + "//HangarData//" + alliance.AllianceId + "//hangar.json", this);

            return(true);
        }