예제 #1
0
        public static Command_Action SetUpCampCommand(Caravan caravan)
        {
            Command_Action command_Action = new Command_Action
            {
                defaultLabel = "SetUpCamp".Translate(),
                defaultDesc  = "SetUpCampDesc".Translate(),
                icon         = SetUpCampCommandTex,
                action       = delegate()
                {
                    SoundStarter.PlayOneShotOnCamera(SoundDefOf.Tick_High, null);
                    Camp(caravan);
                }
            };

            tmpSettleFailReason.Length = 0;
            if (!TileFinder.IsValidTileForNewSettlement(caravan.Tile, tmpSettleFailReason))
            {
                command_Action.Disable(tmpSettleFailReason.ToString());
            }
            if (Find.WorldObjects.AnyWorldObjectOfDefAt(SetUpCampDefOf.AbandonedCamp, caravan.Tile))
            {
                command_Action.Disable("SetUpCampOccupied".Translate());
            }
            return(command_Action);
        }
예제 #2
0
 public static int RandomSettlementTileFor_HillDwarves(Faction faction, bool mustBeAutoChoosable = false)
 {
     for (int i = 0; i < 500; i++)
     {
         int num;
         if ((from _ in Enumerable.Range(0, 100)
              select Rand.Range(0, Find.WorldGrid.TilesCount)).TryRandomElementByWeight(delegate(int x)
         {
             Tile tile = Find.WorldGrid[x];
             if (!tile.biome.canBuildBase || tile.hilliness == Hilliness.Impassable)
             {
                 return(0f);
             }
             List <int> neighbors = new List <int>();
             if (tile.hilliness == Hilliness.LargeHills)
             {
                 return(1000f);
             }
             return(0f); //tile.biome.settlementSelectionWeight;
         }, out num))
         {
             if (TileFinder.IsValidTileForNewSettlement(num, null))
             {
                 return(num);
             }
         }
     }
     Log.Error("Failed to find faction base tile for " + faction);
     return(0);
 }
예제 #3
0
        protected override bool CanDoNext()
        {
            if (!base.CanDoNext())
            {
                return(false);
            }
            int selectedTile = Find.WorldInterface.SelectedTile;

            if (selectedTile < 0)
            {
                Messages.Message("MustSelectLandingSite".Translate(), MessageSound.RejectInput);
                return(false);
            }
            StringBuilder stringBuilder = new StringBuilder();

            if (!TileFinder.IsValidTileForNewSettlement(selectedTile, stringBuilder))
            {
                Messages.Message(stringBuilder.ToString(), MessageSound.RejectInput);
                return(false);
            }
            Tile item = Find.WorldGrid[selectedTile];

            if (!TutorSystem.AllowAction(string.Concat("ChooseBiome-", item.biome.defName, "-", item.hilliness.ToString())))
            {
                return(false);
            }
            return(true);
        }
예제 #4
0
        protected override bool CanDoNext()
        {
            if (!base.CanDoNext())
            {
                return(false);
            }
            int selectedTile = Find.WorldInterface.SelectedTile;

            if (selectedTile < 0)
            {
                Messages.Message("MustSelectStartingSite".TranslateWithBackup("MustSelectLandingSite"), MessageTypeDefOf.RejectInput, historical: false);
                return(false);
            }
            StringBuilder stringBuilder = new StringBuilder();

            if (!TileFinder.IsValidTileForNewSettlement(selectedTile, stringBuilder))
            {
                Messages.Message(stringBuilder.ToString(), MessageTypeDefOf.RejectInput, historical: false);
                return(false);
            }
            Tile tile = Find.WorldGrid[selectedTile];

            if (!TutorSystem.AllowAction("ChooseBiome-" + tile.biome.defName + "-" + tile.hilliness.ToString()))
            {
                return(false);
            }
            return(true);
        }
        public static int RandomSettlementTileFor_WoodElves(Faction faction, bool mustBeAutoChoosable = false)
        {
            for (var i = 0; i < 500; i++)
            {
                if ((from _ in Enumerable.Range(0, 100)
                     select Rand.Range(0, Find.WorldGrid.TilesCount)).TryRandomElementByWeight(delegate(int x)
                {
                    Tile tile = Find.WorldGrid[x];
                    if (!tile.biome.canBuildBase || tile.hilliness == Hilliness.Impassable)
                    {
                        return(0f);
                    }
                    if (tile.biome == BiomeDef.Named("LotRE_MallornForest"))
                    {
                        return(1000f);
                    }

                    return(0f);     //tile.biome.settlementSelectionWeight;
                }, out var num))
                {
                    if (TileFinder.IsValidTileForNewSettlement(num, null))
                    {
                        return(num);
                    }
                }
            }
            Log.Error("Failed to find faction base tile for " + faction);
            return(0);
        }
예제 #6
0
 public static int RandomSettlementTileFor(FactionDefExtension options, Faction faction, bool mustBeAutoChoosable = false, Predicate <int> extraValidator = null)
 {
     for (int i = 0; i < 500; i++)
     {
         if ((from _ in Enumerable.Range(0, 100)
              select Rand.Range(0, Find.WorldGrid.TilesCount)).TryRandomElementByWeight(delegate(int x)
         {
             Tile tile = Find.WorldGrid[x];
             if (options.disallowedBiomes != null && options.disallowedBiomes.Contains(tile.biome))
             {
                 return(0f);
             }
             if (options.allowedBiomes != null && !options.allowedBiomes.Contains(tile.biome))
             {
                 return(0f);
             }
             if (!tile.biome.canBuildBase || !tile.biome.implemented || tile.hilliness == Hilliness.Impassable)
             {
                 return(0f);
             }
             if (mustBeAutoChoosable && !tile.biome.canAutoChoose)
             {
                 return(0f);
             }
             return((extraValidator != null && !extraValidator(x)) ? 0f : tile.biome.settlementSelectionWeight);
         }, out int result) && TileFinder.IsValidTileForNewSettlement(result))
         {
             return(result);
         }
     }
     Log.Error("Failed to find faction base tile for " + faction);
     return(0);
 }
        protected override bool CanDoNext()
        {
            bool result;

            if (!base.CanDoNext())
            {
                result = false;
            }
            else
            {
                int selectedTile = Find.WorldInterface.SelectedTile;
                if (selectedTile < 0)
                {
                    Messages.Message("MustSelectLandingSite".Translate(), MessageTypeDefOf.RejectInput, false);
                    result = false;
                }
                else
                {
                    StringBuilder stringBuilder = new StringBuilder();
                    if (!TileFinder.IsValidTileForNewSettlement(selectedTile, stringBuilder))
                    {
                        Messages.Message(stringBuilder.ToString(), MessageTypeDefOf.RejectInput, false);
                        result = false;
                    }
                    else
                    {
                        Tile tile = Find.WorldGrid[selectedTile];
                        result = TutorSystem.AllowAction("ChooseBiome-" + tile.biome.defName + "-" + tile.hilliness.ToString());
                    }
                }
            }
            return(result);
        }
        //The same as TileFinder.TryFindNewSiteTile EXCEPT
        // this one finds locations with caves
        public static bool TryFindNewSiteTile(out int tile, int minDist = 8, int maxDist                = 30,
                                              bool allowCaravans        = false, bool preferCloserTiles = true, int nearThisTile = -1)
        {
            Func <int, int> findTile = delegate(int root)
            {
                int             minDist2  = minDist;
                int             maxDist2  = maxDist;
                Predicate <int> validator = (int x) =>
                                            !Find.WorldObjects.AnyWorldObjectAt(x) &&
                                            Find.World.HasCaves(x) && TileFinder.IsValidTileForNewSettlement(x, null);
                bool preferCloserTiles2 = preferCloserTiles;
                int  result;
                if (TileFinder.TryFindPassableTileWithTraversalDistance(root, minDist2, maxDist2, out result, validator,
                                                                        false, preferCloserTiles2))
                {
                    return(result);
                }
                return(-1);
            };
            int arg;

            if (nearThisTile != -1)
            {
                arg = nearThisTile;
            }
            else if (!TileFinder.TryFindRandomPlayerTile(out arg, allowCaravans, (int x) => findTile(x) != -1))
            {
                tile = -1;
                return(false);
            }
            tile = findTile(arg);
            return(tile != -1);
        }
예제 #9
0
        /// <summary>
        ///     Get a random settle-able tile from the filtered tiles.
        /// </summary>
        /// <returns>A random tile ID (or Tile.Invalid if no tile could be found).</returns>
        public int RandomFilteredTile()
        {
            if (_matchingTileIds.Count == 0)
            {
                Messages.Message("PLFILT_FilterTilesFirst".Translate(), MessageTypeDefOf.RejectInput);
                return(Tile.Invalid);
            }

            var random = new System.Random();

            var minTries = Math.Min(_matchingTileIds.Count, 500);

            for (var i = 0; i < minTries; i++)
            {
                var minRange = Math.Min(_matchingTileIds.Count, 100);

                if ((from _ in Enumerable.Range(0, minRange) select _matchingTileIds[random.Next(_matchingTileIds.Count)]).TryRandomElementByWeight(delegate(int x)
                {
                    var tile = Find.WorldGrid[x];

                    if (!PrepareLanding.Instance.GameData.UserData.Options.AllowImpassableHilliness &&
                        tile.hilliness == Hilliness.Impassable)
                    {
                        return(0f);
                    }

                    if (!tile.biome.canBuildBase || !tile.biome.implemented)
                    {
                        return(0f);
                    }

                    if (!tile.biome.canAutoChoose)
                    {
                        return(0f);
                    }

                    return(tile.biome.factionBaseSelectionWeight);
                }, out var tileId))
                {
                    if (TileFinder.IsValidTileForNewSettlement(tileId))
                    {
                        return(tileId);
                    }
                }
            }

            Messages.Message("PLFILT_FailedFindValidBaseTile".Translate(), MessageTypeDefOf.RejectInput);
            Log.Error("[PrepareLanding] Failed to find a valid tile for a base.");
            return(Tile.Invalid);
        }
        public static int RandomSettlementTileFor_Townsfolk(Faction faction, bool mustBeAutoChoosable = false)
        {
            for (var i = 0; i < 500; i++)
            {
                if (!(from _ in Enumerable.Range(0, 100)
                      select Rand.Range(0, Find.WorldGrid.TilesCount)).TryRandomElementByWeight(delegate(int x)
                {
                    var tile = Find.WorldGrid[x];
                    if (!tile.biome.canBuildBase || tile.hilliness == Hilliness.Impassable)
                    {
                        return(0f);
                    }

                    var neighbors = new List <int>();
                    Find.WorldGrid.GetTileNeighbors(x, neighbors);
                    //Log.Message("Neighbors " + neighbors.Count.ToString());
                    if (neighbors.Count <= 0)
                    {
                        return(tile.biome.settlementSelectionWeight);
                    }

                    foreach (var y in neighbors)
                    {
                        var tile2 = Find.WorldGrid[y];
                        if (tile2.biome == BiomeDefOf.IceSheet || tile2.biome == BiomeDef.Named("SeaIce"))
                        {
                            return(0f);
                        }

                        if (tile2.WaterCovered)
                        {
                            return(1000f);
                        }
                    }

                    return(tile.biome.settlementSelectionWeight);
                }, out var num))
                {
                    continue;
                }

                if (TileFinder.IsValidTileForNewSettlement(num))
                {
                    return(num);
                }
            }

            Log.Error("Failed to find faction base tile for " + faction);
            return(0);
        }
예제 #11
0
        //The same as TileFinder.TryFindNewSiteTile EXCEPT
        // this one finds locations with caves
        public static bool TryFindNewSiteTile(out int tile, int minDist = 8, int maxDist                = 30,
                                              bool allowCaravans        = false, bool preferCloserTiles = true, int nearThisTile = -1)
        {
            int findTile(int root)
            {
                bool validator(int x)
                {
                    return(!Find.WorldObjects.AnyWorldObjectAt(x) && Find.World.HasCaves(x) &&
                           TileFinder.IsValidTileForNewSettlement(x));
                }

                var tileFinderMode = TileFinderMode.Near;

                if (!preferCloserTiles)
                {
                    tileFinderMode = TileFinderMode.Furthest;
                }

                if (TileFinder.TryFindPassableTileWithTraversalDistance(root, minDist, maxDist, out var result,
                                                                        validator,
                                                                        false, tileFinderMode))
                {
                    return(result);
                }

                return(-1);
            }

            int arg;

            if (nearThisTile != -1)
            {
                arg = nearThisTile;
            }
            else if (!TileFinder.TryFindRandomPlayerTile(out arg, allowCaravans, x => findTile(x) != -1))
            {
                tile = -1;
                return(false);
            }

            tile = findTile(arg);
            return(tile != -1);
        }
예제 #12
0
        void GenerateCity(WorldObjectDef def, bool abandoned, System.Predicate <Faction> factionFilter = null)
        {
            var city = (City)WorldObjectMaker.MakeWorldObject(def);

            city.SetFaction(GenCity.RandomCityFaction(factionFilter));
            if (!abandoned)
            {
                city.inhabitantFaction = city.Faction;
            }

            city.Tile = TileFinder.RandomSettlementTileFor(city.Faction);
            city.Name = city.ChooseName();
            if (!TileFinder.IsValidTileForNewSettlement(city.Tile))
            {
                // (Faction Control) ensure valid tile for existing saves
                city.Tile = TileFinder.RandomStartingTile();
            }

            Find.WorldObjects.Add(city);
        }
        public static int RandomSettlementTileFor_ElderThings(Faction faction, bool mustBeAutoChoosable = false)
        {
            for (int i = 0; i < 500; i++)
            {
                int num;
                if ((from _ in Enumerable.Range(0, 100)
                     select Rand.Range(0, Find.WorldGrid.TilesCount)).TryRandomElementByWeight(delegate(int x)
                {
                    Tile tile = Find.WorldGrid[x];
                    if (!tile.biome.canBuildBase || tile.hilliness == Hilliness.Impassable)
                    {
                        return(0f);
                    }
                    List <int> neighbors = new List <int>();
                    Find.WorldGrid.GetTileNeighbors(x, neighbors);
                    //Log.Message("Neighbors " + neighbors.Count.ToString());
                    if (neighbors != null && neighbors.Count > 0)
                    {
                        foreach (int y in neighbors)
                        {
                            Tile tile2 = Find.WorldGrid[y];
                            if (tile2.hilliness == Hilliness.Mountainous &&
                                tile2.biome == BiomeDefOf.IceSheet)
                            {
                                return(1000f);
                            }
                        }
                    }

                    return(tile.biome.settlementSelectionWeight);
                }, out num))
                {
                    if (TileFinder.IsValidTileForNewSettlement(num, null))
                    {
                        return(num);
                    }
                }
            }
            Log.Error("Failed to find faction base tile for " + faction);
            return(0);
        }
예제 #14
0
        private bool tryFindTile(out int tile)
        {
            int findTile(int root)
            {
                bool validator(int x) => !Find.WorldObjects.AnyWorldObjectAt(x) && TileFinder.IsValidTileForNewSettlement(x, null) && (Find.WorldGrid[x].biome.defName == "CaveOasis" || Find.WorldGrid[x].biome.defName == "TunnelworldCave" || Find.WorldGrid[x].biome.defName == "CaveEntrance" || Find.WorldGrid[x].biome.defName == "InfestedMountains" || Find.WorldGrid[x].biome.defName == "DesertCanyon");

                if (TileFinder.TryFindPassableTileWithTraversalDistance(root, SiteTuning.ItemStashQuestSiteDistanceRange.min, SiteTuning.ItemStashQuestSiteDistanceRange.max, out int result, validator))
                {
                    return(result);
                }
                return(-1);
            }

            if (!TileFinder.TryFindRandomPlayerTile(out int arg, false, (int x) => findTile(x) != -1))
            {
                tile = -1;
                return(false);
            }
            tile = findTile(arg);
            return(tile != -1);
        }
예제 #15
0
        public override IEnumerable <Gizmo> GetGizmos()
        {
            if (error)
            {
                return(new List <Gizmo>());
            }
            StringBuilder failReason = new StringBuilder();

            if (!TileFinder.IsValidTileForNewSettlement(this.Tile, failReason))
            {
                setUpCampCommand.Disable(failReason.ToString());
            }
            else
            {
                setUpCampCommand.disabled       = false;
                setUpCampCommand.disabledReason = null;
            }
            List <Gizmo> list = base.GetGizmos().ToList();

            list.Add(setUpCampCommand);
            return(list);
        }
예제 #16
0
        void GenerateCities(int per100kTiles, bool abandoned)
        {
            int cityCount = GenMath.RoundRandom(Find.WorldGrid.TilesCount / 100000F * per100kTiles);

            for (int i = 0; i < cityCount; i++)
            {
                var city = (City)WorldObjectMaker.MakeWorldObject(DefDatabase <WorldObjectDef> .GetNamed(abandoned ? "City_Abandoned" : "City_Faction"));
                city.SetFaction(GenCity.RandomCityFaction());
                if (!abandoned)
                {
                    city.inhabitantFaction = city.Faction;
                }
                city.Tile = TileFinder.RandomSettlementTileFor(city.Faction);
                city.Name = SettlementNameGenerator.GenerateSettlementName(city);
                if (!TileFinder.IsValidTileForNewSettlement(city.Tile))
                {
                    // (Faction Control) ensure valid tile for existing saves
                    city.Tile = TileFinder.RandomStartingTile();
                }
                Find.WorldObjects.Add(city);
            }
        }
        /*
         * this method manages faction expansion.
         * Each faction has a timer, when it ends a new settlement is built
         */
        private void NaturalSettlementExpansion()
        {
            if (!EndGame_Settings.FactionExpansion)
            {
                return;
            }

            foreach (LE_FactionInfo info in factionInfo.ToList())
            {
                if (info.faction.defeated)
                {
                    factionInfo.Remove(info);
                    return;
                }

                if (info.expansionCoolddown > Find.TickManager.TicksGame)
                {
                    return;
                }

                info.expansionCoolddown = Find.TickManager.TicksGame + (int)daysToExpansion.Evaluate(Find.WorldObjects.Settlements.Count(s => s.Faction == info.faction)) + ExpansionCooldown.RandomInRange;
                if (!Find.WorldObjects.Settlements.Where(x => x.Faction == info.faction && Find.WorldGrid.ApproxDistanceInTiles(Find.AnyPlayerHomeMap.Tile, x.Tile) > 45).TryRandomElement(out Settlement origin))
                {
                    continue;
                }
                Settlement expand = (Settlement)WorldObjectMaker.MakeWorldObject(WorldObjectDefOf.Settlement);
                expand.SetFaction(info.faction);
                expand.Tile = TileFinder.RandomSettlementTileFor(expand.Faction, false, x => Find.WorldGrid.ApproxDistanceInTiles(Find.AnyPlayerHomeMap.Tile, x) <
                                                                 Find.WorldGrid.ApproxDistanceInTiles(Find.AnyPlayerHomeMap.Tile, origin.Tile) - 20 && Find.WorldGrid.ApproxDistanceInTiles(x, origin.Tile) < 40 &&
                                                                 TileFinder.IsValidTileForNewSettlement(x, null));
                expand.Name = SettlementNameGenerator.GenerateSettlementName(expand, info.faction.def.settlementNameMaker);
                Find.WorldObjects.Add(expand);
                GetByFaction(info.faction).resources -= LARGE_EVENT_Cache_RESOURCE_VALUE;
                Messages.Message("MessageExpanded".Translate(origin, info.faction, expand), expand, MessageTypeDefOf.NeutralEvent, false);
                GetByFaction(info.faction).history += "HistoryDate".Translate(5500 + (Find.TickManager.TicksGame / Global.YearInTicks)) + "MessageExpanded".Translate(origin, info.faction, expand) + "\n\n";
            }
        }
예제 #18
0
        public static bool IsValidTileForNewSettlement(int tile, StringBuilder reason = null)
        {
            if (tile == -1)
            {
                reason?.Append("selectedInvalidTile".Translate());
                return(false);
            }

            if (!TileFinder.IsValidTileForNewSettlement(tile, reason))
            {
                return(false);
            }

            foreach (WorldSettlementFC settlement in Find.WorldObjects.AllWorldObjects.Where(obj => obj.GetType() == typeof(WorldSettlementFC)))
            {
                if (Find.WorldGrid.IsNeighborOrSame(settlement.Tile, tile))
                {
                    reason?.Append("FactionBaseAdjacent".Translate());
                    return(false);
                }
            }

            return(true);
        }
        /// <summary>
        ///     Main workhorse method that does the actual tile filtering. <see cref="Filter" /> is actually a wrapper around this
        ///     method.
        /// </summary>
        protected void FilterTiles()
        {
            // do a preventive check before filtering anything
            if (!FilterPreCheck())
            {
                return;
            }

            // clear all previous matching tiles and remove all previously highlighted tiles on the world map
            ClearMatchingTiles();

            var separator = "-".Repeat(80);

            FilterInfoLogger.AppendMessage($"{separator}\nNew Filtering\n{separator}", textColor: Color.yellow);

            var globalFilterStopWatch = new Stopwatch();
            var localFilterStopWatch  = new Stopwatch();

            globalFilterStopWatch.Start();

            // filter tiles
            var result         = new List <int>();
            var firstUnionDone = false;

            FilterInfoLogger.AppendMessage($"Starting filtering with: {_allValidTileIds.Count} tiles.");

            var usedFilters = 0;

            for (var i = 0; i < _sortedFilters.Count; i++)
            {
                // get the filter
                var filter = _sortedFilters[i];

                // only use an active filter
                if (!filter.IsFilterActive)
                {
                    continue;
                }

                // add filter (used for logging purpose)
                usedFilters++;

                // use all valid tiles until we have a first result
                var currentList = firstUnionDone ? result : _allValidTileIds;

                // do the actual filtering
                localFilterStopWatch.Start();
                filter.FilterAction(currentList);
                localFilterStopWatch.Stop();
                var filterTime = localFilterStopWatch.Elapsed;
                localFilterStopWatch.Reset();

                // check if anything was filtered
                var filteredTiles = filter.FilteredTiles;
                if ((filteredTiles.Count == 0) && filter.IsFilterActive)
                {
                    var conjunctionMessage = ".";
                    if (usedFilters > 1)
                    {
                        conjunctionMessage = $"(in conjunction with the previous {usedFilters - 1} filters)";
                    }

                    FilterInfoLogger.AppendErrorMessage(
                        $"{filter.RunningDescription}: this filter resulted in 0 matching tiles{conjunctionMessage} Maybe the filtering was a little bit too harsh?",
                        "Filter resulted in 0 tiles", sendToLog: true);

                    globalFilterStopWatch.Stop();
                    return;
                }

                // just send a warning that even if some filter was active it resulted in all tiles matching...
                // this might happen, for example, on 5% coverage wold where the map is composed of only one biome.
                if (filteredTiles.Count == _allValidTileIds.Count)
                {
                    FilterInfoLogger.AppendWarningMessage(
                        $"{filter.RunningDescription}: this filter results in all valid tiles matching.", true);
                }

                // actually make a union with the empty result (as of now) when we have the first filter giving something.
                if (!firstUnionDone)
                {
                    result         = filteredTiles.Union(result).ToList();
                    firstUnionDone = true;
                }
                else
                {
                    // just intersect this filter result with all the previous results
                    result = filteredTiles.Intersect(result).ToList();
                }

                FilterInfoLogger.AppendMessage($"{filter.RunningDescription}: {result.Count} tiles found.");
                FilterInfoLogger.AppendMessage(
                    $"\t\"{filter.SubjectThingDef}\" filter ran in: {filterTime}.");
            }

            // all results into one list
            _matchingTileIds.AddRange(result);

            FilterInfoLogger.AppendMessage(
                $"Before checking for valid tiles: a total of {_matchingTileIds.Count} tile(s) matches all filters.");

            // last pass, remove all tile that are deemed as not being settleable
            if (!_userData.Options.AllowInvalidTilesForNewSettlement)
            {
                _matchingTileIds.RemoveAll(tileId => TileFinder.IsValidTileForNewSettlement(tileId) == false);
            }

            globalFilterStopWatch.Stop();

            // check if the applied filters gave no resulting tiles (the set of applied filters was probably too harsh).
            if (_matchingTileIds.Count == 0)
            {
                FilterInfoLogger.AppendErrorMessage("No tile matches the given filter(s).", sendToLog: true);
            }
            else
            {
                FilterInfoLogger.AppendMessage($"All {usedFilters} filter(s) ran in {globalFilterStopWatch.Elapsed}.");
                FilterInfoLogger.AppendSuccessMessage(
                    $"A total of {_matchingTileIds.Count} tile(s) matches all filters.", true);
            }

            // now highlight filtered tiles
            PrepareLanding.Instance.TileHighlighter.HighlightTileList(_matchingTileIds);
        }
        private bool TryUseResourcesAtPeace(Faction f)
        {
            if (f == null)
            {
                return(false);
            }
            int chance = PeaceEventChance.RandomInRange;

            // Roads
            if (!f.def.techLevel.IsNeolithicOrWorse() && chance < 50)
            {
                Settlement set1 = new Settlement(), set2 = new Settlement();
                foreach (Settlement s in Find.WorldObjects.Settlements.Where(x => x.Faction == f).InRandomOrder())
                {
                    if (Find.WorldObjects.Settlements.Where(x => x != s && x.Faction == f && Utilities.Reachable(x, s, 50)).TryRandomElement(out set2))
                    {
                        set1 = s;
                        break;
                    }
                }
                if (set1 == null || set2 == null)
                {
                    return(false);
                }
                List <int> p = new List <int>();

                using (WorldPath path = Find.World.pathFinder.FindPath(set1.Tile, set2.Tile, null))
                {
                    p = path.NodesReversed;

                    for (int i = 0; i < (p.Count() - 1); i++)
                    {
                        if (Find.WorldGrid[p[i]].potentialRoads == null)
                        {
                            continue;
                        }
                        if (Find.WorldGrid[p[i]].potentialRoads.Any(x => x.road == RoadDefOf.AncientAsphaltHighway) || Find.WorldGrid[p[i]].potentialRoads.Any(x => x.road == RoadDefOf.AncientAsphaltRoad) || Find.WorldGrid[p[i]].potentialRoads.Any(x => x.road == EndGameDefOf.StoneRoad))
                        {
                            if (Find.WorldGrid[p[i + 1]].potentialRoads != null && (Find.WorldGrid[p[i + 1]].potentialRoads.Any(x => x.road == RoadDefOf.AncientAsphaltHighway) || Find.WorldGrid[p[i + 1]].potentialRoads.Any(x => x.road == RoadDefOf.AncientAsphaltRoad) || Find.WorldGrid[p[i + 1]].potentialRoads.Any(x => x.road == EndGameDefOf.StoneRoad)))
                            {
                                p.Remove(p[i + 1]);
                            }
                        }
                        if (i == (p.Count() - 1))
                        {
                            return(false);
                        }
                    }
                    if (p.Count() == 0)
                    {
                        return(false);
                    }
                    WorldObject dispute = WorldObjectMaker.MakeWorldObject(EndGameDefOf.Roads_Camp);
                    dispute.GetComponent <WorldComp_DisputeRoads>().StartComp(set1.Tile, set2.Tile, p);
                    dispute.Tile = p.First();
                    dispute.SetFaction(f);
                    Find.WorldObjects.Add(dispute);
                    Messages.Message("MessageFactionRoads".Translate(set1.Faction, set1, set2), dispute, MessageTypeDefOf.NeutralEvent);
                    GetByFaction(f).resources -= MEDIUM_EVENT_RESOURCE_VALUE;
                    GetByFaction(f).history   += "HistoryDate".Translate(5500 + (Find.TickManager.TicksGame / Global.YearInTicks)) + "MessageFactionRoads".Translate(set1.Faction, set1, set2) + "\n\n";
                }
                return(true);
            }
            // Goodwill randomizer
            if (chance < 100)
            {
                if (!f.def.CanEverBeNonHostile)
                {
                    return(false);
                }
                if (!Find.FactionManager.AllFactionsListForReading.Where(x => !x.def.isPlayer && x.def.CanEverBeNonHostile).TryRandomElement(out Faction faction))
                {
                    return(false);
                }

                f.TryAffectGoodwillWith(faction, new IntRange(-10, 10).RandomInRange, false, false);
                factionInfo.Find(x => x.faction == f).resources -= 200;
                return(true);
            }
            // Settlement Expansion
            if (chance < 300 && Find.WorldObjects.Settlements.Count(x => x.Faction == f) < 3 && factionInfo.Find(x => x.faction == f).resources > 1000)
            {
                if (!Find.WorldObjects.Settlements.Where(x => x.Faction == f).TryRandomElement(out Settlement origin))
                {
                    return(false);
                }
                Settlement expand = (Settlement)WorldObjectMaker.MakeWorldObject(WorldObjectDefOf.Settlement);
                expand.SetFaction(f);
                expand.Tile = TileFinder.RandomSettlementTileFor(expand.Faction, false, x => Find.WorldGrid.ApproxDistanceInTiles(Find.AnyPlayerHomeMap.Tile, x) <
                                                                 Find.WorldGrid.ApproxDistanceInTiles(Find.AnyPlayerHomeMap.Tile, origin.Tile) - 20 && Find.WorldGrid.ApproxDistanceInTiles(x, origin.Tile) < 40 &&
                                                                 TileFinder.IsValidTileForNewSettlement(x, null));
                expand.Name = SettlementNameGenerator.GenerateSettlementName(expand, f.def.settlementNameMaker);
                Find.WorldObjects.Add(expand);
                Messages.Message("MessageExpanded".Translate(origin, f, expand), expand, MessageTypeDefOf.NeutralEvent, false);
                GetByFaction(f).history += "HistoryDate".Translate(5500 + (Find.TickManager.TicksGame / Global.YearInTicks)) + "MessageExpanded".Translate(origin, f, expand) + "\n\n";
                factionInfo.Find(x => x.faction == f).resources -= LARGE_EVENT_Cache_RESOURCE_VALUE;
                return(true);
            }

            return(false);
        }
예제 #21
0
        public override IEnumerable <Gizmo> GetGizmos()
        {
            foreach (Gizmo gizmo in base.GetGizmos())
            {
                yield return(gizmo);
            }

            if (IsPlayerControlled)
            {
                if (vehicle.CompFueledTravel != null)
                {
                    yield return(vehicle.CompFueledTravel.FuelCountGizmo);

                    foreach (Gizmo fuelGizmo in vehicle.CompFueledTravel.DevModeGizmos())
                    {
                        yield return(fuelGizmo);
                    }
                }
                if (!vehicle.CompVehicleLauncher.inFlight && Find.WorldObjects.SettlementAt(Tile) is Settlement settlement2)
                {
                    yield return(GizmoHelper.AerialVehicleTradeCommand(this, settlement2.Faction, settlement2.TraderKind));
                }
                if (vehicle.CompVehicleLauncher.ControlInFlight || !vehicle.CompVehicleLauncher.inFlight)
                {
                    Command_Action launchCommand = new Command_Action()
                    {
                        defaultLabel = "CommandLaunchGroup".Translate(),
                        defaultDesc  = "CommandLaunchGroupDesc".Translate(),
                        icon         = VehicleTex.LaunchCommandTex,
                        alsoClickIfOtherInGroupClicked = false,
                        action = delegate()
                        {
                            LaunchTargeter.Instance.BeginTargeting(vehicle, new Func <GlobalTargetInfo, float, bool>(ChoseTargetOnMap), this, true, VehicleTex.TargeterMouseAttachment, false, null,
                                                                   (GlobalTargetInfo target, List <FlightNode> path, float fuelCost) => vehicle.CompVehicleLauncher.launchProtocol.TargetingLabelGetter(target, Tile, path, fuelCost));
                        }
                    };
                    if (vehicle.CompFueledTravel.EmptyTank)
                    {
                        launchCommand.Disable("VehicleLaunchOutOfFuel".Translate());
                    }
                    yield return(launchCommand);
                }
                if (!vehicle.CompVehicleLauncher.inFlight)
                {
                    foreach (Settlement settlement in Find.WorldObjects.ObjectsAt(flightPath.First.tile).Where(o => o is Settlement).Cast <Settlement>())
                    {
                        yield return(GizmoHelper.ShuttleTradeCommand(this, settlement));

                        if (WorldHelper.CanOfferGiftsTo(this, settlement))
                        {
                            yield return(new Command_Action
                            {
                                defaultLabel = "CommandOfferGifts".Translate(),
                                defaultDesc = "CommandOfferGiftsDesc".Translate(),
                                icon = VehicleTex.OfferGiftsCommandTex,
                                action = delegate()
                                {
                                    Pawn playerNegotiator = WorldHelper.FindBestNegotiator(vehicle, null, null);
                                    Find.WindowStack.Add(new Dialog_Trade(playerNegotiator, settlement, true));
                                }
                            });
                        }
                    }
                    Command_Settle commandSettle = new Command_Settle
                    {
                        defaultLabel = "CommandSettle".Translate(),
                        defaultDesc  = "CommandSettleDesc".Translate(),
                        icon         = SettleUtility.SettleCommandTex,
                        action       = delegate()
                        {
                            SoundDefOf.Tick_High.PlayOneShotOnCamera(null);
                            void settleHere()
                            {
                                SettlementVehicleUtility.Settle(this);
                            };
                            SettlementProximityGoodwillUtility.CheckConfirmSettle(Tile, settleHere);
                        }
                    };
                    if (!TileFinder.IsValidTileForNewSettlement(Tile, tmpSettleFailReason))
                    {
                        commandSettle.Disable(tmpSettleFailReason.ToString());
                    }
                    else if (SettleUtility.PlayerSettlementsCountLimitReached)
                    {
                        if (Prefs.MaxNumberOfPlayerSettlements > 1)
                        {
                            commandSettle.Disable("CommandSettleFailReachedMaximumNumberOfBases".Translate());
                        }
                        else
                        {
                            commandSettle.Disable("CommandSettleFailAlreadyHaveBase".Translate());
                        }
                    }
                    yield return(commandSettle);
                }
                if (Prefs.DevMode)
                {
                    yield return(new Command_Action
                    {
                        defaultLabel = "Debug: Land at Nearest Player Settlement",
                        action = delegate()
                        {
                            List <Settlement> playerSettlements = Find.WorldObjects.Settlements.Where(s => s.Faction == Faction.OfPlayer).ToList();
                            Settlement nearestSettlement = playerSettlements.MinBy(s => Ext_Math.SphericalDistance(s.DrawPos, DrawPos));

                            LaunchProtocol launchProtocol = vehicle.CompVehicleLauncher.launchProtocol;
                            Rot4 vehicleRotation = launchProtocol.landingProperties.forcedRotation ?? Rot4.Random;
                            IntVec3 cell = CellFinderExtended.RandomCenterCell(nearestSettlement.Map, (IntVec3 cell) => !MapHelper.VehicleBlockedInPosition(vehicle, Current.Game.CurrentMap, cell, vehicleRotation));
                            VehicleSkyfaller_Arriving skyfaller = (VehicleSkyfaller_Arriving)ThingMaker.MakeThing(vehicle.CompVehicleLauncher.Props.skyfallerIncoming);
                            skyfaller.vehicle = vehicle;

                            GenSpawn.Spawn(skyfaller, cell, nearestSettlement.Map, vehicleRotation);
                            Destroy();
                        }
                    });

                    yield return(new Command_Action
                    {
                        defaultLabel = "Debug: Initiate Crash Event",
                        action = delegate()
                        {
                            InitiateCrashEvent(null);
                        }
                    });
                }
            }
        }
예제 #22
0
        //Drawing
        public override void DoWindowContents(Rect inRect)
        {
            FactionFC faction = Find.World.GetComponent <FactionFC>();

            faction.roadBuilder.displayPaths();

            if (Find.WorldSelector.selectedTile != -1 && Find.WorldSelector.selectedTile != currentTileSelected)
            {
                currentTileSelected = Find.WorldSelector.selectedTile;
                //Log.Message("Current: " + currentTileSelected + ", Selected: " + Find.WorldSelector.selectedTile);
                currentBiomeSelected = DefDatabase <BiomeResourceDef> .GetNamed(Find.WorldGrid.tiles[currentTileSelected].biome.ToString(), false);

                //default biome
                if (currentBiomeSelected == default(BiomeResourceDef))
                {
                    //Log Modded Biome
                    currentBiomeSelected = BiomeResourceDefOf.defaultBiome;
                }
                currentHillinessSelected = DefDatabase <BiomeResourceDef> .GetNamed(Find.WorldGrid.tiles[currentTileSelected].hilliness.ToString());

                if (currentBiomeSelected.canSettle == true && currentHillinessSelected.canSettle == true && currentTileSelected != 1)
                {
                    timeToTravel = FactionColonies.ReturnTicksToArrive(Find.World.GetComponent <FactionFC>().capitalLocation, currentTileSelected);
                }
                else
                {
                    timeToTravel = 0;
                }
            }


            //grab before anchor/font
            GameFont   fontBefore   = Text.Font;
            TextAnchor anchorBefore = Text.Anchor;


            int silverToCreateSettlement = (int)(traitUtilsFC.cycleTraits(new double(), "createSettlementMultiplier", Find.World.GetComponent <FactionFC>().traits, "multiply") * (FactionColonies.silverToCreateSettlement + (500 * (Find.World.GetComponent <FactionFC>().settlements.Count() + Find.World.GetComponent <FactionFC>().settlementCaravansList.Count())) + (traitUtilsFC.cycleTraits(new double(), "createSettlementBaseCost", Find.World.GetComponent <FactionFC>().traits, "add"))));



            //Draw Label
            Text.Font   = GameFont.Medium;
            Text.Anchor = TextAnchor.MiddleCenter;
            Widgets.Label(new Rect(0, 0, 268, 40), "SettleANewColony".Translate());

            //hori line
            Widgets.DrawLineHorizontal(0, 40, 300);


            //Upper menu
            Widgets.DrawMenuSection(new Rect(5, 45, 258, 220));

            DrawLabelBox(10, 50, 100, 100, "TravelTime".Translate(), GenDate.ToStringTicksToDays(timeToTravel));
            DrawLabelBox(153, 50, 100, 100, "InitialCost".Translate(), silverToCreateSettlement + " " + "Silver".Translate());


            //Lower Menu label
            Text.Font   = GameFont.Medium;
            Text.Anchor = TextAnchor.MiddleCenter;
            Widgets.Label(new Rect(0, 270, 268, 40), "BaseProductionStats".Translate());


            //Lower menu
            Widgets.DrawMenuSection(new Rect(5, 310, 258, 220));


            //Draw production
            Text.Font   = GameFont.Small;
            Text.Anchor = TextAnchor.MiddleCenter;

            //Production headers
            Widgets.Label(new Rect(40, 310, 60, 25), "Base".Translate());
            Widgets.Label(new Rect(110, 310, 60, 25), "Modifier".Translate());
            Widgets.Label(new Rect(180, 310, 60, 25), "Final".Translate());

            if (currentTileSelected != -1)
            {
                for (int i = 0; i < Find.World.GetComponent <FactionFC>().returnNumberResource(); i++)
                {
                    int height = 15;
                    if (Widgets.ButtonImage(new Rect(20, 335 + i * (5 + height), height, height), faction.returnResourceByInt(i).getIcon()))
                    {
                        Find.WindowStack.Add(new descWindowFC("SettlementProductionOf".Translate() + ": " + faction.returnResourceByInt(i).label, char.ToUpper(faction.returnResourceByInt(i).label[0]) + faction.returnResourceByInt(i).label.Substring(1)));
                    }
                    Widgets.Label(new Rect(40, 335 + i * (5 + height), 60, height + 2), (currentBiomeSelected.BaseProductionAdditive[i] + currentHillinessSelected.BaseProductionAdditive[i]).ToString());
                    Widgets.Label(new Rect(110, 335 + i * (5 + height), 60, height + 2), (currentBiomeSelected.BaseProductionMultiplicative[i] * currentHillinessSelected.BaseProductionMultiplicative[i]).ToString());
                    Widgets.Label(new Rect(180, 335 + i * (5 + height), 60, height + 2), ((currentBiomeSelected.BaseProductionAdditive[i] + currentHillinessSelected.BaseProductionAdditive[i]) * (currentBiomeSelected.BaseProductionMultiplicative[i] * currentHillinessSelected.BaseProductionMultiplicative[i])).ToString());
                }
            }



            //Settle button
            Text.Font   = GameFont.Small;
            Text.Anchor = TextAnchor.MiddleCenter;
            int buttonLength = 130;

            if (Widgets.ButtonText(new Rect((InitialSize.x - 32 - buttonLength) / 2f, 535, buttonLength, 32), "Settle".Translate() + ": (" + silverToCreateSettlement + ")")) //add inital cost
            {                                                                                                                                                                 //if click button to settle
                if (PaymentUtil.getSilver() >= silverToCreateSettlement)                                                                                                      //if have enough monies to make new settlement
                {
                    StringBuilder reason = new StringBuilder();
                    if (!TileFinder.IsValidTileForNewSettlement(currentTileSelected, reason) || currentTileSelected == -1 || Find.World.GetComponent <FactionFC>().checkSettlementCaravansList(currentTileSelected.ToString()))
                    {
                        //Alert Error to User
                        Messages.Message(reason.ToString() ?? "CaravanOnWay".Translate() + "!", MessageTypeDefOf.NegativeEvent);
                    }
                    else
                    {   //Else if valid tile
                        PaymentUtil.paySilver(silverToCreateSettlement);
                        //if PROCESS MONEY HERE

                        //create settle event
                        FCEvent tmp = FCEventMaker.MakeEvent(FCEventDefOf.settleNewColony);
                        tmp.location        = currentTileSelected;
                        tmp.planetName      = Find.World.info.name;
                        tmp.timeTillTrigger = Find.TickManager.TicksGame + timeToTravel;
                        tmp.source          = Find.World.GetComponent <FactionFC>().capitalLocation;
                        Find.World.GetComponent <FactionFC>().addEvent(tmp);

                        Find.World.GetComponent <FactionFC>().settlementCaravansList.Add(tmp.location.ToString());
                        Messages.Message("CaravanSentToLocation".Translate() + " " + GenDate.ToStringTicksToDays((tmp.timeTillTrigger - Find.TickManager.TicksGame)) + "!", MessageTypeDefOf.PositiveEvent);
                        // when event activate FactionColonies.createPlayerColonySettlement(currentTileSelected);
                    }
                }
                else
                {  //if don't have enough monies to make settlement
                    Messages.Message("NotEnoughSilverToSettle".Translate() + "!", MessageTypeDefOf.NeutralEvent);
                }
            }



            //reset anchor/font
            Text.Font   = fontBefore;
            Text.Anchor = anchorBefore;
        }
예제 #23
0
        //// Added for testing purposes...
        //private Site CreateSite(int tile, SitePartDef sitePart, int days, Faction siteFaction, List<Thing> items)
        //{
        //    WorldObjectDef woDef;
        //    float chance = Rand.Value;
        //    //if (chance < 0.5f)
        //    //    woDef = WorldObjectDefOf.AbandonedFactionBase;
        //    //else
        //        woDef = WorldObjectDefOf.Site;

        //    Site site = (Site)WorldObjectMaker.MakeWorldObject(woDef);
        //    //site.Tile = tile;
        //    site.core = DefDatabase<SiteCoreDef>.GetNamed("Anomaly_ItemStash");

        //    if (sitePart != null)
        //        site.parts.Add(sitePart);

        //    if (siteFaction != null)
        //        site.SetFaction(siteFaction);

        //    if (days > 0)
        //        site.GetComponent<TimeoutComp>().StartTimeout(days * 60000);

        //    if (items != null && items.Count > 0)
        //        site.GetComponent<ItemStashContentsComp>().contents.TryAddRangeOrTransfer(items);

        //    //Find.WorldObjects.Add(site);
        //    return site;
        //}


        // From RimWorld.Planet.TileFinder.TryFindNewSiteTile(..)
        private bool TryFindNewAnomalyTile(out int tile, int minDist = 7, int maxDist = 27, bool allowCaravans = false, bool preferCloserTiles = true, int nearThisTile = -1)
        {
            Func <int, int> findTile = delegate(int root)
            {
                int             minDist2           = minDist;
                int             maxDist2           = maxDist;
                Predicate <int> validator          = (int x) => !Find.WorldObjects.AnyWorldObjectAt(x) && TileFinder.IsValidTileForNewSettlement(x, null);
                TileFinderMode  preferCloserTiles2 = TileFinderMode.Random;
                if (preferCloserTiles)
                {
                    preferCloserTiles2 = TileFinderMode.Near;
                }
                int result = default(int);
                if (TileFinder.TryFindPassableTileWithTraversalDistance(root, minDist2, maxDist2, out result, validator, false, preferCloserTiles2))
                {
                    return(result);
                }
                return(-1);
            };
            int arg = default(int);

            if (nearThisTile != -1)
            {
                arg = nearThisTile;
            }
            else if (!TileFinder.TryFindRandomPlayerTile(out arg, allowCaravans, (Predicate <int>)((int x) => findTile(x) != -1)))
            {
                tile = -1;
                return(false);
            }
            tile = findTile(arg);
            return(tile != -1);
        }
예제 #24
0
        public static bool CreatePOI(PlanetTileInfo tileInfo, string gameName, bool biomeStrict, bool costStrict, bool itemsStrict)
        {
            if (tileInfo.tile >= Find.WorldGrid.TilesCount)
            {
                return(false);
            }

            if (!TileFinder.IsValidTileForNewSettlement(tileInfo.tile))
            {
                return(false);
            }

            if (biomeStrict && tileInfo.biomeName != Find.WorldGrid.tiles[tileInfo.tile].biome.defName)
            {
                Debug.Warning(Debug.POI, "Skipped blueprint due to wrong biome");
                return(false);
            }

            string    filename = SnapshotStoreManager.Instance.SnapshotNameFor(tileInfo.mapId, gameName);
            Blueprint bp       = BlueprintLoader.LoadWholeBlueprintAtPath(filename);

            if (bp == null)
            {
                return(false);
            }

            if (tileInfo.originX + bp.width > Find.World.info.initialMapSize.x || tileInfo.originZ + bp.height > Find.World.info.initialMapSize.z)
            {
                Debug.Warning(Debug.POI, "Skipped because of exceeding size ({{0} + {1} > {2} && {3} + {4} > {5})", tileInfo.originX, bp.width, Find.World.info.initialMapSize.x, tileInfo.originZ, bp.height, Find.World.info.initialMapSize.z);
                return(false);
            }

            BlueprintAnalyzer ba = new BlueprintAnalyzer(bp);

            ba.Analyze();
            if (costStrict && (ba.result.totalItemsCost < 1000))
            {
                Debug.Warning(Debug.POI, "Skipped blueprint due to low total cost or tiles count");
                return(false);
            }

            if (ba.result.occupiedTilesCount < 50 || ba.result.totalArea < 200)
            {
                Debug.Warning(Debug.POI, "Skipped blueprint due to low area ({0}) and/or items count {1}", ba.result.totalArea, ba.result.occupiedTilesCount);
                return(false);
            }

            var poiType = ba.determinedType;

            Faction faction = null;

            if (Rand.Chance(ba.chanceOfHavingFaction()))
            {
                Find.FactionManager.TryGetRandomNonColonyHumanlikeFaction(out faction, false, false, minTechLevel: MinTechLevelForPOIType(poiType));
            }

            RealRuinsPOIWorldObject site = TryCreateWorldObject(tileInfo.tile, faction);

            if (site == null)
            {
                return(false);
            }

            RealRuinsPOIComp comp = site.GetComponent <RealRuinsPOIComp>();

            if (comp == null)
            {
                Debug.Error(Debug.BlueprintTransfer, "POI Component is null!");
            }
            else
            {
                comp.blueprintName           = tileInfo.mapId;
                comp.gameName                = gameName;
                comp.originX                 = tileInfo.originX;
                comp.originZ                 = tileInfo.originZ;
                comp.poiType                 = (int)poiType;
                comp.militaryPower           = ba.militaryPower;
                comp.mannableCount           = ba.mannableCount;
                comp.approximateSnapshotCost = ba.result.totalItemsCost;
                comp.bedsCount               = ba.result.bedsCount;
            }

            return(true);
        }
예제 #25
0
        /// <summary>
        ///     Main workhorse method that does the actual tile filtering. <see cref="Filter" /> is actually a wrapper around this
        ///     method.
        /// </summary>
        private void FilterTiles()
        {
            // do a preventive check before filtering anything
            if (!FilterPreCheck())
            {
                return;
            }

            // clear all previous matching tiles and remove all previously highlighted tiles on the world map
            ClearMatchingTiles();

            FilterInfoLogger.AppendTitleMessage("PLFILT_NewFilterfing".Translate(), textColor: Color.yellow);

            var globalFilterStopWatch = new Stopwatch();
            var localFilterStopWatch  = new Stopwatch();

            globalFilterStopWatch.Start();

            // filter tiles
            var result         = new List <int>();
            var firstUnionDone = false;

            var msgText = string.Format("PLFILT_StartingFilteringWithxTiles".Translate(), _allValidTileIds.Count);

            FilterInfoLogger.AppendMessage(msgText);

            var usedFilters = 0;

            for (var i = 0; i < _sortedFilters.Count; i++)
            {
                // get the filter
                var filter = _sortedFilters[i];

                // only use an active filter
                if (!filter.IsFilterActive)
                {
                    continue;
                }

                // add filter (used for logging purpose)
                usedFilters++;

                // use all valid tiles until we have a first result
                var currentList = firstUnionDone ? result : _allValidTileIds;

                // do the actual filtering
                localFilterStopWatch.Start();
                filter.FilterAction(currentList);
                localFilterStopWatch.Stop();
                var filterTime = localFilterStopWatch.Elapsed;
                localFilterStopWatch.Reset();

                // check if anything was filtered
                var filteredTiles = filter.FilteredTiles;
                if (filteredTiles.Count == 0 && filter.IsFilterActive)
                {
                    var conjunctionMessage = usedFilters > 1
                        ? string.Format("PLFILT_InConjunctionPreviousFilters".Translate(), usedFilters - 1)
                        : ".";

                    var msgZeroMatchingTiles = string.Format("PLFILT_ZeroMatchingTiles".Translate(), conjunctionMessage);
                    FilterInfoLogger.AppendErrorMessage($"{filter.RunningDescription}: {msgZeroMatchingTiles}",
                                                        "PLFILT_FilterResultZeroTiles".Translate(), sendToLog: true);

                    globalFilterStopWatch.Stop();
                    return;
                }

                // just send a warning that even if some filter was active it resulted in all tiles matching...
                // this might happen, for example, on 5% coverage wold where the map is composed of only one biome.
                if (filteredTiles.Count == _allValidTileIds.Count)
                {
                    var msgAllValidTilesMatching = "PLFILT_AllValidTilesMatching".Translate();
                    FilterInfoLogger.AppendWarningMessage($"{filter.RunningDescription}: {msgAllValidTilesMatching}.",
                                                          true);
                }

                // actually make a union with the empty result (as of now) when we have the first filter giving something.
                if (!firstUnionDone)
                {
                    result         = filteredTiles.Union(result).ToList();
                    firstUnionDone = true;
                }
                else
                {
                    // just intersect this filter result with all the previous results
                    result = filteredTiles.Intersect(result).ToList();
                }

                FilterInfoLogger.AppendMessage(
                    $"{filter.RunningDescription}: {result.Count} {"PLFILT_TilesFound".Translate()}.");
                FilterInfoLogger.AppendMessage(
                    $"\t\"{filter.SubjectThingDef}\" {"PLFILT_FilterRanIn".Translate()}: {filterTime}.");
            }

            // all results into one list
            _matchingTileIds.AddRange(result);

            FilterInfoLogger.AppendMessage(string.Format("PLFILT_xTilesMatchAllFilters".Translate(),
                                                         _matchingTileIds.Count));

            // last pass, remove all tile that are deemed as not being settleable
            if (!_userData.Options.AllowInvalidTilesForNewSettlement)
            {
                _matchingTileIds.RemoveAll(tileId => TileFinder.IsValidTileForNewSettlement(tileId) == false);
            }

            globalFilterStopWatch.Stop();

            // check if the applied filters gave no resulting tiles (the set of applied filters was probably too harsh).
            if (_matchingTileIds.Count == 0)
            {
                FilterInfoLogger.AppendErrorMessage("PLFILT_NoTileMatchesFilter".Translate(), sendToLog: true);
            }
            else
            {
                var msgAllFiltersRanIn = string.Format("PLFILT_AllFiltersRanIn".Translate(), usedFilters,
                                                       globalFilterStopWatch.Elapsed);

                FilterInfoLogger.AppendMessage(msgAllFiltersRanIn);
                var msgTotalOfxTilesMatchAllFilters = string.Format("PLFILT_TotalOfxTilesMatchAllFilters".Translate(),
                                                                    _matchingTileIds.Count);
                FilterInfoLogger.AppendSuccessMessage(msgTotalOfxTilesMatchAllFilters, true);
            }

            // now highlight filtered tiles
            LongEventHandler.ExecuteWhenFinished(delegate
            {
                PrepareLanding.Instance.TileHighlighter.HighlightTileList(_matchingTileIds);
            });
        }
예제 #26
0
        // Expansion
        private bool doExpansion()
        {
            int tile = TileFinder.RandomStartingTile();

            if (!TileFinder.IsValidTileForNewSettlement(tile))
            {
                return(false);
            }
            List <Settlement> settlements = Find.WorldObjects.Settlements.ToList <Settlement>();

            if (settlements.Count > IncidentWorker_NPCExpansion.maxExpansionLimit)
            {
                return(false);
            }
            List <Settlement> candidateSettlements = new List <Settlement>();

            for (int i = 0; i < settlements.Count; i++)
            {
                Settlement SettlerCandidateBase = settlements[i];
                if (SettlerCandidateBase.Faction.IsPlayer || SettlerCandidateBase.Faction.def.settlementGenerationWeight == 0f)
                {
                }
                else
                {
                    if (Find.WorldGrid.TraversalDistanceBetween(tile, SettlerCandidateBase.Tile, true) <= IncidentWorker_NPCExpansion.expansionRadius)
                    {
                        candidateSettlements.Add(SettlerCandidateBase);
                    }
                }
            }

            Settlement SettlerBase;

            if (candidateSettlements.Count != 0)
            {
                SettlerBase = candidateSettlements.RandomElement <Settlement>();
            }
            else
            {
                // fail due to no valid candidate with supply line
                return(false);
            }

            Settlement settlement = (Settlement)WorldObjectMaker.MakeWorldObject(WorldObjectDefOf.Settlement);

            settlement.SetFaction(SettlerBase.Faction);
            bool flag3 = settlement.Faction == null;

            if (flag3)
            {
                return(false);
            }
            else
            {
                settlement.Tile = tile;
                settlement.Name = SettlementNameGenerator.GenerateSettlementName(settlement, null);
                Find.WorldObjects.Add(settlement);
            }

            return(true);
        }
예제 #27
0
        protected override bool TryExecuteWorker(IncidentParms parms)
        {
            if (!enableExpansion)
            {
                return(false);
            }

            int tile = TileFinder.RandomStartingTile();

            if (!TileFinder.IsValidTileForNewSettlement(tile))
            {
                return(false);
            }
            List <Settlement> settlements = Find.WorldObjects.Settlements.ToList <Settlement>();

            if (settlements.Count > maxExpansionLimit)
            {
                Log.Message("current settlememt count of " + settlements.Count.ToString() + " greater than max expansion limit of " + maxExpansionLimit.ToString());
                return(false);
            }
            List <Settlement> candidateSettlements = new List <Settlement>();

            for (int i = 0; i < settlements.Count; i++)
            {
                Settlement SettlerCandidateBase = settlements[i];
                if (SettlerCandidateBase.Faction.IsPlayer || SettlerCandidateBase.Faction.def.settlementGenerationWeight == 0f)
                {
                }
                else
                {
                    if (Find.WorldGrid.TraversalDistanceBetween(tile, SettlerCandidateBase.Tile, true) <= expansionRadius)
                    {
                        candidateSettlements.Add(SettlerCandidateBase);
                    }
                }
            }

            Settlement SettlerBase;

            if (candidateSettlements.Count != 0)
            {
                SettlerBase = candidateSettlements.RandomElement <Settlement>();
            }
            else
            {
                // fail due to no valid candidate with supply line
                return(false);
            }

            Settlement settlement = (Settlement)WorldObjectMaker.MakeWorldObject(WorldObjectDefOf.Settlement);

            settlement.SetFaction(SettlerBase.Faction);
            bool flag3 = settlement.Faction == null;

            if (flag3)
            {
                return(false);
            }
            else
            {
                settlement.Tile = tile;
                settlement.Name = SettlementNameGenerator.GenerateSettlementName(settlement, null);
                Find.WorldObjects.Add(settlement);
                Find.LetterStack.ReceiveLetter("LabelExpansion".Translate(), "DescExpansion".Translate(SettlerBase.Faction.Name, SettlerBase.Name, settlement.Name), LetterDefOf.NeutralEvent, settlement, null, null);
                ExpandableWorldObjectsUtility.ExpandableWorldObjectsUpdate();
            }

            return(true);
        }
        public static bool Prefix(Faction faction, ref int __result, bool mustBeAutoChoosable = false, Predicate <int> extraValidator = null)
        {
            if (Controller.Settings.usingFactionControl.Equals(true))
            {
                return(true);
            }
            float minTemp = -500f;
            float maxTemp = 500f;

            if (faction != null)
            {
                if (!faction.IsPlayer)
                {
                    if (faction.leader != null)
                    {
                        minTemp = faction.leader.def.GetStatValueAbstract(StatDefOf.ComfyTemperatureMin, null);
                        maxTemp = faction.leader.def.GetStatValueAbstract(StatDefOf.ComfyTemperatureMax, null);
                    }
                }
            }
            int num;

            for (int i = 0; i < 2500; i++)
            {
                if ((
                        from _ in Enumerable.Range(0, 100)
                        select Rand.Range(0, Find.WorldGrid.TilesCount)).TryRandomElementByWeight <int>((int x) => {
                    Tile item = Find.WorldGrid[x];
                    if (!item.biome.canBuildBase || !item.biome.implemented || item.hilliness == Hilliness.Impassable)
                    {
                        return(0f);
                    }
                    if (mustBeAutoChoosable && !item.biome.canAutoChoose)
                    {
                        return(0f);
                    }
                    if (extraValidator != null && !extraValidator(x))
                    {
                        return(0f);
                    }
                    if (Controller.Settings.checkTemp.Equals(true))
                    {
                        if (i < 1000)
                        {
                            if (item.temperature < (minTemp - 45) || item.temperature > (maxTemp + 45))
                            {
                                return(0f);
                            }
                            if (item.temperature < (minTemp - 36) || item.temperature > (maxTemp + 36))
                            {
                                if (Rand.Value > 0.1f)
                                {
                                    return(0f);
                                }
                            }
                            if (item.temperature < (minTemp - 28) || item.temperature > (maxTemp + 28))
                            {
                                if (Rand.Value > 0.2f)
                                {
                                    return(0f);
                                }
                            }
                            if (item.temperature < (minTemp - 21) || item.temperature > (maxTemp + 21))
                            {
                                if (Rand.Value > 0.3f)
                                {
                                    return(0f);
                                }
                            }
                            if (item.temperature < (minTemp - 15) || item.temperature > (maxTemp + 15))
                            {
                                if (Rand.Value > 0.4f)
                                {
                                    return(0f);
                                }
                            }
                            if (item.temperature < (minTemp - 10) || item.temperature > (maxTemp + 10))
                            {
                                if (Rand.Value > 0.5f)
                                {
                                    return(0f);
                                }
                            }
                            if (item.temperature < (minTemp - 6) || item.temperature > (maxTemp + 6))
                            {
                                if (Rand.Value > 0.6f)
                                {
                                    return(0f);
                                }
                            }
                            if (item.temperature < (minTemp - 3) || item.temperature > (maxTemp + 3))
                            {
                                if (Rand.Value > 0.7f)
                                {
                                    return(0f);
                                }
                            }
                            if (item.temperature < (minTemp - 1) || item.temperature > (maxTemp + 1))
                            {
                                if (Rand.Value > 0.8f)
                                {
                                    return(0f);
                                }
                            }
                            if (item.temperature < minTemp || item.temperature > maxTemp)
                            {
                                if (Rand.Value > 0.9f)
                                {
                                    return(0f);
                                }
                            }
                        }
                        else if (i < 1500)
                        {
                            if (item.temperature < (minTemp - 45) || item.temperature > (maxTemp + 45))
                            {
                                if (Rand.Value > 0.2f)
                                {
                                    return(0f);
                                }
                            }
                            if (item.temperature < (minTemp - 36) || item.temperature > (maxTemp + 36))
                            {
                                if (Rand.Value > 0.4f)
                                {
                                    return(0f);
                                }
                            }
                            if (item.temperature < (minTemp - 28) || item.temperature > (maxTemp + 28))
                            {
                                if (Rand.Value > 0.6f)
                                {
                                    return(0f);
                                }
                            }
                            if (item.temperature < (minTemp - 21) || item.temperature > (maxTemp + 21))
                            {
                                if (Rand.Value > 0.8f)
                                {
                                    return(0f);
                                }
                            }
                        }
                    }
                    return(item.biome.settlementSelectionWeight);
                }, out num))
                {
                    if (TileFinder.IsValidTileForNewSettlement(num, null))
                    {
                        if (faction == null || faction.def.hidden.Equals(true) || faction.def.isPlayer.Equals(true))
                        {
                            __result = num;
                            return(false);
                        }
                        else if (Controller.factionCenters.ContainsKey(faction))
                        {
                            float test = Find.WorldGrid.ApproxDistanceInTiles(Controller.factionCenters[faction], num);
                            if (faction.def.defName == "Pirate" || faction.def.defName == "TribalRaiders")
                            {
                                if (test < (Controller.maxFactionSprawl * 3))
                                {
                                    __result = num;
                                    return(false);
                                }
                            }
                            else
                            {
                                if (test < Controller.maxFactionSprawl)
                                {
                                    __result = num;
                                    return(false);
                                }
                            }
                        }
                        else
                        {
                            bool locationOK = true;
                            foreach (KeyValuePair <Faction, int> factionCenter in Controller.factionCenters)
                            {
                                float test = Find.WorldGrid.ApproxDistanceInTiles(factionCenter.Value, num);
                                if (test < Controller.minFactionSeparation)
                                {
                                    locationOK = false;
                                }
                            }
                            if (locationOK.Equals(true))
                            {
                                __result = num;
                                Controller.factionCenters.Add(faction, num);
                                return(false);
                            }
                        }
                    }
                }
            }
            Log.Warning(string.Concat("Failed to find faction base tile for ", faction));
            if (Controller.failureCount.ContainsKey(faction))
            {
                Controller.failureCount[faction]++;
                if (Controller.failureCount[faction] == 10)
                {
                    Controller.failureCount.Remove(faction);
                    if (Controller.factionCenters.ContainsKey(faction))
                    {
                        Controller.factionCenters.Remove(faction);
                        Log.Warning("  Relocating faction center.");
                    }
                }
            }
            else
            {
                Log.Warning("  Retrying.");
                Controller.failureCount.Add(faction, 1);
            }
            __result = 0;
            return(false);
        }
        /*
         * Destructive prefix
         */
        public static bool Prefix(Faction faction, ref int __result, bool mustBeAutoChoosable = false, Predicate <int> extraValidator = null)
        {
            int num;

            // Increase 500 to 2500
            for (int i = 0; i < 2500; i++)
            {
                if ((
                        from _ in Enumerable.Range(0, 100)
                        select Rand.Range(0, Find.WorldGrid.TilesCount)).TryRandomElementByWeight <int>((int x) => {
                    Tile item = Find.WorldGrid[x];
                    if (!item.biome.canBuildBase || !item.biome.implemented || item.hilliness == Hilliness.Impassable)
                    {
                        return(0f);
                    }
                    if (mustBeAutoChoosable && !item.biome.canAutoChoose)
                    {
                        return(0f);
                    }
                    if (extraValidator != null && !extraValidator(x))
                    {
                        return(0f);
                    }
                    return(item.biome.settlementSelectionWeight);
                }, out num))
                {
                    // Remove TryRandomElementByWeight
                    if (TileFinder.IsValidTileForNewSettlement(num, null))
                    {
                        // Add all of this
                        if (faction == null || faction.def.hidden.Equals(true) || faction.def.isPlayer.Equals(true))
                        {
                            __result = num;
                            return(false);
                        }
                        else if (Controller.factionCenters.ContainsKey(faction))
                        {
                            double sprawl = Controller.maxFactionSprawl;
                            if (faction.def.defName.Equals("Pirate"))
                            {
                                sprawl = Controller.pirateSprawl;
                            }

                            float test = Find.WorldGrid.ApproxDistanceInTiles(Controller.factionCenters[faction], num);
                            if (faction.def.maxCountAtGameStart == (faction.def.requiredCountAtGameStart * 2))
                            {
                                if (test < (sprawl * 3))
                                {
                                    __result = num;
                                    return(false);
                                }
                            }
                            else
                            {
                                if (test < sprawl)
                                {
                                    __result = num;
                                    return(false);
                                }
                            }
                        }
                        else
                        {
                            bool locationOK = true;
                            foreach (KeyValuePair <Faction, int> factionCenter in Controller.factionCenters)
                            {
                                float test = Find.WorldGrid.ApproxDistanceInTiles(factionCenter.Value, num);
                                if (test < Controller.minFactionSeparation)
                                {
                                    locationOK = false;
                                }
                            }
                            if (locationOK.Equals(true))
                            {
                                __result = num;
                                Controller.factionCenters.Add(faction, num);
                                return(false);
                            }
                        }
                    }
                }
            }
            Log.Warning(string.Concat("Failed to find faction base tile for ", faction));
            // Add the following
            if (Controller.failureCount.ContainsKey(faction))
            {
                Controller.failureCount[faction]++;
                if (Controller.failureCount[faction] == 10)
                {
                    Controller.failureCount.Remove(faction);
                    if (Controller.factionCenters.ContainsKey(faction))
                    {
                        Controller.factionCenters.Remove(faction);
                        Log.Warning("  Relocating faction center.");
                    }
                }
            }
            else
            {
                Log.Warning("  Retrying.");
                Controller.failureCount.Add(faction, 1);
            }
            // End of changes
            __result = 0;
            return(false);
        }
        protected override bool TryExecuteWorker(IncidentParms parms)
        {
            int     tile = -1;
            bool    result;
            Faction faction = Find.FactionManager.RandomEnemyFaction(false, false, true);

            for (int i = 0; i < 20; i++)
            {
                tile = TileFinder.RandomSettlementTileFor(faction, false, null);
                if (TileFinder.IsValidTileForNewSettlement(tile, null))
                {
                    break;
                }
                else
                {
                    tile = -1;
                }
            }
            if (tile != -1)
            {
                Site site = (Site)WorldObjectMaker.MakeWorldObject(SiteDefOfReconAndDiscovery.RD_Adventure);
                site.Tile = tile;
                site.SetFaction(faction);
                SitePart starGate = new SitePart(site, SiteDefOfReconAndDiscovery.RD_Stargate, SiteDefOfReconAndDiscovery.RD_Stargate.Worker.GenerateDefaultParams
                                                     (StorytellerUtility.DefaultSiteThreatPointsNow(), tile, faction));
                site.AddPart(starGate);
                float value = Rand.Value;
                if ((double)value < 0.25)
                {
                    SitePart abandonedCastle = new SitePart(site, SiteDefOfReconAndDiscovery.RD_AbandonedCastle,
                                                            SiteDefOfReconAndDiscovery.RD_AbandonedCastle.Worker.GenerateDefaultParams
                                                                (StorytellerUtility.DefaultSiteThreatPointsNow(), tile, faction));
                    abandonedCastle.hidden = true;
                    site.AddPart(abandonedCastle);
                }
                else if ((double)value < 0.50)
                {
                    SitePart abandonedColony = new SitePart(site, SiteDefOfReconAndDiscovery.RD_AbandonedColony,
                                                            SiteDefOfReconAndDiscovery.RD_AbandonedColony.Worker.GenerateDefaultParams
                                                                (StorytellerUtility.DefaultSiteThreatPointsNow(), tile, faction));
                    abandonedColony.hidden = true;
                    site.AddPart(abandonedColony);
                }
                else if ((double)value < 0.75)
                {
                    SitePart preciousLump = new SitePart(site, SitePartDefOf.PreciousLump,
                                                         SitePartDefOf.PreciousLump.Worker.GenerateDefaultParams
                                                             (StorytellerUtility.DefaultSiteThreatPointsNow(), tile, faction));
                    preciousLump.hidden = true;
                    site.AddPart(preciousLump);
                }
                else
                {
                    site      = (Site)WorldObjectMaker.MakeWorldObject(WorldObjectDefOf.Site);
                    site.Tile = tile;
                    site.SetFaction(faction);
                    SitePart starGate2 = new SitePart(site, SiteDefOfReconAndDiscovery.RD_Stargate, SiteDefOfReconAndDiscovery.RD_Stargate.Worker.GenerateDefaultParams
                                                          (StorytellerUtility.DefaultSiteThreatPointsNow(), tile, faction));
                    site.AddPart(starGate2);
                    // TODO: check if this works correctly
                    SitePart outpost = new SitePart(site, SitePartDefOf.Outpost, SitePartDefOf.Outpost.Worker.GenerateDefaultParams
                                                        (StorytellerUtility.DefaultSiteThreatPointsNow(), tile, faction));
                    outpost.hidden = true;
                    site.parts.Add(outpost);
                    SitePart turrets = new SitePart(site, SitePartDefOf.Turrets, SitePartDefOf.Turrets.Worker.GenerateDefaultParams
                                                        (StorytellerUtility.DefaultSiteThreatPointsNow(), tile, faction));
                    turrets.hidden = true;
                    site.parts.Add(turrets);
                }
                if (Rand.Value < 0.2f)
                {
                    SitePart scatteredManhunters = new SitePart(site, SiteDefOfReconAndDiscovery.RD_ScatteredManhunters, SiteDefOfReconAndDiscovery.RD_ScatteredManhunters.Worker.GenerateDefaultParams
                                                                    (StorytellerUtility.DefaultSiteThreatPointsNow(), tile, faction));

                    scatteredManhunters.hidden = true;

                    site.parts.Add(scatteredManhunters);
                }
                if (Rand.Value < 0.85f)
                {
                    SitePart scatteredTreasure = new SitePart(site, SiteDefOfReconAndDiscovery.RD_ScatteredTreasure,
                                                              SiteDefOfReconAndDiscovery.RD_ScatteredTreasure.Worker.GenerateDefaultParams
                                                                  (StorytellerUtility.DefaultSiteThreatPointsNow(), tile, faction));

                    scatteredTreasure.hidden = true;

                    site.parts.Add(scatteredTreasure);
                }
                site.GetComponent <TimeoutComp>().StartTimeout(10 * 60000);
                base.SendStandardLetter(parms, site);
                Find.WorldObjects.Add(site);
                result = true;
            }
            else
            {
                result = false;
            }

            return(result);
        }