public void ReplaceInAll(string target, string replacement)
            {
                List <IMyTerminalBlock> blockList = new List <IMyTerminalBlock>();

                gridTerminalSystem.GetBlocks(blockList);
                Replace(target, replacement, blockList);
            }
Esempio n. 2
0
        public void Sync(IMyGridTerminalSystem GridTerminalSystem, IMyCubeGrid grid)
        {
            MergeBlocks.Clear();
            MiningDrills.Clear();
            GatlingGuns.Clear();
            RocketLaunchers.Clear();
            ProgramBlocks.Clear();
            LaserAntennas.Clear();
            RadioAntennas.Clear();
            TextPanels.Clear();
            ControlUnits.Clear();
            Connectors.Clear();
            Sensors.Clear();
            Gyros.Clear();
            Thrusters.Clear();
            Cameras.Clear();
            AllBlocks.Clear();
            AllMyBlocks.Clear();
            Reactors.Clear();
            Batteries.Clear();
            Groups.Clear();

            GridTerminalSystem.GetBlocks(AllBlocks);
            GridTerminalSystem.GetBlocksOfType(AllMyBlocks, b => b.CubeGrid == grid);
            GridTerminalSystem.GetBlocksOfType(MergeBlocks, b => b.CubeGrid == grid);
            GridTerminalSystem.GetBlocksOfType(Cameras, b => b.CubeGrid == grid);
            GridTerminalSystem.GetBlocksOfType(Gyros, b => b.CubeGrid == grid);
            GridTerminalSystem.GetBlocksOfType(Thrusters, b => b.CubeGrid == grid);
            GridTerminalSystem.GetBlocksOfType(Sensors, b => b.CubeGrid == grid);
            GridTerminalSystem.GetBlocksOfType(Connectors, b => b.CubeGrid == grid);
            GridTerminalSystem.GetBlocksOfType(ProgramBlocks, b => b.CubeGrid == grid);
            GridTerminalSystem.GetBlocksOfType(LaserAntennas, b => b.CubeGrid == grid);
            GridTerminalSystem.GetBlocksOfType(RadioAntennas, b => b.CubeGrid == grid);
            GridTerminalSystem.GetBlocksOfType(TextPanels, b => b.CubeGrid == grid);
            GridTerminalSystem.GetBlocksOfType(ControlUnits, b => b.CubeGrid == grid);
            GridTerminalSystem.GetBlocksOfType(MiningDrills, b => b.CubeGrid == grid);
            GridTerminalSystem.GetBlocksOfType(GatlingGuns, b => b.CubeGrid == grid);
            GridTerminalSystem.GetBlocksOfType(RocketLaunchers, b => b.CubeGrid == grid);
            GridTerminalSystem.GetBlocksOfType(Reactors, b => b.CubeGrid == grid);
            GridTerminalSystem.GetBlocksOfType(Batteries, b => b.CubeGrid == grid);
            GridTerminalSystem.GetBlockGroups(Groups);

            foreach (var sensor in Sensors)
            {
                sensor.DetectEnemy      = true;
                sensor.DetectPlayers    = true;
                sensor.DetectLargeShips = true;
                sensor.DetectSmallShips = true;
                sensor.DetectOwner      = true;
                sensor.DetectStations   = true;
                sensor.DetectAsteroids  = true;

                sensor.BackExtend   = 50;
                sensor.FrontExtend  = 50;
                sensor.LeftExtend   = 50;
                sensor.RightExtend  = 50;
                sensor.TopExtend    = 50;
                sensor.BottomExtend = 50;
            }
        }
        public static IEnumerable <IMyTerminalBlock> GetBlocks(this IMyGridTerminalSystem src)
        {
            var temp = new List <IMyTerminalBlock>();

            src.GetBlocks(temp);
            return(temp);
        }
Esempio n. 4
0
    /*** Refreshes blocks.  If you add or remove blocks, call this. ***/
    public void Refresh()
    {
        List <IMyTerminalBlock> kBlocks = new List <IMyTerminalBlock>();

        GridTerminalSystem.GetBlocks(kBlocks);
        Blocks = new EasyBlocks(kBlocks);
    }
Esempio n. 5
0
        public static void gridDestructible(IMyCubeGrid grid, bool enable)
        {
            IMyGridTerminalSystem gridTerminal = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid(grid);

            if (gridTerminal == null)
            {
                return;
            }
            List <IMyTerminalBlock> blocks = new List <IMyTerminalBlock>();

            gridTerminal.GetBlocks(blocks);
            HashSet <VRage.Game.ModAPI.Ingame.IMyCubeGrid> applied = new HashSet <VRage.Game.ModAPI.Ingame.IMyCubeGrid>();

            foreach (var block in blocks)
            {
                if (applied.Contains(block.CubeGrid))
                {
                    continue;
                }

                applied.Add(block.CubeGrid);
                (block.CubeGrid as MyCubeGrid).DestructibleBlocks = enable;
            }
            if (!applied.Contains(grid))
            {
                (grid as MyCubeGrid).DestructibleBlocks = enable;
            }
        }
Esempio n. 6
0
        public static bool isActiveBeaconSecurity(IMyCubeGrid grid)
        {
            if (grid == null)
            {
                return(false);
            }

            IMyGridTerminalSystem gridTerminal = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid(grid);

            if (gridTerminal == null)
            {
                return(false);
            }
            List <IMyTerminalBlock> blocks = new List <IMyTerminalBlock>();

            gridTerminal.GetBlocks(blocks);
            foreach (var block in blocks)
            {
                BeaconSecurity bs = block.GameLogic as BeaconSecurity;
                if (bs != null && bs.IsBeaconSecurity && bs.OwnerId != 0 && bs.IsWorking)
                {
                    return(true); // one beacon removed, one more stay - nothing to do...
                }
            }
            return(false);
        }
        private List <IMyTerminalBlock> GetBlocksInCurrentGrid(IMyProgrammableBlock pbInstance, IMyGridTerminalSystem GTS)
        {
            List <IMyTerminalBlock> blocks = new List <IMyTerminalBlock>();

            GTS.GetBlocks(blocks);

            return(blocks.Where(block => block.CubeGrid == pbInstance.CubeGrid).ToList());
        }
 public void ScanMiscInventories(IMyGridTerminalSystem GTS, GridManager gridManager, bool full)
 {
     if (full)
     {
         List <IMyTerminalBlock> blocks = new List <IMyTerminalBlock>();
         GTS.GetBlocks(blocks);
         _inventoryOwners = blocks.FindAll(block => Filter(block, gridManager));
     }
     else
     {
         _inventoryOwners = _inventoryOwners.FindAll(block => block.GetInventory() != null);
     }
 }
Esempio n. 9
0
        virtual protected List <IMyTerminalBlock> GetHackedBlocks()
        {
            List <IMyTerminalBlock> TerminalBlocks = new List <IMyTerminalBlock>();
            List <IMyTerminalBlock> HackedBlocks   = new List <IMyTerminalBlock>();

            Term.GetBlocks(TerminalBlocks);

            foreach (IMyTerminalBlock Block in TerminalBlocks)
            {
                if (Block.IsBeingHacked)
                {
                    HackedBlocks.Add(Block);
                }
            }

            return(HackedBlocks);
        }
Esempio n. 10
0
        List <IMyLightingBlock> GetLights()
        {
            List <IMyLightingBlock> lBlocks   = new List <IMyLightingBlock>();
            List <IMyTerminalBlock> allBlocks = new List <IMyTerminalBlock>();



            GridTerminalSystem.GetBlocks(allBlocks); // Where allBlocks is a list type.

            for (int i = 0; i < allBlocks.Count; i++)
            {
                if (allBlocks[i] is IMyLightingBlock && allBlocks[i].CustomName.Contains("BL"))
                {
                    lBlocks.Add(allBlocks[i] as IMyLightingBlock);
                }
            }

            return(lBlocks);
        }
Esempio n. 11
0
        protected bool TrackTargetPickSubtarget(Ingame.MyDetectedEntityInfo Target)
        {
            if (TurretPosition.DistanceTo(Target.Position) > Turret.Range)
            {
                return(false);
            }
            if (!Target.IsGrid())
            {
                IMyEntity TargetEntity = MyAPIGateway.Entities.GetEntityById(Target.EntityId);
                if (TurretPosition.DistanceTo(TargetEntity.GetPosition()) > Turret.Range)
                {
                    return(false);
                }
                Turret.TrackTarget(TargetEntity);
                return(true);
            }
            IMyCubeGrid Grid = MyAPIGateway.Entities.GetEntityById(Target.EntityId) as IMyCubeGrid;

            if (Grid == null)
            {
                return(false);
            }
            List <IMyTerminalBlock> TermBlocks = new List <IMyTerminalBlock>();
            IMyGridTerminalSystem   Term       = Grid.GetTerminalSystem();

            if (Term == null)
            {
                return(false);
            }
            Term.GetBlocks(TermBlocks);
            TermBlocks.RemoveAll(x => !x.IsFunctional);
            if (!TermBlocks.Any())
            {
                Turret.TrackTarget(Grid);
                return(true);
            }

            var PrioritizedBlocks = TermBlocks.OrderByDescending(x => PriorityIndex(x)).ThenBy(x => DistanceSq(x.GetPosition()));

            Turret.TrackTarget(PrioritizedBlocks.First());
            return(true);
        }
Esempio n. 12
0
        public void Main()
        {
            Blocks = new List <IMyTerminalBlock>();
            List <IMyAssembler>      assemblers      = new List <IMyAssembler>();
            List <IMyRefinery>       refineries      = new List <IMyRefinery>();
            List <IMyRadioAntenna>   antennas        = new List <IMyRadioAntenna>();
            List <IMyTextPanel>      textPanels      = new List <IMyTextPanel>();
            List <IMyCargoContainer> cargoContainers = new List <IMyCargoContainer>();



            GridTerminalSystem.GetBlocks(Blocks);
            GridTerminalSystem.GetBlocksOfType(assemblers);
            GridTerminalSystem.GetBlocksOfType(refineries);
            GridTerminalSystem.GetBlocksOfType(antennas);
            GridTerminalSystem.GetBlocksOfType(textPanels);
            GridTerminalSystem.GetBlocksOfType(cargoContainers);

            List <IMyCargoContainer> primaryStorage = GetPrimaryStorage(cargoContainers);


            OrganizeInventory(primaryStorage);
            //foreach (IMyCargoContainer block in cargoContainers)
            //{

            //    Echo(block.DefinitionDisplayNameText + " " + IsLargeCargo(block));
            //}


            //Dictionary<string, IMyInventoryItem> InventoryObjects = GetInvetoryObjects();

            //IMyTerminalBlock programmableBlock = Blocks.Where(b => b.CustomName == "Programmable block").FirstOrDefault();

            //programmableBlock.CustomData = "";

            //foreach (KeyValuePair<string, IMyInventoryItem> nameObjectPair in InventoryObjects)
            //{

            //    programmableBlock.CustomData += string.Format("{0}-{1}\n", nameObjectPair.Key, GetItemTypeName(nameObjectPair.Value));
            //    Echo(nameObjectPair.Key + " " + GetItemTypeName(nameObjectPair.Value));
            //}
        }
Esempio n. 13
0
        protected double GetCargoMass()
        {
            double mass = 0;
            List <IMyTerminalBlock> blocks = new List <IMyTerminalBlock>();

            GridTerminalSystem.GetBlocks(blocks);
            for (int i = 0; i < blocks.Count; i++)
            {
                var count = blocks[i].GetInventoryCount(); // Multiple inventories in Refineriers, Assemblers, Arc Furnances.
                for (var inv = 0; inv < count; inv++)
                {
                    var inventory = blocks[i].GetInventory(inv);
                    if (inventory != null) // null means, no items in inventory.
                    {
                        mass += (double)inventory.CurrentMass;
                    }
                }
            }
            return(mass);
        }
Esempio n. 14
0
        //All three must be true
        //Ship is not trash
        //Ship Controlls are functional
        //Weapons Exist on ship
        //There have been a few added restrictions that must be true for a ship[ to be alive
        public bool IsAlive()
        {
            string errors      = "";
            bool   shipWorking = true;

            try
            {
                if (ShipControls != null &&
                    (!((Sandbox.ModAPI.Ingame.IMyCubeBlock)ShipControls).IsWorking)) // ||
                //!((Sandbox.ModAPI.Ingame.IMyCubeBlock) ShipControls).IsWorking))
                {
                    errors     += "Ship Controlls are down: ";
                    shipWorking = false;
                }
                if (ShipControls == null)
                {
                    errors     += "Ship Controlls are down: ";
                    shipWorking = false;
                }


                List <IMyTerminalBlock> allBlocks = new List <IMyTerminalBlock>();
                GridTerminalSystem.GetBlocks(allBlocks);
                if (Ship != null && allBlocks.Count < 10)
                {
                    errors     += "Ship Too Small: ";
                    shipWorking = false;
                }

                if (Ship != null && Ship.Physics.Mass < 1000)
                {
                    errors     += "Ship Too Small: ";
                    shipWorking = false;
                }

                if (Ship != null && Ship.IsTrash())
                {
                    errors     += "The ship is trashed: ";
                    shipWorking = false;
                }
                if (Ship == null)
                {
                    errors     += "The ship is trashed: ";
                    shipWorking = false;
                }

                if (Ship != null && !Ship.InScene)
                {
                    errors     += "The ship is trashed: ";
                    shipWorking = false;
                }

                if (!shipWorking && navigation != null)
                {
                    navigation.TurnOffGyros(false);
                    ManualFire(false);
                    _beaconName = "Disabled Drone: " + errors;
                    NameBeacon();
                }
                if (!shipWorking)
                {
                    Util.GetInstance().Log("[Drone.IsAlive] A Drone Has Died -> ", "droneDeaths.txt");
                }
            }

            catch
            {
                shipWorking = false;
            }
            return(shipWorking);
        }
Esempio n. 15
0
        //this method will look for active ship grids/drones/players and keep killing them untill it cant find any within
        //its local known nearby objects
        public bool FindNearbyAttackTarget()
        {
            //return false;
            FindWeapons();
            ClearTarget();

            Dictionary <IMyEntity, IMyEntity> nearbyDrones      = new Dictionary <IMyEntity, IMyEntity>();
            Dictionary <IMyEntity, IMyEntity> nearbyOnlineShips = new Dictionary <IMyEntity, IMyEntity>();
            List <IMyPlayer> nearbyPlayers = new List <IMyPlayer>();



            MyAPIGateway.Players.GetPlayers(nearbyPlayers);
            nearbyPlayers =
                nearbyPlayers.Where(
                    x => x.PlayerID != _ownerId && (x.GetPosition() - Ship.GetPosition()).Length() < 2000)
                .ToList();

            bool playersNearby = nearbyPlayers.Any();

            Util.GetInstance().Log("[Drone.FindNearbyAttacktarget] enemy players nearby? " + playersNearby);
            for (int i = 0; i < _nearbyFloatingObjects.Count; i++)
            {
                if ((_nearbyFloatingObjects.ToList()[i].GetPosition() - Ship.GetPosition()).Length() > 10)
                {
                    var entity = _nearbyFloatingObjects.ToList()[i];

                    var grid = entity as IMyCubeGrid;
                    if (grid != null)
                    {
                        var gridTerminal = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid(grid);

                        List <IMyTerminalBlock> val = new List <IMyTerminalBlock>();
                        gridTerminal.GetBlocks(val);
                        var isFriendly = GridFriendly(val);

                        List <IMyTerminalBlock> T = new List <IMyTerminalBlock>();
                        gridTerminal.GetBlocksOfType <IMyRemoteControl>(T);

                        List <IMyTerminalBlock> reactorBlocks = new List <IMyTerminalBlock>();
                        gridTerminal.GetBlocksOfType <IMyPowerProducer>(reactorBlocks);


                        bool isOnline =
                            reactorBlocks.Exists(x => (x.IsWorking) && !isFriendly);

                        bool isDrone =
                            T.Exists(
                                x =>
                                (((IMyRemoteControl)x).CustomName.Contains("Drone#") && x.IsWorking &&
                                 !isFriendly));


                        var droneControl =
                            (IMyEntity)
                            T.FirstOrDefault(
                                x => ((IMyRemoteControl)x).CustomName.Contains("Drone#") && x.IsWorking &&
                                !isFriendly);

                        var shipPower =
                            (IMyEntity)
                            reactorBlocks.FirstOrDefault(
                                x => (((IMyPowerProducer)x).CurrentPowerOutput > 0 && x.IsWorking) && !isFriendly);


                        Util.GetInstance().Log(entity.Name + "   " + isOnline + ":Online " + isDrone + ":Drone " + (shipPower != null) + ":hasPower", "friendly.txt");
                        Util.GetInstance().Log(" ", "friendly.txt");
                        if (isDrone && isOnline)
                        {
                            nearbyDrones.Add(grid, droneControl);
                        }
                        else if (isOnline)
                        {
                            nearbyOnlineShips.Add(grid, shipPower ?? droneControl);
                        }
                    }
                }
            }

            if (nearbyDrones.Count > 0)
            {
                Util.GetInstance().Log("[Drone.FindNearbyAttacktarget] nearby drone count " + nearbyDrones.Count);
                var myTarget =
                    nearbyDrones
                    .OrderBy(x => (x.Key.GetPosition() - Ship.GetPosition()).Length())
                    .ToList();

                if (myTarget.Count > 0)
                {
                    var target = myTarget[0];


                    IMyGridTerminalSystem   gridTerminal = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid((IMyCubeGrid)target.Key);
                    List <IMyTerminalBlock> T            = new List <IMyTerminalBlock>();
                    gridTerminal.GetBlocks(T);

                    if (T.Count >= _minTargetSize)
                    {
                        _target       = (IMyCubeGrid)target.Key;
                        _targetPlayer = null;
                        try
                        {
                            if (!FindTargetKeyPoint(_target, _target.Physics.LinearVelocity))
                            {
                                OrbitAttackTarget(_target.GetPosition(), _target.Physics.LinearVelocity);
                            }
                            return(true);
                        }
                        catch
                        {
                        }
                    }
                }
            }

            if (nearbyOnlineShips.Count > 0)
            {
                Util.GetInstance().Log("[Drone.FindNearbyAttacktarget] nearby ship count " + nearbyOnlineShips.Count);
                var myTargets =
                    nearbyOnlineShips
                    .OrderBy(x => (x.Key.GetPosition() - Ship.GetPosition()).Length())
                    .ToList();

                foreach (var target in myTargets)
                {
                    IMyGridTerminalSystem   gridTerminal = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid((IMyCubeGrid)target.Key);
                    List <IMyTerminalBlock> T            = new List <IMyTerminalBlock>();
                    gridTerminal.GetBlocks(T);

                    if (T.Count >= _minTargetSize)
                    {
                        _target       = (IMyCubeGrid)target.Key;
                        _targetPlayer = null;
                        try
                        {
                            FindTargetKeyPoint(_target, _target.Physics.LinearVelocity);

                            return(true);
                        }
                        catch { OrbitAttackTarget(_target.GetPosition(), _target.Physics.LinearVelocity); }
                    }
                }
            }

            //if (playersNearby && nearbyPlayers.Count > 0)
            //{
            //    Util.GetInstance().Log("[Drone.FindNearbyAttacktarget] nearby player count " + nearbyPlayers.Count);
            //    var myTarget = nearbyPlayers.OrderBy(x => ((x).GetPosition() - Ship.GetPosition()).Length()).ToList();

            //    if (myTarget.Count > 0)
            //    {
            //        _target = null;
            //        _targetPlayer = myTarget[0];
            //        OrbitAttackTarget(_targetPlayer.GetPosition(), new Vector3D(0, 0, 0));
            //        return true;
            //    }
            //}
            return(false);
        }
Esempio n. 16
0
        public IMyCubeGrid FindEnemyTarget()
        {
            _target = null;
            Dictionary <IMyEntity, IMyEntity> nearbyOnlineShips = new Dictionary <IMyEntity, IMyEntity>();
            Dictionary <IMyEntity, IMyEntity> nearbyDrones      = new Dictionary <IMyEntity, IMyEntity>();
            bool targetSet = false;

            for (int i = 0; i < _nearbyFloatingObjects.Count; i++)
            {
                if ((_nearbyFloatingObjects.ToList()[i].GetPosition() - Ship.GetPosition()).Length() > 10)
                {
                    var entity = _nearbyFloatingObjects.ToList()[i];

                    var grid = entity as IMyCubeGrid;
                    if (grid != null)
                    {
                        var gridTerminal = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid(grid);

                        List <Sandbox.ModAPI.Ingame.IMyTerminalBlock> val = new List <IMyTerminalBlock>();
                        gridTerminal.GetBlocks(val);
                        var isFriendly = GridFriendly(val);

                        List <IMyTerminalBlock> T = new List <IMyTerminalBlock>();
                        gridTerminal.GetBlocksOfType <IMyRemoteControl>(T);

                        List <IMyTerminalBlock> reactorBlocks = new List <IMyTerminalBlock>();
                        gridTerminal.GetBlocksOfType <IMyReactor>(reactorBlocks);

                        List <IMyTerminalBlock> batteryBlocks = new List <IMyTerminalBlock>();
                        gridTerminal.GetBlocksOfType <IMyBatteryBlock>(batteryBlocks);


                        bool isOnline =
                            (reactorBlocks.Exists(x => (x.IsWorking)) ||
                             batteryBlocks.Exists(x => (x.IsWorking))) && !isFriendly;

                        bool isDrone =
                            T.Exists(
                                x =>
                                (((IMyRemoteControl)x).CustomName.Contains("Drone#") && x.IsWorking &&
                                 !isFriendly));


                        var droneControl =
                            (IMyEntity)
                            T.FirstOrDefault(
                                x => ((IMyRemoteControl)x).CustomName.Contains("Drone#") && x.IsWorking &&
                                !isFriendly);

                        var shipPower =
                            (IMyEntity)
                            reactorBlocks.FirstOrDefault(
                                x => x.IsWorking && !isFriendly);

                        if (isDrone && isOnline)
                        {
                            nearbyDrones.Add(grid, droneControl);
                        }
                        else if (isOnline)
                        {
                            if (!nearbyOnlineShips.ContainsKey(grid))
                            {
                                nearbyOnlineShips.Add(grid, shipPower ?? droneControl);
                            }
                        }
                    }
                }
            }

            if (nearbyDrones.Count > 0)
            {
                var myTarget =
                    nearbyDrones
                    .OrderBy(x => (x.Key.GetPosition() - Ship.GetPosition()).Length())
                    .ToList();

                if (myTarget.Count > 0)
                {
                    var target = myTarget[0];


                    IMyGridTerminalSystem gridTerminal =
                        MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid((IMyCubeGrid)target.Key);
                    List <IMyTerminalBlock> T = new List <IMyTerminalBlock>();
                    gridTerminal.GetBlocks(T);

                    if (T.Count >= _minTargetSize)
                    {
                        if (!targetSet)
                        {
                            _target       = (IMyCubeGrid)target.Key;
                            _targetPlayer = null;
                            targetSet     = true;
                        }
                        if (!targets.ContainsKey(_target))
                        {
                            targets.Add(_target, new TargetDetails(_target));
                        }
                    }
                }
            }

            if (nearbyOnlineShips.Count > 0)
            {
                var myTargets =
                    nearbyOnlineShips
                    .OrderBy(x => (x.Key.GetPosition() - Ship.GetPosition()).Length())
                    .ToList();

                foreach (var target in myTargets)
                {
                    IMyGridTerminalSystem gridTerminal =
                        MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid((IMyCubeGrid)target.Key);
                    List <IMyTerminalBlock> T = new List <IMyTerminalBlock>();
                    gridTerminal.GetBlocks(T);

                    if (T.Count >= _minTargetSize)
                    {
                        if (!targetSet)
                        {
                            _target       = (IMyCubeGrid)target.Key;
                            _targetPlayer = null;
                            targetSet     = true;
                        }
                        if (!targets.ContainsKey(_target))
                        {
                            targets.Add(_target, new TargetDetails(_target));
                        }
                    }
                }
            }
            return(_target);
        }
Esempio n. 17
0
        public static IMyFaction GetOwnerFaction(this IMyCubeGrid Grid, bool RecalculateOwners = false)
        {
            try
            {
                if (RecalculateOwners)
                {
                    (Grid as MyCubeGrid).RecalculateOwners();
                }

                IMyFaction FactionFromBigowners = null;
                IMyFaction Faction = null;
                if (Grid.BigOwners.Count > 0 && Grid.BigOwners[0] != 0)
                {
                    long OwnerID = Grid.BigOwners[0];
                    FactionFromBigowners = GeneralExtensions.FindOwnerFactionById(OwnerID);
                }
                else
                {
                    Grid.LogError("Grid.GetOwnerFaction", new Exception("Cannot get owner faction via BigOwners.", new Exception("BigOwners is empty.")));
                }

                IMyGridTerminalSystem   Term          = Grid.GetTerminalSystem();
                List <IMyTerminalBlock> AllTermBlocks = new List <IMyTerminalBlock>();
                Term.GetBlocks(AllTermBlocks);

                if (AllTermBlocks.Empty())
                {
                    Grid.DebugWrite("Grid.GetOwnerFaction", $"Terminal system is empty!");
                    return(null);
                }

                var BiggestOwnerGroup = AllTermBlocks.GroupBy(x => x.GetOwnerFactionTag()).OrderByDescending(gp => gp.Count()).FirstOrDefault();
                if (BiggestOwnerGroup != null)
                {
                    string factionTag = BiggestOwnerGroup.Key;
                    Faction = MyAPIGateway.Session.Factions.TryGetFactionByTag(factionTag);
                    if (Faction != null)
                    {
                        Grid.DebugWrite("Grid.GetOwnerFaction", $"Found owner faction {factionTag} via terminal system");
                    }
                    return(Faction ?? FactionFromBigowners);
                }
                else
                {
                    Grid.DebugWrite("Grid.GetOwnerFaction", $"CANNOT GET FACTION TAGS FROM TERMINALSYSTEM!");
                    List <IMyShipController> Controllers = Grid.GetBlocks <IMyShipController>();
                    if (Controllers.Any())
                    {
                        List <IMyShipController> MainControllers;

                        if (Controllers.Any(x => x.IsMainCockpit(), out MainControllers))
                        {
                            Faction = MyAPIGateway.Session.Factions.TryGetFactionByTag(MainControllers[0].GetOwnerFactionTag());
                            if (Faction != null)
                            {
                                Grid.DebugWrite("Grid.GetOwnerFaction", $"Found owner faction {Faction.Tag} via main cockpit");
                                return(Faction ?? FactionFromBigowners);
                            }
                        } // Controls falls down if faction was not found by main cockpit

                        Faction = MyAPIGateway.Session.Factions.TryGetFactionByTag(Controllers[0].GetOwnerFactionTag());
                        if (Faction != null)
                        {
                            Grid.DebugWrite("Grid.GetOwnerFaction", $"Found owner faction {Faction.Tag} via cockpit");
                            return(Faction ?? FactionFromBigowners);
                        }
                        else
                        {
                            Grid.DebugWrite("Grid.GetOwnerFaction", $"Unable to owner faction via cockpit!");
                            Faction = MyAPIGateway.Session.Factions.TryGetFactionByTag(AllTermBlocks.First().GetOwnerFactionTag());
                            if (Faction != null)
                            {
                                Grid.DebugWrite("Grid.GetOwnerFaction", $"Found owner faction {Faction.Tag} via first terminal block");
                                return(Faction ?? FactionFromBigowners);
                            }
                            else
                            {
                                Grid.DebugWrite("Grid.GetOwnerFaction", $"Unable to owner faction via first terminal block!");
                                return(Faction ?? FactionFromBigowners);
                            }
                        }
                    }
                    else
                    {
                        Faction = MyAPIGateway.Session.Factions.TryGetFactionByTag(AllTermBlocks.First().GetOwnerFactionTag());
                        if (Faction != null)
                        {
                            Grid.DebugWrite("Grid.GetOwnerFaction", $"Found owner faction {Faction.Tag} via first terminal block");
                            return(Faction ?? FactionFromBigowners);
                        }
                        else
                        {
                            Grid.DebugWrite("Grid.GetOwnerFaction", $"Unable to owner faction via first terminal block!");
                            return(Faction ?? FactionFromBigowners);
                        }
                    }
                }
            }
            catch (Exception Scrap)
            {
                Grid.LogError("Faction.GetOwnerFaction", Scrap);
                return(null);
            }
        }