Exemplo n.º 1
0
        public override void CompTick()
        {
            Thing oldISR2G = parent;
            var   level    = 0;

            switch (oldISR2G.def.defName)
            {
            case "RotR_ISR2G":
                level = 1;
                break;

            case "RotR_AISR2G":
                level = 2;
                break;
            }

            if (level <= 0)
            {
                return;
            }

            var newThingDefName = level == 1 ? "RotR_ISR2GNew" : "RotR_AISR2GNew";
            var newThing        = ThingMaker.MakeThing(ThingDef.Named(newThingDefName));
            var position        = oldISR2G.Position;
            var map             = oldISR2G.MapHeld;

            RoadsOfTheRim.DebugLog("Replacing a ISR2G level " + level + " at position " + position);
            oldISR2G.Destroy();
            GenPlace.TryPlaceThing(newThing, position, map, ThingPlaceMode.Near);
        }
Exemplo n.º 2
0
        public static void Postfix(ref IEnumerable <Gizmo> __result, Caravan __instance)
        {
            var isThereAConstructionSiteHere =
                Find.WorldObjects.AnyWorldObjectOfDefAt(DefDatabase <WorldObjectDef> .GetNamed("RoadConstructionSite"),
                                                        __instance.Tile);
            var isTheCaravanWorkingOnASite = true;

            try
            {
                isTheCaravanWorkingOnASite = __instance.GetComponent <WorldObjectComp_Caravan>().currentlyWorkingOnSite;
            }
            catch (Exception e)
            {
                RoadsOfTheRim.DebugLog(null, e);
            }

            __result = __result.Concat(new Gizmo[] { RoadsOfTheRim.AddConstructionSite(__instance) })
                       .Concat(new Gizmo[] { RoadsOfTheRim.RemoveConstructionSite(__instance.Tile) });
            if (isThereAConstructionSiteHere & !isTheCaravanWorkingOnASite &&
                RoadsOfTheRim.RoadBuildingState.CurrentlyTargeting == null)
            {
                __result = __result.Concat(new Gizmo[] { RoadsOfTheRim.WorkOnSite(__instance) });
            }

            if (isTheCaravanWorkingOnASite)
            {
                __result = __result.Concat(new Gizmo[] { RoadsOfTheRim.StopWorkingOnSite(__instance) });
            }
        }
Exemplo n.º 3
0
        /*
         * For resources (including work) that are part of the cost of both the road to build and the best existing road,
         * grant CostUpgradeRebate% (default 30%) of the best existing road build costs as a rebate on the costs of the road to be built
         * i.e. the exisitng road cost 300 stones, the new road cost 600 stones, the rebate is 300*30% = 90 stones
         */
        public static void GetUpgradeModifiers(int fromTile_int, int toTile_int, RoadDef roadToBuild, out Dictionary <string, int> rebate)
        {
            rebate = new Dictionary <string, int>();
            RoadDef bestExistingRoad = RoadsOfTheRim.BestExistingRoad(fromTile_int, toTile_int);

            if (bestExistingRoad != null)
            {
                DefModExtension_RotR_RoadDef bestExistingRoadDefModExtension = bestExistingRoad.GetModExtension <DefModExtension_RotR_RoadDef>();
                DefModExtension_RotR_RoadDef roadToBuildRoadDefModExtension  = roadToBuild.GetModExtension <DefModExtension_RotR_RoadDef>();
                if (bestExistingRoadDefModExtension != null && roadToBuildRoadDefModExtension != null && RoadsOfTheRim.isRoadBetter(roadToBuild, bestExistingRoad))
                {
                    foreach (string resourceName in DefModExtension_RotR_RoadDef.allResourcesAndWork)
                    {
                        int existingCost = bestExistingRoadDefModExtension.GetCost(resourceName);
                        int toBuildCost  = roadToBuildRoadDefModExtension.GetCost(resourceName);
                        if (existingCost != 0 && toBuildCost != 0)
                        {
                            if ((int)(existingCost * (float)RoadsOfTheRim.settings.CostUpgradeRebate / 100) > toBuildCost)
                            {
                                rebate[resourceName] = toBuildCost;
                            }
                            else
                            {
                                rebate[resourceName] = (int)(existingCost * (float)RoadsOfTheRim.settings.CostUpgradeRebate / 100);
                            }
                        }
                    }
                }
            }
        }
        private void PopulateDescription()
        {
            InitListOfSettlements();
            var s = new List <string>();

            if (listOfSettlements != null && listOfSettlements.Count > 0)
            {
                foreach (var si in listOfSettlements.Take(MaxSettlementsInDescription))
                {
                    s.Add("RoadsOfTheRim_siteDescription".Translate(si.settlement.Name,
                                                                    $"{si.distance / (float) GenDate.TicksPerDay:0.00}"));
                }
            }

            NeighbouringSettlementsDescription = string.Join(", ", s.ToArray());
            RoadsOfTheRim.DebugLog(NeighbouringSettlementsDescription);
            if (listOfSettlements != null && listOfSettlements.Count <= MaxSettlementsInDescription)
            {
                return;
            }

            if (listOfSettlements != null)
            {
                NeighbouringSettlementsDescription +=
                    "RoadsOfTheRim_siteDescriptionExtra".Translate(
                        listOfSettlements.Count - MaxSettlementsInDescription);
            }
        }
Exemplo n.º 5
0
        // I had to take into account the old defs of ISR2G that used to be buildings, and replace them with new ISR2G defs that are craftable items
        public void OldDefsCleanup()
        {
            int     newISRG2  = 0;
            int     newAISRG2 = 0;
            Caravan caravan   = this.GetCaravan();

            foreach (Thing aThing in CaravanInventoryUtility.AllInventoryItems(caravan))
            {
                if (aThing.GetInnerIfMinified().def.defName == "RotR_ISR2G")
                {
                    newISRG2++;
                    aThing.Destroy();
                }
                else if (aThing.GetInnerIfMinified().def.defName == "RotR_AISR2G")
                {
                    newAISRG2++;
                    aThing.Destroy();
                }
            }
            for (int i = newISRG2; i > 0; i--)
            {
                Thing newThing = ThingMaker.MakeThing(ThingDef.Named("RotR_ISR2GNew"));
                CaravanInventoryUtility.GiveThing(caravan, newThing);
                RoadsOfTheRim.DebugLog("Replacing an ISR2G in caravan " + caravan.ToString());
            }
            for (int j = newAISRG2; j > 0; j--)
            {
                Thing newThing = ThingMaker.MakeThing(ThingDef.Named("RotR_AISR2GNew"));
                CaravanInventoryUtility.GiveThing(caravan, newThing);
                RoadsOfTheRim.DebugLog("Replacing an AISR2G in caravan " + caravan.ToString());
            }
        }
        public static void PostFix(ref float __result, int tile, bool perceivedStatic, int?ticksAbs,
                                   StringBuilder explanation)
        {
            if (__result <= 999f || !Find.WorldGrid.InBounds(tile))
            {
                return;
            }

            try
            {
                var tile2 = Find.WorldGrid[tile];
                if (tile2.Roads == null)
                {
                    return;
                }

                RoadDef BestRoad = null;
                foreach (var roadLink in tile2.Roads)
                {
                    var currentRoad = roadLink.road;
                    if (currentRoad == null)
                    {
                        continue;
                    }

                    if (BestRoad == null)
                    {
                        BestRoad = currentRoad;
                        continue;
                    }

                    if (BestRoad.movementCostMultiplier < currentRoad.movementCostMultiplier)
                    {
                        BestRoad = roadLink.road;
                    }
                }

                var roadDefExtension = BestRoad?.GetModExtension <DefModExtension_RotR_RoadDef>();
                if (roadDefExtension == null)
                {
                    return;
                }

                if ((!tile2.biome.impassable || !(roadDefExtension.biomeModifier > 0)) &&
                    tile2.hilliness != Hilliness.Impassable)
                {
                    return;
                }

                __result = 12f;
                RoadsOfTheRim.DebugLog(
                    $"[RotR] - Impassable Tile {tile} of biome {tile2.biome.label} movement difficulty patched to 12");
            }
            catch (Exception e)
            {
                RoadsOfTheRim.DebugLog(
                    $"[RotR] - CalculatedMovementDifficultyAt Patch - Catastrophic failure for tile {Find.WorldGrid[tile]}",
                    e);
            }
        }
        /*
         * Faction help must be handled here, since it's independent of whether or not a caravan is here.
         * Make it with a delay of 1/50 s compared to the CaravanComp so both functions end up playing nicely along each other
         * Don't work at night !
         */
        public override void CompTick()
        {
            try
            {
                if (((RoadConstructionSite)parent).helpFromFaction == null ||
                    CaravanNightRestUtility.RestingNowAt(((RoadConstructionSite)parent).Tile) ||
                    Find.TickManager.TicksGame % 100 != 50)
                {
                    return;
                }

                ((RoadConstructionSite)parent).TryToSkipBetterRoads();  // No need to work if there's a better road here
                var amountOfWork = ((RoadConstructionSite)parent).FactionHelp();

                var percentOfWorkLeftToDoAfter = (GetLeft("Work") - amountOfWork) / GetCost("Work");
                foreach (var resourceName in DefModExtension_RotR_RoadDef.allResources)
                {
                    ReduceLeft(resourceName,
                               (int)Math.Round(GetLeft(resourceName) - (percentOfWorkLeftToDoAfter * GetCost(resourceName))));
                }

                UpdateProgress(amountOfWork);
            }
            catch (Exception e)
            {
                RoadsOfTheRim.DebugLog("Construction Site CompTick. parentsite = " + (RoadConstructionSite)parent, e);
            }
        }
Exemplo n.º 8
0
        public void TryToSkipBetterRoads(Caravan caravan = null)
        {
            RoadConstructionLeg nextLeg = GetNextLeg();

            if (nextLeg != null) // nextLeg == null should never happen
            {
                RoadDef bestExistingRoad = RoadsOfTheRim.BestExistingRoad(Tile, nextLeg.Tile);
                // We've found an existing road that is better than the one we intend to build : skip this leg and move to the next
                if (!RoadsOfTheRim.isRoadBetter(roadDef, bestExistingRoad))
                {
                    Messages.Message("RoadsOfTheRim_BetterRoadFound".Translate(caravan.Name, bestExistingRoad.label, roadDef.label), MessageTypeDefOf.NeutralEvent);
                    int currentTile = Tile;
                    Tile = nextLeg.Tile; // The construction site moves to the next leg
                    RoadConstructionLeg nextNextLeg = nextLeg.Next;
                    if (nextNextLeg != null)
                    {
                        nextNextLeg.Previous = null;  // The nextNext leg is now the next
                        GetComponent <WorldObjectComp_ConstructionSite>().setCosts();
                        MoveWorkersToNextLeg(currentTile);
                    }
                    else // Finish construction
                    {
                        GetComponent <WorldObjectComp_ConstructionSite>().EndConstruction(caravan);
                    }
                    Find.World.worldObjects.Remove(nextLeg);
                }
            }
        }
Exemplo n.º 9
0
 public static void Postfix(ref DiaNode __result, Pawn negotiator, Faction faction)
 {
     // Allies can help build roads
     if (faction.PlayerRelationKind == FactionRelationKind.Ally)
     {
         __result.options.Insert(0, RoadsOfTheRim.HelpRoadConstruction(faction, negotiator));
     }
 }
Exemplo n.º 10
0
 public static void Postfix(ref AcceptanceReport __result, Designator_RemoveBridge __instance, IntVec3 c)
 {
     if (c.InBounds(__instance.Map) && c.GetTerrain(__instance.Map) == TerrainDefOf.ConcreteBridge)
     {
         __result = true;
         RoadsOfTheRim.DebugLog(c.GetTerrain(__instance.Map).label);
     }
 }
Exemplo n.º 11
0
 public static void Prefix()
 {
     if (RoadsOfTheRim.RoadBuildingState.CurrentlyTargeting != null)
     {
         //RoadsOfTheRim.DebugLog("StopTargeting");
         RoadsOfTheRim.FinaliseConstructionSite(RoadsOfTheRim.RoadBuildingState.CurrentlyTargeting);
         RoadsOfTheRim.RoadBuildingState.CurrentlyTargeting = null;
     }
 }
Exemplo n.º 12
0
        public static void Postifx(ref float __result, WorldGrid __instance, ref int fromTile, ref int toTile, ref StringBuilder explanation)
        {
            List <Tile.RoadLink> roads = __instance.tiles[fromTile].Roads;

            if (roads == null)
            {
                return;
            }
            if (toTile == -1)
            {
                toTile = __instance.FindMostReasonableAdjacentTileForDisplayedPathCost(fromTile);
            }
            float BiomeModifier  = 0;
            float HillModifier   = 0;
            float WinterModifier = 0;

            for (int i = 0; i < roads.Count; i++)
            {
                if (roads[i].neighbor == toTile)
                {
                    Tile  ToTileAsTile    = Find.WorldGrid[toTile];
                    float HillinessOffset = (float)HillinessMovementDifficultyOffset.Invoke(null, new object[] { ToTileAsTile.hilliness });
                    if (HillinessOffset > 12f)
                    {
                        HillinessOffset = 12f;
                    }

                    // If the tile has an impassable biome, set the biomemovement difficulty to 12, as per the patch for CalculatedMovementDifficultyAt
                    float biomeMovementDifficulty = (ToTileAsTile.biome.impassable ? 12f : ToTileAsTile.biome.movementDifficulty);

                    // Calculate biome, Hillines & winter modifiers, update explanation &  multiply result by biome modifier
                    float RoadModifier = RoadsOfTheRim.calculateRoadModifier(
                        roads[i].road,
                        biomeMovementDifficulty,
                        HillinessOffset,
                        WorldPathGrid.GetCurrentWinterMovementDifficultyOffset(toTile),
                        out BiomeModifier,
                        out HillModifier,
                        out WinterModifier
                        );
                    float resultBefore = __result;
                    __result *= RoadModifier;
                    if (explanation != null)
                    {
                        explanation.AppendLine();
                        explanation.Append(String.Format(
                                               "The road cancels {0:P0} of the biome ({3:##.###}), {1:P0} of the hills ({4:##.###}) & {2:P0} of winter movement costs. Total modifier={5} applied to {6}",
                                               BiomeModifier, HillModifier, WinterModifier,
                                               biomeMovementDifficulty, HillinessOffset, RoadModifier, resultBefore
                                               ));
                    }
                    return;
                }
            }
        }
Exemplo n.º 13
0
        public override IEnumerable <Gizmo> GetGizmos()
        {
            foreach (var g in base.GetGizmos())
            {
                yield return(g);

                g.disabledReason = null;
            }

            // Ability to remove the construction site without needing to go there with a Caravan.
            yield return(RoadsOfTheRim.RemoveConstructionSite(Tile));
        }
 private void SetSiteFromTile()
 {
     try
     {
         site = (RoadConstructionSite)Find.WorldObjects.WorldObjectOfDefAt(
             DefDatabase <WorldObjectDef> .GetNamed("RoadConstructionSite"), GetCaravan().Tile);
     }
     catch (Exception e)
     {
         RoadsOfTheRim.DebugLog("", e);
     }
 }
Exemplo n.º 15
0
 public bool setSiteFromTile()
 {
     try
     {
         site = (RoadConstructionSite)Find.WorldObjects.WorldObjectOfDefAt(DefDatabase <WorldObjectDef> .GetNamed("RoadConstructionSite", true), (GetCaravan().Tile));
         return(true);
     }
     catch (Exception e)
     {
         RoadsOfTheRim.DebugLog("", e);
         return(false);
     }
 }
Exemplo n.º 16
0
 public static void PostFix(ref float __result, int tile, bool perceivedStatic, int?ticksAbs, StringBuilder explanation)
 {
     if (__result > 999f)
     {
         try
         {
             if (Find.WorldGrid.InBounds(tile))
             {
                 Tile tile2 = Find.WorldGrid.tiles[tile];
                 List <Tile.RoadLink> roads = tile2.Roads;
                 if (roads?.Count > 0)
                 {
                     RoadDef BestRoad = null;
                     for (int i = 0; i < roads.Count; i++)
                     {
                         if (BestRoad == null)
                         {
                             BestRoad = roads[i].road;
                         }
                         else
                         {
                             if (BestRoad.movementCostMultiplier < roads[i].road.movementCostMultiplier)
                             {
                                 BestRoad = roads[i].road;
                             }
                         }
                     }
                     if (BestRoad != null)
                     {
                         DefModExtension_RotR_RoadDef roadDefExtension = BestRoad.GetModExtension <DefModExtension_RotR_RoadDef>();
                         if (roadDefExtension != null && ((tile2.biome.impassable && roadDefExtension.biomeModifier > 0) || (tile2.hilliness == Hilliness.Impassable)))
                         {
                             __result = 12f;
                             //RoadsOfTheRim.DebugLog(String.Format("[RotR] - Impassable Tile {0} of biome {1} movement difficulty patched to 12", tile , tile2.biome.label));
                         }
                     }
                 }
             }
             else
             {
                 RoadsOfTheRim.DebugLog("[RotR] - CalculatedMovementDifficultyAt Patch - Tile out of bounds");
             }
         }
         catch (Exception e)
         {
             RoadsOfTheRim.DebugLog("[RotR] - CalculatedMovementDifficultyAt Patch - Catastrophic failure", e);
             return;
         }
     }
 }
Exemplo n.º 17
0
 public override void PostClose() // If the menu was somehow closed without picking a road, delete the construction site
 {
     try
     {
         if (site.roadDef == null)
         {
             RoadsOfTheRim.DeleteConstructionSite(site.Tile);
         }
     }
     catch (Exception e)
     {
         RoadsOfTheRim.DebugLog(null, e);
     }
 }
Exemplo n.º 18
0
        public static void Postfix(ref TransferableOneWayWidget widget, List <TransferableOneWay> transferables)
        {
            RoadsOfTheRim.DebugLog("DEBUG AddPawnsSection: ");
            List <TransferableOneWay> source = new List <TransferableOneWay>();

            foreach (TransferableOneWay tow in transferables)
            {
                if (tow.ThingDef.IsWithinCategory(ThingCategoryDef.Named("RoadEquipment")))
                {
                    source.Add(tow);
                    RoadsOfTheRim.DebugLog("Found an ISR2G");
                }
            }
            widget.AddSection("RoadsOfTheRim_RoadEquipment".Translate(), source);
        }
        /*
         * Returns the cost modifiers for building a road from one tile to another, based on Elevation, Hilliness, Swampiness & river crossing
         */
        private static void GetCostsModifiers(int fromTile_int, int toTile_int, ref float elevationModifier,
                                              ref float hillinessModifier, ref float swampinessModifier, ref float bridgeModifier)
        {
            try
            {
                var settings = LoadedModManager.GetMod <RoadsOfTheRim>().GetSettings <RoadsOfTheRimSettings>();
                var fromTile = Find.WorldGrid[fromTile_int];
                var toTile   = Find.WorldGrid[toTile_int];

                // Cost increase from elevation : if elevation is above {CostIncreaseElevationThreshold} (default 1000m), cost is doubled every {ElevationCostDouble} (default 2000m)
                elevationModifier = fromTile.elevation <= settings.CostIncreaseElevationThreshold
                    ? 0
                    : (fromTile.elevation - settings.CostIncreaseElevationThreshold) /
                                    RoadsOfTheRimSettings.ElevationCostDouble;
                elevationModifier += toTile.elevation <= settings.CostIncreaseElevationThreshold
                    ? 0
                    : (toTile.elevation - settings.CostIncreaseElevationThreshold) /
                                     RoadsOfTheRimSettings.ElevationCostDouble;

                // Hilliness and swampiness are the average between that of the from & to tiles
                // Hilliness is 0 on flat terrain, never negative. It's between 0 (flat) and 5(Impassable)
                var hilliness  = Math.Max((((float)fromTile.hilliness + (float)toTile.hilliness) / 2) - 1, 0);
                var swampiness = (fromTile.swampiness + toTile.swampiness) / 2;

                // Hilliness and swampiness double the costs when they equal {HillinessCostDouble} (default 4) and {SwampinessCostDouble} (default 0.5)
                hillinessModifier  = hilliness / RoadsOfTheRimSettings.HillinessCostDouble;
                swampinessModifier = swampiness / RoadsOfTheRimSettings.SwampinessCostDouble;

                bridgeModifier = 0f;

                /* TO DO : River crossing
                 * List<int> fromTileNeighbors = new List<int>();
                 * Find.WorldGrid.GetTileNeighbors(parent.Tile, fromTileNeighbors);
                 * foreach (Tile.RiverLink aRiver in fromTile.Rivers )
                 * {
                 *  Log.Message("River in FROM tile : neighbor="+aRiver.neighbor+", river="+aRiver.river.ToString());
                 * }
                 */
            }
            catch (Exception e)
            {
                RoadsOfTheRim.DebugLog(null, e);
            }
        }
Exemplo n.º 20
0
        public void populateDescription()
        {
            initListOfSettlements();
            List <string> s = new List <string>();

            if ((listOfSettlements != null) && (listOfSettlements.Count > 0))
            {
                foreach (SettlementInfo si in listOfSettlements.Take(MaxSettlementsInDescription))
                {
                    s.Add("RoadsOfTheRim_siteDescription".Translate(si.settlement.Name, string.Format("{0:0.00}", (float)si.distance / (float)GenDate.TicksPerDay)));
                }
            }
            NeighbouringSettlementsDescription = String.Join(", ", s.ToArray());
            RoadsOfTheRim.DebugLog(NeighbouringSettlementsDescription);
            if (listOfSettlements.Count > MaxSettlementsInDescription)
            {
                NeighbouringSettlementsDescription += "RoadsOfTheRim_siteDescriptionExtra".Translate(listOfSettlements.Count - MaxSettlementsInDescription);
            }
        }
Exemplo n.º 21
0
        public void searchForSettlements(int startTile, ref List <SettlementInfo> settlementsSearched)
        {
            var       timer     = System.Diagnostics.Stopwatch.StartNew();
            WorldGrid worldGrid = Find.WorldGrid;

            foreach (Settlement s in Find.WorldObjects.Settlements)
            {
                if (worldGrid.ApproxDistanceInTiles(startTile, s.Tile) <= maxNeighbourDistance)
                {
                    int distance = CaravanArrivalTimeEstimator.EstimatedTicksToArrive(startTile, s.Tile, null);
                    if (distance <= maxTicksToNeighbour)
                    {
                        settlementsSearched.Add(new SettlementInfo(s, distance));
                    }
                }
            }
            timer.Stop();
            RoadsOfTheRim.DebugLog("Time spent searching for settlements : " + timer.ElapsedMilliseconds + "ms");
        }
Exemplo n.º 22
0
        public string ResourcesAlreadyConsumed()
        {
            List <String> l = new List <string>();

            try
            {
                foreach (string resourceName in DefModExtension_RotR_RoadDef.allResourcesAndWork)
                {
                    if (GetCost(resourceName) > 0 && GetLeft(resourceName) < GetCost(resourceName))
                    {
                        l.Add(String.Format("{0} {1}", GetCost(resourceName) - GetLeft(resourceName), resourceName));
                    }
                }
            }
            catch
            {
                RoadsOfTheRim.DebugLog("resourcesAlreadyConsumed failed. This will happen after upgrading to the 20190207 version");
            }
            return(String.Join(", ", l.ToArray()));
        }
        /*
         * For resources (including work) that are part of the cost of both the road to build and the best existing road,
         * grant CostUpgradeRebate% (default 30%) of the best existing road build costs as a rebate on the costs of the road to be built
         * i.e. the exisitng road cost 300 stones, the new road cost 600 stones, the rebate is 300*30% = 90 stones
         */
        private static void GetUpgradeModifiers(int fromTile_int, int toTile_int, RoadDef roadToBuild,
                                                out Dictionary <string, int> rebate)
        {
            rebate = new Dictionary <string, int>();
            var bestExistingRoad = RoadsOfTheRim.BestExistingRoad(fromTile_int, toTile_int);

            if (bestExistingRoad == null)
            {
                return;
            }

            var bestExistingRoadDefModExtension = bestExistingRoad.GetModExtension <DefModExtension_RotR_RoadDef>();
            var roadToBuildRoadDefModExtension  = roadToBuild.GetModExtension <DefModExtension_RotR_RoadDef>();

            if (bestExistingRoadDefModExtension == null || roadToBuildRoadDefModExtension == null ||
                !RoadsOfTheRim.IsRoadBetter(roadToBuild, bestExistingRoad))
            {
                return;
            }

            foreach (var resourceName in DefModExtension_RotR_RoadDef.allResourcesAndWork)
            {
                var existingCost = bestExistingRoadDefModExtension.GetCost(resourceName);
                var toBuildCost  = roadToBuildRoadDefModExtension.GetCost(resourceName);
                if (existingCost == 0 || toBuildCost == 0)
                {
                    continue;
                }

                if ((int)(existingCost * (float)RoadsOfTheRim.settings.CostUpgradeRebate / 100) > toBuildCost)
                {
                    rebate[resourceName] = toBuildCost;
                }
                else
                {
                    rebate[resourceName] =
                        (int)(existingCost * (float)RoadsOfTheRim.settings.CostUpgradeRebate / 100);
                }
            }
        }
Exemplo n.º 24
0
        /*
         * Faction help must be handled here, since it's independent of whether or not a caravan is here.
         * Make it with a delay of 1/50 s compared to the CaravanComp so both functions end up playing nicely along each other
         * Don't work at night !
         */
        public override void CompTick()
        {
            try
            {
                if ((((RoadConstructionSite)parent).helpFromFaction != null) && (!CaravanNightRestUtility.RestingNowAt(((RoadConstructionSite)parent).Tile)) && (Find.TickManager.TicksGame % 100 == 50))
                {
                    ((RoadConstructionSite)parent).TryToSkipBetterRoads();   // No need to work if there's a better road here
                    float amountOfWork = ((RoadConstructionSite)parent).factionHelp();

                    float percentOfWorkLeftToDoAfter = ((float)GetLeft("Work") - amountOfWork) / (float)GetCost("Work");
                    foreach (string resourceName in DefModExtension_RotR_RoadDef.allResources)
                    {
                        ReduceLeft(resourceName, (int)Math.Round((float)GetLeft(resourceName) - (percentOfWorkLeftToDoAfter * (float)GetCost(resourceName))));
                    }
                    UpdateProgress(amountOfWork);
                }
            }
            catch (Exception e)
            {
                RoadsOfTheRim.DebugLog("Construction Site CompTick. parentsite = " + ((RoadConstructionSite)parent), e);
            }
        }
Exemplo n.º 25
0
        /*
         * Returns the road with the best movement cost multiplier between 2 neighbouring tiles.
         * returns null if there's no road or if the tiles are not neighbours
         */
        public static RoadDef BestExistingRoad(int fromTile_int, int toTile_int)
        {
            RoadDef bestExistingRoad = null;

            try
            {
                WorldGrid worldGrid = Find.WorldGrid;
                Tile      fromTile  = worldGrid[fromTile_int];
                Tile      toTile    = worldGrid[toTile_int];

                if (fromTile.potentialRoads != null)
                {
                    foreach (Tile.RoadLink aLink in fromTile.potentialRoads)
                    {
                        if (aLink.neighbor == toTile_int & RoadsOfTheRim.isRoadBetter(aLink.road, bestExistingRoad))
                        {
                            bestExistingRoad = aLink.road;
                        }
                    }
                }
                if (toTile.potentialRoads != null)
                {
                    foreach (Tile.RoadLink aLink in toTile.potentialRoads)
                    {
                        if (aLink.neighbor == fromTile_int & RoadsOfTheRim.isRoadBetter(aLink.road, bestExistingRoad))
                        {
                            bestExistingRoad = aLink.road;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                DebugLog(null, e);
            }
            return(bestExistingRoad);
        }
        public string ResourcesAlreadyConsumed()
        {
            var resourceList = new List <string>();

            try
            {
                foreach (var resourceName in DefModExtension_RotR_RoadDef.allResourcesAndWork)
                {
                    if (GetCost(resourceName) <= 0 || GetLeft(resourceName) >= GetCost(resourceName))
                    {
                        continue;
                    }

                    resourceList.Add($"{GetCost(resourceName) - GetLeft(resourceName)} {resourceName}");
                }
            }
            catch
            {
                RoadsOfTheRim.DebugLog(
                    "resourcesAlreadyConsumed failed. This will happen after upgrading to the 20190207 version");
            }

            return(string.Join(", ", resourceList.ToArray()));
        }
        // I had to take into account the old defs of ISR2G that used to be buildings, and replace them with new ISR2G defs that are craftable items
        private void OldDefsCleanup()
        {
            var newISRG2  = 0;
            var newAISRG2 = 0;
            var caravan   = GetCaravan();

            foreach (var aThing in CaravanInventoryUtility.AllInventoryItems(caravan))
            {
                switch (aThing.GetInnerIfMinified().def.defName)
                {
                case "RotR_ISR2G":
                    newISRG2++;
                    aThing.Destroy();
                    break;

                case "RotR_AISR2G":
                    newAISRG2++;
                    aThing.Destroy();
                    break;
                }
            }

            for (var i = newISRG2; i > 0; i--)
            {
                var newThing = ThingMaker.MakeThing(ThingDef.Named("RotR_ISR2GNew"));
                CaravanInventoryUtility.GiveThing(caravan, newThing);
                RoadsOfTheRim.DebugLog("Replacing an ISR2G in caravan " + caravan);
            }

            for (var j = newAISRG2; j > 0; j--)
            {
                var newThing = ThingMaker.MakeThing(ThingDef.Named("RotR_AISR2GNew"));
                CaravanInventoryUtility.GiveThing(caravan, newThing);
                RoadsOfTheRim.DebugLog("Replacing an AISR2G in caravan " + caravan);
            }
        }
Exemplo n.º 28
0
        public override void CompTick()
        {
            Thing oldISR2G = this.parent;
            int   level    = 0;

            if (oldISR2G.def.defName == "RotR_ISR2G")
            {
                level = 1;
            }
            else if (oldISR2G.def.defName == "RotR_AISR2G")
            {
                level = 2;
            }
            if (level > 0)
            {
                string  newThingDefName = (level == 1 ? "RotR_ISR2GNew" : "RotR_AISR2GNew");
                Thing   newThing        = ThingMaker.MakeThing(ThingDef.Named(newThingDefName));
                IntVec3 position        = oldISR2G.Position;
                Map     map             = oldISR2G.MapHeld;
                RoadsOfTheRim.DebugLog("Replacing a ISR2G level " + level + " at position " + position.ToString());
                oldISR2G.Destroy();
                GenPlace.TryPlaceThing(newThing, position, map, ThingPlaceMode.Near);
            }
        }
Exemplo n.º 29
0
        public override void DoWindowContents(Rect inRect)
        {
            if (Event.current.isKey && site != null)
            {
                RoadsOfTheRim.DeleteConstructionSite(site.Tile);
                Close();
            }

            //Resources icons
            for (var i = 0; i < 9; i++)
            {
                // Icon
                var      ResourceRect = new Rect(0, 202f + (i * 40f), 32f, 32f);
                ThingDef theDef;
                switch (i)
                {
                case 0:
                    theDef = ThingDefOf.Spark;
                    break;

                case 1:
                    theDef = ThingDefOf.WoodLog;
                    break;

                case 2:
                    theDef = ThingDefOf.BlocksGranite;
                    break;

                case 3:
                    theDef = ThingDefOf.Steel;
                    break;

                case 4:
                    theDef = ThingDefOf.Chemfuel;
                    break;

                case 5:
                    theDef = ThingDefOf.Plasteel;
                    break;

                case 6:
                    theDef = ThingDefOf.Uranium;
                    break;

                case 7:
                    theDef = ThingDefOf.ComponentIndustrial;
                    break;

                default:
                    theDef = ThingDefOf.ComponentSpacer;
                    break;
                }

                if (i == 0)
                {
                    Widgets.ButtonImage(ResourceRect, ContentFinder <Texture2D> .Get("UI/Commands/AddConstructionSite"));
                }
                else
                {
                    Widgets.ThingIcon(ResourceRect, theDef);
                }
            }

            // Sections : one per type of buildable road
            var nbOfSections = 0;
            var groupSize    = new Vector2(144, 512 + 128);

            foreach (var aDef in buildableRoads)
            {
                var roadDefExtension = aDef.GetModExtension <DefModExtension_RotR_RoadDef>();

                // Check if a tech is necessary to build this road, don't display the road if it isn't researched yet
                var NeededTech     = roadDefExtension.techNeededToBuild;
                var TechResearched = NeededTech == null || NeededTech.IsFinished;

                if (!TechResearched)
                {
                    continue;
                }

                GUI.BeginGroup(new Rect(new Vector2(64 + (144 * nbOfSections), 32f), groupSize));

                // Buildable Road icon
                var theButton = ContentFinder <Texture2D> .Get("UI/Commands/Build_" + aDef.defName);

                var ButtonRect = new Rect(8, 8, 128, 128);
                if (Widgets.ButtonImage(ButtonRect, theButton))
                {
                    if (Event.current.button == 0)
                    {
                        SoundDefOf.Tick_High.PlayOneShotOnCamera();
                        if (site != null)
                        {
                            site.roadDef = aDef;
                            Close();
                            RoadsOfTheRim.RoadBuildingState.CurrentlyTargeting = site;
                            RoadsOfTheRim.RoadBuildingState.Caravan            = caravan;
                            RoadConstructionLeg.Target(site);
                        }
                    }
                }

                // Buildable Road label
                Text.Anchor = TextAnchor.MiddleCenter;
                Text.Font   = GameFont.Medium;
                var NameRect = new Rect(0, 144, 144f, 32f);
                Widgets.Label(NameRect, aDef.label);

                // Resources amounts
                Text.Font = GameFont.Small;
                var i = 0;
                foreach (var resourceName in DefModExtension_RotR_RoadDef.allResourcesAndWork)
                {
                    var ResourceAmountRect = new Rect(0, 176f + (i++ *40f), 144f, 32f);
                    Widgets.Label(ResourceAmountRect,
                                  roadDefExtension.GetCost(resourceName) > 0
                            ? (roadDefExtension.GetCost(resourceName) *
                               ((float)RoadsOfTheRim.settings.BaseEffort / 10)).ToString()
                            : "-"
                                  );
                }

                GUI.EndGroup();
                nbOfSections++;
            }

            Text.Anchor = TextAnchor.UpperLeft;
        }
        public override void CompTick()
        {
            OldDefsCleanup();
            if (Find.TickManager.TicksGame % 100 != 0)
            {
                return;
            }

            var caravan = GetCaravan();

            // Wake up the caravan if it's ready to work
            if (workOnWakeUp && CaravanCurrentState() == CaravanState.ReadyToWork)
            {
                workOnWakeUp           = false;
                currentlyWorkingOnSite = true;
                Messages.Message("RotR_CaravanWakesUp".Translate(caravan.Label, site.roadDef.label),
                                 MessageTypeDefOf.NeutralEvent);
            }

            // Do some work & stop working if finished
            // Caravan is working AND there's a site here AND caravan can work AND the site is indeed the same the caravan was working on
            if (currentlyWorkingOnSite & IsThereAConstructionSiteHere() &
                (CaravanCurrentState() == CaravanState.ReadyToWork) && GetCaravan().Tile == GetSite().Tile)
            {
                base.CompTick();
                site.TryToSkipBetterRoads(caravan); // No need to work if there's a better road here
                if (RoadsOfTheRim.DoSomeWork(caravan, GetSite(), out _))
                {
                    StopWorking();
                    UnsetSite();
                }
            }

            // Site tile and Caravan tile mismatch
            if (GetSite() != null && GetCaravan().Tile != GetSite().Tile)
            {
                StopWorking();
                UnsetSite();
            }

            // Stop working as soon as the caravan moves, or rests, or is downed
            if (currentlyWorkingOnSite & (CaravanCurrentState() != CaravanState.ReadyToWork))
            {
                StopWorking();
                var stoppedReason = "";
                // More general use of workOnWakeUp : set it to true if the caravan was working on a site but stopped working for any reason listed in CaravanState
                workOnWakeUp = true;
                if (CaravanCurrentState() == CaravanState.AllOwnersDowned)
                {
                    stoppedReason = "RotR_EveryoneDown".Translate();
                }

                if (CaravanCurrentState() == CaravanState.AllOwnersHaveMentalBreak)
                {
                    stoppedReason = "RotR_EveryoneCrazy".Translate();
                }

                // I decided to remove this (Issue #38) so code should never reach here
                if (CaravanCurrentState() == CaravanState.ImmobilizedByMass)
                {
                    stoppedReason = "RotR_TooHeavy".Translate();
                }

                if (CaravanCurrentState() == CaravanState.NightResting)
                {
                    stoppedReason = "RotR_RestingAtNight".Translate();
                }

                if (stoppedReason != "")
                {
                    Messages.Message("RotR_CaravanStopped".Translate(caravan.Label, site.roadDef.label) + stoppedReason,
                                     MessageTypeDefOf.RejectInput);
                }

                // This should not happen ?
                else
                {
                    workOnWakeUp = false;
                }
            }

            if (!IsThereAConstructionSiteHere())
            {
                StopWorking();
            }
        }