public DroneNavigation(IMyCubeGrid ship, IMyControllableEntity shipControls,
                               List <IMyEntity> nearbyFloatingObjects, double maxEngagementRange)
        {
            //stuff passed from sip
            _shipControls          = shipControls;
            Ship                   = ship;
            GridTerminalSystem     = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid(ship);
            _nearbyFloatingObjects = nearbyFloatingObjects;

            var value = (ship.LocalAABB.Max - ship.LocalAABB.Center).Length();

            if (ship.Physics.Mass > 100000)
            {
                FollowRange = 600 + value;
            }
            else
            {
                FollowRange = 400 + value;
            }

            ShipOrientation();
            FindGyros();

            _initialized = true;
        }
예제 #2
0
            /// <summary>
            /// be sure to get a new one after a reset, CNS changes will not be respected
            /// </summary>
            /// <param name="stopFromDestGrid">how close to centreDestination grid to stop, if centreDestination is a grid</param>
            /// <returns></returns>
            public CollisionAvoidance(ref NavSettings CNS, GridDimensions gridDims)
            {
                VRage.Exceptions.ThrowIf <ArgumentNullException>(CNS == null, "CNS");
                VRage.Exceptions.ThrowIf <ArgumentNullException>(gridDims == null, "gridDims");

                this.CNS             = CNS;
                this.wayDest         = (Vector3D)CNS.getWayDest();
                this.myGridDims      = gridDims;
                this.ignoreAsteroids = CNS.ignoreAsteroids;
                myLogger             = new Logger(gridDims.myGrid.DisplayName, "CollisionAvoidance");

                // decide whether to use collision avoidance or slowdown
                switch (CNS.getTypeOfWayDest())
                {
                case NavSettings.TypeOfWayDest.BLOCK:
                case NavSettings.TypeOfWayDest.GRID:
                    // run slowdown. see Navigator.calcMoveAndRotate()
                    this.destGrid = CNS.CurrentGridDest.Grid;
                    break;

                case NavSettings.TypeOfWayDest.LAND:
                default:
                    if (CNS.landingState != NavSettings.LANDING.OFF && CNS.CurrentGridDest != null)
                    {
                        this.destGrid = CNS.CurrentGridDest.Grid;
                    }
                    break;
                }

                log(myLogger, "created CollisionAvoidance", ".ctor()", Logger.severity.TRACE);
                currentStage = stage.S0_start;
            }
예제 #3
0
        private static void FilterEntitiesForMedbayCheck(ulong steamId, HashSet <IMyEntity> entitiesFound, HashSet <IMyEntity> entitiesToConceal)
        {
            foreach (IMyEntity entity in entitiesFound)
            {
                if (!(entity is IMyCubeGrid))
                {
                    continue;
                }

                if (entity.DisplayName.Contains("CommRelay"))
                {
                    continue;
                }

                if (!entity.InScene)
                {
                    continue;
                }

                if (((IMyCubeGrid)entity).GridSizeEnum != MyCubeSize.Small && !PluginSettings.Instance.ConcealIncludeLargeGrids)
                {
                    continue;
                }

                IMyCubeGrid grid     = (IMyCubeGrid)entity;
                long        playerId = PlayerMap.Instance.GetFastPlayerIdFromSteamId(steamId);
                if (!grid.BigOwners.Contains(playerId) && !grid.SmallOwners.Contains(playerId))
                {
                    continue;
                }

                bool found = false;
                // Check to see if grid is close to dock / shipyard
                foreach (IMyCubeGrid checkGrid in ProcessDockingZone.ZoneCache)
                {
                    try
                    {
                        if (Vector3D.Distance(checkGrid.GetPosition( ), grid.GetPosition( )) < 100d)
                        {
                            found = true;
                            break;
                        }
                    }
                    catch
                    {
                        continue;
                    }
                }

                if (!found)
                {
                    // Check for block type rules
                }

                if (!found)
                {
                    entitiesToConceal.Add(entity);
                }
            }
        }
예제 #4
0
        private static bool CheckRevealMedbay(IMyCubeGrid grid, ulong steamId)
        {
            // Live dangerously
            List <IMySlimBlock> blocks = new List <IMySlimBlock>();

            grid.GetBlocks(blocks, x => x.FatBlock != null);
            foreach (IMySlimBlock block in blocks)
            {
                IMyCubeBlock cubeBlock = block.FatBlock;

                if (cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_MedicalRoom))
                {
                    IMyMedicalRoom medical = (IMyMedicalRoom)cubeBlock;
                    if (!medical.Enabled)
                    {
                        continue;
                    }

                    long playerId = PlayerMap.Instance.GetFastPlayerIdFromSteamId(steamId);
                    //if (medical.Owner == playerId || (medical.ShareMode == MyOwnershipShareModeEnum.Faction && Player.CheckPlayerSameFaction(medical.Owner, playerId)))
                    if (medical.HasPlayerAccess(playerId))
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
예제 #5
0
 public CanFlyTo(Vector3D destination, Sandbox.ModAPI.IMyCubeGrid gridDest, GridDimensions gridDims, bool isAlternate, bool ignoreAsteroids)
 {
     this.myGrid          = gridDims.myGrid;
     this.gridDest        = gridDest;
     this.myAttached      = AttachedGrids.getFor(gridDims.myGrid);
     this.ignoreAsteroids = ignoreAsteroids;
     myLogger             = new Logger(gridDims.myGrid.DisplayName, "CanFlyTo");
     collisionSpheres     = new Spheres(destination, gridDims, isAlternate);
     log(myLogger, "got grid dest: " + this.gridDest, ".ctor()", Logger.severity.TRACE);
 }
        public static Dictionary <string, List <IMyCubeBlock> > GetZonesInGrid(IMyCubeGrid cubeGrid)
        {
            Dictionary <String, List <IMyCubeBlock> > testList = new Dictionary <string, List <IMyCubeBlock> >();
            List <IMySlimBlock> cubeBlocks = new List <IMySlimBlock>();

            cubeGrid.GetBlocks(cubeBlocks);
            foreach (IMySlimBlock entityBlock in cubeBlocks)
            {
                if (entityBlock.FatBlock == null)
                {
                    continue;
                }

                if (!(entityBlock.FatBlock is IMyCubeBlock))
                {
                    continue;
                }

                IMyCubeBlock cubeBlock = (IMyCubeBlock)entityBlock.FatBlock;

                if (!(cubeBlock is IMyBeacon))
                {
                    continue;
                }

                IMyBeacon beacon = (IMyBeacon)cubeBlock;
                if (beacon.CustomName == null || beacon.CustomName == "")
                {
                    continue;
                }

                if (testList.ContainsKey(beacon.CustomName))
                {
                    testList[beacon.CustomName].Add(entityBlock.FatBlock);
                }
                else
                {
                    List <IMyCubeBlock> testBeaconList = new List <IMyCubeBlock>();
                    testBeaconList.Add(entityBlock.FatBlock);
                    testList.Add(beacon.CustomName, testBeaconList);
                }
            }

            Dictionary <String, List <IMyCubeBlock> > resultList = new Dictionary <string, List <IMyCubeBlock> >();

            foreach (KeyValuePair <String, List <IMyCubeBlock> > p in testList)
            {
                if (p.Value.Count == 4)
                {
                    resultList.Add(p.Key, p.Value);
                }
            }

            return(resultList);
        }
예제 #7
0
        //Working - and damn good I might add
        //returns status means -1 = not activated, 0 = notEngaged, 1 = InCombat
        public int Guard(Vector3D position)
        {
            Util.GetInstance().Log("[Drone.Guard] Guarding:");
            ManualFire(false);

            if (Math.Abs((position - Ship.GetPosition()).Length()) < ConquestMod.MaxEngagementRange)
            {
                if (navigation.AvoidNearbyEntities())
                {
                    Util.GetInstance().Log("[Drone.Guard] " + myNumber + " Drone Avoiding");
                }

                var distance = (position - Ship.GetPosition()).Length();


                if (FindNearbyAttackTarget())
                {
                    Util.GetInstance().Log("[Drone.Guard] " + myNumber + " drone found a target");
                    return(1);
                }


                if (distance > navigation.FollowRange * 1.2)
                {
                    if (!navigation.Avoiding && navigation.Follow(position))
                    {
                        _beaconName = "Following";
                    }
                }
                else
                {
                    if (!navigation.Avoiding && navigation.Orbit(position))
                    {
                        _beaconName = "Orbiting";
                    }
                }
            }
            else if (Ship != null && navigation != null)
            {
                _beaconName = "Returning";
                navigation.Follow(position);
                _target = null;
            }
            NameBeacon();

            return(0);
        }
예제 #8
0
		public static Dictionary<string, List<IMyCubeBlock>> GetZonesInGrid(IMyCubeGrid cubeGrid)
		{
			Dictionary<String, List<IMyCubeBlock>> testList = new Dictionary<string, List<IMyCubeBlock>>();
			List<IMySlimBlock> cubeBlocks = new List<IMySlimBlock>();
			cubeGrid.GetBlocks(cubeBlocks);
			foreach (IMySlimBlock entityBlock in cubeBlocks)
			{
				if (entityBlock.FatBlock == null)
					continue;

				if (!(entityBlock.FatBlock is IMyCubeBlock))
					continue;

				IMyCubeBlock cubeBlock = (IMyCubeBlock)entityBlock.FatBlock;

				if (!(cubeBlock is IMyBeacon))
					continue;

				IMyBeacon beacon = (IMyBeacon)cubeBlock;
				if (beacon.CustomName == null || beacon.CustomName == "")
					continue;

				if (testList.ContainsKey(beacon.CustomName))
				{
					testList[beacon.CustomName].Add(entityBlock.FatBlock);
				}
				else
				{
					List<IMyCubeBlock> testBeaconList = new List<IMyCubeBlock>();
					testBeaconList.Add(entityBlock.FatBlock);
					testList.Add(beacon.CustomName, testBeaconList);
				}
			}

			Dictionary<String, List<IMyCubeBlock>> resultList = new Dictionary<string, List<IMyCubeBlock>>();
			foreach (KeyValuePair<String, List<IMyCubeBlock>> p in testList)
			{
				if (p.Value.Count == 4)
				{
					resultList.Add(p.Key, p.Value);
				}
			}

			return resultList;
		}
예제 #9
0
        private List <Sandbox.ModAPI.IMySlimBlock> GetGateList()
        {
            HashSet <IMyEntity> hash = new HashSet <IMyEntity>();
            List <Sandbox.ModAPI.IMySlimBlock> gateList = new List <Sandbox.ModAPI.IMySlimBlock>();

            Sandbox.ModAPI.MyAPIGateway.Entities.GetEntities(hash, (x) => x is Sandbox.ModAPI.IMyCubeGrid);


            foreach (var entity in hash)
            {
                List <Sandbox.ModAPI.IMySlimBlock> blocks = new List <Sandbox.ModAPI.IMySlimBlock>();
                Sandbox.ModAPI.IMyCubeGrid         grid   = entity as Sandbox.ModAPI.IMyCubeGrid;

                try
                {
                    grid.GetBlocks(blocks, (x) => x.FatBlock is IMyDoor &&
                                   (x.FatBlock as IMyTerminalBlock).CustomName.Contains("Portal"));
                }
                catch
                {
                    MyAPIGateway.Utilities.ShowNotification("Error When trying to find Portals", 250);
                }


                foreach (var block in blocks)
                {
                    try
                    {
                        String name = (block.FatBlock as IMyTerminalBlock).CustomName;
                        gateList.Add(block);
                        //MyAPIGateway.Utilities.ShowNotification("Added Door,  Pos = " + block.FatBlock.Position.ToString() +
                        // " Name = " + name, 250);
                    }
                    catch
                    {
                        MyAPIGateway.Utilities.ShowNotification("Error", 250);
                    }
                }
            }


            return(gateList);
        }
        public static bool IsGridInside(IMyCubeGrid dockingEntity, List <IMyCubeBlock> beaconList)
        {
            // Get bounding box of both the docking zone and docking ship
            OrientedBoundingBoxD targetBounding  = Entity.GetBoundingBox(beaconList);
            OrientedBoundingBoxD dockingBounding = Entity.GetBoundingBox(dockingEntity);

            // If the docking entity is bigger in some way than the zone, this will fail (docking ship larger than dock) ???
            if (!Entity.GreaterThan(dockingBounding.HalfExtent * 2, targetBounding.HalfExtent * 2))
            {
                return(false);
            }

            // Make sure the docking zone contains the docking ship.  If they intersect or are disjointed, then fail
            if (targetBounding.Contains(ref dockingBounding) != ContainmentType.Contains)
            {
                return(false);
            }

            return(true);
        }
예제 #11
0
		public static bool IsGridInside(IMyCubeGrid dockingEntity, List<IMyCubeBlock> beaconList)
		{
			// Get bounding box of both the docking zone and docking ship
			OrientedBoundingBoxD targetBounding = Entity.GetBoundingBox(beaconList);
			OrientedBoundingBoxD dockingBounding = Entity.GetBoundingBox(dockingEntity);

			// If the docking entity is bigger in some way than the zone, this will fail (docking ship larger than dock) ???
			if (!Entity.GreaterThan(dockingBounding.HalfExtent * 2, targetBounding.HalfExtent * 2))
			{
				return false;
			}

			// Make sure the docking zone contains the docking ship.  If they intersect or are disjointed, then fail
			if (targetBounding.Contains(ref dockingBounding) != ContainmentType.Contains)
			{
				return false;
			}

			return true;
		}
예제 #12
0
        // @wip @feature Attach to entity add/update events instead for less expensive searching of autopilot ships
        private void findNavigators()
        {
            HashSet <IMyEntity> entities = new HashSet <IMyEntity>();

            MyAPIGateway.Entities.GetEntities(entities, e => e is Sandbox.ModAPI.IMyCubeGrid);
            foreach (IMyEntity entity in entities)
            {
                Sandbox.ModAPI.IMyCubeGrid grid = entity as Sandbox.ModAPI.IMyCubeGrid;
                if (grid == null || grid.Closed || grid.MarkedForClose || grid.Physics == null)
                {
                    continue;
                }
                if (!allNavigators.ContainsKey(grid))
                {
                    myLogger.debugLog("new grid added " + grid.DisplayName, "build", Logger.severity.INFO);
                    Navigator cGridHandler = new Navigator(grid);
                    allNavigators.Add(grid, cGridHandler);
                }
            }
        }
        public DroneNavigation(IMyCubeGrid ship, IMyControllableEntity shipControls,
            List<IMyEntity> nearbyFloatingObjects, double maxEngagementRange)
        {
            //stuff passed from sip
            _shipControls = shipControls;
            Ship = ship;
            GridTerminalSystem = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid(ship);
            _nearbyFloatingObjects = nearbyFloatingObjects;

            var value = (ship.LocalAABB.Max - ship.LocalAABB.Center).Length();

            if (ship.Physics.Mass > 100000)
                FollowRange = 600 + value;
            else
                FollowRange = 400 + value;

            ShipOrientation();
            FindGyros();

            _initialized = true;
        }
예제 #14
0
        //Disables all beacons and antennas and deletes the ship.
        public void DeleteShip()
        {
            var lstSlimBlock = new List <IMySlimBlock>();

            Ship.GetBlocks(lstSlimBlock, (x) => x.FatBlock is IMyRadioAntenna);
            foreach (var block in lstSlimBlock)
            {
                IMyRadioAntenna antenna = (IMyRadioAntenna)block.FatBlock;
                ITerminalAction act     = antenna.GetActionWithName("OnOff_Off");
                act.Apply(antenna);
            }

            lstSlimBlock = new List <IMySlimBlock>();
            Ship.GetBlocks(lstSlimBlock, (x) => x.FatBlock is IMyBeacon);
            foreach (var block in lstSlimBlock)
            {
                IMyBeacon       beacon = (IMyBeacon)block.FatBlock;
                ITerminalAction act    = beacon.GetActionWithName("OnOff_Off");
                act.Apply(beacon);
            }

            MyAPIGateway.Entities.RemoveEntity(Ship as IMyEntity);
            Ship = null;
        }
예제 #15
0
        public Drone(IMyEntity ent, BroadcastingTypes broadcasting)
        {
            var ship = (IMyCubeGrid)ent;
            double maxEngagementRange = ConquestMod.MaxEngagementRange;
            broadcastingType = broadcasting;

            Ship = ship;
            var lstSlimBlock = new List<IMySlimBlock>();

            GridTerminalSystem = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid(ship);

            //If it has any type of cockipt
            ship.GetBlocks(lstSlimBlock, (x) => x.FatBlock is IMyShipController);
            FindWeapons();

            //If no cockpit the ship is either no ship or is broken.
            if (lstSlimBlock.Count != 0)
            {
                //Make the controls be the cockpit
                ShipControls = lstSlimBlock[0].FatBlock as IMyControllableEntity;

                _ownerId = ((Sandbox.ModAPI.IMyTerminalBlock)ShipControls).OwnerId;

                #region Activate Beacons && Antennas

                //Maximise radius on antennas and beacons.
                lstSlimBlock.Clear();
                ship.GetBlocks(lstSlimBlock, (x) => x.FatBlock is IMyRadioAntenna);
                foreach (var block in lstSlimBlock)
                {
                    IMyRadioAntenna antenna =
                        (IMyRadioAntenna)block.FatBlock;
                    if (antenna != null)
                    {
                        //antenna.GetActionWithName("SetCustomName").Apply(antenna, new ListReader<TerminalActionParameter>(new List<TerminalActionParameter>() { TerminalActionParameter.Get("Combat Drone " + _manualGats.Count) }));
                        antenna.SetValueFloat("Radius", 5000);//antenna.GetMaximum<float>("Radius"));
                        ITerminalAction act = antenna.GetActionWithName("OnOff_On");
                        act.Apply(antenna);
                    }
                }

                lstSlimBlock = new List<IMySlimBlock>();
                ship.GetBlocks(lstSlimBlock, (x) => x.FatBlock is IMyBeacon);
                foreach (var block in lstSlimBlock)
                {
                    IMyBeacon beacon = (IMyBeacon)block.FatBlock;
                    if (beacon != null)
                    {
                        beacon.SetValueFloat("Radius", 5000);//beacon.GetMaximum<float>("Radius"));
                        ITerminalAction act = beacon.GetActionWithName("OnOff_On");
                        act.Apply(beacon);
                    }
                }

                #endregion

                //SetWeaponPower(true);
                //AmmoManager.ReloadReactors(_allReactors);
                //AmmoManager.ReloadGuns(_manualGats);
                ship.GetBlocks(lstSlimBlock, x => x is IMyEntity);

                List<IMyTerminalBlock> massBlocks =
                    new List<IMyTerminalBlock>();

                GridTerminalSystem.GetBlocksOfType<IMyVirtualMass>(massBlocks);

                List<IMyTerminalBlock> allTerminalBlocks = new List<IMyTerminalBlock>();
                GridTerminalSystem.GetBlocksOfType<IMyCubeBlock>(allTerminalBlocks);
                HealthBlockBase = allTerminalBlocks.Count;

                if (ShipControls != null)
                {

                    navigation = new DroneNavigation(ship, ShipControls, _nearbyFloatingObjects, maxEngagementRange);
                }

            }
            Ship.OnBlockAdded += RecalcMaxHp;
            myNumber = numDrones;
            numDrones++;
        }
예제 #16
0
        public Drone(IMyEntity ent, BroadcastingTypes broadcasting)
        {
            var    ship = (IMyCubeGrid)ent;
            double maxEngagementRange = ConquestMod.MaxEngagementRange;

            broadcastingType = broadcasting;

            Ship = ship;
            var lstSlimBlock = new List <IMySlimBlock>();

            GridTerminalSystem = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid(ship);

            //If it has any type of cockipt
            ship.GetBlocks(lstSlimBlock, (x) => x.FatBlock is IMyShipController);
            FindWeapons();
            SetupActions();



            //If no cockpit the ship is either no ship or is broken.
            if (lstSlimBlock.Count != 0)
            {
                //Make the controls be the cockpit
                ShipControls = lstSlimBlock[0].FatBlock as IMyControllableEntity;

                _ownerId = ((Sandbox.ModAPI.IMyTerminalBlock)ShipControls).OwnerId;


                #region Activate Beacons && Antennas


                //Maximise radius on antennas and beacons.
                lstSlimBlock.Clear();
                ship.GetBlocks(lstSlimBlock, (x) => x.FatBlock is IMyRadioAntenna);
                foreach (var block in lstSlimBlock)
                {
                    IMyRadioAntenna antenna =
                        (IMyRadioAntenna)block.FatBlock;
                    if (antenna != null)
                    {
                        //antenna.GetActionWithName("SetCustomName").Apply(antenna, new ListReader<TerminalActionParameter>(new List<TerminalActionParameter>() { TerminalActionParameter.Get("Combat Drone " + _manualGats.Count) }));
                        antenna.SetValueFloat("Radius", 10000);//antenna.GetMaximum<float>("Radius"));
                        _blockOn.Apply(antenna);
                    }
                }

                lstSlimBlock = new List <IMySlimBlock>();
                ship.GetBlocks(lstSlimBlock, (x) => x.FatBlock is IMyBeacon);
                foreach (var block in lstSlimBlock)
                {
                    IMyBeacon beacon = (IMyBeacon)block.FatBlock;
                    if (beacon != null)
                    {
                        beacon.SetValueFloat("Radius", 10000);//beacon.GetMaximum<float>("Radius"));
                        _blockOn.Apply(beacon);
                    }
                }

                #endregion

                //SetWeaponPower(true);
                //AmmoManager.ReloadReactors(_allReactors);
                //AmmoManager.ReloadGuns(_manualGats);
                ship.GetBlocks(lstSlimBlock, x => x is IMyEntity);

                List <IMyTerminalBlock> massBlocks =
                    new List <IMyTerminalBlock>();

                GridTerminalSystem.GetBlocksOfType <IMyVirtualMass>(massBlocks);

                List <IMyTerminalBlock> allTerminalBlocks = new List <IMyTerminalBlock>();
                GridTerminalSystem.GetBlocksOfType <IMyCubeBlock>(allTerminalBlocks);
                HealthBlockBase = allTerminalBlocks.Count;


                if (ShipControls != null)
                {
                    navigation = new DroneNavigation(ship, ShipControls, _nearbyFloatingObjects, maxEngagementRange);
                }
            }
            Ship.OnBlockAdded += RecalcMaxHp;
            myNumber           = numDrones;
            numDrones++;
        }
예제 #17
0
        private static bool CheckRevealBlockRules(IMyCubeGrid grid, List <IMyPlayer> players, out string reason)
        {
            reason = "";
            // This is actually faster, but doesn't include power checks

            // Live dangerously
            List <IMySlimBlock> blocks = new List <IMySlimBlock>();

            grid.GetBlocks(blocks, x => x.FatBlock != null);
            //CubeGrids.GetAllConnectedBlocks(_processedGrids, grid, blocks, x => x.FatBlock != null);
            //bool found = false;
            //bool powered = false;
            foreach (IMySlimBlock block in blocks)
            {
                IMyCubeBlock cubeBlock = block.FatBlock;

                if (cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_Beacon))
                {
                    //MyObjectBuilder_Beacon beacon = (MyObjectBuilder_Beacon)cubeBlock.GetObjectBuilderCubeBlock();
                    IMyBeacon beacon = (IMyBeacon)cubeBlock;
                    if (!beacon.Enabled)
                    {
                        continue;
                    }

                    //Sandbox.ModAPI.Ingame.IMyFunctionalBlock functionalBlock = (Sandbox.ModAPI.Ingame.IMyFunctionalBlock)cubeBlock;
                    //if (!functionalBlock.Enabled)
                    //	continue;

                    //Console.WriteLine("Beacon: {0} {1} {2}", beacon.BroadcastRadius, terminalBlock.IsWorking, terminalBlock.IsFunctional);
                    //if (!terminalBlock.IsWorking)
                    //	continue;


                    foreach (IMyPlayer player in players)
                    {
                        double distance = 0d;
                        if (Entity.GetDistanceBetweenPointAndPlayer(grid.GetPosition(), player, out distance))
                        {
                            if (distance < beacon.Radius)
                            {
                                //found = true;
                                //break;
                                reason = string.Format("{0} distance to beacon broadcast: {1}", player.DisplayName, distance);
                                return(true);
                            }
                        }
                    }
                }

                if (cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_RadioAntenna))
                {
                    //MyObjectBuilder_RadioAntenna antenna = (MyObjectBuilder_RadioAntenna)cubeBlock.GetObjectBuilderCubeBlock();
                    IMyRadioAntenna antenna = (IMyRadioAntenna)cubeBlock;

                    if (!antenna.Enabled)
                    {
                        continue;
                    }

                    //Sandbox.ModAPI.Ingame.IMyFunctionalBlock functionalBlock = (Sandbox.ModAPI.Ingame.IMyFunctionalBlock)cubeBlock;
                    //if (!functionalBlock.Enabled)
                    //	continue;

                    foreach (IMyPlayer player in players)
                    {
                        double distance = 0d;
                        if (Entity.GetDistanceBetweenPointAndPlayer(grid.GetPosition(), player, out distance))
                        {
                            if (distance < antenna.Radius)
                            {
                                //found = true;
                                //break;
                                reason = string.Format("{0} distance to antenna broadcast: {1}", player.DisplayName, distance);
                                return(true);
                            }
                        }
                    }
                }

                if (cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_MedicalRoom))
                {
                    //MyObjectBuilder_MedicalRoom medical = (MyObjectBuilder_MedicalRoom)cubeBlock.GetObjectBuilderCubeBlock();
                    IMyMedicalRoom medical = (IMyMedicalRoom)cubeBlock;
                    if (!medical.Enabled)
                    {
                        continue;
                    }

                    IMyFunctionalBlock functionalBlock = (IMyFunctionalBlock)cubeBlock;
                    if (!functionalBlock.IsFunctional)
                    {
                        continue;
                    }

                    //if (!functionalBlock.Enabled)
                    //	continue;

                    if (PluginSettings.Instance.DynamicConcealIncludeMedBays)
                    {
                        lock (Online)
                        {
                            foreach (ulong connectedPlayer in Online)
                            {
                                long playerId = PlayerMap.Instance.GetFastPlayerIdFromSteamId(connectedPlayer);
                                //if (medical.Owner == playerId || (medical.ShareMode == MyOwnershipShareModeEnum.Faction && Player.CheckPlayerSameFaction(medical.Owner, playerId)))
                                if (functionalBlock.OwnerId == playerId)
                                {
                                    reason = string.Format("Grid has medbay and player is logged in - playerid: {0}", playerId);
                                    return(true);
                                }

                                if (functionalBlock.GetUserRelationToOwner(playerId) == MyRelationsBetweenPlayerAndBlock.FactionShare)
                                {
                                    reason = string.Format("Grid has medbay and player is factionshare - playerid: {0}", playerId);
                                    return(true);
                                }
                            }
                        }

                        /*
                         * foreach (ulong connectedPlayer in PlayerManager.Instance.ConnectedPlayers)
                         * {
                         *      long playerId = PlayerMap.Instance.GetFastPlayerIdFromSteamId(connectedPlayer);
                         *      //if (medical.Owner == playerId || (medical.ShareMode == MyOwnershipShareModeEnum.Faction && Player.CheckPlayerSameFaction(medical.Owner, playerId)))
                         *      //if (functionalBlock.OwnerId == playerId || (functionalBlock.GetUserRelationToOwner(playerId) == Sandbox.Common.MyRelationsBetweenPlayerAndBlock.FactionShare))
                         *      if(medical.HasPlayerAccess(playerId))
                         *      {
                         *              reason = string.Format("Grid has medbay and player is logged in - playerid: {0}", playerId);
                         *              return true;
                         *      }
                         * }
                         */
                    }
                    else
                    {
                        reason = string.Format("Grid has medbay and conceal can not include medbays");
                        return(true);
                    }
                }

                if (cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_ProductionBlock))
                {
                    MyObjectBuilder_ProductionBlock production = (MyObjectBuilder_ProductionBlock)cubeBlock.GetObjectBuilderCubeBlock();
                    if (!production.Enabled)
                    {
                        continue;
                    }

                    IMyProductionBlock productionBlock = (IMyProductionBlock)cubeBlock;
                    if (production.Queue.Length > 0)
                    {
                        reason = string.Format("Grid has production facility that has a queue");
                        return(true);
                    }
                }
            }

            return(false);
        }
예제 #18
0
        private static void ConcealEntity(IMyEntity entity)
        {
            int pos = 0;

            try
            {
                if (!entity.InScene)
                {
                    return;
                }

                MyObjectBuilder_CubeGrid builder = CubeGrids.SafeGetObjectBuilder((IMyCubeGrid)entity);
                if (builder == null)
                {
                    return;
                }

                pos = 1;
                IMyCubeGrid grid      = (IMyCubeGrid)entity;
                long        ownerId   = 0;
                string      ownerName = "";
                if (CubeGrids.GetOwner(builder, out ownerId))
                {
                    //ownerId = grid.BigOwners.First();
                    ownerName = PlayerMap.Instance.GetPlayerItemFromPlayerId(ownerId).Name;
                }

                pos = 2;
                if (entity.Physics != null)
                {
                    entity.Physics.LinearVelocity  = Vector3.Zero;
                    entity.Physics.AngularVelocity = Vector3.Zero;
                }

                /*
                 * entity.InScene = false;
                 * entity.CastShadows = false;
                 * entity.Visible = false;
                 */

                builder.PersistentFlags = MyPersistentEntityFlags2.None;
                MyAPIGateway.Entities.RemapObjectBuilder(builder);

                pos = 3;
                if (RemovedGrids.Contains(entity.EntityId))
                {
                    Logging.WriteLineAndConsole("Conceal", string.Format("Concealing - Id: {0} DUPE FOUND - Display: {1} OwnerId: {2} OwnerName: {3}", entity.EntityId, entity.DisplayName, ownerId, ownerName, builder.EntityId));
                    BaseEntityNetworkManager.BroadcastRemoveEntity(entity, false);
                }
                else
                {
                    if (!PluginSettings.Instance.DynamicConcealServerOnly)
                    {
                        /*
                         * if (PluginSettings.Instance.DynamicBlockManagementEnabled)
                         * {
                         *      bool enable = false;
                         *      lock (BlockManagement.Instance.GridDisabled)
                         *      {
                         *              if(BlockManagement.Instance.GridDisabled.Contains(entity.EntityId))
                         *                      enable = true;
                         *      }
                         *
                         *      if(enable)
                         *              BlockManagement.Instance.EnableGrid((IMyCubeGrid)entity);
                         * }
                         */
                        IMyEntity newEntity = MyAPIGateway.Entities.CreateFromObjectBuilder(builder);
                        Logging.WriteLineAndConsole("Conceal", string.Format("Start Concealing - Id: {0} -> {4} Display: {1} OwnerId: {2} OwnerName: {3}", entity.EntityId, entity.DisplayName, ownerId, ownerName, newEntity.EntityId));
                        if (newEntity == null)
                        {
                            Logging.WriteLineAndConsole("Conceal", string.Format("Issue - CreateFromObjectBuilder failed: {0}", newEntity.EntityId));
                            return;
                        }

                        RemovedGrids.Add(entity.EntityId);
                        BaseEntityNetworkManager.BroadcastRemoveEntity(entity, false);
                        MyAPIGateway.Entities.AddEntity(newEntity, false);
                        Logging.WriteLineAndConsole("Conceal", string.Format("End Concealing - Id: {0} -> {4} Display: {1} OwnerId: {2} OwnerName: {3}", entity.EntityId, entity.DisplayName, ownerId, ownerName, newEntity.EntityId));
                    }
                    else
                    {
                        Logging.WriteLineAndConsole("Conceal", string.Format("Start Concealing - Id: {0} -> {4} Display: {1} OwnerId: {2} OwnerName: {3}", entity.EntityId, entity.DisplayName, ownerId, ownerName, builder.EntityId));
                        entity.InScene = false;
                        Logging.WriteLineAndConsole("Conceal", string.Format("End Concealing - Id: {0} -> {4} Display: {1} OwnerId: {2} OwnerName: {3}", entity.EntityId, entity.DisplayName, ownerId, ownerName, builder.EntityId));
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.WriteLineAndConsole(string.Format("ConcealEntity({1}): {0}", ex.ToString(), pos));
            }
        }
예제 #19
0
        private static bool CheckConcealBlockRules(IMyCubeGrid grid, List <IMyPlayer> players)
        {
            List <IMySlimBlock> blocks = new List <IMySlimBlock>();

            // Live dangerously
            grid.GetBlocks(blocks, x => x.FatBlock != null);
            //CubeGrids.GetAllConnectedBlocks(_processedGrids, grid, blocks, x => x.FatBlock != null);

            int beaconCount = 0;

            //bool found = false;
            //bool powered = false;
            foreach (IMySlimBlock block in blocks)
            {
                IMyCubeBlock cubeBlock = block.FatBlock;

                if (cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_Beacon))
                {
                    IMyBeacon beacon = (IMyBeacon)cubeBlock;
                    //MyObjectBuilder_Beacon beacon = (MyObjectBuilder_Beacon)cubeBlock.GetObjectBuilderCubeBlock();
                    beaconCount++;
                    // Keep this return here, as 4 beacons always means true
                    if (beaconCount >= 4)
                    {
                        return(true);
                    }

                    if (!beacon.Enabled)
                    {
                        continue;
                    }

                    IMyTerminalBlock terminalBlock = (IMyTerminalBlock)cubeBlock;
//					Console.WriteLine("Found: {0} {1} {2}", beacon.BroadcastRadius, terminalBlock.IsWorking, terminalBlock.IsFunctional);
                    //if (!terminalBlock.IsWorking)
                    //{
//						continue;
                    //}

                    foreach (IMyPlayer player in players)
                    {
                        double distance = 0d;
                        if (Entity.GetDistanceBetweenPointAndPlayer(grid.GetPosition(), player, out distance))
                        {
                            if (distance < beacon.Radius)
                            {
//								Console.WriteLine("Not concealed due to broadcast radius");
                                //found = true;
                                //break;
                                return(true);
                            }
                        }
                    }
                }

                if (cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_RadioAntenna))
                {
                    //MyObjectBuilder_RadioAntenna antenna = (MyObjectBuilder_RadioAntenna)cubeBlock.GetObjectBuilderCubeBlock();
                    IMyRadioAntenna antenna = (IMyRadioAntenna)cubeBlock;

                    if (!antenna.Enabled)
                    {
                        continue;
                    }

                    IMyTerminalBlock terminalBlock = (IMyTerminalBlock)cubeBlock;
                    //if (!terminalBlock.IsWorking)
                    //	continue;

                    foreach (IMyPlayer player in players)
                    {
                        double distance = 0d;
                        if (Entity.GetDistanceBetweenPointAndPlayer(grid.GetPosition(), player, out distance))
                        {
                            if (distance < antenna.Radius)
                            {
//								Console.WriteLine("Not concealed due to antenna broadcast radius");
                                //found = true;
                                //break;
                                return(true);
                            }
                        }
                    }
                }

                if (cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_MedicalRoom))
                {
                    //MyObjectBuilder_MedicalRoom medical = (MyObjectBuilder_MedicalRoom)cubeBlock.GetObjectBuilderCubeBlock();
                    IMyMedicalRoom medical = (IMyMedicalRoom)cubeBlock;

                    if (!medical.Enabled)
                    {
                        continue;
                    }

                    IMyFunctionalBlock functionalBlock = (IMyFunctionalBlock)cubeBlock;
                    //if (!terminalBlock.IsWorking)
                    //	continue;

                    if (PluginSettings.Instance.DynamicConcealIncludeMedBays)
                    {
                        lock (Online)
                        {
                            foreach (ulong connectedPlayer in Online)
                            {
                                //if (PlayerMap.Instance.GetPlayerIdsFromSteamId(connectedPlayer).Count < 1)
                                //continue;

                                //long playerId = PlayerMap.Instance.GetPlayerIdsFromSteamId(connectedPlayer).First();
                                long playerId = PlayerMap.Instance.GetFastPlayerIdFromSteamId(connectedPlayer);

                                if (functionalBlock.OwnerId == playerId || (functionalBlock.GetUserRelationToOwner(playerId) == MyRelationsBetweenPlayerAndBlock.FactionShare))
                                //if (functionalBlock.Owner == playerId || (functionalBlock.ShareMode == MyOwnershipShareModeEnum.Faction && Player.CheckPlayerSameFaction(functionalBlock.Owner, playerId)))
                                //if (medical.HasPlayerAccess(playerId))
                                {
                                    return(true);
                                }
                            }
                        }

                        /*
                         * foreach (ulong connectedPlayer in PlayerManager.Instance.ConnectedPlayers)
                         * {
                         *      //if (PlayerMap.Instance.GetPlayerIdsFromSteamId(connectedPlayer).Count < 1)
                         *              //continue;
                         *
                         *      //long playerId = PlayerMap.Instance.GetPlayerIdsFromSteamId(connectedPlayer).First();
                         *      long playerId = PlayerMap.Instance.GetFastPlayerIdFromSteamId(connectedPlayer);
                         *      //if (medical.Owner == playerId || (medical.ShareMode == MyOwnershipShareModeEnum.Faction && Player.CheckPlayerSameFaction(medical.Owner, playerId)))
                         *      if(medical.HasPlayerAccess(playerId))
                         *      {
                         *              return true;
                         *      }
                         * }
                         */
                    }
                    else
                    {
                        return(true);
                    }
                }

                if (cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_Refinery) || cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_Assembler))
                {
                    //MyObjectBuilder_ProductionBlock production = (MyObjectBuilder_ProductionBlock)cubeBlock.GetObjectBuilderCubeBlock();
                    IMyProductionBlock production = (IMyProductionBlock)cubeBlock;
                    if (!production.Enabled)
                    {
                        continue;
                    }

                    if (production.IsProducing)
                    {
                        return(true);
                    }
                }

                foreach (string subType in PluginSettings.Instance.DynamicConcealIgnoreSubTypeList)
                {
                    if (cubeBlock.BlockDefinition.SubtypeName.Contains(subType))
                    {
//						Console.WriteLine("Not concealed due subtype");
                        //found = true;
                        return(true);
                    }
                }
            }

            return(false);
        }
 static public bool DoesGridContainZone(IMyCubeGrid cubeGrid)
 {
     return(GetZonesInGrid(cubeGrid).Count > 0);
 }
예제 #21
0
        private void ScanForBlockItems( )
        {
            HashSet <IMyEntity> entities = new HashSet <IMyEntity>( );

            try
            {
                MyAPIGateway.Entities.GetEntities(entities);
            }
            catch (Exception ex)
            {
                Essentials.Log.Error("Entity list busy, skipping scan.", ex);
            }

            foreach (IMyEntity entity in entities)
            {
                if (!(entity is IMyCubeGrid))
                {
                    continue;
                }

                if (entity.Physics == null)
                {
                    continue;
                }

                if (!entity.InScene)
                {
                    continue;
                }

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

                Dictionary <SettingsBlockEnforcementItem, int> blocks = new Dictionary <SettingsBlockEnforcementItem, int>( );
                foreach (IMyTerminalBlock myTerminalBlock in gridTerminal.Blocks)
                {
                    IMyTerminalBlock block = myTerminalBlock;
                    foreach (SettingsBlockEnforcementItem item in PluginSettings.Instance.BlockEnforcementItems)
                    {
                        if (item.Mode == SettingsBlockEnforcementItem.EnforcementMode.Off)
                        {
                            continue;
                        }

                        if (item.Mode == SettingsBlockEnforcementItem.EnforcementMode.BlockTypeId && string.IsNullOrEmpty(item.BlockTypeId))
                        {
                            Essentials.Log.Warn("Block Enforcement item for \"{0}\" is set to mode BlockTypeId but does not have BlockTypeId set.");
                            continue;
                        }
                        if (item.Mode == SettingsBlockEnforcementItem.EnforcementMode.BlockSubtypeId && string.IsNullOrEmpty(item.BlockSubtypeId))
                        {
                            Essentials.Log.Warn("Block Enforcement item for \"{0}\" is set to mode BlockSubtypeId but does not have BlockSubtypeId set.");
                            continue;
                        }

                        if (item.Mode == SettingsBlockEnforcementItem.EnforcementMode.BlockSubtypeId &&
                            !string.IsNullOrEmpty(block.BlockDefinition.SubtypeId) &&
                            block.BlockDefinition.SubtypeId.Contains(item.BlockSubtypeId))
                        {
                            if (blocks.ContainsKey(item))
                            {
                                blocks[item] += 1;
                            }
                            else
                            {
                                blocks.Add(item, 1);
                            }
                        }

                        if (item.Mode == SettingsBlockEnforcementItem.EnforcementMode.BlockTypeId &&
                            !string.IsNullOrEmpty(block.BlockDefinition.TypeIdString) &&
                            block.BlockDefinition.TypeIdString.Contains(item.BlockTypeId))
                        {
                            if (blocks.ContainsKey(item))
                            {
                                blocks[item] += 1;
                            }
                            else
                            {
                                blocks.Add(item, 1);
                            }
                        }
                    }
                }

                /*
                 * MyObjectBuilder_CubeGrid gridBuilder = CubeGrids.SafeGetObjectBuilder(grid);
                 * if (gridBuilder == null)
                 *      continue;
                 *
                 * Dictionary<string, int> blocks = new Dictionary<string, int>();
                 * foreach (MyObjectBuilder_CubeBlock block in gridBuilder.CubeBlocks)
                 * {
                 *      foreach(SettingsBlockEnforcementItem item in PluginSettings.Instance.BlockEnforcementItems)
                 *      {
                 *              if (!item.Enabled)
                 *                      continue;
                 *
                 *              if (block.GetId().ToString().Contains(item.BlockTypeId))
                 *              {
                 *                      if (blocks.ContainsKey(item.BlockTypeId))
                 *                              blocks[item.BlockTypeId] += 1;
                 *                      else
                 *                              blocks.Add(item.BlockTypeId, 1);
                 *              }
                 *      }
                 * }
                 */

                foreach (SettingsBlockEnforcementItem item in PluginSettings.Instance.BlockEnforcementItems)
                {
                    if (item.Mode == SettingsBlockEnforcementItem.EnforcementMode.Off)
                    {
                        continue;
                    }

                    if (!blocks.ContainsKey(item))
                    {
                        continue;
                    }

                    if (blocks[item] > item.MaxPerGrid)
                    {
                        //foreach(long playerId in CubeGrids.GetBigOwners(gridBuilder))
                        foreach (long playerId in grid.BigOwners)
                        {
                            ulong steamId = PlayerMap.Instance.GetSteamIdFromPlayerId(playerId);
                            if (steamId > 0)
                            {
                                //Communication.SendPrivateInformation(steamId, string.Format("You have exceeded the max block count of {0} on the ship '{1}'.  We are removing {2} blocks to enforce this block limit.", item.BlockTypeId, gridBuilder.DisplayName, blocks[item.BlockTypeId] - item.MaxPerGrid));
                                Communication.SendPrivateInformation(steamId, string.Format("You have exceeded the max block count of {0} on the ship '{1}'.  We are removing {2} blocks to enforce this block limit.", item.BlockTypeId, grid.DisplayName, blocks[item] - item.MaxPerGrid));
                            }
                        }

                        //DeleteReverse(item.BlockTypeId, blocks[item.BlockTypeId] - item.MaxPerGrid, grid, gridBuilder);
                        DeleteReverse(item, blocks[item] - item.MaxPerGrid, grid);
                    }
                }
            }
        }
예제 #22
0
        private void DeleteReverse(SettingsBlockEnforcementItem blockEnforcementSetting, int remove, IMyCubeGrid grid)
        {
            int count = 0;
            IMyGridTerminalSystem gridTerminal = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid(grid);

            List <Sandbox.ModAPI.IMyTerminalBlock> blocksToRemove = new List <Sandbox.ModAPI.IMyTerminalBlock>( );

            for (int r = gridTerminal.Blocks.Count - 1; r >= 0; r--)
            {
                Sandbox.ModAPI.IMyTerminalBlock block = (Sandbox.ModAPI.IMyTerminalBlock)gridTerminal.Blocks[r];
                switch (blockEnforcementSetting.Mode)
                {
                case SettingsBlockEnforcementItem.EnforcementMode.BlockSubtypeId:
                    if (!string.IsNullOrEmpty(block.BlockDefinition.SubtypeId) && block.BlockDefinition.SubtypeId.Contains(blockEnforcementSetting.BlockSubtypeId))
                    {
                        blocksToRemove.Add(block);
                        count++;
                    }
                    break;

                case SettingsBlockEnforcementItem.EnforcementMode.BlockTypeId:
                    if (block.BlockDefinition.TypeIdString.Contains(blockEnforcementSetting.BlockTypeId))
                    {
                        blocksToRemove.Add(block);
                        count++;
                    }
                    break;
                }

                if (count == remove)
                {
                    break;
                }
            }

            /*
             * List<MyObjectBuilder_CubeBlock> blocksToRemove = new List<MyObjectBuilder_CubeBlock>();
             * for (int r = gridBuilder.CubeBlocks.Count - 1; r >= 0; r--)
             * {
             *      MyObjectBuilder_CubeBlock block = gridBuilder.CubeBlocks[r];
             *      if (block.GetId().ToString().Contains(id))
             *      {
             *              blocksToRemove.Add(block);
             *              count++;
             *      }
             *
             *      if (count == remove)
             *              break;
             * }
             */

            if (blocksToRemove.Count < 1)
            {
                return;
            }

            List <Vector3I> razeList = new List <Vector3I>( );

            foreach (Sandbox.ModAPI.IMyTerminalBlock block in blocksToRemove)
            {
                razeList.Add(block.Min);
            }

            Wrapper.GameAction(() =>
            {
                grid.RazeBlocks(razeList);
            });
        }
		private static bool CheckRevealMedbay( IMyCubeGrid grid, ulong steamId )
		{
			// Live dangerously
			List<IMySlimBlock> blocks = new List<IMySlimBlock>( );
			grid.GetBlocks( blocks, x => x.FatBlock != null );
                        long playerId = PlayerMap.Instance.GetFastPlayerIdFromSteamId( steamId );
			foreach ( IMySlimBlock block in blocks )
			{
				IMyCubeBlock cubeBlock = block.FatBlock;

                if ( cubeBlock.BlockDefinition.TypeId == typeof( MyObjectBuilder_MedicalRoom ) )
                {
                    IMyMedicalRoom medical = (IMyMedicalRoom)cubeBlock;
                    if ( !medical.Enabled )
                        continue;

                    //if (medical.Owner == playerId || (medical.ShareMode == MyOwnershipShareModeEnum.Faction && Player.CheckPlayerSameFaction(medical.Owner, playerId)))
                    if ( medical.HasPlayerAccess( playerId ) )
                    {
                        return true;
                    }
                }

                if ( cubeBlock.BlockDefinition.TypeId == typeof( MyObjectBuilder_CryoChamber ) )
                {
                    MyCryoChamber cryo = (MyCryoChamber)cubeBlock;
                    if ( cryo.Pilot == null )
                        continue;

                    if ( cryo.HasPlayerAccess( playerId ) )
                    {
                        return true;
                    }
                }
            }

            return false;
		}
		private static bool CheckRevealBlockRules( IMyCubeGrid grid, List<IMyPlayer> players, out string reason )
		{
			reason = "";
			// This is actually faster, but doesn't include power checks

			// Live dangerously
			List<IMySlimBlock> blocks = new List<IMySlimBlock>( );
			grid.GetBlocks( blocks, x => x.FatBlock != null );
			//CubeGrids.GetAllConnectedBlocks(_processedGrids, grid, blocks, x => x.FatBlock != null);
			//bool found = false;
			//bool powered = false;
			foreach ( IMySlimBlock block in blocks )
			{
				IMyCubeBlock cubeBlock = block.FatBlock;

				if ( cubeBlock.BlockDefinition.TypeId == typeof( MyObjectBuilder_Beacon ) )
				{
					//MyObjectBuilder_Beacon beacon = (MyObjectBuilder_Beacon)cubeBlock.GetObjectBuilderCubeBlock();
					IMyBeacon beacon = (IMyBeacon)cubeBlock;
					if ( !beacon.Enabled )
						continue;

					//Sandbox.ModAPI.Ingame.IMyFunctionalBlock functionalBlock = (Sandbox.ModAPI.Ingame.IMyFunctionalBlock)cubeBlock;
					//if (!functionalBlock.Enabled)
					//	continue;

					//Console.WriteLine("Beacon: {0} {1} {2}", beacon.BroadcastRadius, terminalBlock.IsWorking, terminalBlock.IsFunctional);
					//if (!terminalBlock.IsWorking)
					//	continue;


					foreach ( IMyPlayer player in players )
					{
						double distance;
						if ( Entity.GetDistanceBetweenPointAndPlayer( grid.GetPosition( ), player, out distance ) )
						{
							if ( distance < beacon.Radius )
							{
								//found = true;
								//break;
								reason = string.Format( "{0} distance to beacon broadcast: {1}", player.DisplayName, distance );
								return true;
							}
						}
					}
				}

				if ( cubeBlock.BlockDefinition.TypeId == typeof( MyObjectBuilder_RadioAntenna ) )
				{
					//MyObjectBuilder_RadioAntenna antenna = (MyObjectBuilder_RadioAntenna)cubeBlock.GetObjectBuilderCubeBlock();
					IMyRadioAntenna antenna = (IMyRadioAntenna)cubeBlock;

					if ( !antenna.Enabled )
						continue;

					//Sandbox.ModAPI.Ingame.IMyFunctionalBlock functionalBlock = (Sandbox.ModAPI.Ingame.IMyFunctionalBlock)cubeBlock;
					//if (!functionalBlock.Enabled)
					//	continue;

					foreach ( IMyPlayer player in players )
					{
						double distance = 0d;
						if ( Entity.GetDistanceBetweenPointAndPlayer( grid.GetPosition( ), player, out distance ) )
						{
							if ( distance < antenna.Radius )
							{
								//found = true;
								//break;
								reason = string.Format( "{0} distance to antenna broadcast: {1}", player.DisplayName, distance );
								return true;
							}
						}
					}
				}

				if ( cubeBlock.BlockDefinition.TypeId == typeof( MyObjectBuilder_MedicalRoom ) )
				{
					//MyObjectBuilder_MedicalRoom medical = (MyObjectBuilder_MedicalRoom)cubeBlock.GetObjectBuilderCubeBlock();
					IMyMedicalRoom medical = (IMyMedicalRoom)cubeBlock;
					if ( !medical.Enabled )
						continue;

					IMyFunctionalBlock functionalBlock = (IMyFunctionalBlock)cubeBlock;
					if ( !functionalBlock.IsFunctional )
						continue;

					//if (!functionalBlock.Enabled)
					//	continue;

					if ( PluginSettings.Instance.DynamicConcealIncludeMedBays )
					{
						lock ( Online )
						{
							foreach ( ulong connectedPlayer in Online )
							{
								long playerId = PlayerMap.Instance.GetFastPlayerIdFromSteamId( connectedPlayer );
								//if (medical.Owner == playerId || (medical.ShareMode == MyOwnershipShareModeEnum.Faction && Player.CheckPlayerSameFaction(medical.Owner, playerId)))
								if ( functionalBlock.OwnerId == playerId )
								{
									reason = string.Format( "Grid has medbay and player is logged in - playerid: {0}", playerId );
                                    //return true;

                                    //medbay is up for reveal, put it into the medbay queue to be revealed before other grids
                                    RevealMedbays( (IMyEntity)grid, reason );
                                    //return false so this grid doesn't get duplicated in the regular queue
                                    return false;
                                }

								if ( functionalBlock.GetUserRelationToOwner( playerId ) == MyRelationsBetweenPlayerAndBlock.FactionShare )
								{
									reason = string.Format( "Grid has medbay and player is factionshare - playerid: {0}", playerId );
                                    //return true;

                                    //medbay is up for reveal, put it into the medbay queue to be revealed before other grids
                                    RevealMedbays( (IMyEntity)grid, reason );
                                    //return false so this grid doesn't get duplicated in the regular queue
                                    return false;
                                }
							}
						}

                        /*
						foreach (ulong connectedPlayer in PlayerManager.Instance.ConnectedPlayers)
						{
							long playerId = PlayerMap.Instance.GetFastPlayerIdFromSteamId(connectedPlayer);
							//if (medical.Owner == playerId || (medical.ShareMode == MyOwnershipShareModeEnum.Faction && Player.CheckPlayerSameFaction(medical.Owner, playerId)))
							//if (functionalBlock.OwnerId == playerId || (functionalBlock.GetUserRelationToOwner(playerId) == Sandbox.Common.MyRelationsBetweenPlayerAndBlock.FactionShare))
							if(medical.HasPlayerAccess(playerId))
							{
								reason = string.Format("Grid has medbay and player is logged in - playerid: {0}", playerId);
								return true;
							}
						}
						 */
                    }
					else
					{
						reason = string.Format( "Grid has medbay and conceal can not include medbays" );
                        //return true;

                        //medbay is up for reveal, put it into the medbay queue to be revealed before other grids
                        RevealMedbays( (IMyEntity)grid, reason );
                        //return false so this grid doesn't get duplicated in the regular queue
                        return false;
                    }
                }

                if ( cubeBlock.BlockDefinition.TypeId == typeof( MyObjectBuilder_CryoChamber) )
                {
                        MyCryoChamber cryo = (MyCryoChamber)cubeBlock;
                        if ( cryo.Pilot == null )
                            continue;
                        
                    if ( !cryo.IsFunctional )
                        continue;                    

                    if ( PluginSettings.Instance.DynamicConcealIncludeMedBays )
                    {
                        lock ( Online )
                        {
                            foreach ( ulong connectedPlayer in Online )
                            {
                                long playerId = PlayerMap.Instance.GetFastPlayerIdFromSteamId( connectedPlayer );
                                IMyPlayer cryoUser = (IMyPlayer) cryo.Pilot;

                                if ( cryoUser.PlayerID == playerId )
                                {
                                    reason = string.Format( "Grid has cryopod and player is inside - playerid: {0}", playerId );
                                    //return true;

                                    //medbay is up for reveal, put it into the medbay queue to be revealed before other grids
                                    RevealMedbays( (IMyEntity)grid, reason );
                                    //return false so this grid doesn't get duplicated in the regular queue
                                    return false;
                                }

                                if ( cryo.HasPlayerAccess( playerId ) )
                                {
                                    reason = string.Format( "Grid has cryopod and player can use - playerid: {0}", playerId );
                                    //return true;

                                    //medbay is up for reveal, put it into the medbay queue to be revealed before other grids
                                    RevealMedbays( (IMyEntity)grid, reason );
                                    //return false so this grid doesn't get duplicated in the regular queue
                                    return false;
                                }
                            }
                        }
                    }
                    else
                    {
                        reason = string.Format( "Grid has cryopod and conceal can not include cryopods" );
                        //return true;

                        //medbay is up for reveal, put it into the medbay queue to be revealed before other grids
                        RevealMedbays( (IMyEntity)grid, reason );
                        //return false so this grid doesn't get duplicated in the regular queue
                        return false;
                    }
                }

                if ( cubeBlock.BlockDefinition.TypeId == typeof( MyObjectBuilder_ProductionBlock ) )
				{
					MyObjectBuilder_ProductionBlock production = (MyObjectBuilder_ProductionBlock)cubeBlock.GetObjectBuilderCubeBlock( );
					if ( !production.Enabled )
						continue;

					IMyProductionBlock productionBlock = (IMyProductionBlock)cubeBlock;
					if ( production.Queue.Length > 0 )
					{
						reason = string.Format( "Grid has production facility that has a queue" );
						return true;
					}
				}
			}

			return false;
		}
		private static bool CheckConcealForce( IMyCubeGrid grid, ulong steamId )
		{
			List<IMySlimBlock> blocks = new List<IMySlimBlock>( );

			// Live dangerously
			grid.GetBlocks( blocks, x => x.FatBlock != null );
			foreach ( IMySlimBlock block in blocks )
			{
				IMyCubeBlock cubeBlock = block.FatBlock;

				if ( cubeBlock.BlockDefinition.TypeId == typeof( MyObjectBuilder_MedicalRoom ) )
				{
					MyObjectBuilder_MedicalRoom medical = (MyObjectBuilder_MedicalRoom)cubeBlock.GetObjectBuilderCubeBlock( );

					if ( !medical.Enabled )
						continue;

					IMyTerminalBlock terminalBlock = (IMyTerminalBlock)cubeBlock;
					long playerId = PlayerMap.Instance.GetFastPlayerIdFromSteamId( steamId );
					if ( medical.Owner == playerId || ( medical.ShareMode == MyOwnershipShareModeEnum.Faction && Player.CheckPlayerSameFaction( medical.Owner, playerId ) ) )
					{
						return true;
					}
				}
			}

			return false;
		}
		private static bool CheckConcealBlockRules( IMyCubeGrid grid, List<IMyPlayer> players )
		{
			List<IMySlimBlock> blocks = new List<IMySlimBlock>( );            

			// Live dangerously
			grid.GetBlocks( blocks, x => x.FatBlock != null );
			//CubeGrids.GetAllConnectedBlocks(_processedGrids, grid, blocks, x => x.FatBlock != null);

			int beaconCount = 0;
			//bool found = false;
			//bool powered = false;
			foreach ( IMySlimBlock block in blocks )
			{
				IMyCubeBlock cubeBlock = block.FatBlock;

				if ( cubeBlock.BlockDefinition.TypeId == typeof( MyObjectBuilder_Beacon ) )
				{
					IMyBeacon beacon = (IMyBeacon)cubeBlock;
					//MyObjectBuilder_Beacon beacon = (MyObjectBuilder_Beacon)cubeBlock.GetObjectBuilderCubeBlock();
					beaconCount++;
					// Keep this return here, as 4 beacons always means true
					if ( beaconCount >= 4 )
					{
						return true;
					}

					if ( !beacon.Enabled )
						continue;

					IMyTerminalBlock terminalBlock = (IMyTerminalBlock)cubeBlock;
					//					Console.WriteLine("Found: {0} {1} {2}", beacon.BroadcastRadius, terminalBlock.IsWorking, terminalBlock.IsFunctional);
					//if (!terminalBlock.IsWorking)
					//{
					//						continue;
					//}

					foreach ( IMyPlayer player in players )
					{
						double distance;
						if ( Entity.GetDistanceBetweenPointAndPlayer( grid.GetPosition( ), player, out distance ) )
						{
							if ( distance < beacon.Radius )
							{
								//								Console.WriteLine("Not concealed due to broadcast radius");
								//found = true;
								//break;
								return true;
							}
						}
					}
				}

				if ( cubeBlock.BlockDefinition.TypeId == typeof( MyObjectBuilder_RadioAntenna ) )
				{
					//MyObjectBuilder_RadioAntenna antenna = (MyObjectBuilder_RadioAntenna)cubeBlock.GetObjectBuilderCubeBlock();
					IMyRadioAntenna antenna = (IMyRadioAntenna)cubeBlock;

					if ( !antenna.Enabled )
						continue;

					IMyTerminalBlock terminalBlock = (IMyTerminalBlock)cubeBlock;
					//if (!terminalBlock.IsWorking)
					//	continue;

					foreach ( IMyPlayer player in players )
					{
						double distance;
						if ( Entity.GetDistanceBetweenPointAndPlayer( grid.GetPosition( ), player, out distance ) )
						{
							if ( distance < antenna.Radius )
							{
								//								Console.WriteLine("Not concealed due to antenna broadcast radius");
								//found = true;
								//break;
								return true;
							}
						}
					}
				}

				if ( cubeBlock.BlockDefinition.TypeId == typeof( MyObjectBuilder_MedicalRoom ) )
				{
					//MyObjectBuilder_MedicalRoom medical = (MyObjectBuilder_MedicalRoom)cubeBlock.GetObjectBuilderCubeBlock();
					IMyMedicalRoom medical = (IMyMedicalRoom)cubeBlock;

					if ( !medical.Enabled )
						continue;

					IMyFunctionalBlock functionalBlock = (IMyFunctionalBlock)cubeBlock;
					//if (!terminalBlock.IsWorking)
					//	continue;

					if ( PluginSettings.Instance.DynamicConcealIncludeMedBays )
					{
						lock ( Online )
						{
							foreach ( ulong connectedPlayer in Online )
							{
								//if (PlayerMap.Instance.GetPlayerIdsFromSteamId(connectedPlayer).Count < 1)
								//continue;

								//long playerId = PlayerMap.Instance.GetPlayerIdsFromSteamId(connectedPlayer).First();
								long playerId = PlayerMap.Instance.GetFastPlayerIdFromSteamId( connectedPlayer );

								if ( functionalBlock.OwnerId == playerId || ( functionalBlock.GetUserRelationToOwner( playerId ) == MyRelationsBetweenPlayerAndBlock.FactionShare ) )
								//if (functionalBlock.Owner == playerId || (functionalBlock.ShareMode == MyOwnershipShareModeEnum.Faction && Player.CheckPlayerSameFaction(functionalBlock.Owner, playerId)))
								//if (medical.HasPlayerAccess(playerId))
								{
									return true;
								}
							}
						}

						/*
						foreach (ulong connectedPlayer in PlayerManager.Instance.ConnectedPlayers)
						{
							//if (PlayerMap.Instance.GetPlayerIdsFromSteamId(connectedPlayer).Count < 1)
								//continue;

							//long playerId = PlayerMap.Instance.GetPlayerIdsFromSteamId(connectedPlayer).First();
							long playerId = PlayerMap.Instance.GetFastPlayerIdFromSteamId(connectedPlayer);
							//if (medical.Owner == playerId || (medical.ShareMode == MyOwnershipShareModeEnum.Faction && Player.CheckPlayerSameFaction(medical.Owner, playerId)))
							if(medical.HasPlayerAccess(playerId))
							{
								return true;
							}
						}
						 */
					}
					else
					{
						return true;
					}
				}

                if ( cubeBlock.BlockDefinition.TypeId == typeof( MyObjectBuilder_CryoChamber ) )
                {
                    MyCryoChamber cryo = (MyCryoChamber)cubeBlock;
                    
                    if ( cryo.Pilot != null )
                        return true;
                }            

                if ( cubeBlock.BlockDefinition.TypeId == typeof( MyObjectBuilder_Refinery ) || cubeBlock.BlockDefinition.TypeId == typeof( MyObjectBuilder_Assembler ) )
				{
					//MyObjectBuilder_ProductionBlock production = (MyObjectBuilder_ProductionBlock)cubeBlock.GetObjectBuilderCubeBlock();
					IMyProductionBlock production = (IMyProductionBlock)cubeBlock;
					if ( !production.Enabled )
						continue;

					if ( production.IsProducing )
						return true;
				}

				foreach ( string subType in PluginSettings.Instance.DynamicConcealIgnoreSubTypeList )
				{
					if ( cubeBlock.BlockDefinition.SubtypeName.Contains( subType ) )
					{
						//						Console.WriteLine("Not concealed due subtype");
						//found = true;
						return true;
					}
				}
			}

			return false;
		}
        private void DeleteReverse( SettingsBlockEnforcementItem blockEnforcementSetting, int remove, IMyCubeGrid grid )
        {
            int count = 0;
            IMyGridTerminalSystem gridTerminal = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid( grid );

            List<Sandbox.ModAPI.IMyTerminalBlock> blocksToRemove = new List<Sandbox.ModAPI.IMyTerminalBlock>( );
            for ( int r = gridTerminal.Blocks.Count - 1; r >= 0; r-- )
            {
                Sandbox.ModAPI.IMyTerminalBlock block = (Sandbox.ModAPI.IMyTerminalBlock)gridTerminal.Blocks[ r ];
                switch ( blockEnforcementSetting.Mode )
                {
                    case SettingsBlockEnforcementItem.EnforcementMode.BlockSubtypeId:
                        if ( !string.IsNullOrEmpty( block.BlockDefinition.SubtypeId ) && block.BlockDefinition.SubtypeId.Contains( blockEnforcementSetting.BlockSubtypeId ) )
                        {
                            blocksToRemove.Add( block );
                            count++;
                        }
                        break;
                    case SettingsBlockEnforcementItem.EnforcementMode.BlockTypeId:
                        if ( block.BlockDefinition.TypeIdString.Contains( blockEnforcementSetting.BlockTypeId ) )
                        {
                            blocksToRemove.Add( block );
                            count++;
                        }
                        break;
                }

                if ( count == remove )
                    break;
            }

            /*
            List<MyObjectBuilder_CubeBlock> blocksToRemove = new List<MyObjectBuilder_CubeBlock>();
            for (int r = gridBuilder.CubeBlocks.Count - 1; r >= 0; r--)
            {
                MyObjectBuilder_CubeBlock block = gridBuilder.CubeBlocks[r];
                if (block.GetId().ToString().Contains(id))
                {
                    blocksToRemove.Add(block);
                    count++;
                }

                if (count == remove)
                    break;
            }
            */

            if ( blocksToRemove.Count < 1 )
                return;

            List<Vector3I> razeList = new List<Vector3I>( );
            foreach ( Sandbox.ModAPI.IMyTerminalBlock block in blocksToRemove )
            {
                razeList.Add( block.Min );
            }

            Wrapper.GameAction( ( ) =>
            {
                grid.RazeBlocks( razeList );
            } );
        }
예제 #28
0
        private static void RevealEntity(KeyValuePair <IMyEntity, string> item)
        {
            IMyEntity entity = item.Key;
            string    reason = item.Value;
            //Wrapper.GameAction(() =>
            //{
            MyObjectBuilder_CubeGrid builder = CubeGrids.SafeGetObjectBuilder((IMyCubeGrid)entity);

            if (builder == null)
            {
                return;
            }

            IMyCubeGrid grid      = (IMyCubeGrid)entity;
            long        ownerId   = 0;
            string      ownerName = "";

            if (CubeGrids.GetBigOwners(builder).Count > 0)
            {
                ownerId   = CubeGrids.GetBigOwners(builder).First();
                ownerName = PlayerMap.Instance.GetPlayerItemFromPlayerId(ownerId).Name;
            }

            /*
             * entity.InScene = true;
             * entity.CastShadows = true;
             * entity.Visible = true;
             */

            builder.PersistentFlags = (MyPersistentEntityFlags2.InScene | MyPersistentEntityFlags2.CastShadows);
            MyAPIGateway.Entities.RemapObjectBuilder(builder);
            //builder.EntityId = 0;

            if (RemovedGrids.Contains(entity.EntityId))
            {
                Logging.WriteLineAndConsole("Conceal", string.Format("Revealing - Id: {0} DUPE FOUND Display: {1} OwnerId: {2} OwnerName: {3}  Reason: {4}", entity.EntityId, entity.DisplayName.Replace("\r", "").Replace("\n", ""), ownerId, ownerName, reason));
                BaseEntityNetworkManager.BroadcastRemoveEntity(entity, false);
            }
            else
            {
                if (!PluginSettings.Instance.DynamicConcealServerOnly)
                {
                    IMyEntity newEntity = MyAPIGateway.Entities.CreateFromObjectBuilder(builder);
                    Logging.WriteLineAndConsole("Conceal", string.Format("Start Revealing - Id: {0} -> {4} Display: {1} OwnerId: {2} OwnerName: {3}  Reason: {5}", entity.EntityId, entity.DisplayName.Replace("\r", "").Replace("\n", ""), ownerId, ownerName, newEntity.EntityId, reason));
                    if (newEntity == null)
                    {
                        Logging.WriteLineAndConsole("Conceal", string.Format("Issue - CreateFromObjectBuilder failed: {0}", newEntity.EntityId));
                        return;
                    }

                    RemovedGrids.Add(entity.EntityId);
                    BaseEntityNetworkManager.BroadcastRemoveEntity(entity, false);
                    MyAPIGateway.Entities.AddEntity(newEntity, true);

                    /*CC
                     * if (PluginSettings.Instance.DynamicClientConcealEnabled)
                     * {
                     *      ClientEntityManagement.AddEntityState(newEntity.EntityId);
                     * }
                     */

                    builder.EntityId = newEntity.EntityId;
                    List <MyObjectBuilder_EntityBase> addList = new List <MyObjectBuilder_EntityBase>();
                    addList.Add(newEntity.GetObjectBuilder());
                    MyAPIGateway.Multiplayer.SendEntitiesCreated(addList);
                    Logging.WriteLineAndConsole("Conceal", string.Format("End Revealing - Id: {0} -> {4} Display: {1} OwnerId: {2} OwnerName: {3}  Reason: {5}", entity.EntityId, entity.DisplayName.Replace("\r", "").Replace("\n", ""), ownerId, ownerName, newEntity.EntityId, reason));
                }
                else
                {
                    Logging.WriteLineAndConsole("Conceal", string.Format("Start Revealing - Id: {0} -> {4} Display: {1} OwnerId: {2} OwnerName: {3}  Reason: {4}", entity.EntityId, entity.DisplayName.Replace("\r", "").Replace("\n", ""), ownerId, ownerName, reason));
                    entity.InScene = true;
                    // Send to users, client will remove if doesn't need - this solves login problem

                    /*CC
                     * if (PluginSettings.Instance.DynamicClientConcealEnabled)
                     * {
                     *      ClientEntityManagement.AddEntityState(entity.EntityId);
                     *      List<MyObjectBuilder_EntityBase> addList = new List<MyObjectBuilder_EntityBase>();
                     *      addList.Add(entity.GetObjectBuilder());
                     * MyAPIGateway.Multiplayer.SendEntitiesCreated(addList);
                     * }
                     */
                    Logging.WriteLineAndConsole("Conceal", string.Format("End Revealing - Id: {0} -> {4} Display: {1} OwnerId: {2} OwnerName: {3}  Reason: {4}", entity.EntityId, entity.DisplayName.Replace("\r", "").Replace("\n", ""), ownerId, ownerName, reason));
                }
            }
            //});
        }
예제 #29
0
        static public void RevealAll( )
        {
            HashSet <IMyEntity> entities = new HashSet <IMyEntity>( );

            Wrapper.GameAction(() =>
            {
                MyAPIGateway.Entities.GetEntities(entities);
            });

            List <MyObjectBuilder_EntityBase> addList = new List <MyObjectBuilder_EntityBase>( );
            int count = 0;

            Wrapper.GameAction(() =>
            {
                foreach (IMyEntity entity in entities)
                {
                    if (entity.InScene)
                    {
                        continue;
                    }

                    if (!(entity is IMyCubeGrid))
                    {
                        continue;
                    }

                    MyObjectBuilder_CubeGrid builder = CubeGrids.SafeGetObjectBuilder((IMyCubeGrid)entity);
                    if (builder == null)
                    {
                        continue;
                    }

                    count++;
                    IMyCubeGrid grid = (IMyCubeGrid)entity;
                    long ownerId     = 0;
                    string ownerName = "";
                    if (CubeGrids.GetBigOwners(builder).Count > 0)
                    {
                        ownerId   = CubeGrids.GetBigOwners(builder).First( );
                        ownerName = PlayerMap.Instance.GetPlayerItemFromPlayerId(ownerId).Name;
                    }

                    //grid.PersistentFlags = (MyPersistentEntityFlags2.InScene | MyPersistentEntityFlags2.CastShadows);
                    //grid.InScene = true;
                    //grid.CastShadows = true;
                    builder.PersistentFlags = (MyPersistentEntityFlags2.InScene | MyPersistentEntityFlags2.CastShadows);
                    MyAPIGateway.Entities.RemapObjectBuilder(builder);
                    if (PluginSettings.Instance.DynamicShowMessages)
                    {
                        Essentials.Log.Info("Force Revealing - Id: {0} -> {4} Display: {1} OwnerId: {2} OwnerName: {3}", entity.EntityId, entity.DisplayName.Replace("\r", "").Replace("\n", ""), ownerId, ownerName, builder.EntityId);
                    }

                    IMyEntity newEntity = MyAPIGateway.Entities.CreateFromObjectBuilder(builder);
                    if (newEntity == null)
                    {
                        Essentials.Log.Warn("CreateFromObjectBuilder failed: {0}", builder.EntityId);
                        continue;
                    }
                    //these methods no longer exist.
                    //KEEEEEEEEN!

                    //BaseEntityNetworkManager.BroadcastRemoveEntity( entity, false );

                    /*
                     *                  MyAPIGateway.Entities.AddEntity( newEntity );
                     *                  addList.Add( newEntity.GetObjectBuilder( ) );
                     *                  MyAPIGateway.Multiplayer.SendEntitiesCreated( addList );
                     *                  addList.Clear( );
                     */
                    MyAPIGateway.Entities.CreateFromObjectBuilderAndAdd(newEntity.GetObjectBuilder());
                }
            });
            if (PluginSettings.Instance.DynamicShowMessages)
            {
                Essentials.Log.Info("Revealed {0} grids", count);
            }
        }
예제 #30
0
        public static bool ToggleMedbayGrids(ulong steamId)
        {
            if (_checkConceal || _checkReveal)
            {
                Communication.SendPrivateInformation(steamId, "Server busy");
                return(false);
            }

            _checkConceal = true;
            _checkReveal  = true;
            try
            {
                DateTime start = DateTime.Now;

                // Toggle off
                HashSet <IMyEntity> entities      = new HashSet <IMyEntity>();
                HashSet <IMyEntity> entitiesFound = new HashSet <IMyEntity>();

                try
                {
                    MyAPIGateway.Entities.GetEntities(entities);
                }
                catch
                {
                    Logging.WriteLineAndConsole("CheckAndConcealEntities(): Error getting entity list, skipping check");
                    return(false);
                }

                CubeGrids.GetGridsUnconnected(entitiesFound, entities);

                HashSet <IMyEntity> entitiesToConceal = new HashSet <IMyEntity>();
                foreach (IMyEntity entity in entitiesFound)
                {
                    if (!(entity is IMyCubeGrid))
                    {
                        continue;
                    }

                    if (entity.DisplayName.Contains("CommRelay"))
                    {
                        continue;
                    }

                    if (!entity.InScene)
                    {
                        continue;
                    }

                    if (((IMyCubeGrid)entity).GridSizeEnum != MyCubeSize.Small && !PluginSettings.Instance.ConcealIncludeLargeGrids)
                    {
                        continue;
                    }

                    IMyCubeGrid grid     = (IMyCubeGrid)entity;
                    long        playerId = PlayerMap.Instance.GetFastPlayerIdFromSteamId(steamId);
                    if (!grid.BigOwners.Contains(playerId) && !grid.SmallOwners.Contains(playerId))
                    {
                        continue;
                    }

                    bool found = false;
                    // Check to see if grid is close to dock / shipyard
                    foreach (IMyCubeGrid checkGrid in ProcessDockingZone.ZoneCache)
                    {
                        try
                        {
                            if (Vector3D.Distance(checkGrid.GetPosition(), grid.GetPosition()) < 100d)
                            {
                                found = true;
                                break;
                            }
                        }
                        catch
                        {
                            continue;
                        }
                    }

                    if (!found)
                    {
                        // Check for block type rules
                    }

                    if (!found)
                    {
                        entitiesToConceal.Add(entity);
                    }
                }

                if (entitiesToConceal.Count > 0)
                {
                    //if (PluginSettings.Instance.DynamicClientConcealEnabled)
                    //{
                    //ClientEntityManagement.Refresh(steamId);
                    //}

                    Communication.SendClientMessage(steamId, string.Format("/conceal {0}", string.Join(",", entitiesToConceal.Select(x => x.EntityId.ToString() + ":" + ((MyObjectBuilder_CubeGrid)x.GetObjectBuilder()).CubeBlocks.Count.ToString() + ":" + x.DisplayName).ToArray())));
                    Thread.Sleep(1500);
                    ConcealEntities(entitiesToConceal);
                    //CheckAndRevealEntities();
                }

                if ((DateTime.Now - start).TotalMilliseconds > 2000)
                {
                    Logging.WriteLineAndConsole(string.Format("Completed Toggle: {0}ms", (DateTime.Now - start).TotalMilliseconds));
                }
            }
            catch (Exception ex)
            {
                Logging.WriteLineAndConsole(string.Format("CheckAndConceal(): {0}", ex.ToString()));
            }
            finally
            {
                _checkConceal = false;
                _checkReveal  = false;
            }

            return(true);
        }
        static public void FindByName(String pylonName, out Dictionary <String, List <IMyCubeBlock> > testList, out List <IMyCubeBlock> beaconList, long playerId)
        {
            IMyCubeGrid beaconParent = null;

            testList   = new Dictionary <string, List <IMyCubeBlock> >();
            beaconList = new List <IMyCubeBlock>();
            HashSet <IMyEntity> entities = new HashSet <IMyEntity>();

            Wrapper.GameAction(() =>
            {
                MyAPIGateway.Entities.GetEntities(entities, null);
            });

            foreach (IMyEntity entity in entities)
            {
                if (!(entity is IMyCubeGrid))
                {
                    continue;
                }

                IMyCubeGrid cubeGrid = (IMyCubeGrid)entity;

                if (cubeGrid == null || cubeGrid.GridSizeEnum == MyCubeSize.Small)
                {
                    continue;
                }

                if (!cubeGrid.BigOwners.Contains(playerId) && !cubeGrid.SmallOwners.Contains(playerId))
                {
                    continue;
                }

                testList.Clear();
                beaconList.Clear();
                beaconParent = cubeGrid;

                List <IMySlimBlock> cubeBlocks = new List <IMySlimBlock>();
                cubeGrid.GetBlocks(cubeBlocks);
                foreach (IMySlimBlock entityBlock in cubeBlocks)
                {
                    if (entityBlock.FatBlock == null)
                    {
                        continue;
                    }

                    if (!(entityBlock.FatBlock is IMyCubeBlock))
                    {
                        continue;
                    }

                    IMyCubeBlock cubeBlock = (IMyCubeBlock)entityBlock.FatBlock;

                    if (!(cubeBlock is IMyBeacon))
                    {
                        continue;
                    }

                    IMyTerminalBlock beacon = (IMyTerminalBlock)cubeBlock;

                    /*
                     * MyObjectBuilder_CubeBlock blockObject;
                     * try
                     * {
                     *      blockObject = entityBlock.FatBlock.GetObjectBuilderCubeBlock();
                     *      if (blockObject == null)
                     *              continue;
                     * }
                     * catch
                     * {
                     *      continue;
                     * }
                     *
                     * if (!(blockObject is MyObjectBuilder_Beacon))
                     *      continue;
                     *
                     * MyObjectBuilder_Beacon beacon = (MyObjectBuilder_Beacon)blockObject;
                     */

                    if (beacon.CustomName == null || beacon.CustomName == "")
                    {
                        continue;
                    }

                    if (beacon.IsFunctional &&
                        beacon.CustomName.ToLower() == pylonName.ToLower()
                        )
                    {
                        beaconList.Add(entityBlock.FatBlock);
                        Vector3D beaconPos = Entity.GetBlockEntityPosition(entityBlock.FatBlock);
                        continue;
                    }

                    if (testList.ContainsKey(beacon.CustomName))
                    {
                        testList[beacon.CustomName].Add(entityBlock.FatBlock);
                    }
                    else
                    {
                        List <IMyCubeBlock> testBeaconList = new List <IMyCubeBlock>();
                        testBeaconList.Add(entityBlock.FatBlock);
                        testList.Add(beacon.CustomName, testBeaconList);
                    }
                }

                if (beaconList.Count == 4)
                {
                    break;
                }
            }
        }
예제 #32
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);
        }
예제 #33
0
        public static void CheckAndConcealEntities()
        {
            if (_checkConceal)
            {
                return;
            }

            _checkConceal = true;
            try
            {
                DateTime start      = DateTime.Now;
                double   distCheck  = 0d;
                double   blockRules = 0d;
                double   getGrids   = 0d;
                double   co         = 0f;

                ProcessedGrids.Clear();
                List <IMyPlayer>    players          = new List <IMyPlayer>();
                HashSet <IMyEntity> entities         = new HashSet <IMyEntity>();
                HashSet <IMyEntity> entitiesFiltered = new HashSet <IMyEntity>();
                HashSet <IMyEntity> entitiesFound    = new HashSet <IMyEntity>();

                try
                {
                    MyAPIGateway.Players.GetPlayers(players);
                }
                catch (Exception ex)
                {
                    Logging.WriteLineAndConsole(string.Format("Error getting players list.  Check and Conceal failed: {0}", ex.ToString()));
                    return;
                }

                try
                {
                    MyAPIGateway.Entities.GetEntities(entities);
                }
                catch
                {
                    Logging.WriteLineAndConsole("CheckAndConcealEntities(): Error getting entity list, skipping check");
                    return;
                }

                foreach (IMyEntity entity in entities)
                {
                    if (!(entity is IMyCubeGrid))
                    {
                        continue;
                    }

                    if (!entity.InScene)
                    {
                        continue;
                    }

                    entitiesFiltered.Add(entity);
                }

                DateTime getGridsStart = DateTime.Now;
                CubeGrids.GetGridsUnconnected(entitiesFound, entitiesFiltered);
                getGrids += (DateTime.Now - getGridsStart).TotalMilliseconds;

                HashSet <IMyEntity> entitiesToConceal = new HashSet <IMyEntity>();
                foreach (IMyEntity entity in entitiesFound)
                {
                    if (!(entity is IMyCubeGrid))
                    {
                        continue;
                    }

                    if (entity.DisplayName.Contains("CommRelay"))
                    {
                        continue;
                    }

                    if (entity.Physics == null)                     // Projection
                    {
                        continue;
                    }

                    if (!entity.InScene)
                    {
                        continue;
                    }

                    if (((IMyCubeGrid)entity).GridSizeEnum != MyCubeSize.Small && !PluginSettings.Instance.ConcealIncludeLargeGrids)
                    {
                        continue;
                    }

                    IMyCubeGrid grid = (IMyCubeGrid)entity;

                    bool     found     = false;
                    DateTime distStart = DateTime.Now;
                    foreach (IMyPlayer player in players)
                    {
                        double distance = 0f;
                        if (Entity.GetDistanceBetweenGridAndPlayer(grid, player, out distance))
                        {
                            if (distance < PluginSettings.Instance.DynamicConcealDistance)
                            {
                                found = true;
                            }
                        }
                    }
                    distCheck += (DateTime.Now - distStart).TotalMilliseconds;

                    if (!found)
                    {
                        // Check to see if grid is close to dock / shipyard
                        foreach (IMyCubeGrid checkGrid in ProcessDockingZone.ZoneCache)
                        {
                            try
                            {
                                if (Vector3D.Distance(checkGrid.GetPosition(), grid.GetPosition()) < 100d)
                                {
                                    found = true;
                                    break;
                                }
                            }
                            catch
                            {
                                continue;
                            }
                        }
                    }

                    if (!found)
                    {
                        // Check for block type rules
                        DateTime blockStart = DateTime.Now;
                        if (CheckConcealBlockRules(grid, players))
                        {
                            found = true;
                        }

                        blockRules += (DateTime.Now - blockStart).TotalMilliseconds;
                    }

                    if (!found)
                    {
                        entitiesToConceal.Add(entity);
                    }
                }

                DateTime coStart = DateTime.Now;
                if (entitiesToConceal.Count > 0)
                {
                    ConcealEntities(entitiesToConceal);
                }
                co += (DateTime.Now - coStart).TotalMilliseconds;

                if ((DateTime.Now - start).TotalMilliseconds > 2000)
                {
                    Logging.WriteLineAndConsole(string.Format("Completed Conceal Check: {0}ms (gg: {3}, dc: {2} ms, br: {1}ms, co: {4}ms)", (DateTime.Now - start).TotalMilliseconds, blockRules, distCheck, getGrids, co));
                }
            }
            catch (Exception ex)
            {
                Logging.WriteLineAndConsole(string.Format("CheckAndConceal(): {0}", ex.ToString()));
            }
            finally
            {
                _checkConceal = false;
            }
        }
예제 #34
0
 //sets targets to null
 private void ClearTarget()
 {
     _target       = null;
     _targetPlayer = null;
 }
예제 #35
0
        public static void CheckAndRevealEntities()
        {
            if (_checkReveal)
            {
                return;
            }

            _checkReveal = true;
            try
            {
                DateTime start = DateTime.Now;
                double   br    = 0f;
                double   re    = 0f;

                List <IMyPlayer>    players  = new List <IMyPlayer>();
                HashSet <IMyEntity> entities = new HashSet <IMyEntity>();
                //Wrapper.GameAction(() =>
                //{
                MyAPIGateway.Players.GetPlayers(players);
                MyAPIGateway.Entities.GetEntities(entities);
                //});

                Dictionary <IMyEntity, string> entitiesToReveal = new Dictionary <IMyEntity, string>();
                string currentReason = "";
                //HashSet<IMyEntity> entitiesToReveal = new HashSet<IMyEntity>();
                foreach (IMyEntity entity in entities)
                {
                    if (entity.MarkedForClose)
                    {
                        continue;
                    }

                    if (!(entity is IMyCubeGrid))
                    {
                        continue;
                    }

                    if (entity.InScene)
                    {
                        continue;
                    }

                    IMyCubeGrid grid  = (IMyCubeGrid)entity;
                    bool        found = false;
                    currentReason = "";
                    foreach (IMyPlayer player in players)
                    {
                        double distance = 0f;
                        if (Entity.GetDistanceBetweenGridAndPlayer(grid, player, out distance))
                        {
                            if (distance < PluginSettings.Instance.DynamicConcealDistance)
                            {
                                found         = true;
                                currentReason = string.Format("{0} distance to grid: {1}", player.DisplayName, distance);
                            }
                        }
                    }

                    if (!found)
                    {
                        DateTime brStart = DateTime.Now;
                        if (CheckRevealBlockRules(grid, players, out currentReason))
                        {
                            found = true;
                        }
                        br += (DateTime.Now - brStart).TotalMilliseconds;
                    }

                    if (found)
                    {
                        entitiesToReveal.Add(entity, currentReason);
                    }
                }

                DateTime reStart = DateTime.Now;
                if (entitiesToReveal.Count > 0)
                {
                    RevealEntities(entitiesToReveal);
                }
                re += (DateTime.Now - reStart).TotalMilliseconds;

                if ((DateTime.Now - start).TotalMilliseconds > 2000)
                {
                    Logging.WriteLineAndConsole(string.Format("Completed Reveal Check: {0}ms (br: {1}ms, re: {2}ms)", (DateTime.Now - start).TotalMilliseconds, br, re));
                }
            }
            catch (Exception ex)
            {
                Logging.WriteLineAndConsole(string.Format("CheckAndReveal(): {0}", ex.ToString()));
            }
            finally
            {
                _checkReveal = false;
            }
        }
예제 #36
0
 //sets targets to null
 private void ClearTarget()
 {
     _target = null;
     _targetPlayer = null;
 }
예제 #37
0
        //target key points on an enemy ship to disable them
        private bool FindTargetKeyPoint(IMyCubeGrid grid, Vector3D velocity)
        {
            //get position, get lenier velocity in each direction
            //add them like 10 times and add that to current coord
                if (grid != null)
                {
                    IMyGridTerminalSystem gridTerminal =
                        MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid(grid);

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

                    List<IMyTerminalBlock> cockpitsTarget =
                        new List<IMyTerminalBlock>();
                    gridTerminal.GetBlocksOfType<IMyCockpit>(cockpitsTarget);

                    List<IMyTerminalBlock> allBlocksTarget =
                        new List<IMyTerminalBlock>();
                    gridTerminal.GetBlocksOfType<Sandbox.ModAPI.IMyTerminalBlock>(allBlocksTarget);

                    List<IMyTerminalBlock> missileLuanchersTarget =
                        new List<IMyTerminalBlock>();
                    gridTerminal.GetBlocksOfType<IMyMissileGunObject>(missileLuanchersTarget);

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

                    List<IMyTerminalBlock> mergeBlocks =
                        new List<IMyTerminalBlock>();
                    gridTerminal.GetBlocksOfType<IMyShipMergeBlock>(mergeBlocks);

                    MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid(_target);
                    List<IMySlimBlock> weaponsTarget = new List<IMySlimBlock>();

                    grid.GetBlocks(weaponsTarget,
                        (x) => x.FatBlock != null && x.FatBlock is IMyUserControllableGun);
                    //now that we have a list of reactors and guns lets primary one.
                    //try to find a working gun, if none are found then find a reactor to attack

                    //guns, rockets, cockpits,reactors,batteries
                    foreach (var merge in mergeBlocks.OrderBy(x => (x.GetPosition() - Ship.GetPosition()).Length()))
                    {
                        if (merge != null)
                        {
                            var item = ((IMyCubeBlock)merge);
                            if (item.IsFunctional)
                            {
                                OrbitAttackTarget(item.GetPosition(), velocity);
                                return true;
                            }
                        }
                    }
                    foreach (var weapon in weaponsTarget.OrderBy(x=>(x.FatBlock.GetPosition() - Ship.GetPosition()).Length()))
                    {
                        if (weapon != null)
                        {
                            var item = (weapon.FatBlock);

                            if (item.IsFunctional)
                            {
                                OrbitAttackTarget(item.GetPosition(), velocity);
                                return true;
                            }
                        }
                    }
                    foreach (var missile in missileLuanchersTarget.OrderBy(x => (x.GetPosition() - Ship.GetPosition()).Length()))
                    {
                        if (missile != null)
                        {
                            var item = ((IMyCubeBlock) missile);
                            if (item.IsFunctional)
                            {
                                OrbitAttackTarget(item.GetPosition(), velocity);
                                return true;
                            }
                        }
                    }
                    foreach (var reactor in reactorsTarget.OrderBy(x => (x.GetPosition() - Ship.GetPosition()).Length()))
                    {
                        if (reactor != null)
                        {
                            var item = ((IMyCubeBlock)reactor);
                            if (item.IsFunctional)
                            {
                                OrbitAttackTarget(item.GetPosition(), velocity);
                                return true;
                            }
                        }
                    }
                    foreach (var battery in batteriesTarget.OrderBy(x => (x.GetPosition() - Ship.GetPosition()).Length()))
                    {
                        if (battery != null)
                        {
                            var item = ((IMyCubeBlock)battery);
                            if ( item.IsFunctional)
                            {
                                OrbitAttackTarget(item.GetPosition(), velocity);
                                return true;
                            }
                        }
                    }
                    foreach (var c*k in cockpitsTarget.OrderBy(x => (x.GetPosition() - Ship.GetPosition()).Length()))
                    {
                        if (c*k != null)
                        {
                            var item = ((IMyCubeBlock)c*k);
                            if (item.IsFunctional)
                            {
                                OrbitAttackTarget(item.GetPosition(), velocity);
                                return true;
                            }
                        }
                    }
                }
            return false;
        }
예제 #38
0
        //target key points on an enemy ship to disable them
        private bool FindTargetKeyPoint(IMyCubeGrid grid, Vector3D velocity)
        {
            //get position, get lenier velocity in each direction
            //add them like 10 times and add that to current coord
            if (grid != null)
            {
                IMyGridTerminalSystem gridTerminal =
                    MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid(grid);

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

                List <IMyTerminalBlock> cockpitsTarget =
                    new List <IMyTerminalBlock>();
                gridTerminal.GetBlocksOfType <IMyCockpit>(cockpitsTarget);

                List <IMyTerminalBlock> allBlocksTarget =
                    new List <IMyTerminalBlock>();
                gridTerminal.GetBlocksOfType <Sandbox.ModAPI.IMyTerminalBlock>(allBlocksTarget);

                List <IMyTerminalBlock> missileLuanchersTarget =
                    new List <IMyTerminalBlock>();
                gridTerminal.GetBlocksOfType <IMyMissileGunObject>(missileLuanchersTarget);

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

                List <IMyTerminalBlock> mergeBlocks =
                    new List <IMyTerminalBlock>();
                gridTerminal.GetBlocksOfType <IMyShipMergeBlock>(mergeBlocks);

                MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid(_target);
                List <IMySlimBlock> weaponsTarget = new List <IMySlimBlock>();

                grid.GetBlocks(weaponsTarget,
                               (x) => x.FatBlock != null && x.FatBlock is IMyUserControllableGun);
                //now that we have a list of reactors and guns lets primary one.
                //try to find a working gun, if none are found then find a reactor to attack

                //guns, rockets, cockpits,reactors,batteries
                foreach (var merge in mergeBlocks.OrderBy(x => (x.GetPosition() - Ship.GetPosition()).Length()))
                {
                    if (merge != null)
                    {
                        var item = ((IMyCubeBlock)merge);
                        if (item.IsFunctional)
                        {
                            OrbitAttackTarget(item.GetPosition(), velocity);
                            return(true);
                        }
                    }
                }
                foreach (var weapon in weaponsTarget.OrderBy(x => (x.FatBlock.GetPosition() - Ship.GetPosition()).Length()))
                {
                    if (weapon != null)
                    {
                        var item = (weapon.FatBlock);

                        if (item.IsFunctional)
                        {
                            OrbitAttackTarget(item.GetPosition(), velocity);
                            return(true);
                        }
                    }
                }
                foreach (var missile in missileLuanchersTarget.OrderBy(x => (x.GetPosition() - Ship.GetPosition()).Length()))
                {
                    if (missile != null)
                    {
                        var item = ((IMyCubeBlock)missile);
                        if (item.IsFunctional)
                        {
                            OrbitAttackTarget(item.GetPosition(), velocity);
                            return(true);
                        }
                    }
                }
                foreach (var reactor in reactorsTarget.OrderBy(x => (x.GetPosition() - Ship.GetPosition()).Length()))
                {
                    if (reactor != null)
                    {
                        var item = ((IMyCubeBlock)reactor);
                        if (item.IsFunctional)
                        {
                            OrbitAttackTarget(item.GetPosition(), velocity);
                            return(true);
                        }
                    }
                }
                foreach (var battery in batteriesTarget.OrderBy(x => (x.GetPosition() - Ship.GetPosition()).Length()))
                {
                    if (battery != null)
                    {
                        var item = ((IMyCubeBlock)battery);
                        if (item.IsFunctional)
                        {
                            OrbitAttackTarget(item.GetPosition(), velocity);
                            return(true);
                        }
                    }
                }
                foreach (var c*k in cockpitsTarget.OrderBy(x => (x.GetPosition() - Ship.GetPosition()).Length()))
                {
                    if (c*k != null)
                    {
                        var item = ((IMyCubeBlock)c*k);
                        if (item.IsFunctional)
                        {
                            OrbitAttackTarget(item.GetPosition(), velocity);
                            return(true);
                        }
                    }
                }
            }
            return(false);
        }
예제 #39
0
        static public void RevealAll()
        {
            HashSet <IMyEntity> entities = new HashSet <IMyEntity>();

            Wrapper.GameAction(() =>
            {
                MyAPIGateway.Entities.GetEntities(entities);
            });

            List <MyObjectBuilder_EntityBase> addList = new List <MyObjectBuilder_EntityBase>();
            int count = 0;

            Wrapper.GameAction(() =>
            {
                foreach (IMyEntity entity in entities)
                {
                    if (entity.InScene)
                    {
                        continue;
                    }

                    if (!(entity is IMyCubeGrid))
                    {
                        continue;
                    }

                    MyObjectBuilder_CubeGrid builder = CubeGrids.SafeGetObjectBuilder((IMyCubeGrid)entity);
                    if (builder == null)
                    {
                        continue;
                    }

                    count++;
                    IMyCubeGrid grid = (IMyCubeGrid)entity;
                    long ownerId     = 0;
                    string ownerName = "";
                    if (CubeGrids.GetBigOwners(builder).Count > 0)
                    {
                        ownerId   = CubeGrids.GetBigOwners(builder).First();
                        ownerName = PlayerMap.Instance.GetPlayerItemFromPlayerId(ownerId).Name;
                    }

                    //grid.PersistentFlags = (MyPersistentEntityFlags2.InScene | MyPersistentEntityFlags2.CastShadows);
                    //grid.InScene = true;
                    //grid.CastShadows = true;
                    builder.PersistentFlags = (MyPersistentEntityFlags2.InScene | MyPersistentEntityFlags2.CastShadows);
                    MyAPIGateway.Entities.RemapObjectBuilder(builder);
                    Logging.WriteLineAndConsole("Conceal", string.Format("Force Revealing - Id: {0} -> {4} Display: {1} OwnerId: {2} OwnerName: {3}", entity.EntityId, entity.DisplayName.Replace("\r", "").Replace("\n", ""), ownerId, ownerName, builder.EntityId));

                    IMyEntity newEntity = MyAPIGateway.Entities.CreateFromObjectBuilder(builder);
                    if (newEntity == null)
                    {
                        Logging.WriteLineAndConsole("Conceal", string.Format("Issue - CreateFromObjectBuilder failed: {0}", newEntity.EntityId));
                        continue;
                    }

                    BaseEntityNetworkManager.BroadcastRemoveEntity(entity, false);
                    MyAPIGateway.Entities.AddEntity(newEntity, true);
                    addList.Add(newEntity.GetObjectBuilder());
                    MyAPIGateway.Multiplayer.SendEntitiesCreated(addList);
                    addList.Clear();
                }
            });

            Logging.WriteLineAndConsole(string.Format("Revealed {0} grids", count));
        }
예제 #40
0
        //Disables all beacons and antennas and deletes the ship.
        public void DeleteShip()
        {
            var lstSlimBlock = new List<IMySlimBlock>();
            Ship.GetBlocks(lstSlimBlock, (x) => x.FatBlock is IMyRadioAntenna);
            foreach (var block in lstSlimBlock)
            {
                IMyRadioAntenna antenna = (IMyRadioAntenna)block.FatBlock;
                ITerminalAction act = antenna.GetActionWithName("OnOff_Off");
                act.Apply(antenna);
            }

            lstSlimBlock = new List<IMySlimBlock>();
            Ship.GetBlocks(lstSlimBlock, (x) => x.FatBlock is IMyBeacon);
            foreach (var block in lstSlimBlock)
            {
                IMyBeacon beacon = (IMyBeacon)block.FatBlock;
                ITerminalAction act = beacon.GetActionWithName("OnOff_Off");
                act.Apply(beacon);
            }

            MyAPIGateway.Entities.RemoveEntity(Ship as IMyEntity);
            Ship = null;
        }
예제 #41
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 => (((IMyPowerProducer)x).CurrentPowerOutput > 0 && x.IsWorking) && !isFriendly);

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

                        bool isMothership =
                            T.Exists(x => x.CustomName.Contains("#ConquestMothership"));

                        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);

                        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;
        }
예제 #42
0
        //Working - and damn good I might add
        //returns status means -1 = not activated, 0 = notEngaged, 1 = InCombat
        public int Guard(Vector3D position)
        {
            Util.GetInstance().Log("[Drone.Guard] Guarding:");
            ManualFire(false);

            if (Math.Abs((position - Ship.GetPosition()).Length()) < ConquestMod.MaxEngagementRange)
            {
                if (navigation.AvoidNearbyEntities())
                {
                    Util.GetInstance().Log("[Drone.Guard] " + myNumber + " Drone Avoiding");
                }

                var distance = (position - Ship.GetPosition()).Length();

                if (FindNearbyAttackTarget())
                {
                    Util.GetInstance().Log("[Drone.Guard] " + myNumber + " drone found a target");
                    return 1;
                }

                if (distance > navigation.FollowRange*1.2)
                {
                    if (!navigation.Avoiding && navigation.Follow(position))
                    {
                        _beaconName = "Following";
                    }
                }
                else
                {
                    if (!navigation.Avoiding && navigation.Orbit(position))
                    {
                        _beaconName = "Orbiting";

                    }
                }

            }
            else if (Ship!=null && navigation != null)
            {
                _beaconName = "Returning";
                navigation.Follow(position);
                _target = null;
            }
            NameBeacon();

            return 0;
        }
예제 #43
0
		static public bool DoesGridContainZone(IMyCubeGrid cubeGrid)
		{
			return GetZonesInGrid(cubeGrid).Count > 0;
		}
예제 #44
0
        public void GetMultiblockConfig()
        {
#warning TODO: Restrict barrel placement to directly in front of the main body

            List <Sandbox.ModAPI.IMySlimBlock> connectedBlocks = new List <Sandbox.ModAPI.IMySlimBlock>();

            Sandbox.ModAPI.IMyCubeGrid grid = (Sandbox.ModAPI.IMyCubeGrid)MDBody.CubeGrid;
            Matrix          localMatrix     = MDBody.LocalMatrix;
            List <Vector3I> searchQueue     = new List <Vector3I>()
            {
                FindOffset(localMatrix, new Vector3I(2, 0, 1)),  //right port
                FindOffset(localMatrix, new Vector3I(-2, 0, 1)), //left port
                FindOffset(localMatrix, new Vector3I(0, 0, 3)),  //front port
            };

            while (searchQueue.Count > 0)
            {
                Vector3I searchLocation = searchQueue[0];

                Sandbox.ModAPI.IMySlimBlock block = grid.GetCubeBlock(searchLocation);

                if (block != null)
                {
                    if (!connectedBlocks.Contains(block))
                    {
                        if (block.GetObjectBuilder().SubtypeId.ToString().Contains("MassDriver"))
                        {
                            connectedBlocks.Add(block);
                        }

                        switch (block.GetObjectBuilder().SubtypeId.ToString())
                        {
                        case "MassDriverCord":
                            searchQueue.Add(FindOffset(block.FatBlock.LocalMatrix, new Vector3I(0, 0, 1)));       //front port
                            searchQueue.Add(FindOffset(block.FatBlock.LocalMatrix, new Vector3I(0, 0, -1)));      //back port
                            break;

                        case "MassDriverCordSupport":
                            searchQueue.Add(FindOffset(block.FatBlock.LocalMatrix, new Vector3I(0, 0, 1)));       //front port
                            searchQueue.Add(FindOffset(block.FatBlock.LocalMatrix, new Vector3I(0, 0, -1)));      //back port
                            break;

                        case "MassDriverCordTurn":
                            searchQueue.Add(FindOffset(block.FatBlock.LocalMatrix, new Vector3I(1, 0, 0)));       //right port
                            searchQueue.Add(FindOffset(block.FatBlock.LocalMatrix, new Vector3I(0, -1, 0)));      //bottom port
                            break;

                        case "MassDriverCapacitor":
                            //need to change the translation matrix a little because of the block's even-block-count depth and height
                            Vector3 fixedCapTranslation = block.FatBlock.LocalMatrix.Translation + block.FatBlock.LocalMatrix.Forward + block.FatBlock.LocalMatrix.Down;
                            Matrix  fixedCapMatrix      = block.FatBlock.LocalMatrix;
                            fixedCapMatrix.Translation = fixedCapTranslation;

                            searchQueue.Add(FindOffset(fixedCapMatrix, new Vector3I(0, 0, 2)));      //front port
                            searchQueue.Add(FindOffset(fixedCapMatrix, new Vector3I(0, 0, -3)));     //back port
                            searchQueue.Add(FindOffset(fixedCapMatrix, new Vector3I(0, -1, 0)));     //bottom port
                            break;

                        case "MassDriverBarrelSector":
                            searchQueue.Add(FindOffset(block.FatBlock.LocalMatrix, new Vector3I(0, 0, 2)));      //front port
                            searchQueue.Add(FindOffset(block.FatBlock.LocalMatrix, new Vector3I(0, 0, -2)));     //back port
                            break;

                        case "MassDriverBarrelTip":
                            searchQueue.Add(FindOffset(block.FatBlock.LocalMatrix, new Vector3I(0, 0, -2)));     //back port
                            break;

                        default:

                            break;
                        }
                    }
                }

                searchQueue.RemoveAt(0);
            }

            //count attached parts
            //
            int barrelCount      = connectedBlocks.FindAll(b => b.GetObjectBuilder().SubtypeId.ToString().Contains("MassDriverBarrel")).Count;
            int compulsatorCount = connectedBlocks.FindAll(b => b.GetObjectBuilder().SubtypeId.ToString() == "MassDriverCapacitor").Count;

            //build list of connected batteries
            //
            compulsators = new List </*Sandbox.ModAPI.*/ IMyBatteryBlock>();
            foreach (var batt in connectedBlocks.FindAll(b => b.GetObjectBuilder().SubtypeId.ToString() == "MassDriverCapacitor"))
            {
                compulsators.Add(batt.FatBlock as /*Sandbox.ModAPI.*/ IMyBatteryBlock);
            }

            //update custom name and info instance
            //
            MDBody.SetCustomName("Mass Driver (" + barrelCount.ToString() + "B|" + compulsatorCount.ToString() + "C)");

            if (Data.Drivers.Find(d => d.Id == MDBody.EntityId) == null) //add entry for damage handler
            {
                Data.Drivers.Add(new MDInfo(MDBody.EntityId, compulsatorCount));
            }
            else
            {
                MDInfo existingEntry = Data.Drivers.Find(d => d.Id == MDBody.EntityId);
                existingEntry.DamageMultiplier = compulsatorCount;
            }

            MyAPIGateway.Utilities.ShowMessage("", Data.Drivers.Count().ToString());
        }