Esempio n. 1
0
		public ThrustProfiler(IMyCubeGrid grid)
		{
			if (grid == null)
				throw new NullReferenceException("grid");

			myLogger = new Logger("ThrustProfiler", () => grid.DisplayName);
			myGrid = grid;

			foreach (Base6Directions.Direction direction in Base6Directions.EnumDirections)
				thrustersInDirection.Add(direction, new List<MyThrust>());

			List<IMySlimBlock> thrusters = new List<IMySlimBlock>();
			myGrid.GetBlocks(thrusters, block => block.FatBlock != null && block.FatBlock is IMyThrust);
			foreach (IMySlimBlock thrust in thrusters)
				newThruster(thrust);

			myGrid.OnBlockAdded += grid_OnBlockAdded;
			myGrid.OnBlockRemoved += grid_OnBlockRemoved;
		}
Esempio n. 2
0
        private GridCellCache(IMyCubeGrid grid)
        {
            m_logger = new Logger("GridCellCache", () => grid.DisplayName);
            m_grid = grid;

            List<IMySlimBlock> dummy = new List<IMySlimBlock>();
            MainLock.UsingShared(() => {
                using (lock_cellPositions.AcquireExclusiveUsing())
                    grid.GetBlocks(dummy, slim => {
                        Add(slim);
                        return false;
                    });

                grid.OnBlockAdded += grid_OnBlockAdded;
                grid.OnBlockRemoved += grid_OnBlockRemoved;
                grid.OnClosing += grid_OnClosing;
            });

            m_logger.debugLog("Initialized");
        }
Esempio n. 3
0
        public ThrustProfiler(IMyCubeBlock autopilot)
        {
            if (autopilot == null)
                throw new NullReferenceException("autopilot");

            myLogger = new Logger(GetType().Name, autopilot);
            myGrid = autopilot.CubeGrid;
            Standard = new StandardFlight(autopilot, Base6Directions.Direction.Forward, Base6Directions.Direction.Up);
            Gravity = new StandardFlight(autopilot, Base6Directions.Direction.Up, Base6Directions.Direction.Forward);

            foreach (Base6Directions.Direction direction in Base6Directions.EnumDirections)
                thrustersInDirection.Add(direction, new List<MyThrust>());

            List<IMySlimBlock> thrusters = new List<IMySlimBlock>();
            myGrid.GetBlocks(thrusters, block => block.FatBlock != null && block.FatBlock is IMyThrust);
            foreach (IMySlimBlock thrust in thrusters)
                newThruster(thrust);

            myGrid.OnBlockAdded += grid_OnBlockAdded;
            myGrid.OnBlockRemoved += grid_OnBlockRemoved;

            ClearOverrides();
        }
Esempio n. 4
0
        public static OrientedBoundingBoxD GetBoundingBox(IMyCubeGrid entity)
        {
            var min = new Vector3D(int.MaxValue, int.MaxValue, int.MaxValue);
            var max = new Vector3D(int.MinValue, int.MinValue, int.MinValue);

            float multiplier = 2.5f;
            if (entity.GridSizeEnum == MyCubeSize.Small)
                multiplier = 0.5f;

            List<IMySlimBlock> blocks = new List<IMySlimBlock>();
            entity.GetBlocks(blocks, null);

            foreach (IMySlimBlock block in blocks)
            {
                //Vector3 pos = Entity.GetBlockEntityPosition(block);
                min = Vector3D.Min(block.Position * multiplier, min);
                max = Vector3D.Max(block.Position * multiplier, max);
            }

            Vector3D size = max - min;
            BoundingBoxD bb = new BoundingBoxD(new Vector3D(0, 0, 0), size).Translate(entity.GetPosition() - (size / 2));
            return new OrientedBoundingBoxD(bb.Center, bb.HalfExtents, Quaternion.CreateFromRotationMatrix(entity.WorldMatrix.GetOrientation()));
        }
Esempio n. 5
0
        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;
                }
            }
        }
Esempio n. 6
0
        public static IMyFaction GetOwnerFaction(this IMyCubeGrid Grid, bool RecalculateOwners = false)
        {
            try
            {
                if (RecalculateOwners)
                {
                    (Grid as MyCubeGrid).RecalculateOwners();
                }

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

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

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

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

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

                        Faction = MyAPIGateway.Session.Factions.TryGetFactionByTag(Controllers[0].GetOwnerFactionTag());
                        if (Faction != null)
                        {
                            Grid.DebugWrite("Grid.GetOwnerFaction", $"Found owner faction {Faction.Tag} via cockpit");
                            return(Faction ?? FactionFromBigowners);
                        }
                        else
                        {
                            Grid.DebugWrite("Grid.GetOwnerFaction", $"Unable to owner faction via cockpit!");
                            Faction = MyAPIGateway.Session.Factions.TryGetFactionByTag(AllTermBlocks.First().GetOwnerFactionTag());
                            if (Faction != null)
                            {
                                Grid.DebugWrite("Grid.GetOwnerFaction", $"Found owner faction {Faction.Tag} via first terminal block");
                                return(Faction ?? FactionFromBigowners);
                            }
                            else
                            {
                                Grid.DebugWrite("Grid.GetOwnerFaction", $"Unable to owner faction via first terminal block!");
                                return(Faction ?? FactionFromBigowners);
                            }
                        }
                    }
                    else
                    {
                        Faction = MyAPIGateway.Session.Factions.TryGetFactionByTag(AllTermBlocks.First().GetOwnerFactionTag());
                        if (Faction != null)
                        {
                            Grid.DebugWrite("Grid.GetOwnerFaction", $"Found owner faction {Faction.Tag} via first terminal block");
                            return(Faction ?? FactionFromBigowners);
                        }
                        else
                        {
                            Grid.DebugWrite("Grid.GetOwnerFaction", $"Unable to owner faction via first terminal block!");
                            return(Faction ?? FactionFromBigowners);
                        }
                    }
                }
            }
            catch (Exception Scrap)
            {
                Grid.LogError("Faction.GetOwnerFaction", Scrap);
                return(null);
            }
        }
Esempio n. 7
0
        public static void InitNpcStoreBlock(IMyCubeGrid cubeGrid, ImprovedSpawnGroup spawnGroup)
        {
            var errorLog = new StringBuilder();

            errorLog.Append("Starting Store Block Init For Grid").AppendLine();

            try {
                errorLog.Append(" - Check if Grid Exists").AppendLine();
                if (cubeGrid == null || MyAPIGateway.Entities.Exist(cubeGrid) == false)
                {
                    return;
                }

                errorLog.Append(" - Check if Grid Is Active NPC").AppendLine();
                if (NPCWatcher.ActiveNPCs.ContainsKey(cubeGrid) == false)
                {
                    return;
                }

                errorLog.Append(" - Get Blocks From Grid: " + cubeGrid.CustomName).AppendLine();
                var blockList      = new List <IMySlimBlock>();
                var storeBlockList = new List <IMyStoreBlock>();
                var containerList  = new List <IMyCargoContainer>();
                var gastankList    = new List <IMyGasTank>();
                cubeGrid.GetBlocks(blockList);

                foreach (var block in blockList.Where(x => x.FatBlock != null))
                {
                    var storeBlock = block.FatBlock as IMyStoreBlock;
                    var cargo      = block.FatBlock as IMyCargoContainer;
                    var gasTank    = block.FatBlock as IMyGasTank;

                    if (storeBlock != null)
                    {
                        errorLog.Append("   - Found Store Block " + storeBlock.EntityId.ToString()).AppendLine();
                        storeBlockList.Add(storeBlock);
                    }

                    if (cargo != null)
                    {
                        errorLog.Append("   - Found Container Block " + cargo.EntityId.ToString()).AppendLine();
                        containerList.Add(cargo);
                    }

                    /*
                     * if(gasTank != null) {
                     *
                     *  gastankList.Add(gasTank);
                     *
                     * }
                     */
                }

                var usedCargoContainers = new List <IMyCargoContainer>();
                //var usedTanks = new List<IMyGasTank>();

                errorLog.Append(" - Processing Store Blocks").AppendLine();

                //Process Stores
                foreach (var store in storeBlockList)
                {
                    try{
                        errorLog.Append("   - Check Store For Existing Items And Remove " + store.EntityId.ToString()).AppendLine();
                        var ob = (MyObjectBuilder_StoreBlock)store.SlimBlock.GetObjectBuilder();

                        errorLog.Append("      - Check If ObjectBuilder Null" + store.EntityId.ToString()).AppendLine();
                        if (ob != null)
                        {
                            var existingIdList = new List <long>();

                            if (ob.PlayerItems != null)
                            {
                                foreach (var item in ob.PlayerItems.ToList())
                                {
                                    store.CancelStoreItem(item.Id);
                                }
                            }
                        }
                    }catch (Exception exc) {
                        errorLog.Append("      - Exception Encountered, Probably One Of Those Troublesome ATMs" + store.EntityId.ToString()).AppendLine();
                    }

                    var itemsAvailable = new Dictionary <MyDefinitionId, int>();
                    var gasAvailable   = new Dictionary <MyDefinitionId, int>();
                    var storeInv       = store.GetInventory();
                    var storeitemList  = storeInv.GetItems();

                    errorLog.Append("   - Check Items In Store Inventory To Sell").AppendLine();

                    foreach (var item in storeitemList)
                    {
                        var itemDefId = new MyDefinitionId(item.Content.TypeId, item.Content.SubtypeId);
                        //Logger.AddMsg("Item: " + itemDefId.ToString(), true);

                        if (itemDefId.SubtypeName == "SpaceCredit")
                        {
                            continue;
                        }

                        var amount        = (float)item.Amount;
                        int amountRounded = (int)Math.Floor(amount);

                        if (itemsAvailable.ContainsKey(itemDefId) == false)
                        {
                            itemsAvailable.Add(itemDefId, amountRounded);
                        }
                        else
                        {
                            itemsAvailable[itemDefId] += amountRounded;
                        }
                    }

                    //Get Gas

                    /*
                     * double hydrogen = 100000;
                     * double oxygen = 100000;
                     *
                     * foreach(var tank in gastankList) {
                     *
                     *  if(usedTanks.Contains(tank) == true) {
                     *
                     *      continue;
                     *
                     *  }
                     *
                     *  usedTanks.Add(tank);
                     *
                     *  if(tank.IsWorking == false || tank.IsFunctional == false) {
                     *
                     *      continue;
                     *
                     *  }
                     *
                     *  var tankDef = (MyGasTankDefinition)tank.SlimBlock.BlockDefinition;
                     *  var tankInv = tank.GetInventory();
                     *
                     *  if(tankInv.IsConnectedTo(storeInv) == false || tank.IsSameConstructAs(store) == false) {
                     *
                     *      continue;
                     *
                     *  }
                     *
                     *  if(tankDef.StoredGasId.SubtypeName == "Hydrogen") {
                     *
                     *      hydrogen += tank.Capacity * tank.FilledRatio;
                     *
                     *  }
                     *
                     *  if(tankDef.StoredGasId.SubtypeName == "Oxygen") {
                     *
                     *      oxygen += tank.Capacity * tank.FilledRatio;
                     *
                     *  }
                     *
                     * }
                     *
                     * hydrogen = Math.Floor(hydrogen / 1000);
                     * oxygen = Math.Floor(oxygen / 1000);
                     */

                    errorLog.Append("   - Check Items in Attached Cargo Containers To Sell").AppendLine();

                    //Get Items For Offers
                    foreach (var cargo in containerList)
                    {
                        //Logger.AddMsg("Checking Cargo Container On: " + cargo.CubeGrid.CustomName);

                        if (usedCargoContainers.Contains(cargo))
                        {
                            continue;
                        }

                        var cargoInv = cargo.GetInventory();

                        if (cargoInv.IsConnectedTo(storeInv) == false || cargo.IsSameConstructAs(store) == false)
                        {
                            continue;
                        }

                        usedCargoContainers.Add(cargo);

                        var itemList = cargoInv.GetItems();

                        foreach (var item in itemList)
                        {
                            var itemDefId = new MyDefinitionId(item.Content.TypeId, item.Content.SubtypeId);
                            //Logger.AddMsg("Item: " + itemDefId.ToString(), true);

                            if (itemDefId.SubtypeName == "SpaceCredit")
                            {
                                continue;
                            }

                            var amount        = (float)item.Amount;
                            int amountRounded = (int)Math.Floor(amount);

                            if (itemsAvailable.ContainsKey(itemDefId) == false)
                            {
                                itemsAvailable.Add(itemDefId, amountRounded);
                            }
                            else
                            {
                                itemsAvailable[itemDefId] += amountRounded;
                            }
                        }
                    }

                    if (Logger.LoggerDebugMode == true)
                    {
                        foreach (var item in itemsAvailable.Keys)
                        {
                            Logger.AddMsg("Item For StoreBlock: " + item.ToString() + " - " + itemsAvailable[item], true);
                        }
                    }

                    /*
                     * errorLog.Append("   - Populate Store With Offers").AppendLine();
                     * //TODO: Populate Store With Offers
                     *
                     * IMyPlayer dummyPlayer = null;
                     * var playerList = new List<IMyPlayer>();
                     * MyAPIGateway.Players.GetPlayers(playerList);
                     * var storecube = (store as IMyEntity) as MyCubeBlock;
                     * long originalOwner = store.OwnerId;
                     * long originalPlayerBalance = 0;
                     *
                     * errorLog.Append("   - Search For A Player To Use A Temp Dummy, Since We Cannot Add Credits To NPC Identities To Cover The List Fee").AppendLine();
                     * foreach(var player in playerList) {
                     *
                     *  errorLog.Append("   - Changing Ownership To Player: " + player.DisplayName).AppendLine();
                     *  dummyPlayer = player;
                     *  dummyPlayer.TryGetBalanceInfo(out originalPlayerBalance);
                     *  dummyPlayer.RequestChangeBalance(1000000);
                     *  storecube.ChangeOwner(dummyPlayer.IdentityId, MyOwnershipShareModeEnum.Faction);
                     *  break;
                     *
                     * }
                     */
                    /*
                     * if(hydrogen > 0) {
                     *
                     *  MyStoreItemData gasData = new MyStoreItemData(new MyDefinitionId(typeof(MyObjectBuilder_GasProperties), "Hydrogen"), (int)hydrogen, 150, null, null);
                     *  long gasorderResult = 0;
                     *  var storeAddResult = store.InsertOffer(gasData, out gasorderResult);
                     *  Logger.AddMsg("Hydrogen Add To Store Result: " + storeAddResult.ToString(), true);
                     *
                     * }
                     *
                     * if(oxygen > 0) {
                     *
                     *  MyStoreItemData gasData = new MyStoreItemData(new MyDefinitionId(typeof(MyObjectBuilder_GasProperties), "Oxygen"), (int)hydrogen, 150, null, null);
                     *  long gasorderResult = 0;
                     *  var storeAddResult = store.InsertOffer(gasData, out gasorderResult);
                     *  Logger.AddMsg("Oxygen Add To Store Result: " + storeAddResult.ToString(), true);
                     *
                     * }
                     */

                    errorLog.Append("   - Add Each Item To The Store Block").AppendLine();
                    foreach (var item in itemsAvailable.Keys)
                    {
                        errorLog.Append("     - Checking Item: " + item.ToString()).AppendLine();
                        if (ItemsWithBadValue.Contains(item) || MinimumValuesMaster.ContainsKey(item) == false)
                        {
                            errorLog.Append("     - Item Has Bad Value According To Economy Helper").AppendLine();
                            Logger.AddMsg(item.ToString() + " has invalid economy value or was not in master reference", true);
                            continue;
                        }


                        double          markup         = 1.2; //TODO: Figure out how reputation affects this
                        int             itemValue      = (int)Math.Floor((double)MinimumValuesMaster[item] * markup);
                        MyStoreItemData orderData      = new MyStoreItemData(item, itemsAvailable[item], itemValue, OnSaleComplete, null);
                        long            orderResult    = 0;
                        var             storeAddResult = store.InsertOffer(orderData, out orderResult);
                        errorLog.Append("     - Added Item To Store With Result: " + storeAddResult.ToString()).AppendLine();
                        Logger.AddMsg(item.ToString() + " Add To Store Result: " + storeAddResult.ToString(), true);
                    }

                    /*
                     * if(dummyPlayer != null) {
                     *
                     *  errorLog.Append("   - Changing Owner Back To Original NPC Identity").AppendLine();
                     *  storecube.ChangeOwner(originalOwner, MyOwnershipShareModeEnum.Faction);
                     *  long newPlayerBalance = 0;
                     *  dummyPlayer.TryGetBalanceInfo(out newPlayerBalance);
                     *  var balanceDifference = newPlayerBalance - originalPlayerBalance;
                     *  dummyPlayer.RequestChangeBalance(-balanceDifference);
                     *
                     * }
                     */

                    //Populate Store With Orders

                    if (spawnGroup != null)
                    {
                        if (spawnGroup.ContainerTypesForStoreOrders.Count > 0)
                        {
                            var containerString = spawnGroup.ContainerTypesForStoreOrders[SpawnResources.rnd.Next(0, spawnGroup.ContainerTypesForStoreOrders.Count)];
                            var containerDef    = MyDefinitionManager.Static.GetContainerTypeDefinition(containerString);

                            if (containerDef != null)
                            {
                                foreach (var item in containerDef.Items)
                                {
                                    if (ItemsWithBadValue.Contains(item.DefinitionId) || MinimumValuesMaster.ContainsKey(item.DefinitionId) == false)
                                    {
                                        continue;
                                    }

                                    double          markup         = 1.2;
                                    int             itemCount      = SpawnResources.rnd.Next((int)item.AmountMin, (int)item.AmountMax);
                                    int             itemValue      = (int)Math.Floor((double)MinimumValuesMaster[item.DefinitionId] * markup);
                                    MyStoreItemData orderData      = new MyStoreItemData(item.DefinitionId, itemCount, itemValue, null, null);
                                    long            orderResult    = 0;
                                    var             storeAddResult = store.InsertOrder(orderData, out orderResult);

                                    if (storeAddResult == Sandbox.ModAPI.Ingame.MyStoreInsertResults.Success && SpawnResources.IsIdentityNPC(store.OwnerId) == true)
                                    {
                                        MyAPIGateway.Players.RequestChangeBalance(store.OwnerId, itemCount * itemValue);
                                    }

                                    errorLog.Append("     - Added Item To Store With Result: " + storeAddResult.ToString()).AppendLine();
                                    Logger.AddMsg(item.ToString() + " Add To Store Result: " + storeAddResult.ToString(), true);
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {
                Logger.AddMsg("Init Store Blocks for NPC Grid Failed. Please Provide The Log File To The Modular Encounters Spawner Mod Author:");
                Logger.AddMsg(errorLog.ToString());
            }
        }
        private static List <IMyEntity> DisableTurretsWithoutTargets(IMyEntity entity)
        {
            m_scanCache.Clear();

            List <IMyEntity> turretList = new List <IMyEntity>();

            if (!(entity is IMyCubeGrid))
            {
                return(turretList);
            }

            IMyCubeGrid         grid   = (IMyCubeGrid)entity;
            List <IMySlimBlock> blocks = new List <IMySlimBlock>();

            grid.GetBlocks(blocks);
            //bool disable = false;
            bool ignore = false;

            foreach (IMySlimBlock block in blocks)
            {
                if (block.FatBlock == null)
                {
                    continue;
                }

                if (block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_InteriorTurret) ||
                    block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_LargeGatlingTurret) ||
                    block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_LargeMissileTurret))
                {
                    IMyEntity turret = block.FatBlock;
                    bool      state  = FunctionalBlockEntity.GetState(turret);

                    if (state)
                    {
                        m_turretsEnabled++;
                    }
                    else
                    {
                        m_turretsDisabled++;
                    }

                    if (state)                    // && !ignore)
                    {
                        //Console.WriteLine("Finding targets on: {0}", entity.DisplayName);
                        // No target, so we're not going to enable anything on this grid
                        //if (!disable && DoesGridHaveTarget(grid, block))
                        if (DoesGridHaveTarget(grid, block))
                        {
                            // We'll ignore state and only collect for statistics
                            ignore = true;
                            continue;
                        }

//						Console.WriteLine("Disabling");
                        //disable = true;

                        if (PluginSettings.Instance.DynamicTurretAllowExemption)
                        {
                            IMyFunctionalBlock functional = (IMyFunctionalBlock)turret;
                            if (functional.CustomName.ToLower().Contains("[manualcontrol]"))
                            {
                                continue;
                            }
                        }

                        m_turretsToggled++;
                        turretList.Add(turret);
                    }
                }
            }

            return(turretList);
        }
Esempio n. 9
0
        private void TryUpdateBlockLimits()
        {
            ShowMessageInGame("dbg", "TryUpdateBlockLimits start");
            try
            {
                if (m_mycubegrid == null)
                {
                    return;
                }
                var entity = m_mycubegrid;
                if (!(entity is IMyCubeGrid))
                {
                    return;
                }

                if (entity.Physics == null || entity.MarkedForClose || entity.Closed)
                {
                    return;
                }

                if (!entity.InScene)
                {
                    return;
                }
                bool temphasoverhead = false;
                //  ShowMessageInGame("dbg", "TryUpdateBlockLimits point1");
                if (addonschanged)
                {
                    UpdateAddons();
                }
                CheckAndReplaceOwner();
                //Dictionary<AllLimits.Addons, int> copy_installedAddons = new Dictionary<AllLimits.Addons, int>(MyLimitsSettings.installedAddons);
                Dictionary <AllLimits.BlockLimitItem, int> blocks = new Dictionary <AllLimits.BlockLimitItem, int>();
                IMyCubeGrid         grid            = (IMyCubeGrid)entity;
                List <IMySlimBlock> blockstoProcess = new List <IMySlimBlock>();
                grid.GetBlocks(blockstoProcess, x => x.FatBlock is IMyTerminalBlock);
                foreach (IMySlimBlock myTerminalBlock in blockstoProcess)
                {
                    if (myTerminalBlock?.FatBlock == null)
                    {
                        continue;
                    }

                    IMyTerminalBlock block = (IMyTerminalBlock)myTerminalBlock.FatBlock;
                    foreach (AllLimits.BlockLimitItem item in MyLimitsSettings.Big_List_of_Limits)
                    {
                        if (item.Mode == AllLimits.BlockLimitItem.EnforcementMode.Off)
                        {
                            continue;
                        }

                        if (item.Mode == AllLimits.BlockLimitItem.EnforcementMode.BlockTypeId && string.IsNullOrEmpty(item.BlockTypeId))
                        {
                            ShowMessageInGame("dbg", "Block Enforcement item for \"{0}\" is set to mode BlockTypeId but does not have BlockTypeId set.");
                            continue;
                        }
                        if (item.Mode == AllLimits.BlockLimitItem.EnforcementMode.BlockSubtypeId && string.IsNullOrEmpty(item.BlockSubtypeId))
                        {
                            ShowMessageInGame("dbg", "Block Enforcement item for \"{0}\" is set to mode BlockSubtypeId but does not have BlockSubtypeId set.");
                            continue;
                        }

                        if (item.Mode == AllLimits.BlockLimitItem.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 == AllLimits.BlockLimitItem.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);
                            }
                        }
                    }
                    foreach (AllLimits.BlockLimitItem item in MyLimitsSettings.Big_List_of_Limits)
                    {
                        if (item.Mode == AllLimits.BlockLimitItem.EnforcementMode.Off)
                        {
                            continue;
                        }

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

                        if (blocks[item] > item.MaxPerGrid)
                        {
                            // if (!MyAPIGateway.Session.HasCreativeRights)
                            // {

                            if (MyAPIGateway.Session.Config.Language == MyLanguagesEnum.Russian)
                            {
                                ShowMessageInGame("ShipCore:", string.Format("Вы превысили максимальное количество блоков {0} в корабле '{1}'.  При следующей чистке удаляться {2} блока!", item.BlockSubtypeId, grid.DisplayName, blocks[item] - item.MaxPerGrid));
                            }
                            ShowMessageInGame("ShipCore:", string.Format("You have exceeded the max block count of {0} on the ship '{1}'. Next cleanup will delete {2} block(s) to enforce this block limit.", item.BlockSubtypeId, grid.DisplayName, blocks[item] - item.MaxPerGrid));
                            temphasoverhead = true;
                            //  }
                        }
                    }
                }
                // ShowMessageInGame("dbg", "hasoverhead" + hasoverhead + "temphasoverhead" + temphasoverhead);
                hasoverhead = temphasoverhead;

                if (!(m_block.Closed || m_block.MarkedForClose))
                {
                    SetBlockState();
                    _processing2 = false;
                }
                else
                {
                    _processing2 = false;
                    //ShowMessageInGame("dbg", "hasoverhead null found!");
                }
                ShowMessageInGame("dbg", "TryUpdateBlockLimits end");
            }
            catch
            {
                // ShowMessageInGame("dbg", "TryUpdateBlockLimits catch!");
                _processing2 = false;
            }
            finally
            {
                _processing2 = 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(m_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();
                    Sandbox.ModAPI.Ingame.IMyBeacon beacon = (Sandbox.ModAPI.Ingame.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();
                    Sandbox.ModAPI.Ingame.IMyRadioAntenna antenna = (Sandbox.ModAPI.Ingame.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();
                    Sandbox.ModAPI.Ingame.IMyMedicalRoom medical = (Sandbox.ModAPI.Ingame.IMyMedicalRoom)cubeBlock;
                    if (!medical.Enabled)
                        continue;

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

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

                    if (PluginSettings.Instance.DynamicConcealIncludeMedBays)
                    {
                        lock (m_online)
                        {
                            foreach (ulong connectedPlayer in m_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) == Sandbox.Common.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;

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

            return false;
        }
Esempio n. 11
0
        public void HandleChatCommand(ulong steamId, string command)
        {
            MyPromoteLevel level = MyAPIGateway.Session.GetUserPromoteLevel(steamId);

            Logging.Instance.WriteLine($"Got chat command from {steamId} : {command}");

            if (command.Equals("!join", StringComparison.CurrentCultureIgnoreCase))
            {
                if (!Settings.Instance.Hub)
                {
                    Communication.SendServerChat(steamId, "Join commands are not valid in battle servers!");
                    return;
                }
                Communication.SendServerChat(steamId, $"There are {Servers.Count} battle servers. Please select the one you want by sending '!join [number]'");
                List <int> availableServers = (from server in Servers.Values where server.CanJoin select server.Index + 1).ToList();

                if (availableServers.Count < Servers.Count)
                {
                    Communication.SendServerChat(steamId, $"These servers are ready for matches: {string.Join(", ", availableServers)}");
                }
                else
                {
                    Communication.SendServerChat(steamId, $"All {Servers.Count} servers are available for new matches!");
                }

                return;
            }

            if (command.StartsWith("!join", StringComparison.CurrentCultureIgnoreCase))
            {
                int ind = command.IndexOf(" ");
                if (ind == -1)
                {
                    Communication.SendServerChat(steamId, "Couldn't parse your server selection!");
                    return;
                }

                string     numtex = command.Substring(ind);
                ServerItem server;
                int        num;
                if (!int.TryParse(numtex, out num))
                {
                    Communication.SendServerChat(steamId, "Couldn't parse your server selection!");
                    return;
                }

                if (!Servers.TryGetValue(num - 1, out server))
                {
                    Communication.SendServerChat(steamId, $"Couldn't find server {num}");
                    return;
                }

                if (!server.CanJoin)
                {
                    Communication.SendServerChat(steamId, "Sorry, this server is not open to new members. Please try another.");
                    return;
                }

                IMyPlayer player = Utilities.GetPlayerBySteamId(steamId);

                var         block = player?.Controller?.ControlledEntity?.Entity as IMyCubeBlock;
                IMyCubeGrid grid  = block?.CubeGrid;
                if (grid == null)
                {
                    Communication.SendServerChat(steamId, "Can't find your ship. Make sure you're seated in the ship you want to take with you.");
                    return;
                }

                var blocks = new List <IMySlimBlock>();
                grid.GetBlocks(blocks);

                if (blocks.Count > Settings.Instance.MaxBlockCount)
                {
                    Communication.SendServerChat(steamId, $"Your ship has {blocks.Count} blocks. The limit for this server is {Settings.Instance.MaxBlockCount}");
                    return;
                }

                byte[] payload = Utilities.SerializeAndSign(grid, Utilities.GetPlayerBySteamId(steamId), block.Position);
                Communication.SegmentAndSend(Communication.MessageType.ClientGridPart, payload, MyAPIGateway.Multiplayer.ServerId, steamId);

                server.Join(steamId);

                var timer = new Timer(10000);
                timer.AutoReset = false;
                timer.Elapsed  += (a, b) => MyAPIGateway.Utilities.InvokeOnGameThread(() => grid.Close());
                timer.Start();
                return;
            }

            if (command.Equals("!hub", StringComparison.CurrentCultureIgnoreCase))
            {
                if (Settings.Instance.Hub)
                {
                    Communication.SendServerChat(steamId, "You're already in the hub!");
                    return;
                }
                else if (Settings.Instance.ReturnShip)
                {
                    var         player = Utilities.GetPlayerBySteamId(steamId);
                    var         block  = player?.Controller?.ControlledEntity?.Entity as IMyCubeBlock;
                    IMyCubeGrid grid   = block?.CubeGrid;

                    if (grid == null)
                    {
                        PlayerGrids.TryGetValue(steamId, out grid);
                    }

                    if (grid != null)
                    {
                        byte[] payload = Utilities.SerializeAndSign(grid, player, block?.Position ?? Vector3I.Zero);
                        Communication.SegmentAndSend(Communication.MessageType.ClientGridPart, payload, MyAPIGateway.Multiplayer.ServerId, steamId);
                    }
                }
                Communication.RedirectClient(steamId, Settings.Instance.HubIP);
                return;
            }

            if (level >= MyPromoteLevel.Moderator)
            {
                if (command.StartsWith("!spectate", StringComparison.CurrentCultureIgnoreCase))
                {
                    int ind = command.IndexOf(" ");
                    if (ind == -1)
                    {
                        Communication.SendServerChat(steamId, "Couldn't parse your server selection!");
                        return;
                    }

                    string     numtex = command.Substring(ind);
                    ServerItem server;
                    int        num;
                    if (!int.TryParse(numtex, out num))
                    {
                        Communication.SendServerChat(steamId, "Couldn't parse your server selection!");
                        return;
                    }

                    if (!Servers.TryGetValue(num - 1, out server))
                    {
                        Communication.SendServerChat(steamId, $"Couldn't find server {num}");
                        return;
                    }

                    MyAPIGateway.Utilities.DeleteFileInLocalStorage("Ship.bin", typeof(LinkModCore));
                    Communication.RedirectClient(steamId, server.IP);
                    return;
                }
            }

            if (level >= MyPromoteLevel.Admin)
            {
                if (command.Equals("!endjoin", StringComparison.CurrentCultureIgnoreCase))
                {
                    _lobbyTimer.Stop();
                    _lobbyRunning = false;
                    _matchRunning = true;
                    Communication.SendNotification(0, "MATCH START!", MyFontEnum.Green);
                    Logging.Instance.WriteLine("Starting match");
                    _matchTimer.Start();
                    return;
                }

                if (command.Equals("!endmatch", StringComparison.CurrentCultureIgnoreCase))
                {
                    _matchTimer.Stop();
                    _matchRunning = false;
                    Communication.SendNotification(0, "MATCH OVER!", MyFontEnum.Red, 10000);
                    Logging.Instance.WriteLine("Ending match");
                    Utilities.ScrubServer();
                    return;
                }

                if (command.Equals("!reload", StringComparison.CurrentCultureIgnoreCase))
                {
                    Settings.LoadSettings();
                    Communication.SendServerChat(steamId, "Okay.");
                    return;
                }

                if (command.Equals("!save", StringComparison.CurrentCultureIgnoreCase))
                {
                    Settings.SaveSettings();
                    Communication.SendServerChat(steamId, "Okay.");
                    return;
                }

                if (command.StartsWith("!reset", StringComparison.CurrentCultureIgnoreCase))
                {
                    int ind = command.IndexOf(" ");
                    if (ind == -1)
                    {
                        foreach (var s in Servers.Values)
                        {
                            s.Reset();
                        }
                        Communication.SendServerChat(steamId, "Reset all servers");
                        return;
                    }

                    string     numtex = command.Substring(ind);
                    ServerItem server;
                    int        num;
                    if (!int.TryParse(numtex, out num))
                    {
                        Communication.SendServerChat(steamId, "Couldn't parse your server selection!");
                        return;
                    }

                    if (Servers.TryGetValue(num - 1, out server))
                    {
                        server.Reset();
                        Communication.SendServerChat(steamId, $"Reset server {num}");
                    }
                }
            }

            if (command.Equals("!help", StringComparison.CurrentCultureIgnoreCase))
            {
                if (level >= MyPromoteLevel.Admin)
                {
                    Communication.SendServerChat(steamId, ADMIN_HELP);
                }
                else
                {
                    if (level >= MyPromoteLevel.Moderator)
                    {
                        Communication.SendServerChat(steamId, MODERATOR_HELP);
                    }
                    else
                    {
                        Communication.SendServerChat(steamId, HELP_TEXT);
                    }
                }
            }
        }
        private static void GetAttachedGrids(IMyCubeGrid cubeGrid, ref List <IMyCubeGrid> results)
        {
            if (cubeGrid == null)
            {
                return;
            }

            var blocks = new List <IMySlimBlock>();

            cubeGrid.GetBlocks(blocks, b => b != null && b.FatBlock != null && !b.FatBlock.BlockDefinition.TypeId.IsNull);

            foreach (var block in blocks)
            {
                //MyAPIGateway.Utilities.ShowMessage("Block", string.Format("{0}", block.FatBlock.BlockDefinition.TypeId));

                if (block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_MotorAdvancedStator) ||
                    block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_MotorStator) ||
                    block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_MotorSuspension) ||
                    block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_MotorBase))
                {
                    // The MotorStator which inherits from MotorBase.
                    IMyMotorBase motorBase = block.FatBlock as IMyMotorBase;
                    if (motorBase == null || motorBase.Top == null)
                    {
                        continue;
                    }

                    IMyCubeGrid entityParent = motorBase.TopGrid;
                    if (entityParent == null)
                    {
                        continue;
                    }
                    if (!results.Any(e => e.EntityId == entityParent.EntityId))
                    {
                        results.Add(entityParent);
                        GetAttachedGrids(entityParent, ref results);
                    }
                }
                else if (block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_MotorAdvancedRotor) ||
                         block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_MotorRotor) ||
                         block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_RealWheel) ||
                         block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_Wheel))
                {
                    // The Rotor Part.
                    IMyMotorRotor motorRotor = block.FatBlock as IMyMotorRotor;
                    if (motorRotor == null || motorRotor.Base == null)
                    {
                        continue;
                    }

                    IMyCubeGrid entityParent = motorRotor.Base.CubeGrid;
                    if (!results.Any(e => e.EntityId == entityParent.EntityId))
                    {
                        results.Add(entityParent);
                        GetAttachedGrids(entityParent, ref results);
                    }
                }
                else if (block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_PistonTop))
                {
                    // The Piston Top.
                    IMyPistonTop pistonTop = block.FatBlock as IMyPistonTop;
                    if (pistonTop == null || pistonTop.Piston == null)
                    {
                        continue;
                    }

                    IMyCubeGrid entityParent = pistonTop.Piston.CubeGrid;
                    if (!results.Any(e => e.EntityId == entityParent.EntityId))
                    {
                        results.Add(entityParent);
                        GetAttachedGrids(entityParent, ref results);
                    }
                }
                else if (block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_ExtendedPistonBase) ||
                         block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_PistonBase))
                {
                    IMyPistonBase pistonBase = block.FatBlock as IMyPistonBase;
                    if (pistonBase == null || pistonBase.Top == null)
                    {
                        continue;
                    }

                    IMyCubeGrid entityParent = pistonBase.TopGrid;
                    if (entityParent == null)
                    {
                        continue;
                    }
                    if (!results.Any(e => e.EntityId == entityParent.EntityId))
                    {
                        results.Add(entityParent);
                        GetAttachedGrids(entityParent, ref results);
                    }
                }
            }
        }
Esempio n. 13
0
        // /admin movefrom x y z x y z radius
        public override bool HandleCommand(ulong userId, string[] words)
        {
            HashSet <IMyEntity> entities = new HashSet <IMyEntity>();

            Wrapper.GameAction(() =>
            {
                MyAPIGateway.Entities.GetEntities(entities, x => x is IMyCubeGrid);
            });

            HashSet <long> playerOwners = new HashSet <long>();

            foreach (IMyEntity entity in entities)
            {
                IMyCubeGrid grid = (IMyCubeGrid)entity;
                MyObjectBuilder_CubeGrid gridBlock = (MyObjectBuilder_CubeGrid)grid.GetObjectBuilder();

                foreach (MyObjectBuilder_CubeBlock block in gridBlock.CubeBlocks)
                {
                    if (block.Owner == 0)
                    {
                        continue;
                    }

                    if (!playerOwners.Contains(block.Owner))
                    {
                        playerOwners.Add(block.Owner);
                    }
                }
            }

            Communication.SendPrivateInformation(userId, string.Format("Total block owners: {0}", playerOwners.Count));

            int count = 0;

            foreach (long owner in playerOwners)
            {
                ulong steamId = PlayerMap.Instance.GetPlayerItemFromPlayerId(owner).SteamId;
                if (steamId == 0)
                {
                    count++;
                }
            }

            Communication.SendPrivateInformation(userId, string.Format("Total owners without a steam Id: {0}", count));
            HashSet <long> badPlayers = new HashSet <long>();
            HashSet <long> noLogin    = new HashSet <long>();

            foreach (long owner in playerOwners)
            {
                MyObjectBuilder_Checkpoint.PlayerItem item = PlayerMap.Instance.GetPlayerItemFromPlayerId(owner);
                if (item.SteamId == 0)
                {
                    continue;
                }

                if (!Players.Instance.PlayerLogins.ContainsKey(item.SteamId))
                {
                    Communication.SendPrivateInformation(userId, string.Format("No login information: {0}", item.Name));
                    noLogin.Add(owner);
                    continue;
                }

                PlayerItem playerItem = Players.Instance.PlayerLogins[item.SteamId];
                if (DateTime.Now - playerItem.LastLogin > TimeSpan.FromDays(20))
                {
                    Communication.SendPrivateInformation(userId, string.Format("Player hasn't logged in 20 days: {0}", item.Name));
                    badPlayers.Add(owner);
                }
            }

            Communication.SendPrivateInformation(userId, string.Format("Users not logged in the last 20 days: {0}", badPlayers.Count));
            Communication.SendPrivateInformation(userId, string.Format("Users with no login information: {0}", noLogin.Count));

            /*
             * count = 0;
             * List<CubeGridEntity> grids = SectorObjectManager.Instance.GetTypedInternalData<CubeGridEntity>();
             * foreach(CubeGridEntity grid in grids)
             * {
             *      Thread.Sleep(100);
             *      foreach (CubeBlockEntity block in grid.CubeBlocks)
             *      {
             *              MyObjectBuilder_CubeBlock blockBuilder = (MyObjectBuilder_CubeBlock)block.Export();
             *              if (badPlayers.Contains(blockBuilder.Owner) || noLogin.Contains(blockBuilder.Owner))
             *              {
             *                      //grid.DeleteCubeBlock(block);
             *                      block.Dispose();
             *                      count++;
             *              }
             *      }
             * }
             */

            Wrapper.GameAction(() =>
            {
                MyAPIGateway.Entities.GetEntities(entities, x => x is IMyCubeGrid);

                foreach (IMyEntity entity in entities)
                {
                    IMyCubeGrid grid           = (IMyCubeGrid)entity;
                    List <IMySlimBlock> blocks = new List <IMySlimBlock>();
                    grid.GetBlocks(blocks, x => x.FatBlock != null && x.FatBlock.OwnerId != 0);
                    foreach (IMySlimBlock block in blocks)
                    {
                        IMyCubeBlock cubeBlock = (IMyCubeBlock)block.FatBlock;
                        if (badPlayers.Contains(cubeBlock.OwnerId) || noLogin.Contains(cubeBlock.OwnerId))
                        {
                            grid.RazeBlock(cubeBlock.Min);
                            count++;
                        }
                    }
                }
            });

            Communication.SendPrivateInformation(userId, string.Format("Blocks disposed: {0}", count));

            return(true);
        }
Esempio n. 14
0
        public override bool HandleCommand(ulong userId, string command)
        {
            string[] words         = command.Split(' ');
            bool     showConcealed = true;

            if (words.Length > 0 && words[0].ToLower() == "revealed")
            {
                showConcealed = false;
            }

            if (showConcealed)
            {
                HashSet <IMyEntity> entities = new HashSet <IMyEntity>();
                Wrapper.GameAction(() =>
                {
                    MyAPIGateway.Entities.GetEntities(entities);
                });

                Communication.SendPrivateInformation(userId, "==== Concealed Entities ===");
                int count = 0;
                foreach (IMyEntity entity in entities)
                {
                    if (!(entity is IMyCubeGrid))
                    {
                        continue;
                    }

                    if (entity.InScene)
                    {
                        continue;
                    }

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

                    if (ownerName == "")
                    {
                        ownerName = "No one";
                    }

                    Communication.SendPrivateInformation(userId, string.Format("Id: {0} Display: {1} OwnerId: {2} OwnerName: {3} Position: {4}", entity.EntityId, entity.DisplayName, ownerId, ownerName, General.Vector3DToString(entity.GetPosition())));
                    count++;
                }

                Communication.SendPrivateInformation(userId, string.Format("Total concealed entities: {0}", count));
            }
            else
            {
                HashSet <IMyEntity> entities = new HashSet <IMyEntity>();
                Wrapper.GameAction(() =>
                {
                    MyAPIGateway.Entities.GetEntities(entities);
                });

                Communication.SendPrivateInformation(userId, "==== Revealed Entities ===");
                Communication.SendPrivateInformation(userId, "==== Unconnected Entities ===");
                HashSet <IMyEntity> entitiesFound = new HashSet <IMyEntity>();
                CubeGrids.GetGridsUnconnected(entitiesFound, entities);
                int count = 0;
                List <IMySlimBlock> slimBlocks = new List <IMySlimBlock>();
                foreach (IMyEntity entity in entitiesFound)
                {
                    if (!(entity is IMyCubeGrid))
                    {
                        continue;
                    }

                    if (!entity.InScene)
                    {
                        continue;
                    }

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

                    if (ownerName == "")
                    {
                        ownerName = "No one";
                    }

                    grid.GetBlocks(slimBlocks, null);
                    Communication.SendPrivateInformation(userId, string.Format("Id: {0} Display: {1} OwnerId: {2} OwnerName: {3} Position: {4} BlockCount: {5}", entity.EntityId, entity.DisplayName, ownerId, ownerName, General.Vector3DToString(entity.GetPosition()), slimBlocks.Count));
                    slimBlocks.Clear();
                    count++;
                }

                Communication.SendPrivateInformation(userId, string.Format("Total unconnected revealed entities: {0}", count));

                Communication.SendPrivateInformation(userId, "==== Connected Entities ===");
                HashSet <IMyEntity> connectedFound = new HashSet <IMyEntity>();
                CubeGrids.GetConnectedGrids(connectedFound);
                Console.WriteLine("Here: {0} : {1} {2}", connectedFound.Intersect(entitiesFound).Count(), entitiesFound.Count, connectedFound.Count);
                count = 0;
                slimBlocks.Clear();
                foreach (IMyEntity entity in connectedFound)
                {
                    if (!(entity is IMyCubeGrid))
                    {
                        continue;
                    }

                    if (entitiesFound.Contains(entity))
                    {
                        continue;
                    }

                    if (!entity.InScene)
                    {
                        continue;
                    }

                    if (CubeGrids.GetRecursiveGridList((IMyCubeGrid)entity).Count < 2)
                    {
                        continue;
                    }

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

                    if (ownerName == "")
                    {
                        ownerName = "No one";
                    }

                    grid.GetBlocks(slimBlocks, null);
                    Communication.SendPrivateInformation(userId, string.Format("Id: {0} Display: {1} OwnerId: {2} OwnerName: {3} Position: {4} BlockCount: {5} Connections: {6}", entity.EntityId, entity.DisplayName, ownerId, ownerName, General.Vector3DToString(entity.GetPosition()), slimBlocks.Count, CubeGrids.GetRecursiveGridList(grid).Count));
                    //Communication.SendPrivateInformation(userId, string.Format("Id: {0} Display: {1} OwnerId: {2} OwnerName: {3} Position: {4} BlockCount: {5} Connections: {6}", entity.EntityId, entity.DisplayName, ownerId, ownerName, General.Vector3DToString(entity.GetPosition()), slimBlocks.Count));
                    slimBlocks.Clear();
                    count++;
                }

                Communication.SendPrivateInformation(userId, string.Format("Total connected revealed entities: {0}", count));
            }

            return(true);
        }
Esempio n. 15
0
        private void _cubeGrid_OnBlockOwnershipChanged(IMyCubeGrid cubeGrid)
        {
            // only execute on server instance
            if (ChatCommandLogic.Instance != null && ChatCommandLogic.Instance.ServerCfg == null)
            {
                return;
            }

            if (_firstOwnershipChange)
            {
                _firstOwnershipChange = false;
                _cachedOwners         = new List <long>(cubeGrid.GetAllSmallOwners());
                return;
            }

            var allSmallOwners = cubeGrid.GetAllSmallOwners();

            if (_cachedOwners == allSmallOwners)
            {
                return;
            }

            // if the grid wasn't owned or a owner was removed, we dont need to do anything but update the cached owners
            if (_cachedOwners.Count == 0 || _cachedOwners.Count > allSmallOwners.Count)
            {
                _cachedOwners = new List <long>(allSmallOwners);
                return;
            }

            var newOwners = allSmallOwners.Except(_cachedOwners).ToList();

            if (newOwners.Count == 0)
            {
                return;
            }

            if (!ProtectionHandler.IsProtected(cubeGrid))
            {
                _cachedOwners = new List <long>(allSmallOwners);
                return;
            }

            Dictionary <long, int> blocksPerOwner = new Dictionary <long, int>();

            foreach (IMyCubeGrid attachedCubeGrid in cubeGrid.GetAttachedGrids(AttachedGrids.Static))
            {
                List <IMySlimBlock> blocks = new List <IMySlimBlock>();
                attachedCubeGrid.GetBlocks(blocks, b => b.FatBlock != null);


                foreach (IMySlimBlock block in blocks)
                {
                    long ownerId = block.FatBlock.OwnerId;

                    // we dont want the new owners, the small owners or the 'nobody' (0)
                    if (ownerId == 0 || !attachedCubeGrid.BigOwners.Contains(ownerId) || newOwners.Contains(ownerId))
                    {
                        continue;
                    }

                    if (!blocksPerOwner.ContainsKey(ownerId))
                    {
                        blocksPerOwner.Add(ownerId, 1);
                    }
                    else
                    {
                        blocksPerOwner[ownerId]++;
                    }
                }
            }

            var sortedBpo = new List <KeyValuePair <long, int> >(blocksPerOwner.OrderBy(pair => pair.Value));

            // if we cannot identify an owner we allow the change
            if (sortedBpo.Count == 0)
            {
                _cachedOwners = new List <long>(allSmallOwners);
                return;
            }

            var bigOwner = sortedBpo[0].Key;

            List <IMySlimBlock> ownershipChangedBlocks = new List <IMySlimBlock>();

            cubeGrid.GetBlocks(ownershipChangedBlocks, b => b.FatBlock != null && newOwners.Contains(b.FatBlock.OwnerId));
            foreach (IMySlimBlock slimBlock in ownershipChangedBlocks)
            {
                var block = (Sandbox.Game.Entities.MyCubeBlock)slimBlock.FatBlock; // TODO check if the block was created/built just moments ago, do not change owner otherwise
                block.ChangeOwner(bigOwner, MyOwnershipShareModeEnum.None);
                ConnectionHelper.SendMessageToAllPlayers(new MessageSyncBlockOwner()
                {
                    OwnerId = bigOwner, EntityId = block.EntityId
                });
                // no need to update the cached owners as we don't want them to change
            }

            // TODO maybe allow the faction to build...
        }
Esempio n. 16
0
        public void HandleChatCommand(ulong steamId, string command)
        {
            MyPromoteLevel level = MyAPIGateway.Session.GetUserPromoteLevel(steamId);

            ServerJumpClass.Instance.SomeLog($"Got chat command from {steamId} : {command}");

            if (command.Equals("!join", StringComparison.CurrentCultureIgnoreCase))
            {
                InitJump(steamId);

                return;
            }

            if (command.StartsWith("!join", StringComparison.CurrentCultureIgnoreCase))
            {
                int ind = command.IndexOf(" ");
                if (ind == -1)
                {
                    Communication.SendServerChat(steamId, "Couldn't parse your server selection!");
                    return;
                }

                string     numtex = command.Substring(ind);
                ServerItem server;
                int        num;
                if (!int.TryParse(numtex, out num))
                {
                    Communication.SendServerChat(steamId, "Couldn't parse your server selection!");
                    return;
                }

                if (!Servers.TryGetValue(num - 1, out server))
                {
                    Communication.SendServerChat(steamId, $"Couldn't find server {num}");
                    return;
                }

                if (!server.CanJoin)
                {
                    Communication.SendServerChat(steamId, "Sorry, this server is not open to new members. Please try another.");
                    return;
                }

                IMyPlayer player = Utilities.GetPlayerBySteamId(steamId);

                var         block = player?.Controller?.ControlledEntity?.Entity as IMyCubeBlock;
                IMyCubeGrid grid  = block?.CubeGrid;
                if (grid == null)
                {
                    Communication.SendServerChat(steamId, "Can't find your ship. Make sure you're seated in the ship you want to take with you.");
                    return;
                }

                var blocks = new List <IMySlimBlock>();
                grid.GetBlocks(blocks);

                if (blocks.Count > Settings.MaxBlockCount)
                {
                    Communication.SendServerChat(steamId, $"Your ship has {blocks.Count} blocks. The limit for this server is {Settings.MaxBlockCount}");
                    return;
                }

                byte[] payload = Utilities.SerializeAndSign(grid, Utilities.GetPlayerBySteamId(steamId), block.Position);
                Communication.SegmentAndSend(Communication.MessageType.ClientGridPart, payload, MyAPIGateway.Multiplayer.ServerId, steamId);

                server.Join(steamId);

                var timer = new Timer(10000);
                timer.AutoReset = false;
                timer.Elapsed  += (a, b) => MyAPIGateway.Utilities.InvokeOnGameThread(() => grid.Close());
                timer.Start();
                return;
            }

            if (command.Equals("!hub", StringComparison.CurrentCultureIgnoreCase))
            {
                if (Settings.Hub)
                {
                    Communication.SendServerChat(steamId, "You're already in the hub!");
                    return;
                }
                Communication.RedirectClient(steamId, Settings.HubIP);
                return;
            }

            if (level >= MyPromoteLevel.Moderator)
            {
                if (command.StartsWith("!spectate", StringComparison.CurrentCultureIgnoreCase))
                {
                    int ind = command.IndexOf(" ");
                    if (ind == -1)
                    {
                        Communication.SendServerChat(steamId, "Couldn't parse your server selection!");
                        return;
                    }

                    string     numtex = command.Substring(ind);
                    ServerItem server;
                    int        num;
                    if (!int.TryParse(numtex, out num))
                    {
                        Communication.SendServerChat(steamId, "Couldn't parse your server selection!");
                        return;
                    }

                    if (!Servers.TryGetValue(num - 1, out server))
                    {
                        Communication.SendServerChat(steamId, $"Couldn't find server {num}");
                        return;
                    }

                    ServerJumpClass.Instance.SomeLog("DeleteFileInLocalStorage");
                    //  MyAPIGateway.Utilities.DeleteFileInLocalStorage("Ship.bin", typeof(ServerJump));
                    Communication.RedirectClient(steamId, server.IP);
                    return;
                }
            }

            if (level >= MyPromoteLevel.Admin)
            {
                if (command.Equals("!reload", StringComparison.CurrentCultureIgnoreCase))
                {
                    //Settings.LoadSettings();
                    Communication.SendServerChat(steamId, "Okay.");
                    return;
                }

                if (command.Equals("!save", StringComparison.CurrentCultureIgnoreCase))
                {
                    // Settings.SaveSettings();
                    Communication.SendServerChat(steamId, "Okay.");
                    return;
                }

                if (command.StartsWith("!reset", StringComparison.CurrentCultureIgnoreCase))
                {
                    int ind = command.IndexOf(" ");
                    if (ind == -1)
                    {
                        foreach (var s in Servers.Values)
                        {
                            s.Reset();
                        }
                        Communication.SendServerChat(steamId, "Reset all servers");
                        return;
                    }

                    string     numtex = command.Substring(ind);
                    ServerItem server;
                    int        num;
                    if (!int.TryParse(numtex, out num))
                    {
                        Communication.SendServerChat(steamId, "Couldn't parse your server selection!");
                        return;
                    }

                    if (Servers.TryGetValue(num - 1, out server))
                    {
                        server.Reset();
                        Communication.SendServerChat(steamId, $"Reset server {num}");
                    }
                }
            }

            if (command.Equals("!help", StringComparison.CurrentCultureIgnoreCase))
            {
                if (level >= MyPromoteLevel.Admin)
                {
                    Communication.SendServerChat(steamId, ADMIN_HELP);
                }
                else
                {
                    if (level >= MyPromoteLevel.Moderator)
                    {
                        Communication.SendServerChat(steamId, MODERATOR_HELP);
                    }
                    else
                    {
                        Communication.SendServerChat(steamId, HELP_TEXT);
                    }
                }
            }
        }
Esempio n. 17
0
 private static void RecursiveGetAttachedGrids(IMyCubeGrid grid)
 {
     grid.GetBlocks(Blocks, GetAttachedGridsLoopBlocks);
 }
Esempio n. 18
0
        private static void GetAttachedGrids(IMyCubeGrid cubeGrid, ref List <IMyCubeGrid> results, AttachedGrids type)
        {
            if (cubeGrid == null)
            {
                return;
            }

            var blocks = new List <IMySlimBlock>();

            cubeGrid.GetBlocks(blocks, b => b != null && b.FatBlock != null && !b.FatBlock.BlockDefinition.TypeId.IsNull);

            foreach (var block in blocks)
            {
                //MyAPIGateway.Utilities.ShowMessage("Block", string.Format("{0}", block.FatBlock.BlockDefinition.TypeId));

                if (block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_MotorAdvancedStator) ||
                    block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_MotorStator) ||
                    block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_MotorSuspension) ||
                    block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_MotorBase))
                {
                    // The MotorStator which inherits from MotorBase.
                    IMyMotorBase motorBase = block.FatBlock as IMyMotorBase;
                    if (motorBase == null || motorBase.Top == null)
                    {
                        continue;
                    }

                    IMyCubeGrid entityParent = motorBase.TopGrid;
                    if (entityParent == null)
                    {
                        continue;
                    }
                    if (!results.Any(e => e.EntityId == entityParent.EntityId))
                    {
                        results.Add(entityParent);
                        GetAttachedGrids(entityParent, ref results, type);
                    }
                }
                else if (block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_MotorAdvancedRotor) ||
                         block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_MotorRotor) ||
                         block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_RealWheel) ||
                         block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_Wheel))
                {
                    // The Rotor Part.
                    IMyMotorRotor motorRotor   = block.FatBlock as IMyMotorRotor;
                    IMyCubeGrid   entityParent = null;
                    if (motorRotor == null || motorRotor.Base == null)
                    {
                        // Wheels appear to not properly populate the Stator property.
                        IMyCubeBlock altBlock = Support.FindRotorBase(motorRotor.EntityId);
                        if (altBlock == null)
                        {
                            continue;
                        }

                        entityParent = altBlock.CubeGrid;
                    }
                    else
                    {
                        entityParent = motorRotor.Base.CubeGrid;
                    }
                    if (!results.Any(e => e.EntityId == entityParent.EntityId))
                    {
                        results.Add(entityParent);
                        GetAttachedGrids(entityParent, ref results, type);
                    }
                }
                else if (block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_PistonTop))
                {
                    // The Piston Top.
                    IMyPistonTop pistonTop = block.FatBlock as IMyPistonTop;
                    if (pistonTop == null || pistonTop.Piston == null)
                    {
                        continue;
                    }

                    IMyCubeGrid entityParent = pistonTop.Piston.CubeGrid;
                    if (!results.Any(e => e.EntityId == entityParent.EntityId))
                    {
                        results.Add(entityParent);
                        GetAttachedGrids(entityParent, ref results, type);
                    }
                }
                else if (block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_ExtendedPistonBase) ||
                         block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_PistonBase))
                {
                    IMyPistonBase pistonBase = block.FatBlock as IMyPistonBase;
                    if (pistonBase == null || pistonBase.Top == null)
                    {
                        continue;
                    }

                    IMyCubeGrid entityParent = pistonBase.TopGrid;
                    if (entityParent == null)
                    {
                        continue;
                    }
                    if (!results.Any(e => e.EntityId == entityParent.EntityId))
                    {
                        results.Add(entityParent);
                        GetAttachedGrids(entityParent, ref results, type);
                    }
                }
                else if (block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_ShipConnector) && type == AttachedGrids.All)
                {
                    var connector = (IMyShipConnector)block.FatBlock;

                    if (connector.Status != Sandbox.ModAPI.Ingame.MyShipConnectorStatus.Connected || connector.OtherConnector == null)
                    {
                        continue;
                    }

                    var otherGrid = (IMyCubeGrid)connector.OtherConnector.CubeGrid;

                    if (!results.Any(e => e.EntityId == otherGrid.EntityId))
                    {
                        results.Add(otherGrid);
                        GetAttachedGrids(otherGrid, ref results, type);
                    }
                }
                // Commented out temporarily, as it isn't been used, but may not work under 1.126.
                //else if (block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_LandingGear) && type == AttachedGrids.All)
                //{
                //    var landingGear = (IMyLandingGear)block.FatBlock;
                //    if (landingGear.IsLocked == false)
                //        continue;

                //    var entity = landingGear.GetAttachedEntity();
                //    if (entity == null || !(entity is IMyCubeGrid))
                //        continue;

                //    var otherGrid = (IMyCubeGrid)entity;
                //    if (!results.Any(e => e.EntityId == otherGrid.EntityId))
                //    {
                //        results.Add(otherGrid);
                //        GetAttachedGrids(otherGrid, ref results, type);
                //    }
                //}
            }

            // Loop through all other grids, find their Landing gear, and figure out if they are attached to <cubeGrid>.
            var allShips  = new HashSet <IMyEntity>();
            var checkList = results; // cannot use ref paramter in Lambada expression!?!.

            MyAPIGateway.Entities.GetEntities(allShips, e => e is IMyCubeGrid && !checkList.Contains(e));

            //if (type == AttachedGrids.All)
            //{
            //    foreach (IMyCubeGrid ship in allShips)
            //    {
            //        blocks = new List<IMySlimBlock>();
            //        ship.GetBlocks(blocks,
            //            b =>
            //                b != null && b.FatBlock != null && !b.FatBlock.BlockDefinition.TypeId.IsNull &&
            //                b.FatBlock is IMyLandingGear);

            //        foreach (var block in blocks)
            //        {
            //            var landingGear = (IMyLandingGear)block.FatBlock;
            //            if (landingGear.IsLocked == false)
            //                continue;

            //            var entity = landingGear.GetAttachedEntity();

            //            if (entity == null || entity.EntityId != cubeGrid.EntityId)
            //                continue;

            //            if (!results.Any(e => e.EntityId == ship.EntityId))
            //            {
            //                results.Add(ship);
            //                GetAttachedGrids(ship, ref results, type);
            //            }
            //        }
            //    }
            //}
        }
Esempio n. 19
0
        private void OfferPotentialNpcShip(IMyCubeGrid grid)
        {
            //            ModLog.Info("Potentential NPC:" + grid.CustomName);
            NpcGroupSaveData npcGroupSaveData;

            if (restoredNpcGroupData.TryGetValue(grid.EntityId, out npcGroupSaveData))
            {
                //                ModLog.Info(" Potentential NPC: Found in restored NPC Group data:" + npcGroupSaveData.NpcGroupType.ToString() + " Type="+ npcGroupSaveData.LeaderUnitType.ToString());
                if (npcGroupSaveData.NpcGroupType == NpcGroupType.Backup)
                {
                    npcGroups.Add(new BackupGroup(npcGroupSaveData.State, npcGroupSaveData.GroupDestination,
                                                  grid, heatSystem, audioSystem, DateTime.FromBinary(npcGroupSaveData.SpawnTime)));
                }
                else // Must be convoy
                {
                    if (modBuildWhenLastSaved > 30 || !bInitialInit)
                    {
                        restoredConvoys.Add(grid.EntityId,
                                            RegisterConvoy(grid, npcGroupSaveData.State, npcGroupSaveData.LeaderUnitType,
                                                           npcGroupSaveData.GroupDestination, DateTime.FromBinary(npcGroupSaveData.SpawnTime)));
                    }
                    else
                    {
                        // else old drones with scripts that don't work on 1.193.100

                        if (grid.IsControlledByFaction("GCORP")) // see npcgroup.AttemptDespawn()
                        {
                            ModLog.Info("save build#:" + modBuildWhenLastSaved.ToString() + " Initial=" + bInitialInit.ToString());
                            ModLog.Info("Removing dead drone Grid:" + grid.CustomName);
                            bOldRemovals = true;
                            grid.CloseAll();
                        }
                    }
                }
            }
            else
            {
                //                ModLog.Info(" Potentential NPC: NOT in restored NPC Group data:" + grid.CustomName);
                if (modBuildWhenLastSaved > 30 || !bInitialInit)
                {
                    possibleEscorts.Add(grid);
                }
                else
                {
                    // Need better discernment to not delete placed G-Corp grids like G-Corp AP Turret and GCorp Experimental Mech
                    if (grid.IsControlledByFaction("GCORP")) // see npcgroup.AttemptDespawn()
                    {
                        var slimBlocks = new List <IMySlimBlock>();
                        grid.GetBlocks(slimBlocks, b => b.FatBlock is IMyBeacon);
                        foreach (var slim in slimBlocks)
                        {
                            var fb = slim.FatBlock as IMyBeacon;
                            if (fb.CustomName.Contains(EscortName))
                            {
                                ModLog.Info("Removing dead escort drone Grid:" + grid.CustomName);
                                bOldRemovals = true;
                                grid.CloseAll();
                                break;
                            }
                        }
                    }
                }
            }
        }
Esempio n. 20
0
        private int SwitchShipSystemsOnOff(IMyCubeGrid cubeGrid, SwitchSystems control, bool mode)
        {
            int counter = 0;
            var blocks  = new List <IMySlimBlock>();

            cubeGrid.GetBlocks(blocks, f => f.FatBlock != null);

            foreach (var block in blocks)
            {
                // reactors, batteries
                if ((SwitchSystems.Power & control) == SwitchSystems.Power && block.FatBlock is IMyFunctionalBlock &&
                    (block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_Reactor) ||
                     block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_BatteryBlock)))
                {
                    ((IMyFunctionalBlock)block.FatBlock).Enabled = mode; // turn power on/off.
                    counter++;
                }
                // refineries, arc furnaces, assemblers
                if ((SwitchSystems.Production & control) == SwitchSystems.Production && block.FatBlock is IMyFunctionalBlock &&
                    (block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_Refinery) ||
                     block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_Assembler)))
                {
                    ((IMyFunctionalBlock)block.FatBlock).Enabled = mode; // turn power on/off.
                    counter++;
                }
                if ((SwitchSystems.Programmable & control) == SwitchSystems.Programmable && block.FatBlock is IMyFunctionalBlock &&
                    block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_MyProgrammableBlock))
                {
                    ((IMyFunctionalBlock)block.FatBlock).Enabled = mode; // turn power on/off.
                    counter++;
                }
                if ((SwitchSystems.Projectors & control) == SwitchSystems.Projectors && block.FatBlock is IMyFunctionalBlock &&
                    block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_Projector))
                {
                    ((IMyFunctionalBlock)block.FatBlock).Enabled = mode; // turn power on/off.
                    counter++;
                }
                if ((SwitchSystems.Timers & control) == SwitchSystems.Timers && block.FatBlock is IMyFunctionalBlock &&
                    block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_TimerBlock))
                {
                    ((IMyFunctionalBlock)block.FatBlock).Enabled = mode; // turn power on/off.
                    counter++;
                }
                if ((SwitchSystems.Weapons & control) == SwitchSystems.Weapons && block.FatBlock is IMyFunctionalBlock &&
                    (block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_InteriorTurret) ||
                     block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_LargeGatlingTurret) ||
                     block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_LargeMissileTurret) ||
                     block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_SmallGatlingGun) ||
                     block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_SmallMissileLauncher) ||
                     block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_SmallMissileLauncherReload)))
                {
                    ((IMyFunctionalBlock)block.FatBlock).Enabled = mode; // turn power on/off.
                    counter++;
                }
                if ((SwitchSystems.SpotLights & control) == SwitchSystems.SpotLights && block.FatBlock is IMyFunctionalBlock &&
                    block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_ReflectorLight))
                {
                    ((IMyFunctionalBlock)block.FatBlock).Enabled = mode; // turn power on/off.
                    counter++;
                }
                if ((SwitchSystems.Sensors & control) == SwitchSystems.Sensors && block.FatBlock is IMyFunctionalBlock &&
                    block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_SensorBlock))
                {
                    ((IMyFunctionalBlock)block.FatBlock).Enabled = mode; // turn power on/off.
                    counter++;
                }
                if ((SwitchSystems.Medical & control) == SwitchSystems.Medical && block.FatBlock is IMyFunctionalBlock &&
                    (block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_MedicalRoom) ||
                     block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_CryoChamber)))
                {
                    // Switch the power systems that control the grid instead.
                    // I'm unsure if we should go with it like this, which is why it is as yet undocumented.
                    // The idea is, if you have turned the power off to all ships, you can turn the power back on only for grids with Medical and Cryo.
                    SwitchShipSystemsOnOff(cubeGrid, SwitchSystems.Power, mode);
                    counter++;
                }
                if ((SwitchSystems.Mass & control) == SwitchSystems.Mass && block.FatBlock is IMyFunctionalBlock &&
                    (block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_VirtualMass)))
                {
                    ((IMyFunctionalBlock)block.FatBlock).Enabled = mode; // turn power on/off.
                    counter++;
                }
                if ((SwitchSystems.Grinder & control) == SwitchSystems.Grinder && block.FatBlock is IMyFunctionalBlock &&
                    (block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_ShipGrinder)))
                {
                    ((IMyFunctionalBlock)block.FatBlock).Enabled = mode; // turn power on/off.
                    counter++;
                }
                if ((SwitchSystems.Welder & control) == SwitchSystems.Welder && block.FatBlock is IMyFunctionalBlock &&
                    (block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_ShipWelder)))
                {
                    ((IMyFunctionalBlock)block.FatBlock).Enabled = mode; // turn power on/off.
                    counter++;
                }
            }

            return(counter);
        }
Esempio n. 21
0
        private static void SetDestination(IMyCubeGrid grid, Vector3D destination)
        {
            bool bOldNav = false; // true=old way of NAV, false= new way
            // old= set gyro customname to NAV:
            // new = run PB directly with argument

            bool bKeenAutopilot = false; // force using keen autopilot

            if (ConvoySpeed != 10f)
            {
                ModLog.Info("Using test convoy speed of " + ConvoySpeed.ToString());
            }

            var slimBlocks = new List <IMySlimBlock>();

            grid.GetBlocks(slimBlocks, b => b.FatBlock is IMyProgrammableBlock);
            IMyProgrammableBlock NavPB = null;

            foreach (var slim in slimBlocks)
            {
                //                var block = slim.FatBlock as IMyGyro;
                var block = slim.FatBlock as IMyProgrammableBlock;
                //                    ModLog.Info(" Found PB:" + block.CustomName);
                if (block.CustomName.Contains("NAV"))
                {
                    if (block.CustomData.Contains("Assembly not found."))
                    {
                        ModLog.Info("NAV computer not compiling:" + grid.CustomName);
                        continue;
                    }
                    NavPB = block as IMyProgrammableBlock;
                }
            }
            //            ModLog.Info("Set Destinatiion of:" + grid.CustomName);

            // C <comment>
            // S <max speed>
            // D <arrival distance>
            // W x:y:z
            // W <GPS>
            // set destination
            //                block.CustomName = "NAV: C STARTED_DELIVERY; S 80; D 80 ; W " + destination.X + ":" + destination.Y + ":" + destination.Z;
            //                ModLog.Info("Set Waypoint to: " + block.CustomName);
            string sCommand = "S " + ConvoySpeed.ToString("0") + "; D 80; W " + destination.X + ":" + destination.Y + ":" + destination.Z;


            if (!bOldNav && !bKeenAutopilot && NavPB != null)
            { // new way & not override keen autopilot and we found working nav pb
                // V31 Change to calling Nav module directly
                NavPB.Run(sCommand);
                bKeenAutopilot = false;
            }
            else if (!bKeenAutopilot && NavPB != null)
            { // old way and we found working nav PB
                bool bFound = false;

                slimBlocks.Clear();
                grid.GetBlocks(slimBlocks, b => b.FatBlock is IMyGyro);
                foreach (var slim in slimBlocks)
                {
                    var block = slim.FatBlock as IMyGyro;
                    // using STARTED_DELIVERY as a way to find our grids! For autopilot it's a harmless comment.
                    // NOTE: comment is not correct: it's not used as a way to find our grids

                    // C <comment>
                    // S <max speed>
                    // D <arrival distance>
                    // W x:y:z
                    // W <GPS>
                    // set destination

                    block.CustomName = "NAV: " + sCommand;// C STARTED_DELIVERY; S 80; D 80 ; W " + destination.X + ":" + destination.Y + ":" + destination.Z;
                    ModLog.Info("oldnav. Setting Destination for:" + grid.CustomName + " to:" + block.CustomName);
                    //                ModLog.Info("Set Waypoint to: " + block.CustomName);
                    bFound = true;
                    break;
                }
                if (!bFound)
                {
                    ModLog.Info("No Gyro Found! Defaulting to Keen Autopilot. " + grid.CustomName);
                    bKeenAutopilot = true;
                }
            }
            if (bKeenAutopilot || NavPB == null)
            { // force keen autopilot or didn't find working nav pb
                grid.GetBlocks(slimBlocks, b => b.FatBlock is IMyRemoteControl);
                foreach (var slim in slimBlocks)
                {
                    var remoteControl = slim.FatBlock as IMyRemoteControl;
                    remoteControl.ClearWaypoints();
                    remoteControl.AddWaypoint(destination, "Target");
                    remoteControl.SpeedLimit = ConvoySpeed;
                    remoteControl.SetAutoPilotEnabled(true);
                }
                // throw exception if no remote found? (change to Inactive state...)
            }
        }
        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(m_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))
                {
                    Sandbox.ModAPI.Ingame.IMyBeacon beacon = (Sandbox.ModAPI.Ingame.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;

                    Sandbox.ModAPI.Ingame.IMyTerminalBlock terminalBlock = (Sandbox.ModAPI.Ingame.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();
                    Sandbox.ModAPI.Ingame.IMyRadioAntenna antenna = (Sandbox.ModAPI.Ingame.IMyRadioAntenna)cubeBlock;

                    if (!antenna.Enabled)
                        continue;

                    Sandbox.ModAPI.Ingame.IMyTerminalBlock terminalBlock = (Sandbox.ModAPI.Ingame.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();
                    Sandbox.ModAPI.Ingame.IMyMedicalRoom medical = (Sandbox.ModAPI.Ingame.IMyMedicalRoom)cubeBlock;

                    if (!medical.Enabled)
                        continue;

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

                    if(PluginSettings.Instance.DynamicConcealIncludeMedBays)
                    {
                        lock (m_online)
                        {
                            foreach (ulong connectedPlayer in m_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) == Sandbox.Common.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();
                    Sandbox.ModAPI.Ingame.IMyProductionBlock production = (Sandbox.ModAPI.Ingame.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 int SwitchShipSystemsOnOff(IMyCubeGrid cubeGrid, SwitchSystems control, bool mode)
        {
            int counter = 0;
            var blocks = new List<IMySlimBlock>();
            cubeGrid.GetBlocks(blocks, f => f.FatBlock != null);

            foreach (var block in blocks)
            {
                // reactors, batteries
                if ((SwitchSystems.Power & control) == SwitchSystems.Power && block.FatBlock is IMyFunctionalBlock
                    && (block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_Reactor)
                        || block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_BatteryBlock)))
                {
                    ((IMyFunctionalBlock)block.FatBlock).RequestEnable(mode); // turn power on/off.
                    counter++;
                }
                // refineries, arc furnaces, assemblers
                if ((SwitchSystems.Production & control) == SwitchSystems.Production && block.FatBlock is IMyFunctionalBlock
                    && (block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_Refinery)
                        || block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_Assembler)))
                {
                    ((IMyFunctionalBlock)block.FatBlock).RequestEnable(mode); // turn power on/off.
                    counter++;
                }
                if ((SwitchSystems.Programmable & control) == SwitchSystems.Programmable && block.FatBlock is IMyFunctionalBlock
                    && block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_MyProgrammableBlock))
                {
                    ((IMyFunctionalBlock)block.FatBlock).RequestEnable(mode); // turn power on/off.
                    counter++;
                }
                if ((SwitchSystems.Projectors & control) == SwitchSystems.Projectors && block.FatBlock is IMyFunctionalBlock
                    && block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_Projector))
                {
                    ((IMyFunctionalBlock)block.FatBlock).RequestEnable(mode); // turn power on/off.
                    counter++;
                }
                if ((SwitchSystems.Timers & control) == SwitchSystems.Timers && block.FatBlock is IMyFunctionalBlock
                    && block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_TimerBlock))
                {
                    ((IMyFunctionalBlock)block.FatBlock).RequestEnable(mode); // turn power on/off.
                    counter++;
                }
                if ((SwitchSystems.Weapons & control) == SwitchSystems.Weapons && block.FatBlock is IMyFunctionalBlock
                    && (block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_InteriorTurret)
                        || block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_LargeGatlingTurret)
                        || block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_LargeMissileTurret)
                        || block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_SmallGatlingGun)
                        || block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_SmallMissileLauncher)
                        || block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_SmallMissileLauncherReload)))
                {
                    ((IMyFunctionalBlock)block.FatBlock).RequestEnable(mode); // turn power on/off.
                    counter++;
                }
                if ((SwitchSystems.SpotLights & control) == SwitchSystems.SpotLights && block.FatBlock is IMyFunctionalBlock
                    && block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_ReflectorLight))
                {
                    ((IMyFunctionalBlock)block.FatBlock).RequestEnable(mode); // turn power on/off.
                    counter++;
                }
                if ((SwitchSystems.Sensors & control) == SwitchSystems.Sensors && block.FatBlock is IMyFunctionalBlock
                    && block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_SensorBlock))
                {
                    ((IMyFunctionalBlock)block.FatBlock).RequestEnable(mode); // turn power on/off.
                    counter++;
                }
                if ((SwitchSystems.Medical & control) == SwitchSystems.Medical && block.FatBlock is IMyFunctionalBlock
                    && (block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_MedicalRoom)
                        || block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_CryoChamber)))
                {
                    // Switch the power systems that control the grid instead.
                    // I'm unsure if we should go with it like this, which is why it is as yet undocumented.
                    // The idea is, if you have turned the power off to all ships, you can turn the power back on only for grids with Medical and Cryo.
                    SwitchShipSystemsOnOff(cubeGrid, SwitchSystems.Power, mode);
                    counter++;
                }
            }

            return counter;
        }
        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))
                {
                    Sandbox.ModAPI.Ingame.IMyMedicalRoom medical = (Sandbox.ModAPI.Ingame.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;
        }
Esempio n. 25
0
        /// <summary>
        /// Fix up the blocks in ALL grids to have correct values
        /// This routine could also be used to set text panels for other languages.
        ///
        /// </summary>
        /// <param name="grid"></param>
        void BlocksFixup(IMyCubeGrid grid)
        {
            if (bDumpLocalization)
            {
                ModLog.Info("Grid:" + grid.CustomName + "\n ID=" + grid.EntityId.ToString());
                Vector3D gridPos = grid.GetPosition();
                ModLog.Info(" GPS:" + grid.CustomName + ":" + gridPos.X.ToString("0.00") + ":" + gridPos.Y.ToString("0.00") + ":" + gridPos.Z.ToString("0.00") + ":");
            }

            MyStringId gridID;

            if (MyStringId.TryGet("G" + grid.EntityId.ToString(), out gridID))
            {
                // we found grid name
                string str = VRage.MyTexts.Get(gridID).ToString();
                grid.CustomName = str;
            }

            bool bMiki = false;

            if (grid.EntityId == 135216604045890710)
            {
                bMiki = true;
            }

            long medbayID      = 79910699489349926;
            var  slimBlocksMed = new List <IMySlimBlock>();

            grid.GetBlocks(slimBlocksMed, b => b.FatBlock is IMyMedicalRoom);
            foreach (var slim in slimBlocksMed)
            {
                var medbay = slim.FatBlock as IMyMedicalRoom;
                if (medbay.EntityId == medbayID)
                {
                    medbay.Enabled = true;
                }
            }

            // fix up the Gatling blocks to have max range //V28
            var slimBlocksG = new List <IMySlimBlock>();

            grid.GetBlocks(slimBlocksG, b => b.FatBlock is IMyLargeGatlingTurret);
            foreach (var slim in slimBlocksG)
            {
                var gatling = slim.FatBlock as IMyLargeGatlingTurret;
                //              gatling.Range get only :(
            }

            // fix up the beacon blocks  // V26
            //V 36: dump and get localization
            var slimBlocksB = new List <IMySlimBlock>();

            grid.GetBlocks(slimBlocksB, b => b.FatBlock is IMyBeacon);
            if (bDumpLocalization)
            {
                ModLog.Info("BEACON");
            }
            foreach (var slim in slimBlocksB)
            {
                var beacon = slim.FatBlock as IMyBeacon;
                if (beacon.CustomName.Contains("CLEANCE"))
                {
                    // beacon in HQ has spelling error
                    string sName = beacon.CustomName;
                    ModLog.Info("Fixing Beacon Text:" + sName);
                    beacon.CustomName = sName.Replace("CLEANCE", "CLEARANCE");
                }
                if (bDumpLocalization)
                {
                    ModLog.Info(" B" + beacon.EntityId.ToString() + " :" + beacon.CustomName);
                }
                MyStringId beaconID;
                if (MyStringId.TryGet("B" + beacon.EntityId.ToString(), out beaconID))
                {
                    // we found size setting
                    string str = VRage.MyTexts.Get(beaconID).ToString();
                    beacon.CustomName = str;
                }
            }


            //V 36: dump and get localization
            if (bDumpLocalization)
            {
                ModLog.Info("Antenna");
            }
            var slimBlocksA = new List <IMySlimBlock>();

            grid.GetBlocks(slimBlocksA, b => b.FatBlock is IMyRadioAntenna);
            foreach (var slim in slimBlocksA)
            {
                var antenna = slim.FatBlock as IMyRadioAntenna;
                if (bDumpLocalization)
                {
                    ModLog.Info(" A" + antenna.EntityId.ToString() + " : " + antenna.CustomName);
                }
                MyStringId antenaID;
                if (MyStringId.TryGet("A" + antenna.EntityId.ToString(), out antenaID))
                {
                    // we found size setting
                    string str = VRage.MyTexts.Get(antenaID).ToString();
                    antenna.CustomName = str;
                }
            }


            // fix up the text panel blocks
            var slimBlocks = new List <IMySlimBlock>();

            grid.GetBlocks(slimBlocks, b => b.FatBlock is IMyTextPanel);
            if (bDumpLocalization)
            {
                ModLog.Info("TEXT PANEL");
            }
            foreach (var slim in slimBlocks)
            {
                var textPanel = slim.FatBlock as IMyTextPanel;

                textPanel.ShowOnHUD = false; // optimize; only one pass through textpanels

                //bool bShow = textPanel.GetValueBool("ShowTextOnScreen");
                // V 1.190
                bool bShow = textPanel.ContentType == VRage.Game.GUI.TextPanel.ContentType.TEXT_AND_IMAGE;
                //                bool bShow = textPanel.ShowOnScreen != VRage.Game.GUI.TextPanel.ShowTextOnScreenFlag.NONE;
                if (bShow)
                {
                    if (bDumpLocalization)
                    {
                        string txt = textPanel.GetText();
                        if (!string.IsNullOrWhiteSpace(txt))
                        {
                            ModLog.Info(" T" + textPanel.EntityId.ToString());
                            ModLog.Info(txt);
                        }
                    }
                    //V36: Get screen translations.
                    MyStringId textID;
                    if (MyStringId.TryGet("T" + textPanel.EntityId.ToString(), out textID))
                    {
                        // we found replacement string in MyTexts.
                        string str = VRage.MyTexts.Get(textID).ToString();
                        str = str.Replace("\\n", "\n");
                        textPanel.WriteText(str);
                    }
                    if (MyStringId.TryGet("T" + textPanel.EntityId.ToString() + "_size", out textID))
                    {
                        // we found size setting
                        float  size = textPanel.FontSize;
                        string str  = VRage.MyTexts.Get(textID).ToString();
                        if (float.TryParse(str, out size))
                        {
                            textPanel.FontSize = size;
                        }
                    }
                    if (MyStringId.TryGet("T" + textPanel.EntityId.ToString() + "_padding", out textID))
                    {
                        // we found size setting
                        float  size = textPanel.FontSize;
                        string str  = VRage.MyTexts.Get(textID).ToString();
                        if (float.TryParse(str, out size))
                        {
                            textPanel.TextPadding = size;
                        }
                    }
                    if (MyStringId.TryGet("T" + textPanel.EntityId.ToString() + "_alignment", out textID))
                    {
                        // we found alignment setting
                        string str = VRage.MyTexts.Get(textID).ToString();
                        if (str == "center")
                        {
                            textPanel.Alignment = VRage.Game.GUI.TextPanel.TextAlignment.CENTER;
                        }
                        else if (str == "left")
                        {
                            textPanel.Alignment = VRage.Game.GUI.TextPanel.TextAlignment.LEFT;
                        }
                        else if (str == "right")
                        {
                            textPanel.Alignment = VRage.Game.GUI.TextPanel.TextAlignment.RIGHT;
                        }
                    }
                }
                // V26                else
                {
                    var strings = new List <string>();
                    textPanel.GetSelectedImages(strings);
//                    textPanel.TextPadding = 0; //V26
                    if (strings.Count < 1)
                    {
                        // note: better method would be use use .CustomData of the textpanels.
                        // Using this EntityID method to be backward compatible with player's existing worlds.
                        switch (textPanel.EntityId)
                        {
                        //            long buildGuideID = 80461927256500036;
                        case 110371608100898677:     //TOOLS LOCKER
//                                textPanel.FontSize = 5;
//                                textPanel.Alignment = VRage.Game.GUI.TextPanel.TextAlignment.CENTER;
//                                if (textPanel.GetText().Length < 20)
//                                    textPanel.TextPadding = 20f; // 20%
//                                else textPanel.TextPadding = 1f;
                            break;

                        case 143319951822334717:     //143319951822334717:TEXT!                                SPARE PARTS STORAGE
//                                textPanel.FontSize = 5;

/*
 *                              textPanel.Alignment = VRage.Game.GUI.TextPanel.TextAlignment.CENTER;
 *                              if(textPanel.GetText().Length<20)
 *                                  textPanel.TextPadding = 20f; // 20%
 *                              else textPanel.TextPadding = 1f;
 */
                            break;

                        case 87005598531295535:     //87005598531295535TEXT!EMERGENCY SUPPLIES
                            /*
                             * /                                textPanel.FontSize = 5;
                             * textPanel.Alignment = VRage.Game.GUI.TextPanel.TextAlignment.CENTER;
                             * textPanel.TextPadding = 20f; // 20%
                             */
                            break;


                        case 80461927256500036:     // Crash ship build info screen
                                                    /* "old" text
                                                     * Mabel: Loading survival guide...
                                                     *
                                                     * > Recommend searching cargo
                                                     * and disassembling shuttle for
                                                     * rover parts
                                                     * > Recommend configuration:
                                                     * - Six wheels
                                                     * - Friction 10%
                                                     * - Damping 30%
                                                     * - Strength ~5%
                                                     * (Depends on load)
                                                     * - Speed Limit 100km/h
                                                     */
                                                    /*
                                                     *                              textPanel.WriteText("Mabel: Loading survival guide..."+
                                                     * "\n"+
                                                     * "\n> Recommend searching cargo"+
                                                     * "\n   and disassembling shuttle for"+
                                                     * "\n   rover parts"+
                                                     * "\n> Recommend configuration:"+
                                                     * "\n    -Six wheels"+
                                                     * "\n    - Friction 60%"+
                                                     * "\n    - *Strength 10%" +
                                                     * "\n    - *Power 50%" +
                                                     * "\n    - Speed Limit 50km/h" +
                                                     * "\n  * =Depends on load"
                                                     * );
                                                     */
                            break;

                        /*
                         * ((Ice Mine Entrance))
                         * Static Grid 1300:141864706275857195
                         * { X: 1869175.27852051 Y: -2004745.97266307 Z: 1316375.91819424}
                         * -----TEXTPANELS
                         * 74525033656413945:1:+LCD Panel 2
                         | Galactic Corporation Logo
                         */
                        case 74525033656413945:
                            textPanel.AddImageToSelection("Galactic Corporation Logo");
                            break;

                        // MIKI FIXUP
                        case 81986956045310309:
                            textPanel.AddImageToSelection("MikiScrap");
                            break;

                        case 103164071082162108:
                            textPanel.AddImageToSelection("MikiScrap");
                            break;

                        case 120342266177165062:
                            textPanel.AddImageToSelection("MikiScrap");
                            break;

                        case 96762650175047086:
                            textPanel.AddImageToSelection("MikiScrap");
                            break;

                        case 78808963600022563:
                            textPanel.AddImageToSelection("MikiScrap");
                            break;

                        case 102592293973822089:
                            textPanel.AddImageToSelection("MikiScrap");
                            break;

                        case 93732106466977771:
                            textPanel.AddImageToSelection("MikiScrap");
                            break;

                        case 119196087123513740:
                            textPanel.AddImageToSelection("MikiScrap");
                            break;

                        case 115470908890383058:
                            textPanel.AddImageToSelection("MikiScrap");
                            break;

                        case 84905149027762603:
                            textPanel.AddImageToSelection("MikiScrap");
                            break;

                        case 73748511314883089:
                            textPanel.AddImageToSelection("MikiScrap");
                            break;

                        case 108707493869969783:
                            textPanel.AddImageToSelection("MikiScrap");
                            break;

                        case 107003280298094914:
                            textPanel.AddImageToSelection("MikiScrap");
                            break;

                        case 93717234609661072:
                            textPanel.AddImageToSelection("MikiScrap");
                            break;

                        case 100685062896355827:
                            textPanel.AddImageToSelection("MikiScrap");
                            break;

                        //green house
                        case 110846399081478285:
                            textPanel.AddImageToSelection("MRE Logo");
                            break;

                        //                                Signal Station:139030682896359375
                        //{ X: 1844500.54997961 Y: -1995403.72976435 Z: 1323630.52767273}
                        case 132717438306395557:
                            textPanel.AddImageToSelection("MRE Logo");
                            break;

                        //                                ((MRE MedBay 2))
                        //MRE Emergency Medical Station:120085596920753880
                        //{ X: 1844533.71376673 Y: -1995424.91354928 Z: 1323629.33162825}
                        case 104050761648970549:
                            textPanel.AddImageToSelection("MRE Logo");
                            break;

                        // {X:1856577.01869837 Y:-1999257.98373971 Z:1321414.17733138}
                        case 110250540272021112:
                            textPanel.AddImageToSelection("Galactic Corporation Logo");
                            break;

                        //  {X:1857176.1781222 Y:-2000013.37619576 Z:1321553.01815169}
                        case 89933889116515952:
                            textPanel.AddImageToSelection("Galactic Corporation Logo");
                            break;

                        //((and another HQ SAM))
                        //GCorp Mobile SAM: 89611551362269325
                        //{ X: 1857213.83363977 Y: -1998518.53635201 Z: 1320657.55013411}
                        case 95067624877541028:
                            textPanel.AddImageToSelection("Galactic Corporation Logo");
                            break;

                        //((another HQ SAM))
                        //GCorp Mobile SAM: 104043950566026386
                        //{ X: 1858538.51759973 Y: -1999989.95859322 Z: 1320777.02901595}
                        case 120326586562634149:
                            textPanel.AddImageToSelection("Galactic Corporation Logo");
                            break;

                        //((Bunker in weapons Research))
                        //GCorp Bunker:132649980418733079
                        //{ X: 1843291.04608973 Y: -1996439.44943181 Z: 1324491.09281518}
                        case 102565050409374890:
                            textPanel.AddImageToSelection("Galactic Corporation Logo");
                            textPanel.AddImageToSelection("Automation Simplified");
                            break;

                        case 76555655031247133:
                            textPanel.AddImageToSelection("Galactic Corporation Logo");
                            textPanel.AddImageToSelection("Automation Simplified");
                            break;

                        case 82207545563969038:
                            textPanel.AddImageToSelection("Galactic Corporation Logo");
                            textPanel.AddImageToSelection("Automation Simplified");
                            break;

                        case 140611613672853263:
                            textPanel.AddImageToSelection("Galactic Corporation Logo");
                            textPanel.AddImageToSelection("Automation Simplified");
                            break;

                        //((Air Research))
                        //GCorp Flight Research Center:76779347935557670
                        //{ X: 1854754.1883761 Y: -2005852.06052194 Z: 1325419.84578841}
                        case 91899503586440685:
                            textPanel.AddImageToSelection("Clouds");
                            break;

                        case 89540866723022250:
                            textPanel.AddImageToSelection("Clouds");
                            break;

                        case 139513180460721275:
                            textPanel.AddImageToSelection("Clouds");
                            break;

                        case 123742114812299814:
                            textPanel.AddImageToSelection("Clouds");
                            break;

                        case 72707843196346809:
                            textPanel.AddImageToSelection("Clouds");
                            break;

                        case 84058947393377852:
                            textPanel.AddImageToSelection("Clouds");
                            break;

                        case 124309978476859628:
                            textPanel.AddImageToSelection("Clouds");
                            break;

                        case 85895320964444780:
                            textPanel.AddImageToSelection("Clouds");
                            break;

                        case 117967784354173602:
                            textPanel.AddImageToSelection("Clouds");
                            break;

                        case 128468555565951583:
                            textPanel.AddImageToSelection("Clouds");
                            break;

                        case 107231006349635239:
                            textPanel.AddImageToSelection("Clouds");
                            break;

                        //((MRE hidden Base))
                        //MRE Experiment Base: 104361129531664144
                        //{ X: 1858398.21613573 Y: -1989137.98910994 Z: 1312706.48643797}
                        case 98971232666660757:
                            textPanel.AddImageToSelection("MRE Logo");
                            break;

                        case 97512105090353134:
                            textPanel.AddImageToSelection("MRE Logo");
                            break;

                        case 81228556864103207:
                            textPanel.AddImageToSelection("MRE Logo");
                            break;

                        //((HQ))
                        //GCorp HQ Tower: 144104082158837389
                        //{ X: 1857310.65834681 Y: -1999316.80991158 Z: 1321066.96761458}
                        case 125129893494374181:
                            textPanel.AddImageToSelection("White screen");
                            break;

                        case 134131747655270782:
                            textPanel.AddImageToSelection("White screen");
                            break;

                        case 74727284886995000:
                            textPanel.AddImageToSelection("White screen");
                            break;

                        case 98708608904781783:
                            textPanel.AddImageToSelection("White screen");
                            break;

                        case 138656136990359379:
                            textPanel.AddImageToSelection("White screen");
                            break;

                        case 80870473015345748:
                            textPanel.AddImageToSelection("Galactic Corporation Logo");
                            break;

                        case 98370398719554346:
                            textPanel.AddImageToSelection("White screen");
                            break;

                        case 80724503483430325:
                            textPanel.AddImageToSelection("White screen");
                            break;

                        case 87324639907322082:
                            textPanel.AddImageToSelection("White screen");
                            break;

                        case 110549946960318740:
                            textPanel.AddImageToSelection("Galactic Corporation Logo");
                            textPanel.AddImageToSelection("Automation Simplified");
                            break;

                        case 142860245424722839:
                            textPanel.AddImageToSelection("Galactic Corporation Logo");
                            textPanel.AddImageToSelection("Automation Simplified");
                            break;

                        case 117922822138601150:
                            textPanel.AddImageToSelection("Galactic Corporation Logo");
                            textPanel.AddImageToSelection("Automation Simplified");
                            break;

                        // ((HQ Rocket))
                        //GCorp Space Transport: 97585502667028994
                        //{ X: 1857324.30678431 Y: -1999293.08872018 Z: 1321075.17171614}
                        case 140237983630899577:
                            textPanel.AddImageToSelection("Galactic Corporation Logo");
                            break;

                        case 105805752262318800:
                            textPanel.AddImageToSelection("Arrow");
                            break;

                        case 104593951810486921:
                            textPanel.AddImageToSelection("Galactic Corporation Logo");
                            textPanel.AddImageToSelection("Automation Simplified");
                            break;

                        case 141641456443241951:
                            textPanel.AddImageToSelection("Galactic Corporation Logo");
                            textPanel.AddImageToSelection("Automation Simplified");
                            break;

                        case 101582007425482292:
                            textPanel.AddImageToSelection("Galactic Corporation Logo");
                            textPanel.AddImageToSelection("Automation Simplified");
                            break;

                        case 80366112655444611:
                            textPanel.AddImageToSelection("Galactic Corporation Logo");
                            textPanel.AddImageToSelection("Automation Simplified");
                            break;
                        }
                    }
                }
                if (bMiki)
                {
                    if (
                        textPanel.CustomName == "LCD Panel 10" || // (there are two)
                        textPanel.CustomName == "LCD Panel 5" ||
                        textPanel.CustomName == "LCD Panel 6" ||
                        textPanel.CustomName == "LCD Panel 7" ||
                        textPanel.CustomName == "LCD Panel 9" ||
                        textPanel.CustomName == "LCD Panel 13" ||
                        textPanel.CustomName == "LCD Panel 14" ||
                        textPanel.CustomName == "LCD Panel 15"
                        )
                    {
                        textPanel.ContentType = VRage.Game.GUI.TextPanel.ContentType.TEXT_AND_IMAGE;
                        var strings = new List <string>();
                        textPanel.GetSelectedImages(strings);
                        //                    textPanel.TextPadding = 0; //V26
                        if (strings.Count < 1)
                        { // nothing is currently listed
                            textPanel.AddImageToSelection("MikiScrap");
                        }
                    }
                }
            }

            // fix up the sound blocks
            var slimBlocks2 = new List <IMySlimBlock>();

            grid.GetBlocks(slimBlocks2, b => b.FatBlock is IMySoundBlock);
            MyStringId soundblockID;

            foreach (var slim in slimBlocks2)
            {
                var soundBlock = slim.FatBlock as IMySoundBlock; // Fixed V21
                if (bDumpLocalization)
                {
                    ModLog.Info(" S" + soundBlock.EntityId.ToString());
                    ModLog.Info("  " + soundBlock.SelectedSound.ToString());
                }
                //                if (soundBlock == null) continue; // why do we need this?
                switch (soundBlock.EntityId)
                {
                // air base alpha:
                case 116378614635193269:
                    if (MyStringId.TryGet("WelcomeToGcorp", out soundblockID))
                    {
                        soundBlock.SelectedSound = VRage.MyTexts.Get(soundblockID).ToString();
                    }
                    else
                    {
                        soundBlock.SelectedSound = "WelcomeToGcorp";
                    }
                    break;

                /*
                 * case XXXX:
                 * if (MyStringId.TryGet("IntruderDetectedGCorp", out soundblockID))
                 * {
                 *  soundBlock.SelectedSound = VRage.MyTexts.Get(soundblockID).ToString();
                 * }
                 * else
                 *  soundBlock.SelectedSound = "IntruderDetectedGCorp";
                 * break;
                 */
                // ice mine entrance
                case 101979433782763108:
                    if (MyStringId.TryGet("NotAuthorisedDeployDefences", out soundblockID))
                    {
                        soundBlock.SelectedSound = VRage.MyTexts.Get(soundblockID).ToString();
                    }
                    else
                    {
                        soundBlock.SelectedSound = "NotAuthorisedDeployDefences";
                    }
                    break;

                // ice mine shaft botom
                case 106640376870960334:
                    if (MyStringId.TryGet("MineClosed", out soundblockID))
                    {
                        soundBlock.SelectedSound = VRage.MyTexts.Get(soundblockID).ToString();
                    }
                    else
                    {
                        soundBlock.SelectedSound = "MineClosed";
                    }
                    break;

                //((Upper Ice Mine Meeting Room))
                //{ X: 1869176.67818993 Y: -2004930.50366838 Z: 1316377.58089576}
                case 80185389104537910:
                    soundBlock.SelectedSound = "BigSwitch";
                    break;

                // MRE HIdden base
                case 95206901925432014:
                    soundBlock.SelectedSound = "BigSwitch";
                    break;

                case 100498114358496283:
                    soundBlock.SelectedSound = "BigSwitch";
                    break;

                case 77589249328205128:
                    soundBlock.SelectedSound = "BigSwitch";
                    break;

                case 104066113506074975:
                    soundBlock.SelectedSound = "BigSwitch";
                    break;

                case 90866709199081947:
                    soundBlock.SelectedSound = "BigSwitch";
                    break;

                case 141427853315146800:
                    soundBlock.SelectedSound = "BigSwitch";
                    break;

                case 116242415031561830:
                    soundBlock.SelectedSound = "BigSwitch";
                    break;

                case 110850485077900653:
                    soundBlock.SelectedSound = "BigSwitch";
                    break;

                case 88298229398547791:
                    soundBlock.SelectedSound = "BigSwitch";
                    break;


                // wrecked drone
                case 102293828213773618:
                    soundBlock.SelectedSound = "PowerUpClipped";
                    break;

                //((old drone @ hangar 1))
                case 108074122634121508:
                    soundBlock.SelectedSound = "PowerUpClipped";
                    break;

                // air research
                case 84998344586050021:
                    soundBlock.SelectedSound = "SoundBlockAlert2";
                    break;

                case 91070301367474416:
                    soundBlock.SelectedSound = "AirplaneSound";
                    break;

                case 90629854631902381:
                    if (MyStringId.TryGet("FlightResearchExhibition", out soundblockID))
                    {
                        soundBlock.SelectedSound = VRage.MyTexts.Get(soundblockID).ToString();
                    }
                    else
                    {
                        soundBlock.SelectedSound = "FlightResearchExhibition";
                    }
                    break;

                // air base beta
                case 130193226083241264:
                    if (MyStringId.TryGet("WelcomeToGcorp", out soundblockID))
                    {
                        soundBlock.SelectedSound = VRage.MyTexts.Get(soundblockID).ToString();
                    }
                    else
                    {
                        soundBlock.SelectedSound = "WelcomeToGcorp";
                    }
                    break;

                // mech
                case 82762879450865423:
                    //            bodyGrid.SetSoundBlocks("Mech Intruders Must Be Destroyed"); // fix missing sound on sound block on mech
                    if (MyStringId.TryGet("IntruderRobot", out soundblockID))
                    {
                        soundBlock.SelectedSound = VRage.MyTexts.Get(soundblockID).ToString();
                    }
                    else
                    {
                        soundBlock.SelectedSound = "IntruderRobot";
                    }
                    break;

                // HQ
                case 95872484442737911:
                    soundBlock.SelectedSound = "SoundBlockAlert1";
                    break;

                case 82604291774017685:
                    if (MyStringId.TryGet("WelcomeToGcorp", out soundblockID))
                    {
                        soundBlock.SelectedSound = VRage.MyTexts.Get(soundblockID).ToString();
                    }
                    else
                    {
                        soundBlock.SelectedSound = "WelcomeToGcorp";
                    }
                    break;

                // MIKI
                case 129379111872365143:
                    soundBlock.SelectedSound = "Carmen";
                    break;

                case 140249950038454545:
                    soundBlock.SelectedSound = "LavaLoop";
                    break;
                }
            }
        }
Esempio n. 26
0
        public void FindTargetKeyPoint()
        {
            IMyCubeGrid grid           = Ship;
            var         centerPosition = Ship.GetPosition();

            _keyPoints.Clear();
            //get position, get lenier velocity in each direction
            //add them like 10 times and add that to current coord
            if (grid != null)
            {
                Sandbox.ModAPI.IMyGridTerminalSystem gridTerminal =
                    Sandbox.ModAPI.MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid(grid);

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

                //List<IMyTerminalBlock> solarBlocks = new List<IMyTerminalBlock>();
                //gridTerminal.GetBlocksOfType<IMySolarPanel>(solarBlocks);

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

                List <IMyTerminalBlock> cockpitsTarget =
                    new List <IMyTerminalBlock>();
                gridTerminal.GetBlocksOfType <Sandbox.ModAPI.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 <Sandbox.ModAPI.IMyBatteryBlock>(batteriesTarget);


                List <IMySlimBlock> weaponsTarget = new List <IMySlimBlock>();

                grid.GetBlocks(weaponsTarget, (x) => x.FatBlock is Sandbox.ModAPI.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

                foreach (var weapon in weaponsTarget.OrderBy(x => (x.FatBlock.GetPosition() - Ship.GetPosition()).Length()))
                {
                    if (weapon != null)
                    {
                        if (weapon.FatBlock.IsFunctional)
                        {
                            _keyPoints.Add(weapon.FatBlock as IMyTerminalBlock);
                            var distFromCenter = (centerPosition - weapon.FatBlock.GetPosition()).Length();
                            if (distFromCenter > ShipSize)
                            {
                                ShipSize = distFromCenter;
                            }
                        }
                    }
                }
                foreach (var missile in missileLuanchersTarget.OrderBy(x => (x.GetPosition() - Ship.GetPosition()).Length()))
                {
                    if (missile != null)
                    {
                        if (missile.IsFunctional)
                        {
                            _keyPoints.Add(missile);
                            var distFromCenter = (centerPosition - missile.GetPosition()).Length();
                            if (distFromCenter > ShipSize)
                            {
                                ShipSize = distFromCenter;
                            }
                        }
                    }
                }
                foreach (var reactor in reactorBlocks.OrderBy(x => (x.GetPosition() - Ship.GetPosition()).Length()))
                {
                    if (reactor != null)
                    {
                        if (reactor.IsFunctional)
                        {
                            _keyPoints.Add(reactor);
                            var distFromCenter = (centerPosition - reactor.GetPosition()).Length();
                            if (distFromCenter > ShipSize)
                            {
                                ShipSize = distFromCenter;
                            }
                        }
                    }
                }
                foreach (var reactor in batteryBlocks.OrderBy(x => (x.GetPosition() - Ship.GetPosition()).Length()))
                {
                    if (reactor != null)
                    {
                        if (reactor.IsFunctional)
                        {
                            _keyPoints.Add(reactor);
                            var distFromCenter = (centerPosition - reactor.GetPosition()).Length();
                            if (distFromCenter > ShipSize)
                            {
                                ShipSize = distFromCenter;
                            }
                        }
                    }
                }
                //foreach (var reactor in solarBlocks.OrderBy(x => (x.GetPosition() - Ship.GetPosition()).Length()))
                //{
                //    if (reactor != null)
                //    {
                //        if (reactor.IsFunctional)
                //        {
                //            _keyPoints.Add(reactor);
                //            var distFromCenter = (centerPosition - reactor.GetPosition()).Length();
                //            if (distFromCenter > ShipSize)
                //                ShipSize = distFromCenter;
                //        }
                //    }
                //}
                foreach (var battery in batteriesTarget.OrderBy(x => (x.GetPosition() - Ship.GetPosition()).Length()))
                {
                    if (battery != null)
                    {
                        if (battery.IsFunctional)
                        {
                            _keyPoints.Add(battery);
                            var distFromCenter = (centerPosition - battery.GetPosition()).Length();
                            if (distFromCenter > ShipSize)
                            {
                                ShipSize = distFromCenter;
                            }
                        }
                    }
                }
                foreach (var c*k in cockpitsTarget.OrderBy(x => (x.GetPosition() - Ship.GetPosition()).Length()))
                {
                    if (c*k != null)
                    {
                        if (c*k.IsFunctional)
                        {
                            _keyPoints.Add(c*k);
                            var distFromCenter = (centerPosition - c*k.GetPosition()).Length();
                            if (distFromCenter > ShipSize)
                            {
                                ShipSize = distFromCenter;
                            }
                        }
                    }
                }
            }
        }
        public override bool HandleCommand(ulong userId, string[] words)
        {
            if (words.Length != 1)
            {
                Communication.SendPrivateInformation(userId, GetHelp());
                return(true);
            }

            DateTime            start    = DateTime.Now;
            HashSet <IMyEntity> entities = new HashSet <IMyEntity>();

            MyAPIGateway.Entities.GetEntities(entities);
            int count    = 0;
            int enabled  = 0;
            int disabled = 0;
            int keepOn   = 0;

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

                if (!entity.InScene)
                {
                    continue;
                }

                IMyCubeGrid grid = (IMyCubeGrid)entity;
                //MyObjectBuilder_CubeGrid builder = CubeGrids.SafeGetObjectBuilder((IMyCubeGrid)entity);
                //if (builder == null)
                //	continue;

                List <IMySlimBlock> blocks = new List <IMySlimBlock>();
                grid.GetBlocks(blocks);
                foreach (IMySlimBlock block in blocks)
                //foreach (MyObjectBuilder_CubeBlock block in builder.CubeBlocks)
                {
                    //if (block is MyObjectBuilder_TurretBase)
                    if (block.FatBlock == null)
                    {
                        continue;
                    }

                    if (block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_InteriorTurret) ||
                        block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_LargeGatlingTurret) ||
                        block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_LargeMissileTurret))
                    {
                        //IMyEntity turret = MyAPIGateway.Entities.GetEntityById(block.EntityId);
                        IMyEntity turret = block.FatBlock;
                        bool      state  = FunctionalBlockEntity.GetState(turret);

                        if (words[0].ToLower() == "toggle")
                        {
                            FunctionalBlockEntity.SetState(turret, !state);
                        }

                        count++;

                        if (state)
                        {
                            enabled++;
                        }
                        else
                        {
                            disabled++;
                        }

                        if (words[0].ToLower() == "test" && state)
                        {
                            BoundingSphereD  sphere       = new BoundingSphereD(grid.GetPosition(), 2000);
                            List <IMyEntity> testEntities = MyAPIGateway.Entities.GetEntitiesInSphere(ref sphere);
                            bool             found        = false;
                            foreach (IMyEntity testEntity in testEntities)
                            {
                                if (entity == testEntity)
                                {
                                    continue;
                                }

                                if (testEntity is IMyCubeBlock)
                                {
                                    continue;
                                }

                                if (!(testEntity is IMyControllableEntity))
                                {
                                    //Console.WriteLine("Entity: {0}", testEntity.GetType());
                                    continue;
                                }


                                IMyCubeGrid testGrid = testEntity as IMyCubeGrid;
                                if (testGrid != null)
                                {
                                    foreach (long owner in testGrid.BigOwners)
                                    {
                                        if (block.FatBlock.GetUserRelationToOwner(owner) == MyRelationsBetweenPlayerAndBlock.Enemies ||
                                            block.FatBlock.GetUserRelationToOwner(owner) == MyRelationsBetweenPlayerAndBlock.Neutral)
                                        {
                                            found = true;
                                            keepOn++;
                                            break;
                                        }
                                        else
                                        {
                                            Console.WriteLine("Relation: {0} - {1}", block.FatBlock.GetUserRelationToOwner(owner), testGrid.DisplayName);
                                        }
                                    }

                                    if (found)
                                    {
                                        break;
                                    }
                                }
                                else
                                {
                                    var builderBase             = testEntity.GetObjectBuilder();
                                    MyObjectBuilder_Character c = builderBase as MyObjectBuilder_Character;
                                    if (c != null)
                                    {
                                        ulong steamId = PlayerMap.Instance.GetSteamId(c.EntityId);
                                        if (steamId < 1)
                                        {
                                            continue;
                                        }

                                        long playerId = PlayerMap.Instance.GetFastPlayerIdFromSteamId(steamId);
                                        if (playerId < 1)
                                        {
                                            continue;
                                        }

                                        if (block.FatBlock.GetUserRelationToOwner(playerId) == MyRelationsBetweenPlayerAndBlock.Enemies ||
                                            block.FatBlock.GetUserRelationToOwner(playerId) == MyRelationsBetweenPlayerAndBlock.Neutral)
                                        {
                                            found = true;
                                            keepOn++;
                                            break;
                                        }

/*
 *                                                                              else
 *                                                                              {
 *                                                                                      Console.WriteLine("Character Relation: {0} - {1}", block.FatBlock.GetUserRelationToOwner(playerId), c.DisplayName);
 *                                                                              }
 */
                                        if (found)
                                        {
                                            break;
                                        }
                                    }
                                }
                            }

                            //break;
                        }
                    }
                }
            }

            Communication.SendPrivateInformation(userId, string.Format("{0} turrets.  {1} on, {2} off.  {3} keepon ({4} ms)", count, enabled, disabled, keepOn, (DateTime.Now - start).TotalMilliseconds));
            return(true);
        }
Esempio n. 28
0
        private bool affectEnemyBlocks()
        {
            bool done = true;

            scanArea = scanRange.TransformSlow(thisBlock.WorldMatrix);
            List <IMyEntity> entityList = null;

            lock (MyAPIGateway.Entities) {  // Scan for nearby entities (grids)
                entityList = MyAPIGateway.Entities.GetElementsInBox(ref scanArea);
            }

            if (entityList != null)
            {
                List <IMySlimBlock> gridBlocks = new List <IMySlimBlock>();
                foreach (IMyEntity entity in entityList)
                {
                    try {
                        if (entity is IMyCubeGrid)
                        {
                            IMyCubeGrid grid = entity as IMyCubeGrid;
                            if (isEnemyGrid(grid))
                            {
                                gridBlocks.Clear();
                                grid.GetBlocks(gridBlocks, b => b.FatBlock is IMyTerminalBlock && (b.FatBlock as IMyTerminalBlock).IsWorking && isEnemyBlock(b.FatBlock));
                                //MyAPIGateway.Utilities.ShowNotification("Found grid #"+i+" named "+grid.Name+" & "+grid.GetFriendlyName()+", ID="+grid.EntityId+"; size = "+grid.GridSizeEnum+", owners = "+grid.SmallOwners.ToString()+", grid elements = "+gridBlocks.ToString(), 5000, MyFontEnum.Red);
                                foreach (IMySlimBlock slim in gridBlocks)
                                {
                                    IMyTerminalBlock block    = slim.FatBlock as IMyTerminalBlock;
                                    EMPReaction      reaction = Configuration.getEMPReaction(block);
                                    if (reaction != null)
                                    {
                                        bool share = thisGrid == grid;
                                        if (rand.Next(100) >= (share ? reaction.ResistanceSameGrid : reaction.Resistance))
                                        {
                                            bool   inRange  = reaction.InfRangeSharedGrid;
                                            double distance = reaction.InfRangeSharedGrid ? 0 : Vector3D.Distance(thisBlock.GetPosition(), block.GetPosition());
                                            if (!inRange)
                                            {
                                                double d = reaction.MaxDistance;
                                                if (share)
                                                {
                                                    //MyAPIGateway.Utilities.ShowNotification("boosting range (from "+d+" by "+reaction.SameGridBoost+"x) due to grid sharing ("+emp_grid.EntityId+"/"+emp_grid.GridSizeEnum+" & "+grid.EntityId+"/"+grid.GridSizeEnum+") for block "+block.CustomName+" @ "+distance, 5000, MyFontEnum.Red);
                                                    d *= reaction.SameGridBoost;
                                                }
                                                else
                                                {
                                                    //MyAPIGateway.Utilities.ShowNotification("Not boosting range (from "+d+", using native "+distanceMultiplier+"x instead); no grid sharing ("+emp_grid.EntityId+"/"+emp_grid.GridSizeEnum+" & "+grid.EntityId+"/"+grid.GridSizeEnum+") for block "+block.CustomName+" @ "+distance, 5000, MyFontEnum.Red);
                                                    d *= distanceMultiplier;
                                                }
                                                inRange = distance < d;
                                            }
                                            if (inRange)
                                            {
                                                done &= empBlock(slim, block, distance, share, reaction, !(block is IMyFunctionalBlock), false);
                                            }
                                            else
                                            {
                                                //MyAPIGateway.Utilities.ShowNotification("Not EMPing block "+block.CustomName+" @ "+distance+"; out of range", 5000, MyFontEnum.Red);
                                            }
                                        }
                                        else if (reaction.Resistance < 100)
                                        {
                                            done = false;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex) {
                        //MyAPIGateway.Utilities.ShowNotification("Could not run EMP cycle: "+ex.ToString(), 5000, MyFontEnum.Red);
                        IO.log("Could not run EMP cycle: " + ex.ToString());
                    }
                }
            }
            return(done);
        }
Esempio n. 29
0
        public override bool HandleCommand(ulong userId, string command)
        {
            string[] words = command.Split(' ');
            if (!PluginSettings.Instance.DockingEnabled)
            {
                return(false);
            }

            if (words.Length < 1)
            {
                Communication.SendPrivateInformation(userId, GetHelp());
                return(true);
            }

            if (m_undocking)
            {
                Communication.SendPrivateInformation(userId, string.Format("Server is busy, try again"));
                return(true);
            }

            m_undocking = true;
            try
            {
                String pylonName = String.Join(" ", words);
                if (PlayerMap.Instance.GetPlayerIdsFromSteamId(userId).Count < 1)
                {
                    Communication.SendPrivateInformation(userId, string.Format("Unable to find player Id: {0}", userId));
                    return(true);
                }

                long playerId = PlayerMap.Instance.GetPlayerIdsFromSteamId(userId).First();

                Dictionary <String, List <IMyCubeBlock> > testList;
                List <IMyCubeBlock> beaconList;
                DockingZone.FindByName(pylonName, out testList, out beaconList, playerId);

                if (beaconList.Count == 4)
                {
                    foreach (IMyCubeBlock entity in beaconList)
                    {
                        if (!Entity.CheckOwnership(entity, playerId))
                        {
                            Communication.SendPrivateInformation(userId, string.Format("You do not have permission to use '{0}'.  You must either own all the beacons or they must be shared with faction.", pylonName));
                            return(true);
                        }
                    }

                    IMyCubeBlock e      = beaconList.First();
                    IMyCubeGrid  parent = (IMyCubeGrid)e.Parent;

                    long[]             beaconListIds = beaconList.Select(p => p.EntityId).ToArray();
                    long               ownerId       = beaconList.First().OwnerId;
                    List <DockingItem> dockingItems  = Docking.Instance.Find(d => d.PlayerId == ownerId && d.TargetEntityId == parent.EntityId && d.DockingBeaconIds.Intersect(beaconListIds).Count() == 4);
                    if (dockingItems.Count < 1)
                    {
                        Communication.SendPrivateInformation(userId, string.Format("You have no ships docked in docking zone '{0}'.", pylonName));
                        return(true);
                    }

                    DockingItem dockingItem = dockingItems.First();

                    // Figure out center of docking area, and other distance information
                    double   maxDistance = 99;
                    Vector3D vPos        = new Vector3D(0, 0, 0);
                    foreach (IMyCubeBlock b in beaconList)
                    {
                        Vector3D beaconPos = Entity.GetBlockEntityPosition(b);
                        vPos += beaconPos;
                    }

                    vPos = vPos / 4;
                    foreach (IMyCubeBlock b in beaconList)
                    {
                        Vector3D beaconPos = Entity.GetBlockEntityPosition(b);
                        maxDistance = Math.Min(maxDistance, Vector3D.Distance(vPos, beaconPos));
                    }

                    List <IMySlimBlock> blocks = new List <IMySlimBlock>();
                    parent.GetBlocks(blocks);
                    foreach (IMySlimBlock slim_cbe in blocks)
                    {
                        if (slim_cbe is IMyCubeBlock)
                        {
                            IMyCubeBlock cbe = slim_cbe.FatBlock;
                            if (cbe.GetObjectBuilderCubeBlock() is MyObjectBuilder_Cockpit)
                            {
                                MyObjectBuilder_Cockpit c = (MyObjectBuilder_Cockpit)cbe.GetObjectBuilderCubeBlock();
                                if (c.Pilot != null)
                                {
                                    Communication.SendPrivateInformation(userId, string.Format("Carrier ship has a pilot.  The carrier should be unpiloted and fully stopped before undocking.  (Sometimes this can lag a bit.  Wait 10 seconds and try again)", pylonName));
                                    return(true);
                                }
                            }
                        }
                    }

                    String dockedShipFileName = Essentials.PluginPath + String.Format("\\Docking\\docked_{0}_{1}_{2}.sbc", ownerId, dockingItem.TargetEntityId, dockingItem.DockedEntityId);

                    // Load Entity From File and add to game
                    FileInfo fileInfo = new FileInfo(dockedShipFileName);
                    //CubeGridEntity cubeGrid = new CubeGridEntity(fileInfo);

                    MyObjectBuilder_CubeGrid cubeGrid = BaseObjectManager.ReadSpaceEngineersFile <MyObjectBuilder_CubeGrid, MyObjectBuilder_CubeGridSerializer>(dockedShipFileName);

                    // Rotate our ship relative to our saved rotation and the new carrier rotation
                    cubeGrid.PositionAndOrientation = new MyPositionAndOrientation(Matrix.CreateFromQuaternion(Quaternion.CreateFromRotationMatrix(parent.Physics.GetWorldMatrix().GetOrientation()) * dockingItem.SaveQuat).GetOrientation());
                    // Move our ship relative to the new carrier position and orientation
                    Quaternion newQuat    = Quaternion.CreateFromRotationMatrix(parent.Physics.GetWorldMatrix().GetOrientation());
                    Vector3D   rotatedPos = Vector3D.Transform(dockingItem.SavePos, newQuat);
                    //cubeGrid.Position = rotatedPos + parent.GetPosition();
                    cubeGrid.PositionAndOrientation = new MyPositionAndOrientation(rotatedPos + parent.GetPosition(), cubeGrid.PositionAndOrientation.Value.Forward, cubeGrid.PositionAndOrientation.Value.Up);

                    // Add object to world
                    cubeGrid.EntityId        = BaseEntity.GenerateEntityId();
                    cubeGrid.LinearVelocity  = Vector3.Zero;
                    cubeGrid.AngularVelocity = Vector3.Zero;

                    bool undock = false;
                    Wrapper.GameAction(() =>
                    {
                        try
                        {
                            MyAPIGateway.Entities.CreateFromObjectBuilderAndAdd(cubeGrid);
                            List <MyObjectBuilder_EntityBase> addList = new List <MyObjectBuilder_EntityBase>();
                            addList.Add(cubeGrid);
                            MyAPIGateway.Multiplayer.SendEntitiesCreated(addList);
                            undock = true;
                        }
                        catch (Exception Ex)
                        {
                            Logging.WriteLineAndConsole(string.Format("Error undocking ship: {0}", Ex.ToString()));
                            Communication.SendPrivateInformation(userId, string.Format("Unable to undock ship due to error."));
                        }
                    });

                    if (!undock)
                    {
                        return(true);
                    }

                    //SectorObjectManager.Instance.AddEntity(cubeGrid);

                    // Remove the docking file
                    File.Delete(dockedShipFileName);
                    Docking.Instance.Remove(dockingItem);

                    Communication.SendPrivateInformation(userId, string.Format("The ship '{0}' has been undocked from docking zone '{1}'", dockingItem.DockedName, pylonName));

                    /*
                     * // Queue for cooldown
                     * DockingCooldownItem cItem = new DockingCooldownItem();
                     * cItem.Name = pylonName;
                     * cItem.startTime = DateTime.Now;
                     *
                     * lock (m_cooldownList)
                     *      m_cooldownList.Add(cItem);
                     *
                     * IMyEntity gridEntity = MyAPIGateway.Entities.GetEntityById(dockingItem.DockedEntityId);
                     * IMyCubeGrid cubeGrid = (IMyCubeGrid)gridEntity;
                     *
                     * Quaternion q = Quaternion.CreateFromRotationMatrix(parent.WorldMatrix.GetOrientation()) * dockingItem.SaveQuat;
                     * Quaternion newQuat = Quaternion.CreateFromRotationMatrix(parent.WorldMatrix.GetOrientation());
                     * Vector3 parentPosition = parent.GetPosition();
                     * Vector3 rotatedPos = Vector3.Transform(dockingItem.savePos, newQuat);
                     * Vector3 position = rotatedPos + parentPosition;
                     * Matrix positionMatrix = Matrix.CreateFromQuaternion(q);
                     *
                     * cubeGrid.ChangeGridOwnership(playerId, MyOwnershipShareModeEnum.None);
                     * gridEntity.SetPosition(dockingItem.savePos);
                     *
                     * gridEntity.WorldMatrix = positionMatrix;
                     * gridEntity.SetPosition(position);
                     *
                     * // We need to update again, as this doesn't seem to sync properly?  I set world matrix, and setposition, and it doesn't go where it should, and I
                     * // have to bump into it for it to show up, it's mega weird.
                     *
                     * if (PluginDocking.Settings.DockingItems == null)
                     *      throw new Exception("DockingItems is null");
                     *
                     * // Remove from docked items
                     * PluginDocking.Settings.DockingItems.Remove(dockingItem);
                     *
                     * // Notify user
                     * Communication.SendPrivateInformation(userId, string.Format("The ship '{0}' has been undocked from docking zone '{1}'", gridEntity.DisplayName, pylonName));
                     */
                    // Queue for cooldown

                    /*
                     * DockingCooldownItem cItem = new DockingCooldownItem();
                     * cItem.name = pylonName;
                     * cItem.startTime = DateTime.Now;
                     * PluginDocking.CooldownList.Add(cItem);
                     */
                }
                else if (beaconList.Count > 4)                 // Too many beacons, must be 4
                {
                    Communication.SendPrivateInformation(userId, string.Format("Too many beacons with the name or another zone with the name '{0}'.  Place only 4 beacons to create a zone or try a different zone name.", pylonName));
                }
                else                 // Can't find docking zone
                {
                    Communication.SendPrivateInformation(userId, string.Format("Can not locate docking zone '{0}'.  There must be 4 beacons with the name '{0}' to create a docking zone.  Beacons must be fully built!", pylonName));
                }
            }
            finally
            {
                m_undocking = false;
            }

            return(true);
        }
Esempio n. 30
0
        public override void UpdateBeforeSimulation()
        {
            timer += 1;

            if (timer % 600 == 0)
            {
                for (int i = 0; i < gridList.Count; i++)
                {
                    if (gridList[i] != null)
                    {
                        bool         isSelling = false;
                        IMyTextPanel pn        = null;
                        var          blocklist = new List <IMySlimBlock>();
                        gridList[i].GetBlocks(blocklist, b => b != null);
                        for (int n = 0; n < blocklist.Count; n++)
                        {
                            if (blocklist[n].FatBlock != null)
                            {
                                IMyTextPanel panel = blocklist[n].FatBlock as IMyTextPanel;
                                if (panel != null)
                                {
                                    if (panel.CustomName == "SellLCD")
                                    {
                                        isSelling = true;
                                        pn        = panel;
                                    }
                                }
                            }
                        }
                        if (isSelling == true && pn != null)
                        {
                            float ingotworth = Calculator(gridList[i], "Ingot");
                            float compworth  = Calculator(gridList[i], "Component");

                            Double avg = Math.Round((ingotworth + compworth) / 2f);

                            float maxWorth = 0;
                            float minWorth = 0;
                            if (ingotworth > compworth)
                            {
                                maxWorth = ingotworth;
                                minWorth = compworth;
                            }
                            if (ingotworth < compworth)
                            {
                                maxWorth = compworth;
                                minWorth = ingotworth;
                            }
                            if (ingotworth == compworth)
                            {
                                maxWorth = compworth;
                                minWorth = ingotworth;
                            }
                            List <string> ex = new List <string>();
                            ex = pn.CustomData.Split('\n').ToList();
                            string listing = "No listing";
                            string status  = "Idle";
                            if (ex.Count == 2)
                            {
                                listing = ex[1];
                                if (listing == string.Empty)
                                {
                                    listing = "No listing";
                                }
                                status = ex[0];
                                if (status == string.Empty)
                                {
                                    status = "Idle";
                                }
                            }
                            else if (ex.Count > 2)
                            {
                                listing = "Improper format";
                                status  = "Improper format";
                            }
                            else if (ex.Count == 1)
                            {
                                listing = "Missing format";
                                status  = "Missing format";
                            }
                            string LCDMessage = gridList[i].CustomName + "\n" + status + "\nListing Price: " + listing + "\nAvg Worth: " + String.Format("{0:n0}", avg) + " SC"
                                                + "\nMax Worth: " + String.Format("{0:n0}", maxWorth) + " SC " + "\nMin Worth: " + String.Format("{0:n0}", minWorth) + " SC ";
                            pn.WriteText(LCDMessage);
                        }
                    }
                }
            }
            if (timer % 60 == 0)
            {
                IMyCubeGrid grid = MyAPIGateway.CubeBuilder.FindClosestGrid();
                if (grid != null)
                {
                    //MyVisualScriptLogicProvider.SendChatMessage(grid.CustomName + " grids: " + gridList.Count.ToString());
                    var blocklist = new List <IMySlimBlock>();
                    grid.GetBlocks(blocklist);
                    bool isSelling = false;
                    for (int n = 0; n < blocklist.Count; n++)
                    {
                        if (blocklist[n].FatBlock != null)
                        {
                            //MyAPIGateway.Utilities.ShowNotification(blocklist[n].ToString() + " found", 1, "Red");

                            IMyTextPanel panel = blocklist[n].FatBlock as IMyTextPanel;
                            if (panel != null)
                            {
                                if (panel.CustomName == "SellLCD")
                                {
                                    isSelling = true;
                                }
                            }
                        }
                    }
                    if (isSelling == true)
                    {
                        float  ingotworth = Calculator(grid, "Ingot");
                        float  compworth  = Calculator(grid, "Component");
                        Double avg        = Math.Round((ingotworth + compworth) / 2f);
                        string message    = "This grid is " + grid.CustomName + " and is worth " + String.Format("{0:n0}", ingotworth) + " SC in ingots and " + String.Format("{0:n0}", compworth) + " SC in components";
                        MyAPIGateway.Utilities.ShowNotification(message, 950, "White");
                    }
                }
            }
        }
Esempio n. 31
0
        /// <summary>
        /// Fix up the blocks in ALL grids to have correct values
        /// This routine could also be used to set text panels for other languages.
        ///
        /// </summary>
        /// <param name="grid"></param>
        void BlocksFixup(IMyCubeGrid grid)
        {
            // fix up the Gatling blocks to have max range //V28
            var slimBlocksG = new List <IMySlimBlock>();

            grid.GetBlocks(slimBlocksG, b => b.FatBlock is IMyLargeGatlingTurret);
            foreach (var slim in slimBlocksG)
            {
                var gatling = slim.FatBlock as IMyLargeGatlingTurret;
                //              gatling.Range get only :(
            }
            // fix up the LCD blocks with show on hud // V27
            var slimBlocksT = new List <IMySlimBlock>();

            grid.GetBlocks(slimBlocksT, b => b.FatBlock is IMyTextPanel);
            foreach (var slim in slimBlocksT)
            {
                var textPanel = slim.FatBlock as IMyTextPanel;
                textPanel.ShowOnHUD = false;
            }

            // fix up the beacon blocks  // V26
            var slimBlocksB = new List <IMySlimBlock>();

            grid.GetBlocks(slimBlocksB, b => b.FatBlock is IMyBeacon);
            foreach (var slim in slimBlocksB)
            {
                var beacon = slim.FatBlock as IMyBeacon;
                if (beacon.CustomName.Contains("CLEANCE"))
                {
                    // beacon in HQ has spelling error
                    string sName = beacon.CustomName;
                    ModLog.Info("Fixing Beacon Text:" + sName);
                    beacon.CustomName = sName.Replace("CLEANCE", "CLEARANCE");
                }
            }

            // fix up the text panel blocks
            var slimBlocks = new List <IMySlimBlock>();

            grid.GetBlocks(slimBlocks, b => b.FatBlock is IMyTextPanel);
            foreach (var slim in slimBlocks)
            {
                var textPanel = slim.FatBlock as IMyTextPanel;
                //bool bShow = textPanel.GetValueBool("ShowTextOnScreen");
                // V 1.190
                bool bShow = textPanel.ContentType == VRage.Game.GUI.TextPanel.ContentType.TEXT_AND_IMAGE;
                //                bool bShow = textPanel.ShowOnScreen != VRage.Game.GUI.TextPanel.ShowTextOnScreenFlag.NONE;
                if (bShow)
                {
                    // We've already set this up once before (or world was created post 1.189

                    /* Try to fix text not showing on text panels
                     *
                     * (on further testing, panels are showing.. maybe Keen fixed this themselves?)
                     *
                     * Saw on Rity's stream that they were NOT showing in all places.
                     * And on EpikTek's https://www.youtube.com/watch?v=CkpGGPZd78k
                     * */
//                    textPanel.SetValue("ShowTextOnScreen", false);
//                    textPanel.SetValue("ShowTextOnScreen", true);
                    //                      textPanel.SetShowOnScreen(VRage.Game.GUI.TextPanel.ShowTextOnScreenFlag.PUBLIC);


                    // Could set text of text panels here to be language specific
                    //                  switch (textPanel.EntityId)
                    {
                        //Crashed Shuttle:92770753627258475
                        //{ X: 1868088.00058876 Y: -2003485.99356789 Z: 1316645.85240929}

                        /* Example of setting text:
                         * case 121786820996539580: //TEXT!
                         *  textPanel.WritePublicText(
                         *      "OUTGOING TRANSMISSION\n"
                         + "ERROR: FAILED TO SEND\n"
                         + "\n"
                         + "M,\n"
                         + "I'm going to Mars to talk to\n"
                         + "he CEO about what that\n"
                         + "weasel Bhaskar has been up to.\n"
                         + "I think we can trust him.\n"
                         + "                                \n"
                         + "-T\n"
                         +  );
                         +  break;
                         */
                    }
                }
// V26                else
                {
                    var strings = new List <string>();
                    textPanel.GetSelectedImages(strings);
                    textPanel.TextPadding = 0; //V26
                    if (strings.Count < 1)
                    {
                        // note: better method would be use use .CustomData of the textpanels.
                        // Using this EntityID method to be backward compatible with player's existing worlds.
                        switch (textPanel.EntityId)
                        {
                        //            long buildGuideID = 80461927256500036;
                        case 110371608100898677:     //TOOLS LOCKER
                            textPanel.FontSize    = 5;
                            textPanel.Alignment   = VRage.Game.GUI.TextPanel.TextAlignment.CENTER;
                            textPanel.TextPadding = 20f;         // 20%
                            textPanel.WriteText("TOOLS LOCKER"); // remove left padding from text
                            break;

                        case 143319951822334717:     //143319951822334717:TEXT!                                SPARE PARTS STORAGE
                            textPanel.FontSize    = 5;
                            textPanel.Alignment   = VRage.Game.GUI.TextPanel.TextAlignment.CENTER;
                            textPanel.TextPadding = 20f;     // 20%
//                                textPanel.WriteText("SPARE PARTS STORAGE");
                            break;

                        case 87005598531295535:     //87005598531295535TEXT!EMERGENCY SUPPLIES
                            textPanel.FontSize    = 5;
                            textPanel.Alignment   = VRage.Game.GUI.TextPanel.TextAlignment.CENTER;
                            textPanel.TextPadding = 20f;     // 20%
                            break;


                        case 80461927256500036:     // Crash ship build info screen
                            /* "old" text
                             * Mabel: Loading survival guide...
                             *
                             * > Recommend searching cargo
                             * and disassembling shuttle for
                             * rover parts
                             * > Recommend configuration:
                             * - Six wheels
                             * - Friction 10%
                             * - Damping 30%
                             * - Strength ~5%
                             * (Depends on load)
                             * - Speed Limit 100km/h
                             */
                            textPanel.WriteText("Mabel: Loading survival guide..." +
                                                "\n" +
                                                "\n> Recommend searching cargo" +
                                                "\n   and disassembling shuttle for" +
                                                "\n   rover parts" +
                                                "\n> Recommend configuration:" +
                                                "\n    -Six wheels" +
                                                "\n    - Friction 60%" +
                                                "\n    - *Strength 10%" +
                                                "\n    - *Power 50%" +
                                                "\n    - Speed Limit 50km/h" +
                                                "\n  * =Depends on load"
                                                );
                            break;

                        /*
                         * ((Ice Mine Entrance))
                         * Static Grid 1300:141864706275857195
                         * { X: 1869175.27852051 Y: -2004745.97266307 Z: 1316375.91819424}
                         * -----TEXTPANELS
                         * 74525033656413945:1:+LCD Panel 2
                         | Galactic Corporation Logo
                         */
                        case 74525033656413945:
                            textPanel.AddImageToSelection("Galactic Corporation Logo");
                            break;

                        // MIKI FIXUP
                        case 81986956045310309:
                            textPanel.AddImageToSelection("MikiScrap");
                            break;

                        case 103164071082162108:
                            textPanel.AddImageToSelection("MikiScrap");
                            break;

                        case 120342266177165062:
                            textPanel.AddImageToSelection("MikiScrap");
                            break;

                        case 96762650175047086:
                            textPanel.AddImageToSelection("MikiScrap");
                            break;

                        case 78808963600022563:
                            textPanel.AddImageToSelection("MikiScrap");
                            break;

                        case 102592293973822089:
                            textPanel.AddImageToSelection("MikiScrap");
                            break;

                        case 93732106466977771:
                            textPanel.AddImageToSelection("MikiScrap");
                            break;

                        case 119196087123513740:
                            textPanel.AddImageToSelection("MikiScrap");
                            break;

                        case 115470908890383058:
                            textPanel.AddImageToSelection("MikiScrap");
                            break;

                        case 84905149027762603:
                            textPanel.AddImageToSelection("MikiScrap");
                            break;

                        case 73748511314883089:
                            textPanel.AddImageToSelection("MikiScrap");
                            break;

                        case 108707493869969783:
                            textPanel.AddImageToSelection("MikiScrap");
                            break;

                        case 107003280298094914:
                            textPanel.AddImageToSelection("MikiScrap");
                            break;

                        case 93717234609661072:
                            textPanel.AddImageToSelection("MikiScrap");
                            break;

                        case 100685062896355827:
                            textPanel.AddImageToSelection("MikiScrap");
                            break;

                        //green house
                        case 110846399081478285:
                            textPanel.AddImageToSelection("MRE Logo");
                            break;

                        //                                Signal Station:139030682896359375
                        //{ X: 1844500.54997961 Y: -1995403.72976435 Z: 1323630.52767273}
                        case 132717438306395557:
                            textPanel.AddImageToSelection("MRE Logo");
                            break;

                        //                                ((MRE MedBay 2))
                        //MRE Emergency Medical Station:120085596920753880
                        //{ X: 1844533.71376673 Y: -1995424.91354928 Z: 1323629.33162825}
                        case 104050761648970549:
                            textPanel.AddImageToSelection("MRE Logo");
                            break;

                        // {X:1856577.01869837 Y:-1999257.98373971 Z:1321414.17733138}
                        case 110250540272021112:
                            textPanel.AddImageToSelection("Galactic Corporation Logo");
                            break;

                        //  {X:1857176.1781222 Y:-2000013.37619576 Z:1321553.01815169}
                        case 89933889116515952:
                            textPanel.AddImageToSelection("Galactic Corporation Logo");
                            break;

                        //((and another HQ SAM))
                        //GCorp Mobile SAM: 89611551362269325
                        //{ X: 1857213.83363977 Y: -1998518.53635201 Z: 1320657.55013411}
                        case 95067624877541028:
                            textPanel.AddImageToSelection("Galactic Corporation Logo");
                            break;

                        //((another HQ SAM))
                        //GCorp Mobile SAM: 104043950566026386
                        //{ X: 1858538.51759973 Y: -1999989.95859322 Z: 1320777.02901595}
                        case 120326586562634149:
                            textPanel.AddImageToSelection("Galactic Corporation Logo");
                            break;

                        //((Bunker in weapons Research))
                        //GCorp Bunker:132649980418733079
                        //{ X: 1843291.04608973 Y: -1996439.44943181 Z: 1324491.09281518}
                        case 102565050409374890:
                            textPanel.AddImageToSelection("Galactic Corporation Logo");
                            textPanel.AddImageToSelection("Automation Simplified");
                            break;

                        case 76555655031247133:
                            textPanel.AddImageToSelection("Galactic Corporation Logo");
                            textPanel.AddImageToSelection("Automation Simplified");
                            break;

                        case 82207545563969038:
                            textPanel.AddImageToSelection("Galactic Corporation Logo");
                            textPanel.AddImageToSelection("Automation Simplified");
                            break;

                        case 140611613672853263:
                            textPanel.AddImageToSelection("Galactic Corporation Logo");
                            textPanel.AddImageToSelection("Automation Simplified");
                            break;

                        //((Air Research))
                        //GCorp Flight Research Center:76779347935557670
                        //{ X: 1854754.1883761 Y: -2005852.06052194 Z: 1325419.84578841}
                        case 91899503586440685:
                            textPanel.AddImageToSelection("Clouds");
                            break;

                        case 89540866723022250:
                            textPanel.AddImageToSelection("Clouds");
                            break;

                        case 139513180460721275:
                            textPanel.AddImageToSelection("Clouds");
                            break;

                        case 123742114812299814:
                            textPanel.AddImageToSelection("Clouds");
                            break;

                        case 72707843196346809:
                            textPanel.AddImageToSelection("Clouds");
                            break;

                        case 84058947393377852:
                            textPanel.AddImageToSelection("Clouds");
                            break;

                        case 124309978476859628:
                            textPanel.AddImageToSelection("Clouds");
                            break;

                        case 85895320964444780:
                            textPanel.AddImageToSelection("Clouds");
                            break;

                        case 117967784354173602:
                            textPanel.AddImageToSelection("Clouds");
                            break;

                        case 128468555565951583:
                            textPanel.AddImageToSelection("Clouds");
                            break;

                        case 107231006349635239:
                            textPanel.AddImageToSelection("Clouds");
                            break;

                        //((MRE hidden Base))
                        //MRE Experiment Base: 104361129531664144
                        //{ X: 1858398.21613573 Y: -1989137.98910994 Z: 1312706.48643797}
                        case 98971232666660757:
                            textPanel.AddImageToSelection("MRE Logo");
                            break;

                        case 97512105090353134:
                            textPanel.AddImageToSelection("MRE Logo");
                            break;

                        case 81228556864103207:
                            textPanel.AddImageToSelection("MRE Logo");
                            break;

                        //((HQ))
                        //GCorp HQ Tower: 144104082158837389
                        //{ X: 1857310.65834681 Y: -1999316.80991158 Z: 1321066.96761458}
                        case 125129893494374181:
                            textPanel.AddImageToSelection("White screen");
                            break;

                        case 134131747655270782:
                            textPanel.AddImageToSelection("White screen");
                            break;

                        case 74727284886995000:
                            textPanel.AddImageToSelection("White screen");
                            break;

                        case 98708608904781783:
                            textPanel.AddImageToSelection("White screen");
                            break;

                        case 138656136990359379:
                            textPanel.AddImageToSelection("White screen");
                            break;

                        case 80870473015345748:
                            textPanel.AddImageToSelection("Galactic Corporation Logo");
                            break;

                        case 98370398719554346:
                            textPanel.AddImageToSelection("White screen");
                            break;

                        case 80724503483430325:
                            textPanel.AddImageToSelection("White screen");
                            break;

                        case 87324639907322082:
                            textPanel.AddImageToSelection("White screen");
                            break;

                        case 110549946960318740:
                            textPanel.AddImageToSelection("Galactic Corporation Logo");
                            textPanel.AddImageToSelection("Automation Simplified");
                            break;

                        case 142860245424722839:
                            textPanel.AddImageToSelection("Galactic Corporation Logo");
                            textPanel.AddImageToSelection("Automation Simplified");
                            break;

                        case 117922822138601150:
                            textPanel.AddImageToSelection("Galactic Corporation Logo");
                            textPanel.AddImageToSelection("Automation Simplified");
                            break;

                        // ((HQ Rocket))
                        //GCorp Space Transport: 97585502667028994
                        //{ X: 1857324.30678431 Y: -1999293.08872018 Z: 1321075.17171614}
                        case 140237983630899577:
                            textPanel.AddImageToSelection("Galactic Corporation Logo");
                            break;

                        case 105805752262318800:
                            textPanel.AddImageToSelection("Arrow");
                            break;

                        case 104593951810486921:
                            textPanel.AddImageToSelection("Galactic Corporation Logo");
                            textPanel.AddImageToSelection("Automation Simplified");
                            break;

                        case 141641456443241951:
                            textPanel.AddImageToSelection("Galactic Corporation Logo");
                            textPanel.AddImageToSelection("Automation Simplified");
                            break;

                        case 101582007425482292:
                            textPanel.AddImageToSelection("Galactic Corporation Logo");
                            textPanel.AddImageToSelection("Automation Simplified");
                            break;

                        case 80366112655444611:
                            textPanel.AddImageToSelection("Galactic Corporation Logo");
                            textPanel.AddImageToSelection("Automation Simplified");
                            break;
                        }
                    }
                }
            }

            // fix up the sound blocks
            var slimBlocks2 = new List <IMySlimBlock>();

            grid.GetBlocks(slimBlocks2, b => b.FatBlock is IMySoundBlock);
            foreach (var slim in slimBlocks2)
            {
                var soundBlock = slim.FatBlock as IMySoundBlock; // Fixed V21
//                if (soundBlock == null) continue; // why do we need this?
                switch (soundBlock.EntityId)
                {
                // air base alpha:
                case 116378614635193269:
                    soundBlock.SelectedSound = "WelcomeToGcorp";
                    break;

                // ice mine entrance
                case 101979433782763108:
                    soundBlock.SelectedSound = "NotAuthorisedDeployDefences";
                    break;

                // ice mine shaft botom
                case 106640376870960334:
                    soundBlock.SelectedSound = "MineClosed";
                    break;

                //((Upper Ice Mine Meeting Room))
                //{ X: 1869176.67818993 Y: -2004930.50366838 Z: 1316377.58089576}
                case 80185389104537910:
                    soundBlock.SelectedSound = "BigSwitch";
                    break;

                // MRE HIdden base
                case 95206901925432014:
                    soundBlock.SelectedSound = "BigSwitch";
                    break;

                case 100498114358496283:
                    soundBlock.SelectedSound = "BigSwitch";
                    break;

                case 77589249328205128:
                    soundBlock.SelectedSound = "BigSwitch";
                    break;

                case 104066113506074975:
                    soundBlock.SelectedSound = "BigSwitch";
                    break;

                case 90866709199081947:
                    soundBlock.SelectedSound = "BigSwitch";
                    break;

                case 141427853315146800:
                    soundBlock.SelectedSound = "BigSwitch";
                    break;

                case 116242415031561830:
                    soundBlock.SelectedSound = "BigSwitch";
                    break;

                case 110850485077900653:
                    soundBlock.SelectedSound = "BigSwitch";
                    break;

                case 88298229398547791:
                    soundBlock.SelectedSound = "BigSwitch";
                    break;


                // wrecked drone
                case 102293828213773618:
                    soundBlock.SelectedSound = "PowerUpClipped";
                    break;

                //((old drone @ hangar 1))
                case 108074122634121508:
                    soundBlock.SelectedSound = "PowerUpClipped";
                    break;

                // air research
                case 84998344586050021:
                    soundBlock.SelectedSound = "SoundBlockAlert2";
                    break;

                case 91070301367474416:
                    soundBlock.SelectedSound = "AirplaneSound";
                    break;

                case 90629854631902381:
                    soundBlock.SelectedSound = "FlightResearchExhibition";
                    break;

                // air base beta
                case 130193226083241264:
                    soundBlock.SelectedSound = "WelcomeToGcorp";
                    break;

                // mech
                case 82762879450865423:
                    //            bodyGrid.SetSoundBlocks("Mech Intruders Must Be Destroyed"); // fix missing sound on sound block on mech
                    soundBlock.SelectedSound = "IntruderRobot";
                    break;

                // HQ
                case 95872484442737911:
                    soundBlock.SelectedSound = "SoundBlockAlert1";
                    break;

                case 82604291774017685:
                    soundBlock.SelectedSound = "WelcomeToGcorp";
                    break;

                // MIKI
                case 129379111872365143:
                    soundBlock.SelectedSound = "Carmen";
                    break;

                case 140249950038454545:
                    soundBlock.SelectedSound = "LavaLoop";
                    break;
                }
            }
        }
Esempio n. 32
0
        public override bool HandleCommand(ulong userId, string[] words)
        {
            if (!PluginSettings.Instance.DockingEnabled)
            {
                return(false);
            }

            if (words.Length < 1)
            {
                Communication.SendPrivateInformation(userId, GetHelp());
                return(true);
            }

            if (m_docking)
            {
                Communication.SendPrivateInformation(userId, "Server is busy");
                return(true);
            }

            m_docking = true;
            try
            {
                String pylonName = String.Join(" ", words);

                /*
                 * int timeLeft;
                 * if (Entity.CheckCoolDown(pylonName, out timeLeft))
                 * {
                 *      Communication.Message(String.Format("The docking zone '{0}' is on cooldown.  Please wait a {1} seconds before trying to dock/undock again.", pylonName, Math.Max(0, timeLeft)));
                 *      return;
                 * }
                 */

                if (PlayerMap.Instance.GetPlayerIdsFromSteamId(userId).Count < 1)
                {
                    Communication.SendPrivateInformation(userId, string.Format("Unable to find player Id: {0}", userId));
                    return(true);
                }

                long playerId = PlayerMap.Instance.GetPlayerIdsFromSteamId(userId).First();

                Dictionary <String, List <IMyCubeBlock> > testList;
                List <IMyCubeBlock> beaconList;
                DockingZone.FindByName(pylonName, out testList, out beaconList, playerId);
                if (beaconList.Count == 4)
                {
                    // Check ownership
                    foreach (IMyCubeBlock entityBlock in beaconList)
                    {
                        IMyTerminalBlock terminal = (IMyTerminalBlock)entityBlock;
                        if (!terminal.HasPlayerAccess(playerId))
                        {
                            Communication.SendPrivateInformation(userId, string.Format("You do not have permission to use '{0}'.  You must either own all the beacons or they must be shared with faction.", pylonName));
                            return(true);
                        }
                    }

                    // Check for bounding box intsection of other docking zones
                    int intersectElement = 0;
                    if (Entity.CheckForIntersection(testList, beaconList, out intersectElement))
                    {
                        Communication.SendPrivateInformation(userId, string.Format("The docking zone '{0}' intersects with docking zone '{1}'.  Make sure you place your docking zones so they don't overlap.", pylonName, testList.ElementAt(intersectElement).Key));
                        return(true);
                    }

                    // Check if ship already docked in this zone
                    IMyCubeBlock       e             = beaconList[0];
                    IMyCubeGrid        parent        = (IMyCubeGrid)e.Parent;
                    long[]             beaconListIds = beaconList.Select(b => b.EntityId).ToArray();
                    long               ownerId       = beaconList.First().OwnerId;
                    List <DockingItem> checkItems    = Docking.Instance.Find(d => d.PlayerId == ownerId && d.TargetEntityId == parent.EntityId && d.DockingBeaconIds.Intersect(beaconListIds).Count() == 4);
                    if (checkItems.Count >= PluginSettings.Instance.DockingShipsPerZone)
                    {
                        Communication.SendPrivateInformation(userId, string.Format("Docking zone already '{0}' already contains the maximum capacity of ships.", pylonName));
                        return(true);
                    }

                    // Figure out center of docking area, and other distance information
                    double   maxDistance = 99;
                    Vector3D vPos        = new Vector3D(0, 0, 0);

                    foreach (IMyCubeBlock b in beaconList)
                    {
                        Vector3D beaconPos = Entity.GetBlockEntityPosition(b);
                        vPos += beaconPos;
                    }

                    vPos = vPos / 4;
                    foreach (IMyCubeBlock b in beaconList)
                    {
                        Vector3D beaconPos = Entity.GetBlockEntityPosition(b);
                        maxDistance = Math.Min(maxDistance, Vector3D.Distance(vPos, beaconPos));
                    }

                    // Find ship in docking area
                    IMyCubeGrid         dockingEntity = null;
                    HashSet <IMyEntity> cubeGrids     = new HashSet <IMyEntity>();
                    MyAPIGateway.Entities.GetEntities(cubeGrids, f => f is IMyCubeGrid);
                    foreach (IMyCubeGrid gridCheck in cubeGrids)
                    {
                        if (gridCheck.IsStatic || gridCheck == parent)
                        {
                            continue;
                        }

                        double distance = Vector3D.Distance(gridCheck.GetPosition(), vPos);
                        if (distance < maxDistance)
                        {
                            dockingEntity = gridCheck;
                            break;
                        }
                    }

                    // Figure out if the ship fits in docking area, and then save ship
                    if (dockingEntity != null)
                    {
                        // Get bounding box of both the docking zone and docking ship
                        OrientedBoundingBoxD targetBounding  = Entity.GetBoundingBox(beaconList);
                        OrientedBoundingBoxD dockingBounding = Entity.GetBoundingBox(dockingEntity);

                        // Make sure the docking zone contains the docking ship.  If they intersect or are disjointed, then fail
                        if (!Entity.GreaterThan(dockingBounding.HalfExtent * 2, targetBounding.HalfExtent * 2))
                        {
                            Communication.SendPrivateInformation(userId, string.Format("The ship '{0}' is too large for it's carrier.  The ship's bounding box must fit inside the docking zone bounding box!", dockingEntity.DisplayName));
                            return(true);
                        }

                        if (targetBounding.Contains(ref dockingBounding) != ContainmentType.Contains)
                        {
                            Communication.SendPrivateInformation(userId, string.Format("The ship '{0}' is not fully inside the docking zone '{1}'.  Make sure the ship is fully contained inside the docking zone", dockingEntity.DisplayName, pylonName));
                            return(true);
                        }

                        // Calculate the mass and ensure the docking ship is less than half the mass of the dock
                        float parentMass  = Entity.CalculateMass(parent);
                        float dockingMass = Entity.CalculateMass(dockingEntity);
                        if (dockingMass > parentMass)
                        {
                            Communication.SendPrivateInformation(userId, string.Format("The ship you're trying to dock is too heavy for it's carrier.  The ship mass must be less than half the large ship / stations mass! (DM={0}kg CM={1}kg)", dockingMass, parentMass));
                            return(true);
                        }

                        // Check to see if the ship is piloted, if it is, error out.
                        // TODO: Check to see if we can get a real time copy of this entity?
                        List <IMySlimBlock> blocks = new List <IMySlimBlock>();
                        dockingEntity.GetBlocks(blocks, x => x.FatBlock != null && x.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_Cockpit));
                        foreach (IMySlimBlock slim_cbe in blocks)
                        {
                            MyObjectBuilder_Cockpit c = (MyObjectBuilder_Cockpit)slim_cbe.FatBlock.GetObjectBuilderCubeBlock();
                            if (c.Pilot != null)
                            {
                                Communication.SendPrivateInformation(userId, string.Format("Ship in docking zone '{0}' has a pilot!  Please exit the ship before trying to dock.  (Sometimes this can lag a bit.  Wait 10 seconds and try again)", pylonName));
                                return(true);
                            }
                        }

                        // Save position and rotation information.  Some fun stuff here.
                        // Get our dock rotation as a quaternion
                        Quaternion saveQuat = Quaternion.CreateFromRotationMatrix(parent.WorldMatrix.GetOrientation());
                        // Transform docked ship's local position by inverse of the the parent (unwinds parent) and save it for when we undock
                        Vector3D savePos = Vector3D.Transform(dockingEntity.GetPosition() - parent.GetPosition(), Quaternion.Inverse(saveQuat));
                        // Get local rotation of dock ship, and save it for when we undock
                        saveQuat = Quaternion.Inverse(saveQuat) * Quaternion.CreateFromRotationMatrix(dockingEntity.WorldMatrix.GetOrientation());

                        // Save ship to file and remove
                        FileInfo info = new FileInfo(Essentials.PluginPath + String.Format("\\Docking\\docked_{0}_{1}_{2}.sbc", ownerId, parent.EntityId, dockingEntity.EntityId));
                        //CubeGridEntity dockingGrid = new CubeGridEntity((MyObjectBuilder_CubeGrid)dockingEntity.GetObjectBuilder(), dockingEntity);
                        MyObjectBuilder_CubeGrid gridBuilder = CubeGrids.SafeGetObjectBuilder(dockingEntity);
                        if (gridBuilder == null)
                        {
                            Communication.SendPrivateInformation(userId, string.Format("Failed to load entity for export: {0}", dockingEntity.DisplayName));
                            return(true);
                        }

                        // Save item
                        DockingItem dockItem = new DockingItem();
                        dockItem.DockedEntityId   = dockingEntity.EntityId;
                        dockItem.TargetEntityId   = parent.EntityId;
                        dockItem.PlayerId         = ownerId;
                        dockItem.DockingBeaconIds = beaconList.Select(s => s.EntityId).ToArray();
                        dockItem.DockedName       = dockingEntity.DisplayName;
                        dockItem.SavePos          = savePos;
                        dockItem.SaveQuat         = saveQuat;
                        Docking.Instance.Add(dockItem);

                        // Serialize and save ship to file
                        BaseObjectManager.WriteSpaceEngineersFile <MyObjectBuilder_CubeGrid, MyObjectBuilder_CubeGridSerializer>(gridBuilder, info.FullName);
                        //BaseObjectManager.SaveContentFile<MyObjectBuilder_CubeGrid, MyObjectBuilder_CubeGridSerializer>(gridBuilder, info);
                        BaseEntityNetworkManager.BroadcastRemoveEntity(dockingEntity);
                        //dockingEntity.Close();

                        Communication.SendPrivateInformation(userId, string.Format("Docked ship '{0}' in docking zone '{1}'.", dockItem.DockedName, pylonName));

                        /*
                         * // Add a cool down
                         * DockingCooldownItem cItem = new DockingCooldownItem();
                         * cItem.name = pylonName;
                         * cItem.startTime = DateTime.Now;
                         * PluginDocking.CooldownList.Add(cItem);
                         */
                    }
                    else
                    {
                        Communication.SendPrivateInformation(userId, string.Format("No ships in docking zone '{0}'.", pylonName));
                    }
                }
                else if (beaconList.Count > 4)
                {
                    Communication.SendPrivateInformation(userId, string.Format("Too many beacons with the name or another zone with the name '{0}'.  Place only 4 beacons to create a zone or try a different zone name.", pylonName));
                }
                else
                {
                    Communication.SendPrivateInformation(userId, string.Format("Can not locate docking zone '{0}'.  There must be 4 beacons with the name '{0}' to create a docking zone.  Beacons must be fully built!", pylonName));
                }

                return(true);
            }
            finally
            {
                m_docking = false;
            }
        }
		private void DisableGrid(IMyCubeGrid grid)
		{
			HashSet<long> disabledBlocks = new HashSet<long>();
			List<IMySlimBlock> blocks = new List<IMySlimBlock>();
			grid.GetBlocks(blocks);

			foreach (IMySlimBlock block in blocks)
			{
				if (block.FatBlock == null)
					continue;

				IMyCubeBlock cubeBlock = block.FatBlock;

				if(!(cubeBlock is IMyFunctionalBlock))
					continue;

				if (cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_Reactor) ||
					cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_Thrust) ||
					cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_Battery) ||
					cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_SolarPanel) ||
					cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_Gyro) ||
					cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_MedicalRoom))
				{
					continue;
				}

				if(cubeBlock is IMyProductionBlock)
				{
					IMyProductionBlock productionBlock = (IMyProductionBlock)cubeBlock;

					if (productionBlock.IsProducing)
						continue;
				}

				if (FunctionalBlockEntity.GetState(cubeBlock))
				{
					FunctionalBlockEntity.SetState(cubeBlock, false);
					disabledBlocks.Add(cubeBlock.EntityId);
					_enableCount++;
				}
			}

			lock (GridDisabled)
			{
				GridDisabled.Add(grid.EntityId);
				//if (disabledBlocks.Count > 0)
				//{
					Console.WriteLine("Adding");
					GridBlocksDisabled.Add(grid.EntityId, disabledBlocks);
				//}				
			}
		}
        private void _cubeGrid_OnBlockOwnershipChanged(IMyCubeGrid cubeGrid)
        {
            // only execute on server instance
            if (ChatCommandLogic.Instance != null && ChatCommandLogic.Instance.ServerCfg == null)
                return;

            if (_firstOwnershipChange)
            {
                _firstOwnershipChange = false;
                _cachedOwners = new List<long>(cubeGrid.GetAllSmallOwners());
                return;
            }

            var allSmallOwners = cubeGrid.GetAllSmallOwners();

            if (_cachedOwners == allSmallOwners)
                return;

            // if the grid wasn't owned or a owner was removed, we dont need to do anything but update the cached owners
            if (_cachedOwners.Count == 0 || _cachedOwners.Count > allSmallOwners.Count)
            {
                _cachedOwners = new List<long>(allSmallOwners);
                return;
            }

            var newOwners = allSmallOwners.Except(_cachedOwners).ToList();

            if (newOwners.Count == 0)
                return;

            if (!ProtectionHandler.IsProtected(cubeGrid))
            {
                _cachedOwners = new List<long>(allSmallOwners);
                return;
            }

            Dictionary<long, int> blocksPerOwner = new Dictionary<long, int>();

            foreach (IMyCubeGrid attachedCubeGrid in cubeGrid.GetAttachedGrids(AttachedGrids.Static))
            {

                List<IMySlimBlock> blocks = new List<IMySlimBlock>();
                attachedCubeGrid.GetBlocks(blocks, b => b.FatBlock != null);

                foreach (IMySlimBlock block in blocks)
                {
                    long ownerId = block.FatBlock.OwnerId;

                    // we dont want the new owners, the small owners or the 'nobody' (0)
                    if (ownerId == 0 || !attachedCubeGrid.BigOwners.Contains(ownerId) || newOwners.Contains(ownerId))
                        continue;

                    if (!blocksPerOwner.ContainsKey(ownerId))
                        blocksPerOwner.Add(ownerId, 1);
                    else
                        blocksPerOwner[ownerId]++;
                }
            }

            var sortedBpo = new List<KeyValuePair<long, int>>(blocksPerOwner.OrderBy(pair => pair.Value));

            // if we cannot identify an owner we allow the change
            if (sortedBpo.Count == 0)
            {
                _cachedOwners = new List<long>(allSmallOwners);
                return;
            }

            var bigOwner = sortedBpo[0].Key;

            List<IMySlimBlock> ownershipChangedBlocks = new List<IMySlimBlock>();
            cubeGrid.GetBlocks(ownershipChangedBlocks, b => b.FatBlock != null && newOwners.Contains(b.FatBlock.OwnerId));
            foreach (IMySlimBlock slimBlock in ownershipChangedBlocks)
            {
                var block = (Sandbox.Game.Entities.MyCubeBlock)slimBlock.FatBlock;
                block.ChangeOwner(bigOwner, MyOwnershipShareModeEnum.None);
                ConnectionHelper.SendMessageToAllPlayers(new MessageSyncBlockOwner() {OwnerId = bigOwner, EntityId = block.EntityId});
                // no need to update the cached owners as we don't want them to change
            }

            // TODO maybe allow the faction to build...
        }
Esempio n. 35
0
 private static void GetGridBlocks( IMyCubeGrid grid, List<IMySlimBlock> blockList, Func<IMySlimBlock, bool> collect = null )
 {
     blockList.Clear( );
     List<IMySlimBlock> blocks = new List<IMySlimBlock>( );
     grid.GetBlocks( blocks, collect );
     blockList.AddRange( blocks );
 }
Esempio n. 36
0
        public int SetPBScripts(string scriptName, string PBTag, IMyCubeGrid grid)
        {
            int scriptsChangedCount = 0;

            List <IMySlimBlock> blocks = new List <IMySlimBlock>();
            List <IMySlimBlock> temp   = new List <IMySlimBlock>();

            grid.GetBlocks(blocks);

            for (int i = 0; i < blocks.Count; i++)
            {
                var myProgrammable = blocks[i].FatBlock as IMyProgrammableBlock;

                if (myProgrammable == null || !myProgrammable.CustomName.Contains(PBTag))
                {
                    continue;
                }


                string program = "";
                try
                {
                    program = File.ReadAllText(Path.Combine(new string[]
                    {
                        MyFileSystem.UserDataPath,
                        "IngameScripts",
                        "local",
                        scriptName,
                        "script.cs"
                    }));
                } catch (FileNotFoundException e)
                {
                    try
                    {
                        program = File.ReadAllText(Path.Combine(new string[]
                        {
                            MyFileSystem.UserDataPath,
                            "IngameScripts",
                            "local",
                            scriptName,
                            "Script.cs"
                        }));
                    } catch (FileNotFoundException f)
                    {
                        continue;
                    }
                } catch (DirectoryNotFoundException e)
                {
                    continue;
                }

                if (program == "")
                {
                    continue;
                }

                myProgrammable.ProgramData = program;
                scriptsChangedCount++;
            }

            return(scriptsChangedCount);
        }
Esempio n. 37
0
        public static void UpdateLcdOutput(IMyEntity entity, StationBase station, bool searchOnConnectedGrids = false)
        {
            IMyCubeGrid cubeGrid = entity.GetTopMostParent() as IMyCubeGrid;

            List <IMySlimBlock> textPanels = new List <IMySlimBlock>();

            if (cubeGrid == null)
            {
                return;
            }
            cubeGrid.GetBlocks(
                textPanels,
                e => e?.FatBlock != null && e.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_TextPanel)
                );

            if (searchOnConnectedGrids)
            {
                var connectedShips = GridApi.GetConnectedShips(entity);

                foreach (var connector in connectedShips.Keys)
                {
                    var grid = connectedShips[connector];
                    if (grid == null)
                    {
                        continue;
                    }
                    List <IMySlimBlock> panels = new List <IMySlimBlock>();
                    grid.GetBlocks(
                        panels,
                        e => e?.FatBlock != null &&
                        e.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_TextPanel)
                        );
                    textPanels.AddRange(panels);
                }
            }
            if (textPanels.Count <= 0)
            {
                return;
            }

            Dictionary <string, StringBuilder> output = new Dictionary <string, StringBuilder>();
            IOutputRepresentor outputRepresentor      = StationOutputFactory.CreateRepresentor(station);

            outputRepresentor.CreateOutput(output, cubeGrid);

            foreach (var lcd in textPanels)
            {
                var myLcd = lcd.FatBlock as IMyTextPanel;

                if (myLcd == null)
                {
                    continue;
                }
                var title = myLcd.GetPublicTitle().ToLower();

                if (title.IndexOf("info", StringComparison.Ordinal) != 0)
                {
                    continue;
                }

                foreach (KeyValuePair <string, StringBuilder> pair in output)
                {
                    string lcdTextInfo = "";

                    if (!title.Contains(pair.Key.ToLower()))
                    {
                        continue;
                    }

                    lcdTextInfo = pair.Value.ToString();

                    if (lcdTextInfo == myLcd.GetPublicText())
                    {
                        continue;
                    }

                    myLcd.WritePublicText(lcdTextInfo);
                    myLcd.ShowPublicTextOnScreen();
                }
            }
        }
Esempio n. 38
0
        public override void GridInitialising(IMyCubeGrid grid)
        {
//            ModLog.Info("Checking grid: " + grid.CustomName);

            // TODO: Limit to certain owners?
            // TODO: prevent player from pasting or building and then game loading something with unlock codes.

            // find unlock points
            var slimBlocks = new List <IMySlimBlock>();

            // limit to PBs for now..  could do it from ANYTHING, really...
            grid.GetBlocks(slimBlocks, b => b.FatBlock is IMyProgrammableBlock);
            foreach (var slim in slimBlocks)
            {
                var tb = slim.FatBlock as IMyTerminalBlock;

//                ModLog.Info("Checking PB:" + pb.CustomName);

                string data = tb.CustomData;
                if (data.Contains("[WICORESEARCH]"))
                {
                    int      techgroup = -1;
                    Vector3D location  = tb.GetPosition();
                    //                    ModLog.Info("Found our section");
                    // get an array of the all of lines
                    string[] aLines = data.Split('\n');

                    // walk through all of the lines
                    for (int iLine = 0; iLine < aLines.Count(); iLine++)
                    {
                        if (aLines[iLine].Contains("[WICORESEARCH]"))
                        {
                            //                          ModLog.Info("Found our section  2");
                            int foundCount = 0;
                            // we found our section
                            int iSectionLine = iLine + 1;
                            for (; iSectionLine < aLines.Count(); iSectionLine++)
                            {
                                if (aLines[iSectionLine].StartsWith("["))
                                {
                                    iSectionLine--;
                                    break;
                                }
                                string   sLine     = aLines[iSectionLine].Trim();
                                string[] aKeyValue = sLine.Split('=');
                                if (aKeyValue.Count() > 1)
                                {
                                    // key is 0 value is 1
                                    if (aKeyValue[0] == "Group")
                                    {
//                                        ModLog.Info("Found Group:"+aLines[iSectionLine]);
                                        int  iTest;
                                        bool bOK = int.TryParse(aKeyValue[1], out iTest);
                                        if (bOK)
                                        {
                                            techgroup = iTest;
                                            foundCount++;
                                        }
                                        else
                                        {
                                            ModLog.Info("group parse fail");
                                        }
                                    }
                                    if (aKeyValue[0] == "Location")
                                    {
                                        Vector3D testLocation;
                                        bool     bOK = Vector3D.TryParse(aKeyValue[1], out testLocation);
                                        if (bOK)
                                        {
                                            location = testLocation;
                                        }
                                        foundCount++;
                                    }
                                }
                            }
                            iLine = iSectionLine;
//                            ModLog.Info("Foundcount=" + foundCount.ToString());
                            if (foundCount > 0)
                            {
                                UnlockLocation ul = new UnlockLocation();
                                ul.location  = location;
                                ul.techGroup = techgroup;
//                                ModLog.Info("Adding research unlock from: " + pb.CustomName);
                                unlockLocationList.Add(ul);
                            }
                        }
                    }
                }
            }
        }
        //public readonly static Dictionary<long, IMyCubeGrid> Grids = new Dictionary<long, IMyCubeGrid>();

        public static void DeconstructGrid(IMyInventory inventory, ref IMyCubeGrid SelectedGrid, ref List <MyObjectBuilder_InventoryItem> Items)
        {
            Items.Clear();
            var Blocks = new List <IMySlimBlock>();

            SelectedGrid.GetBlocks(Blocks);
            MyObjectBuilder_PhysicalObject physicalObjBuilder;
            MyPhysicalInventoryItem        phys;
            MyObjectBuilder_CubeBlock      Obj;
            var InvItems = new List <VRage.Game.ModAPI.Ingame.MyInventoryItem>();

            MyDefinitionId Id;

            foreach (var block in Blocks)
            {
                block.FullyDismount(inventory);
                Obj = block.GetObjectBuilder();
                if (Obj.ConstructionStockpile != null)
                {
                    for (var i = 0; i < Obj.ConstructionStockpile.Items.Count(); i++)
                    {
                        phys = new MyPhysicalInventoryItem(Obj.ConstructionStockpile.Items[i].Amount, Obj.ConstructionStockpile.Items[i].PhysicalContent);
                        Id   = phys.Content.GetObjectId();
                        if (!TempItems.ContainsKey(Id))
                        {
                            TempItems.Add(Id, phys);
                        }
                        else
                        {
                            TempItems[Id] = new MyPhysicalInventoryItem(phys.Amount + TempItems[Id].Amount, phys.Content);
                        }
                    }
                }
                if (block.FatBlock != null && block.FatBlock.HasInventory)
                {
                    InvItems.Clear();
                    block.FatBlock.GetInventory().GetItems(InvItems);

                    for (var i = 0; i < InvItems.Count; i++)
                    {
                        physicalObjBuilder = (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject((MyDefinitionId)InvItems[i].Type);
                        phys = new MyPhysicalInventoryItem(InvItems[i].Amount, physicalObjBuilder);
                        Id   = phys.Content.GetObjectId();
                        if (!TempItems.ContainsKey(Id))
                        {
                            TempItems.Add(Id, phys);
                        }
                        else
                        {
                            TempItems[Id] = new MyPhysicalInventoryItem(phys.Amount + TempItems[Id].Amount, phys.Content);
                        }
                    }
                }
            }

            foreach (var item in TempItems)
            {
                Items.Add(item.Value.GetObjectBuilder());
            }
            TempItems.Clear();
        }
		public void EnableGrid(IMyCubeGrid grid)
		{
			List<IMySlimBlock> blocks = new List<IMySlimBlock>();
			grid.GetBlocks(blocks);

			lock (GridDisabled)
			{
				if (!GridBlocksDisabled.ContainsKey(grid.EntityId))
				{
					if (GridDisabled.Contains(grid.EntityId))
						GridDisabled.Remove(grid.EntityId);

					return;
				}
			}

			HashSet<long> disabledBlocks = GridBlocksDisabled[grid.EntityId];
			
			foreach (IMySlimBlock block in blocks)
			{
				if (block.FatBlock == null)
					continue;

				IMyCubeBlock cubeBlock = block.FatBlock;

				if (!(cubeBlock is IMyFunctionalBlock))
					continue;

				if (!disabledBlocks.Contains(cubeBlock.EntityId))
					continue;

				if (!FunctionalBlockEntity.GetState(cubeBlock))
				{
					FunctionalBlockEntity.SetState(cubeBlock, true);
					_enableCount++;
				}
			}

			lock (GridDisabled)
			{
				if(GridDisabled.Contains(grid.EntityId))
					GridDisabled.Remove(grid.EntityId);

				GridBlocksDisabled.Remove(grid.EntityId);
			}
		}
Esempio n. 41
0
 public static void GetBlocks_Safe(this IMyCubeGrid grid, List <IMySlimBlock> blocks, Func <IMySlimBlock, bool> collect = null)
 {
     UsingShared(() => grid.GetBlocks(blocks, collect));
 }
Esempio n. 42
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 Sandbox.ModAPI.Ingame.IMyBeacon))
                    continue;

                Sandbox.ModAPI.Ingame.IMyBeacon beacon = (Sandbox.ModAPI.Ingame.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;
        }
Esempio n. 43
0
        private static void GetAttachedGrids(IMyCubeGrid cubeGrid, ref List <IMyCubeGrid> results, AttachedGrids type)
        {
            if (cubeGrid == null)
            {
                return;
            }

            var blocks = new List <IMySlimBlock>();

            cubeGrid.GetBlocks(blocks, b => b != null && b.FatBlock != null && !b.FatBlock.BlockDefinition.TypeId.IsNull);

            foreach (var block in blocks)
            {
                //MyAPIGateway.Utilities.ShowMessage("Block", string.Format("{0}", block.FatBlock.BlockDefinition.TypeId));

                if (block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_MotorAdvancedStator) ||
                    block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_MotorStator) ||
                    block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_MotorSuspension) ||
                    block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_MotorBase))
                {
                    // The MotorStator which inherits from MotorBase.
                    var motorBase = block.GetObjectBuilder() as MyObjectBuilder_MotorBase;
                    if (motorBase == null || !motorBase.RotorEntityId.HasValue || motorBase.RotorEntityId.Value == 0 || !MyAPIGateway.Entities.EntityExists(motorBase.RotorEntityId.Value))
                    {
                        continue;
                    }
                    var entityParent = MyAPIGateway.Entities.GetEntityById(motorBase.RotorEntityId.Value).Parent as IMyCubeGrid;
                    if (entityParent == null)
                    {
                        continue;
                    }
                    if (!results.Any(e => e.EntityId == entityParent.EntityId))
                    {
                        results.Add(entityParent);
                        GetAttachedGrids(entityParent, ref results, type);
                    }
                }
                else if (block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_MotorAdvancedRotor) ||
                         block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_MotorRotor) ||
                         block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_RealWheel) ||
                         block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_Wheel))
                {
                    // The Rotor Part.
                    var motorCube = Support.FindRotorBase(block.FatBlock.EntityId);
                    if (motorCube == null)
                    {
                        continue;
                    }
                    var entityParent = (IMyCubeGrid)motorCube.Parent;
                    if (!results.Any(e => e.EntityId == entityParent.EntityId))
                    {
                        results.Add(entityParent);
                        GetAttachedGrids(entityParent, ref results, type);
                    }
                }
                else if (block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_PistonTop))
                {
                    // The Piston Top.
                    var pistonCube = Support.FindPistonBase(block.FatBlock.EntityId);
                    if (pistonCube == null)
                    {
                        continue;
                    }
                    var entityParent = (IMyCubeGrid)pistonCube.Parent;
                    if (!results.Any(e => e.EntityId == entityParent.EntityId))
                    {
                        results.Add(entityParent);
                        GetAttachedGrids(entityParent, ref results, type);
                    }
                }
                else if (block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_ExtendedPistonBase) ||
                         block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_PistonBase))
                {
                    var pistonBase = block.GetObjectBuilder() as MyObjectBuilder_PistonBase;
                    if (pistonBase == null || pistonBase.TopBlockId == 0 || !MyAPIGateway.Entities.EntityExists(pistonBase.TopBlockId))
                    {
                        continue;
                    }
                    var entityParent = MyAPIGateway.Entities.GetEntityById(pistonBase.TopBlockId).Parent as IMyCubeGrid;
                    if (entityParent == null)
                    {
                        continue;
                    }
                    if (!results.Any(e => e.EntityId == entityParent.EntityId))
                    {
                        results.Add(entityParent);
                        GetAttachedGrids(entityParent, ref results, type);
                    }
                }
                else if (block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_ShipConnector) && type == AttachedGrids.All)
                {
                    // There isn't a non-Ingame interface for IMyShipConnector at this time.
                    var connector = (Sandbox.ModAPI.Ingame.IMyShipConnector)block.FatBlock;

                    if (connector.IsConnected == false || connector.IsLocked == false || connector.OtherConnector == null)
                    {
                        continue;
                    }

                    var otherGrid = (IMyCubeGrid)connector.OtherConnector.CubeGrid;

                    if (!results.Any(e => e.EntityId == otherGrid.EntityId))
                    {
                        results.Add(otherGrid);
                        GetAttachedGrids(otherGrid, ref results, type);
                    }
                }
                else if (block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_LandingGear) && type == AttachedGrids.All)
                {
                    var landingGear = (IMyLandingGear)block.FatBlock;
                    if (landingGear.IsLocked == false)
                    {
                        continue;
                    }

                    var entity = landingGear.GetAttachedEntity();
                    if (entity == null || !(entity is IMyCubeGrid))
                    {
                        continue;
                    }

                    var otherGrid = (IMyCubeGrid)entity;
                    if (!results.Any(e => e.EntityId == otherGrid.EntityId))
                    {
                        results.Add(otherGrid);
                        GetAttachedGrids(otherGrid, ref results, type);
                    }
                }
            }

            // Loop through all other grids, find their Landing gear, and figure out if they are attached to <cubeGrid>.
            var allShips  = new HashSet <IMyEntity>();
            var checkList = results; // cannot use ref paramter in Lambada expression!?!.

            MyAPIGateway.Entities.GetEntities(allShips, e => e is IMyCubeGrid && !checkList.Contains(e));

            if (type == AttachedGrids.All)
            {
                foreach (IMyCubeGrid ship in allShips)
                {
                    blocks = new List <IMySlimBlock>();
                    ship.GetBlocks(blocks,
                                   b =>
                                   b != null && b.FatBlock != null && !b.FatBlock.BlockDefinition.TypeId.IsNull &&
                                   b.FatBlock is IMyLandingGear);

                    foreach (var block in blocks)
                    {
                        var landingGear = (IMyLandingGear)block.FatBlock;
                        if (landingGear.IsLocked == false)
                        {
                            continue;
                        }

                        var entity = landingGear.GetAttachedEntity();

                        if (entity == null || entity.EntityId != cubeGrid.EntityId)
                        {
                            continue;
                        }

                        if (!results.Any(e => e.EntityId == ship.EntityId))
                        {
                            results.Add(ship);
                            GetAttachedGrids(ship, ref results, type);
                        }
                    }
                }
            }
        }