public static bool Overlaps(this CellRect rect, CellRect other)
 {
     if (rect.maxX <= other.minX) return false;
     if (rect.minX >= other.maxX) return false;
     if (rect.maxZ <= other.minZ) return false;
     if (rect.minZ >= other.maxZ) return false;
     return true;
 }
        private static void GenerateRuinFilth(ref OG_OutpostData outpostData)
        {
            const float dustDensity = 0.3f;
            const float slagDensity = 0.1f;
            if (outpostData.isRuined)
            {
                int areaSideLength = 0;
                if (outpostData.size == OG_OutpostSize.SmallOutpost)
                {
                    areaSideLength = OG_SmallOutpost.areaSideLength;
                }
                else
                {
                    areaSideLength = OG_BigOutpost.areaSideLength;
                }
                CellRect areaRect = new CellRect(outpostData.areaSouthWestOrigin.x, outpostData.areaSouthWestOrigin.z, areaSideLength, areaSideLength);
                foreach (IntVec3 cell in areaRect)
                {
                    if (cell.GetEdifice() != null)
                    {
                        continue;
                    }

                    if (Rand.Value < dustDensity)
                    {
                        GenSpawn.Spawn(ThingDefOf.FilthDirt, cell);
                    }
                    if (Rand.Value < slagDensity)
                    {
                        float slagSelector = Rand.Value;
                        if (slagSelector < 0.33f)
                        {
                            GenSpawn.Spawn(ThingDef.Named("RockRubble"), cell);
                        }
                        else if (slagSelector < 0.66f)
                        {
                            GenSpawn.Spawn(ThingDef.Named("BuildingRubble"), cell);
                        }
                        else
                        {
                            GenSpawn.Spawn(ThingDef.Named("SandbagRubble"), cell);
                        }
                    }
                }
            }
        }
        public static void GenerateDropZone(IntVec3 areaSouthWestOrigin, int zoneAbs, int zoneOrd, ref OG_OutpostData outpostData)
        {
            IntVec3 dropZoneOrigin = Zone.GetZoneOrigin(areaSouthWestOrigin, zoneAbs, zoneOrd);
            IntVec3 sandbagsOrigin = dropZoneOrigin + new IntVec3(1, 0, 1);

            CellRect rect = new CellRect(sandbagsOrigin.x, sandbagsOrigin.z, 9, 9);
            foreach (IntVec3 cell in rect.Cells)
            {
                if (((cell.x == rect.minX) || (cell.x == rect.maxX) || (cell.z == rect.minZ) || (cell.z == rect.maxZ))
                    && ((cell.x != rect.CenterCell.x) && (cell.z != rect.CenterCell.z)))
                {
                    OG_Common.TrySpawnThingAt(ThingDefOf.Sandbags, null, cell, false, Rot4.North, ref outpostData);
                }
                Find.TerrainGrid.SetTerrain(cell, TerrainDefOf.Concrete);
            }
            OG_Common.GenerateHorizontalAndVerticalPavedAlleys(dropZoneOrigin);
            OG_Common.TrySpawnThingAt(ThingDef.Named("OrbitalTradeBeacon"), null, rect.CenterCell, false, Rot4.North, ref outpostData);
            Find.TerrainGrid.SetTerrain(rect.CenterCell, TerrainDef.Named("MetalTile"));

            outpostData.dropZoneCenter = rect.CenterCell;
        }
Exemple #4
0
 protected void CalculateAndAddDisallowedCorners(TraverseParms traverseParms, PathEndMode peMode, CellRect destinationRect)
 {
     disallowedCornerIndices.Clear();
     if (peMode == PathEndMode.Touch)
     {
         int minX = destinationRect.minX;
         int minZ = destinationRect.minZ;
         int maxX = destinationRect.maxX;
         int maxZ = destinationRect.maxZ;
         if (!IsCornerTouchAllowed(minX + 1, minZ + 1, minX + 1, minZ, minX, minZ + 1))
         {
             disallowedCornerIndices.Add(map.cellIndices.CellToIndex(minX, minZ));
         }
         if (!IsCornerTouchAllowed(minX + 1, maxZ - 1, minX + 1, maxZ, minX, maxZ - 1))
         {
             disallowedCornerIndices.Add(map.cellIndices.CellToIndex(minX, maxZ));
         }
         if (!IsCornerTouchAllowed(maxX - 1, maxZ - 1, maxX - 1, maxZ, maxX, maxZ - 1))
         {
             disallowedCornerIndices.Add(map.cellIndices.CellToIndex(maxX, maxZ));
         }
         if (!IsCornerTouchAllowed(maxX - 1, minZ + 1, maxX - 1, minZ, maxX, minZ + 1))
         {
             disallowedCornerIndices.Add(map.cellIndices.CellToIndex(maxX, minZ));
         }
     }
 }
 public LordToilData_AttendShow(CellRect rect, Pawn entertainer, IntVec3 entertainerSpot)
 {
     this.audienceRect    = rect;
     this.entertainer     = entertainer;
     this.entertainerSpot = entertainerSpot;
 }
        public static IntVec3 MiddleEdgeCell(Rot4 dir, Map map, Pawn pawn, Predicate <IntVec3> validator)
        {
            List <IntVec3> cellsToCheck = CellRect.WholeMap(map).GetEdgeCells(dir).Where(x => validator(x)).ToList();
            int            padding      = (pawn.def.size.z / 2) > 3 ? (pawn.def.size.z / 2 + 1) : 3;
            int            startIndex   = cellsToCheck.Count / 2;

            for (int j = 0; j < 10000; j++)
            {
                IntVec3 c = pawn.ClampToMap(CellFinder.RandomEdgeCell(dir, map), map, padding);
                if (pawn.PawnOccupiedCells(c).All(x => validator(x)))
                {
                    return(c);
                }
            }
            Log.Warning("Running secondary spawn cell check for boats");
            int i = 0;

            while (cellsToCheck.Count > 0 && i < cellsToCheck.Count / 2)
            {
                if (i > cellsToCheck.Count)
                {
                    Log.Warning("List of Cells almost went out of bounds. Report to Boats mod author - Smash Phil");
                    break;
                }
                IntVec3 rCell = pawn.ClampToMap(cellsToCheck[startIndex + i], map, padding);
                if (ShipHarmony.debug)
                {
                    Log.Message("Checking r: " + rCell + " | " + validator(rCell));
                }
                List <IntVec3> occupiedCellsRCell = pawn.PawnOccupiedCells(rCell);
                foreach (IntVec3 c in occupiedCellsRCell)
                {
                    if (!validator(c))
                    {
                        goto Block_0;
                    }
                }
                return(rCell);

                Block_0 :;
                IntVec3 lCell = pawn.ClampToMap(cellsToCheck[startIndex - i], map, padding);
                if (ShipHarmony.debug)
                {
                    Log.Message("Checking l: " + lCell + " | " + validator(lCell));
                }
                List <IntVec3> occupiedCellsLCell = pawn.PawnOccupiedCells(rCell);
                foreach (IntVec3 c in occupiedCellsLCell)
                {
                    if (!validator(c))
                    {
                        goto Block_1;
                    }
                }
                return(lCell);

                Block_1 :;
                i++;
                if (ShipHarmony.debug)
                {
                    Log.Message("==============");
                }
            }
            Log.Error("Could not find valid edge cell to spawn boats on. This could be due to the Boat being too large to spawn on the coast of a Mountainous Map.");
            return(pawn.ClampToMap(CellFinder.RandomEdgeCell(dir, map), map, padding));
        }
Exemple #7
0
        public PawnPath FindPath(IntVec3 start, LocalTargetInfo dest, TraverseParms traverseParms, PathEndMode peMode = PathEndMode.OnCell)
        {
            if (DebugSettings.pathThroughWalls)
            {
                traverseParms.mode = TraverseMode.PassAllDestroyableThings;
            }
            Pawn pawn = traverseParms.pawn;

            if (pawn != null && pawn.Map != map)
            {
                Log.Warning(String.Format("Map object was rebuilt, but new pather was not assigned to new map (new {0}) (old {1})", pawn.Map.uniqueID, map.uniqueID));
                Log.Error("Tried to FindPath for pawn which is spawned in another map. His map PathFinder should have been used, not this one. pawn=" + pawn + " pawn.Map=" + pawn.Map + " map=" + map);
                return(PawnPath.NotFound);
            }
            if (!start.IsValid)
            {
                Log.Error("Tried to FindPath with invalid start " + start + ", pawn= " + pawn);
                return(PawnPath.NotFound);
            }
            if (!dest.IsValid)
            {
                Log.Error("Tried to FindPath with invalid dest " + dest + ", pawn= " + pawn);
                return(PawnPath.NotFound);
            }
            if (traverseParms.mode == TraverseMode.ByPawn)
            {
                if (!pawn.CanReach(dest, peMode, Danger.Deadly, traverseParms.canBash, traverseParms.mode))
                {
                    return(PawnPath.NotFound);
                }
            }
            else if (!map.reachability.CanReach(start, dest, peMode, traverseParms))
            {
                return(PawnPath.NotFound);
            }
            PfProfilerBeginSample("FindPath for " + pawn + " from " + start + " to " + dest + (dest.HasThing ? (" at " + dest.Cell) : ""));
            cellIndices      = map.cellIndices;
            pathGrid         = map.pathGrid;
            this.edificeGrid = map.edificeGrid.InnerArray;
            blueprintGrid    = map.blueprintGrid.InnerArray;
            int      x        = dest.Cell.x;
            int      z        = dest.Cell.z;
            int      curIndex = cellIndices.CellToIndex(start);
            int      num      = cellIndices.CellToIndex(dest.Cell);
            ByteGrid byteGrid = pawn?.GetAvoidGrid();
            bool     flag     = traverseParms.mode == TraverseMode.PassAllDestroyableThings || traverseParms.mode == TraverseMode.PassAllDestroyableThingsNotWater;
            bool     flag2    = traverseParms.mode != TraverseMode.NoPassClosedDoorsOrWater && traverseParms.mode != TraverseMode.PassAllDestroyableThingsNotWater;
            bool     flag3    = !flag;
            CellRect cellRect = CalculateDestinationRect(dest, peMode);
            bool     flag4    = cellRect.Width == 1 && cellRect.Height == 1;

            int[]        array       = map.pathGrid.pathGrid;
            TerrainDef[] topGrid     = map.terrainGrid.topGrid;
            EdificeGrid  edificeGrid = map.edificeGrid;
            int          num2        = 0;
            int          num3        = 0;
            Area         allowedArea = GetAllowedArea(pawn);
            bool         flag5       = pawn != null && PawnUtility.ShouldCollideWithPawns(pawn);
            bool         flag6       = (!flag && start.GetRegion(map) != null) & flag2;
            bool         flag7       = !flag || !flag3;
            bool         flag8       = false;
            bool         flag9       = pawn?.Drafted ?? false;
            int          num4        = (pawn?.IsColonist ?? false) ? 100000 : 2000;
            int          num5        = 0;
            int          num6        = 0;
            float        num7        = DetermineHeuristicStrength(pawn, start, dest);
            // BEGIN CHANGED SECTION
            // In case pawn is null
            int num8 = 13;
            int num9 = 18;
            Dictionary <TerrainDef, int>  pawnTerrainCacheCardinal    = new Dictionary <TerrainDef, int>();
            Dictionary <TerrainDef, int>  pawnTerrainCacheDiagonal    = new Dictionary <TerrainDef, int>();
            Dictionary <TerrainDef, bool> pawnSpecialMovementCache    = new Dictionary <TerrainDef, bool>();
            Dictionary <TerrainDef, bool> pawnImpassibleMovementCache = new Dictionary <TerrainDef, bool>();
            Dictionary <TerrainDef, int>  pawnTerrainMovementCache    = new Dictionary <TerrainDef, int>();

            // END CHANGED SECTION
            CalculateAndAddDisallowedCorners(traverseParms, peMode, cellRect);
            InitStatusesAndPushStartNode(ref curIndex, start);
            while (true)
            {
                PfProfilerBeginSample("Open cell");
                if (openList.Count <= 0)
                {
                    string text  = (pawn != null && pawn.CurJob != null) ? pawn.CurJob.ToString() : "null";
                    string text2 = (pawn != null && pawn.Faction != null) ? pawn.Faction.ToString() : "null";
                    Log.Warning(pawn + " pathing from " + start + " to " + dest + " ran out of cells to process.\nJob:" + text + "\nFaction: " + text2);
                    DebugDrawRichData();
                    PfProfilerEndSample();
                    PfProfilerEndSample();
                    return(PawnPath.NotFound);
                }
                num5 += openList.Count;
                num6++;
                CostNode costNode = openList.Pop();
                curIndex = costNode.index;
                if (costNode.cost != calcGrid[curIndex].costNodeCost)
                {
                    PfProfilerEndSample();
                    continue;
                }
                if (calcGrid[curIndex].status == statusClosedValue)
                {
                    PfProfilerEndSample();
                    continue;
                }
                IntVec3 c  = cellIndices.IndexToCell(curIndex);
                int     x2 = c.x;
                int     z2 = c.z;
                if (flag4)
                {
                    if (curIndex == num)
                    {
                        PfProfilerEndSample();
                        PawnPath result = FinalizedPath(curIndex, flag8);
                        PfProfilerEndSample();
                        return(result);
                    }
                }
                else if (cellRect.Contains(c) && !disallowedCornerIndices.Contains(curIndex))
                {
                    PfProfilerEndSample();
                    PawnPath result2 = FinalizedPath(curIndex, flag8);
                    PfProfilerEndSample();
                    return(result2);
                }
                if (num2 > 160000)
                {
                    break;
                }
                PfProfilerEndSample();
                PfProfilerBeginSample("Neighbor consideration");
                for (int i = 0; i < 8; i++)
                {
                    uint num10 = (uint)(x2 + Directions[i]);
                    uint num11 = (uint)(z2 + Directions[i + 8]);
                    if (num10 >= mapSizeX || num11 >= mapSizeZ)
                    {
                        continue;
                    }
                    int num12 = (int)num10;
                    int num13 = (int)num11;
                    int num14 = cellIndices.CellToIndex(num12, num13);
                    if (calcGrid[num14].status == statusClosedValue && !flag8)
                    {
                        continue;
                    }
                    // BEGIN CHANGED SECTION
                    IntVec3    targetCell    = new IntVec3(num12, 0, num13);
                    TerrainDef targetTerrain = topGrid[num14];
                    if (pawn != null)
                    {
                        // Use cache of terrain movement indicators to avoid a lot of repeated computation
                        if (!pawnImpassibleMovementCache.TryGetValue(targetTerrain, out bool impassible))
                        {
                            impassible = pawn.kindDef.UnreachableTerrainCheck(targetTerrain);
                            pawnImpassibleMovementCache[targetTerrain] = impassible;
                        }
                        if (impassible)
                        {
                            // Skip this cell for pathing calculations
                            calcGrid[num14].status = statusClosedValue;
                            continue;
                        }

                        // Overwrite directional move costs
                        if (!pawnTerrainCacheCardinal.TryGetValue(targetTerrain, out num8))
                        {
                            num8 = pawn.TerrainAwareTicksPerMoveCardinal(targetTerrain);
                            pawnTerrainCacheCardinal[targetTerrain] = num8;
                        }
                        if (!pawnTerrainCacheDiagonal.TryGetValue(targetTerrain, out num9))
                        {
                            num9 = pawn.TerrainAwareTicksPerMoveDiagonal(targetTerrain);
                            pawnTerrainCacheDiagonal[targetTerrain] = num9;
                        }
                    }
                    // END CHANGED SECTION
                    int  num15  = 0;
                    bool flag10 = false;
                    //if (!flag2 && new IntVec3(num12, 0, num13).GetTerrain(map).HasTag("Water"))
                    if (!flag2 && targetTerrain.HasTag("Water"))
                    {
                        continue;
                    }
                    if (!pathGrid.WalkableFast(num14))
                    {
                        if (!flag)
                        {
                            continue;
                        }
                        flag10 = true;
                        num15 += 70;
                        Building building = edificeGrid[num14];
                        if (building == null || !IsDestroyable(building))
                        {
                            continue;
                        }
                        num15 += (int)((float)building.HitPoints * 0.2f);
                    }
                    switch (i)
                    {
                    case 4:
                        if (BlocksDiagonalMovement(curIndex - mapSizeX))
                        {
                            if (flag7)
                            {
                                continue;
                            }
                            num15 += 70;
                        }
                        if (BlocksDiagonalMovement(curIndex + 1))
                        {
                            if (flag7)
                            {
                                continue;
                            }
                            num15 += 70;
                        }
                        break;

                    case 5:
                        if (BlocksDiagonalMovement(curIndex + mapSizeX))
                        {
                            if (flag7)
                            {
                                continue;
                            }
                            num15 += 70;
                        }
                        if (BlocksDiagonalMovement(curIndex + 1))
                        {
                            if (flag7)
                            {
                                continue;
                            }
                            num15 += 70;
                        }
                        break;

                    case 6:
                        if (BlocksDiagonalMovement(curIndex + mapSizeX))
                        {
                            if (flag7)
                            {
                                continue;
                            }
                            num15 += 70;
                        }
                        if (BlocksDiagonalMovement(curIndex - 1))
                        {
                            if (flag7)
                            {
                                continue;
                            }
                            num15 += 70;
                        }
                        break;

                    case 7:
                        if (BlocksDiagonalMovement(curIndex - mapSizeX))
                        {
                            if (flag7)
                            {
                                continue;
                            }
                            num15 += 70;
                        }
                        if (BlocksDiagonalMovement(curIndex - 1))
                        {
                            if (flag7)
                            {
                                continue;
                            }
                            num15 += 70;
                        }
                        break;
                    }
                    int num16 = (i > 3) ? num9 : num8;
                    num16 += num15;
                    if (!flag10)
                    {
                        // BEGIN CHANGED SECTION
                        //num16 += array[num14];
                        //num16 = ((!flag9) ? (num16 + topGrid[num14].extraNonDraftedPerceivedPathCost) : (num16 + topGrid[num14].extraDraftedPerceivedPathCost));
                        if (pawn == null)
                        {
                            num16 += array[num14];
                            if (flag9)
                            {
                                num16 += targetTerrain.extraDraftedPerceivedPathCost;
                            }
                            else
                            {
                                num16 += targetTerrain.extraNonDraftedPerceivedPathCost;
                            }
                        }
                        else
                        {
                            // Use cache of terrain perceived cost instead of fixed pathCost grid to avoid a lot of repeated computation while maintaining accuracy
                            if (!pawnTerrainMovementCache.TryGetValue(targetTerrain, out int terrainMoveCost))
                            {
                                terrainMoveCost = pawn.TerrainMoveCost(targetTerrain);
                                pawnTerrainMovementCache[targetTerrain] = terrainMoveCost;
                            }
                            // This was really really expensive, so we opted to mod this pre-calced value
                            //num16 += pathGrid.TerrainCalculatedCostAt(map, pawn, targetCell, true, IntVec3.Invalid, terrainMoveCost);
                            num16 += pathGrid.ApplyTerrainModToCalculatedCost(targetTerrain, array[num14], terrainMoveCost);
                            // Use cache of terrain movement indicators to avoid a lot of repeated computation
                            if (!pawnSpecialMovementCache.TryGetValue(targetTerrain, out bool specialMovement))
                            {
                                specialMovement = pawn.TerrainMoveStat(targetTerrain) != StatDefOf.MoveSpeed;
                                pawnSpecialMovementCache[targetTerrain] = specialMovement;
                            }
                            // Skip applying the PerceivedPathCost hack if we've got a specialized speed stat for this terrain
                            if (!specialMovement)
                            {
                                if (flag9)
                                {
                                    num16 += targetTerrain.extraDraftedPerceivedPathCost;
                                }
                                else
                                {
                                    num16 += targetTerrain.extraNonDraftedPerceivedPathCost;
                                }
                            }
                        }
                        // END CHANGED SECTION
                    }
                    if (byteGrid != null)
                    {
                        num16 += byteGrid[num14] * 8;
                    }
                    if (allowedArea != null && !allowedArea[num14])
                    {
                        num16 += 600;
                    }
                    //new IntVec3(num12, 0, num13) -> targetCell
                    if (flag5 && PawnUtility.AnyPawnBlockingPathAt(targetCell, pawn, actAsIfHadCollideWithPawnsJob: false, collideOnlyWithStandingPawns: false, forPathFinder: true))
                    {
                        num16 += 175;
                    }
                    Building building2 = this.edificeGrid[num14];
                    if (building2 != null)
                    {
                        PfProfilerBeginSample("Edifices");
                        int buildingCost = GetBuildingCost(building2, traverseParms, pawn);
                        if (buildingCost == int.MaxValue)
                        {
                            PfProfilerEndSample();
                            continue;
                        }
                        num16 += buildingCost;
                        PfProfilerEndSample();
                    }
                    List <Blueprint> list = blueprintGrid[num14];
                    if (list != null)
                    {
                        PfProfilerBeginSample("Blueprints");
                        int num17 = 0;
                        for (int j = 0; j < list.Count; j++)
                        {
                            num17 = Mathf.Max(num17, GetBlueprintCost(list[j], pawn));
                        }
                        if (num17 == int.MaxValue)
                        {
                            PfProfilerEndSample();
                            continue;
                        }
                        num16 += num17;
                        PfProfilerEndSample();
                    }
                    int    num18  = num16 + calcGrid[curIndex].knownCost;
                    ushort status = calcGrid[num14].status;
                    if (status == statusClosedValue || status == statusOpenValue)
                    {
                        int num19 = 0;
                        if (status == statusClosedValue)
                        {
                            num19 = num8;
                        }
                        if (calcGrid[num14].knownCost <= num18 + num19)
                        {
                            continue;
                        }
                    }
                    if (flag8)
                    {
                        calcGrid[num14].heuristicCost = Mathf.RoundToInt((float)regionCostCalculator.GetPathCostFromDestToRegion(num14) * RegionHeuristicWeightByNodesOpened.Evaluate(num3));
                        if (calcGrid[num14].heuristicCost < 0)
                        {
                            Log.ErrorOnce("Heuristic cost overflow for " + pawn.ToStringSafe() + " pathing from " + start + " to " + dest + ".", pawn.GetHashCode() ^ 0xB8DC389);
                            calcGrid[num14].heuristicCost = 0;
                        }
                    }
                    else if (status != statusClosedValue && status != statusOpenValue)
                    {
                        int dx    = Math.Abs(num12 - x);
                        int dz    = Math.Abs(num13 - z);
                        int num20 = GenMath.OctileDistance(dx, dz, num8, num9);
                        calcGrid[num14].heuristicCost = Mathf.RoundToInt((float)num20 * num7);
                    }
                    int num21 = num18 + calcGrid[num14].heuristicCost;
                    if (num21 < 0)
                    {
                        Log.ErrorOnce("Node cost overflow for " + pawn.ToStringSafe() + " pathing from " + start + " to " + dest + ".", pawn.GetHashCode() ^ 0x53CB9DE);
                        num21 = 0;
                    }
                    calcGrid[num14].parentIndex  = curIndex;
                    calcGrid[num14].knownCost    = num18;
                    calcGrid[num14].status       = statusOpenValue;
                    calcGrid[num14].costNodeCost = num21;
                    num3++;
                    openList.Push(new CostNode(num14, num21));
                }
                PfProfilerEndSample();
                num2++;
                calcGrid[curIndex].status = statusClosedValue;
                if (num3 >= num4 && flag6 && !flag8)
                {
                    flag8 = true;
                    regionCostCalculator.Init(cellRect, traverseParms, num8, num9, byteGrid, allowedArea, flag9, disallowedCornerIndices);
                    InitStatusesAndPushStartNode(ref curIndex, start);
                    num3 = 0;
                    num2 = 0;
                }
            }
            Log.Warning(pawn + " pathing from " + start + " to " + dest + " hit search limit of " + 160000 + " cells.");
            DebugDrawRichData();
            PfProfilerEndSample();
            PfProfilerEndSample();
            return(PawnPath.NotFound);
        }
        public static void SpawnRectTriggerUnfogArea(CellRect rect, ref TriggerIntrusion triggerIntrusion)
        {
            RectTriggerUnfogArea rectTrigger = (RectTriggerUnfogArea)ThingMaker.MakeThing(ThingDef.Named("RectTriggerUnfogArea"));
            rectTrigger.Rect = rect;
            GenSpawn.Spawn(rectTrigger, rect.CenterCell);

            // Update the trigger intrusion watched cells.
            foreach (IntVec3 cell in rect.Cells)
            {
                if (triggerIntrusion.watchedCells.Contains(cell) == false)
                {
                    triggerIntrusion.watchedCells.Add(cell);
                }
            }
        }
        public void SearchForTargets(IntVec3 center, float radius)
        {
            Pawn     curPawnTarg = null;
            Building curBldgTarg = null;
            //IntVec3 curCell;
            //IEnumerable <IntVec3> targets = GenRadial.RadialCellsAround(center, radius, true);
            //for (int i = 0; i < targets.Count(); i++)
            //{
            //    curCell = targets.ToArray<IntVec3>()[i];
            //    if ( curCell.InBounds(base.Map) && curCell.IsValid)
            //    {
            //        curPawnTarg = curCell.GetFirstPawn(base.Map);
            //        curBldgTarg = curCell.GetFirstBuilding(base.Map);
            //    }
            List <Pawn> targets = new List <Pawn>();

            if (this.age > this.lastStrike)
            {
                targets = TM_Calc.FindAllPawnsAround(base.Map, center, radius);
                if (targets != null && targets.Count > 0)
                {
                    curPawnTarg = targets.RandomElement();
                    if (curPawnTarg != launcher)
                    {
                        CellRect cellRect = CellRect.CenteredOn(curPawnTarg.Position, 2);
                        cellRect.ClipInsideMap(base.Map);
                        DrawStrike(center, curPawnTarg.Position.ToVector3());
                        for (int k = 0; k < Rand.Range(1, 8); k++)
                        {
                            IntVec3 randomCell = cellRect.RandomCell;
                            GenExplosion.DoExplosion(randomCell, base.Map, Rand.Range(.4f, .8f), TMDamageDefOf.DamageDefOf.TM_Lightning, this.launcher, Mathf.RoundToInt(Rand.Range(5 + pwrVal, 9 + (3 * pwrVal)) * this.arcaneDmg), 0, SoundDefOf.Thunder_OnMap, null, null, null, null, 0f, 1, false, null, 0f, 1, 0.1f, true);
                        }
                        GenExplosion.DoExplosion(curPawnTarg.Position, base.Map, 1f, TMDamageDefOf.DamageDefOf.TM_Lightning, this.launcher, Mathf.RoundToInt(Rand.Range(5 + pwrVal, 9 + (3 * pwrVal)) * this.arcaneDmg), 0, SoundDefOf.Thunder_OffMap, null, null, null, null, 0f, 1, false, null, 0f, 1, 0.1f, true);
                        this.lastStrike = this.age + (this.maxStrikeDelay - (int)Rand.Range(0 + (pwrVal * 20), 50 + (pwrVal * 10)));
                    }
                    else
                    {
                        this.lastStrike += 10;
                    }
                }
                else
                {
                    this.lastStrike += 10;
                }
            }

            if (this.age > this.lastStrikeBldg)
            {
                List <Building> list = new List <Building>();
                list.Clear();
                list = (from x in base.Map.listerThings.AllThings
                        where x.Position.InHorDistOf(center, radius) && !x.DestroyedOrNull() && x is Building
                        select x as Building).ToList <Building>();
                if (list.Count > 0)
                {
                    curBldgTarg = list.RandomElement();
                    CellRect cellRect = CellRect.CenteredOn(curBldgTarg.Position, 1);
                    cellRect.ClipInsideMap(base.Map);
                    DrawStrike(center, curBldgTarg.Position.ToVector3());
                    for (int k = 0; k < Rand.Range(1, 8); k++)
                    {
                        IntVec3 randomCell = cellRect.RandomCell;
                        GenExplosion.DoExplosion(randomCell, base.Map, Rand.Range(.2f, .6f), TMDamageDefOf.DamageDefOf.TM_Lightning, this.launcher, Mathf.RoundToInt(Rand.Range(3 + (3 * pwrVal), 7 + (5 * pwrVal)) * this.arcaneDmg), 0, SoundDefOf.Thunder_OffMap, null, null, null, null, 0f, 1, false, null, 0f, 1, 0.1f, true);
                    }
                    GenExplosion.DoExplosion(curBldgTarg.Position, base.Map, 1f, TMDamageDefOf.DamageDefOf.TM_Lightning, this.launcher, Mathf.RoundToInt(Rand.Range(10 + (3 * pwrVal), 25 + (5 * pwrVal)) * this.arcaneDmg), 0, SoundDefOf.Thunder_OffMap, null, null, null, null, 0f, 1, false, null, 0f, 1, 0.1f, true);
                    this.lastStrikeBldg = this.age + (this.maxStrikeDelayBldg - (int)Rand.Range(0 + (pwrVal * 10), pwrVal * 15));
                }
                else
                {
                    this.lastStrikeBldg += 10;
                }
            }

            //}
            DrawStrikeFading();
            age++;
        }
        public static bool TryFindBestWatchCell(Thing toWatch, Pawn pawn, bool desireSit, out IntVec3 result, out Building chair)
        {
            List <int> list   = WatchBuildingUtility.CalculateAllowedDirections(toWatch.def, toWatch.Rotation);
            IntVec3    intVec = IntVec3.Invalid;

            for (int i = 0; i < list.Count; i++)
            {
                CellRect watchCellRect = WatchBuildingUtility.GetWatchCellRect(toWatch.def, toWatch.Position, toWatch.Rotation, list[i]);
                IntVec3  centerCell    = watchCellRect.CenterCell;
                int      num           = watchCellRect.Area * 4;
                for (int j = 0; j < num; j++)
                {
                    IntVec3 intVec2 = centerCell + GenRadial.RadialPattern[j];
                    if (watchCellRect.Contains(intVec2))
                    {
                        bool     flag     = false;
                        Building building = null;
                        if (WatchBuildingUtility.EverPossibleToWatchFrom(intVec2, toWatch.Position, toWatch.Map, false) && !intVec2.IsForbidden(pawn) && pawn.CanReserve(intVec2, 1, -1, null, false) && pawn.Map.pawnDestinationReservationManager.CanReserve(intVec2, pawn, false))
                        {
                            if (desireSit)
                            {
                                building = intVec2.GetEdifice(pawn.Map);
                                if (building != null && building.def.building.isSittable && pawn.CanReserve(building, 1, -1, null, false))
                                {
                                    flag = true;
                                }
                            }
                            else
                            {
                                flag = true;
                            }
                        }
                        if (flag)
                        {
                            if (desireSit)
                            {
                                Rot4 rotation = building.Rotation;
                                Rot4 rot      = new Rot4(list[i]);
                                if (rotation != rot.Opposite)
                                {
                                    intVec = intVec2;
                                    goto IL_191;
                                }
                            }
                            result = intVec2;
                            chair  = building;
                            return(true);
                        }
                        IL_191 :;
                    }
                }
            }
            if (intVec.IsValid)
            {
                result = intVec;
                chair  = intVec.GetEdifice(pawn.Map);
                return(true);
            }
            result = IntVec3.Invalid;
            chair  = null;
            return(false);
        }
 public SectionTerrain(CellRect rect)
 {
     Rect = rect;
     Terrains = new HashSet<TerrainDef>();
 }
        protected void TrySpread()
        {
            IntVec3 intVec = base.Position;
            bool    flag;

            Rand.PushState();
            if (Rand.Chance(0.8f))
            {
                intVec = base.Position + GenRadial.ManualRadialPattern[Rand.RangeInclusive(1, 8)];
                flag   = true;
            }
            else
            {
                intVec = base.Position + GenRadial.ManualRadialPattern[Rand.RangeInclusive(10, 20)];
                flag   = false;
            }
            Rand.PopState();
            if (!intVec.InBounds(base.Map))
            {
                return;
            }

            float chance;

            if (this.def.projectile.damageDef == AdeptusDamageDefOf.OG_Chaos_Deamon_Warpfire)
            {
                chance = WarpfireUtility.ChanceToStartWarpfireIn(intVec, base.Map);
            }
            else
            {
                chance = FireUtility.ChanceToStartFireIn(intVec, base.Map);
            }

            Rand.PushState();
            bool f = Rand.Chance(chance);

            Rand.PopState();
            if (f)
            {
                if (!flag)
                {
                    CellRect startRect = CellRect.SingleCell(base.Position);
                    CellRect endRect   = CellRect.SingleCell(intVec);
                    if (!GenSight.LineOfSight(base.Position, intVec, base.Map, startRect, endRect, null))
                    {
                        return;
                    }
                    Spark spark;
                    if (this.def.projectile.damageDef == AdeptusDamageDefOf.OG_Chaos_Deamon_Warpfire)
                    {
                        spark = (Spark)GenSpawn.Spawn(AdeptusThingDefOf.OG_WarpSpark, base.Position, base.Map, WipeMode.Vanish);
                    }
                    else
                    {
                        spark = (Spark)GenSpawn.Spawn(ThingDefOf.Spark, base.Position, base.Map, WipeMode.Vanish);
                    }
                    spark.Launch(this, intVec, intVec, ProjectileHitFlags.All, null);
                }
                else
                {
                    if (this.def.projectile.damageDef == AdeptusDamageDefOf.OG_Chaos_Deamon_Warpfire)
                    {
                        WarpfireUtility.TryStartWarpfireIn(intVec, base.Map, 0.1f);
                    }
                    else
                    {
                        FireUtility.TryStartFireIn(intVec, base.Map, 0.1f);
                    }
                }
            }
        }
Exemple #13
0
        protected override void Impact(Thing hitThing)
        {
            Map map = base.Map;

            base.Impact(hitThing);
            ThingDef def = this.def;

            CellRect cellRect = CellRect.CenteredOn(base.Position, 1);

            cellRect.ClipInsideMap(map);
            IntVec3 centerCell = cellRect.CenterCell;
            IntVec3 expCell1   = centerCell;
            IntVec3 expCell2   = centerCell;
            IntVec3 target     = base.Position;

            Hediff invul = new Hediff();

            invul.def      = TorannMagicDefOf.TM_HediffInvulnerable;
            invul.Severity = 5;

            pawn = this.launcher as Pawn;
            pawn.health.AddHediff(invul, null, null);

            CompAbilityUserMagic comp = pawn.GetComp <CompAbilityUserMagic>();
            MagicPowerSkill      pwr  = pawn.GetComp <CompAbilityUserMagic>().MagicData.MagicPowerSkill_ValiantCharge.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_ValiantCharge_pwr");
            MagicPowerSkill      ver  = pawn.GetComp <CompAbilityUserMagic>().MagicData.MagicPowerSkill_ValiantCharge.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_ValiantCharge_ver");

            if (initialize)
            {
                Initialize(target, pawn);
                pawn.Rotation = pawn.Rotation.Opposite;
            }

            bool flag = arg_40_0 && arg_41_0 && arg_42_0;

            if (flag)
            {
                if (!destinationReached && this.age >= lastMove + moveRate)
                {
                    lastMove = this.age;
                    XProb(target, pawn);
                    if (target.x == pawn.Position.x)
                    {
                        xflag = true;
                    }
                    if (target.z == pawn.Position.z)
                    {
                        zflag = true;
                    }
                    MoteMaker.ThrowDustPuff(newPos, pawn.Map, Rand.Range(0.8f, 1.2f));
                    newPos = GetNewPos(pawn.Position, pawn.Position.x <= target.x, pawn.Position.z <= target.z, false, 0, 0, xProb, 1 - xProb);
                    pawn.SetPositionDirect(newPos);
                    pawn.Rotation = pawn.Rotation.Opposite;
                    pawn.mindState.priorityWork.ClearPrioritizedWorkAndJobQueue();

                    if (xflag && zflag)
                    {
                        destinationReached = true;
                    }
                }
                DrawWings(pawn, 10);
            }
            else
            {
                // Log.Message("arg_40_0:" + arg_40_0 + " arg_41_0:" + arg_41_0 + " arg_42_0:" + arg_42_0);
                Messages.Message("InvalidTargetLocation".Translate(), MessageTypeDefOf.RejectInput);
                destinationReached = true;
            }

            if (destinationReached)
            {
                zflag = false;
                xflag = false;
                SoundDefOf.AmbientAltitudeWind.sustainFadeoutTime.Equals(30.0f);
                this.FireExplosion(pwr.level, ver.level, centerCell, map, (1.2f + (float)(ver.level * .8f)));
                MoteMaker.ThrowSmoke(pawn.Position.ToVector3(), map, (0.8f + (float)(ver.level * .8f)));

                pawn.mindState.priorityWork.ClearPrioritizedWorkAndJobQueue();
                pawn.Map.pawnDestinationReservationManager.ReleaseAllClaimedBy(pawn);
                pawn.Map.physicalInteractionReservationManager.ReleaseAllClaimedBy(pawn);
                //pawn.Map.pawnDestinationManager.UnreserveAllFor(pawn);
                pawn.jobs.StopAll();
                RemoveInvul(pawn);

                for (int i = 0; i < (2 + ver.level); i++)
                {
                    expCell1 = GetNewPos(expCell1, originPos.x <= target.x, originPos.z <= target.z, false, 0, 0, xProbOrigin, 1 - xProbOrigin);
                    MoteMaker.ThrowSmoke(expCell1.ToVector3(), map, 1.6f);
                    expCell2 = GetNewPos(expCell2, originPos.x <= target.x, originPos.z <= target.z, false, 0, 0, 1 - xProbOrigin, xProbOrigin);
                    MoteMaker.ThrowSmoke(expCell2.ToVector3(), map, 1.6f);
                }
                for (int i = 0; i < (4 + (3 * ver.level)); i++)
                {
                    cellRect = CellRect.CenteredOn(expCell1, (1 + ver.level));
                    IntVec3 randomCell = cellRect.RandomCell;
                    this.FireExplosion(pwr.level, ver.level, randomCell, map, .4f);
                    cellRect   = CellRect.CenteredOn(expCell2, (1 + ver.level));
                    randomCell = cellRect.RandomCell;
                    this.FireExplosion(pwr.level, ver.level, randomCell, map, .4f);
                }
            }
        }
Exemple #14
0
        protected override void Impact(Thing hitThing)
        {
            Map map = base.Map;

            base.Impact(hitThing);
            ThingDef def  = this.def;
            Pawn     pawn = this.launcher as Pawn;

            if (!this.initialized)
            {
                CompAbilityUserMagic comp = pawn.GetComp <CompAbilityUserMagic>();
                MagicPowerSkill      pwr  = pawn.GetComp <CompAbilityUserMagic>().MagicData.MagicPowerSkill_CorpseExplosion.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_CorpseExplosion_pwr");
                MagicPowerSkill      ver  = pawn.GetComp <CompAbilityUserMagic>().MagicData.MagicPowerSkill_CorpseExplosion.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_CorpseExplosion_ver");
                this.arcaneDmg = comp.arcaneDmg;
                pwrVal         = pwr.level;
                verVal         = ver.level;
                if (pawn.story.traits.HasTrait(TorannMagicDefOf.Faceless))
                {
                    MightPowerSkill mpwr = pawn.GetComp <CompAbilityUserMight>().MightData.MightPowerSkill_Mimic.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Mimic_pwr");
                    MightPowerSkill mver = pawn.GetComp <CompAbilityUserMight>().MightData.MightPowerSkill_Mimic.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Mimic_ver");
                    pwrVal = mpwr.level;
                    verVal = mver.level;
                }
                Initialize();

                CellRect cellRect = CellRect.CenteredOn(base.Position, 1);
                cellRect.ClipInsideMap(map);
                IntVec3 curCell = cellRect.CenterCell;
                if (curCell.InBounds(map) && curCell.IsValid)
                {
                    Pawn undead = curCell.GetFirstPawn(map);
                    bool flag   = undead != null && !undead.Dead;
                    if (flag)
                    {
                        if (TM_Calc.IsUndead(undead))
                        {
                            this.targetPawn = undead;
                        }
                        //if (undead.health.hediffSet.HasHediff(TorannMagicDefOf.TM_UndeadHD))
                        //{
                        //    this.targetPawn = undead;
                        //}
                        //if (undead.health.hediffSet.HasHediff(TorannMagicDefOf.TM_UndeadAnimalHD))
                        //{
                        //    this.targetPawn = undead;
                        //}
                    }

                    Thing  corpseThing = curCell.GetFirstItem(map);
                    Corpse corpse      = null;
                    if (corpseThing != null)
                    {
                        bool validator = corpseThing is Corpse;
                        if (validator)
                        {
                            corpse = corpseThing as Corpse;
                            Pawn corpsePawn = corpse.InnerPawn;
                            if (corpsePawn.RaceProps.IsFlesh)
                            {
                                if (corpsePawn.RaceProps.Humanlike || corpsePawn.RaceProps.Animal || TM_Calc.IsUndead(corpsePawn))
                                {
                                    this.targetCorpse = corpse;
                                }
                            }
                        }
                    }
                }
            }

            if (this.targetPawn != null && !this.targetPawn.Destroyed)
            {
                if (this.age == 360)
                {
                    MoteMaker.ThrowText(this.targetPawn.Position.ToVector3ShiftedWithAltitude(AltitudeLayer.MoteOverhead), map, "6", -.5f);
                }
                if (this.age == 300)
                {
                    MoteMaker.ThrowText(this.targetPawn.Position.ToVector3ShiftedWithAltitude(AltitudeLayer.MoteOverhead), map, "5", -.5f);
                }
                if (this.age == 240)
                {
                    MoteMaker.ThrowText(this.targetPawn.Position.ToVector3ShiftedWithAltitude(AltitudeLayer.MoteOverhead), map, "4", -.5f);
                }
                if (this.age == 180)
                {
                    MoteMaker.ThrowText(this.targetPawn.Position.ToVector3ShiftedWithAltitude(AltitudeLayer.MoteOverhead), map, "3", -.5f);
                }
                if (this.age == 120)
                {
                    MoteMaker.ThrowText(this.targetPawn.Position.ToVector3ShiftedWithAltitude(AltitudeLayer.MoteOverhead), map, "2", -.5f);
                }
                if (this.age == 60)
                {
                    MoteMaker.ThrowText(this.targetPawn.Position.ToVector3ShiftedWithAltitude(AltitudeLayer.MoteOverhead), map, "1", -.5f);
                }
                if (this.age == 1)
                {
                    //explode
                    TM_MoteMaker.ThrowBloodSquirt(this.targetPawn.Position.ToVector3Shifted(), map, 1.2f);
                    TM_MoteMaker.ThrowBloodSquirt(this.targetPawn.Position.ToVector3Shifted(), map, .6f);
                    TM_MoteMaker.ThrowBloodSquirt(this.targetPawn.Position.ToVector3Shifted(), map, .8f);
                    if (targetPawn.def != TorannMagicDefOf.TM_SkeletonLichR && targetPawn.def != TorannMagicDefOf.TM_GiantSkeletonR)
                    {
                        if (this.targetPawn.RaceProps.Humanlike)
                        {
                            this.targetPawn.inventory.DropAllNearPawn(this.targetPawn.Position, false, true);
                            this.targetPawn.equipment.DropAllEquipment(this.targetPawn.Position, false);
                            this.targetPawn.apparel.DropAll(this.targetPawn.Position, false);
                        }
                        if (!this.targetPawn.Destroyed)
                        {
                            this.targetPawn.Destroy();
                        }
                    }
                    GenExplosion.DoExplosion(this.targetPawn.Position, map, this.radius, TMDamageDefOf.DamageDefOf.TM_CorpseExplosion, this.launcher, Mathf.RoundToInt((Rand.Range(18f, 30f) + (5f * pwrVal)) * this.arcaneDmg), 0, this.def.projectile.soundExplode, def, this.equipmentDef, null, null, 0f, 01, false, null, 0f, 0, 0.0f, true);
                }
            }

            if (this.targetCorpse != null && !this.targetCorpse.Destroyed)
            {
                if (this.age == 360)
                {
                    MoteMaker.ThrowText(this.targetCorpse.Position.ToVector3ShiftedWithAltitude(AltitudeLayer.MoteOverhead), map, "6", -.5f);
                }
                if (this.age == 300)
                {
                    MoteMaker.ThrowText(this.targetCorpse.Position.ToVector3ShiftedWithAltitude(AltitudeLayer.MoteOverhead), map, "5", -.5f);
                }
                if (this.age == 240)
                {
                    MoteMaker.ThrowText(this.targetCorpse.Position.ToVector3ShiftedWithAltitude(AltitudeLayer.MoteOverhead), map, "4", -.5f);
                }
                if (this.age == 180)
                {
                    MoteMaker.ThrowText(this.targetCorpse.Position.ToVector3ShiftedWithAltitude(AltitudeLayer.MoteOverhead), map, "3", -.5f);
                }
                if (this.age == 120)
                {
                    MoteMaker.ThrowText(this.targetCorpse.Position.ToVector3ShiftedWithAltitude(AltitudeLayer.MoteOverhead), map, "2", -.5f);
                }
                if (this.age == 60)
                {
                    MoteMaker.ThrowText(this.targetCorpse.Position.ToVector3ShiftedWithAltitude(AltitudeLayer.MoteOverhead), map, "1", -.5f);
                }
                if (this.age == 1)
                {
                    //explode
                    TM_MoteMaker.ThrowBloodSquirt(this.targetCorpse.Position.ToVector3Shifted(), map, 1.2f);
                    TM_MoteMaker.ThrowBloodSquirt(this.targetCorpse.Position.ToVector3Shifted(), map, .6f);
                    TM_MoteMaker.ThrowBloodSquirt(this.targetCorpse.Position.ToVector3Shifted(), map, .8f);
                    Pawn corpsePawn = this.targetCorpse.InnerPawn;
                    if (corpsePawn.RaceProps.Humanlike)
                    {
                        corpsePawn.inventory.DropAllNearPawn(this.targetCorpse.Position, false, true);
                        corpsePawn.equipment.DropAllEquipment(this.targetCorpse.Position, false);
                        corpsePawn.apparel.DropAll(this.targetCorpse.Position, false);
                    }
                    GenExplosion.DoExplosion(this.targetCorpse.Position, map, this.radius, TMDamageDefOf.DamageDefOf.TM_CorpseExplosion, this.launcher, Mathf.RoundToInt((Rand.Range(18f, 30f) + (5f * pwrVal)) * this.arcaneDmg), 0, this.def.projectile.soundExplode, def, this.equipmentDef, null, null, 0f, 01, false, null, 0f, 0, 0.0f, true);
                    if (!this.targetCorpse.Destroyed)
                    {
                        this.targetCorpse.Destroy();
                    }
                }
            }
        }
Exemple #15
0
        public override void Impact_Override(Thing hitThing)
        {
            Map map = base.Map;

            base.Impact_Override(hitThing);

            Pawn pawn = this.launcher as Pawn;

            ModOptions.SettingsRef settingsRef = new ModOptions.SettingsRef();

            if (pawn.story.traits.HasTrait(TorannMagicDefOf.Faceless))
            {
                MightPowerSkill mpwr = pawn.GetComp <CompAbilityUserMight>().MightData.MightPowerSkill_Mimic.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Mimic_pwr");
                MightPowerSkill mver = pawn.GetComp <CompAbilityUserMight>().MightData.MightPowerSkill_Mimic.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Mimic_ver");
                pwrVal         = mpwr.level;
                verVal         = mver.level;
                this.arcaneDmg = pawn.GetComp <CompAbilityUserMight>().mightPwr;
            }
            else
            {
                CompAbilityUserMagic comp = pawn.GetComp <CompAbilityUserMagic>();
                MagicPowerSkill      pwr  = pawn.GetComp <CompAbilityUserMagic>().MagicData.MagicPowerSkill_LightningBolt.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_LightningBolt_pwr");
                MagicPowerSkill      ver  = pawn.GetComp <CompAbilityUserMagic>().MagicData.MagicPowerSkill_LightningBolt.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_LightningBolt_ver");
                pwrVal         = pwr.level;
                verVal         = ver.level;
                this.arcaneDmg = comp.arcaneDmg;
            }

            if (settingsRef.AIHardMode && !pawn.IsColonist)
            {
                pwrVal = 3;
                verVal = 3;
            }
            bool flag = hitThing != null;

            if (flag)
            {
                int        DamageAmount = Mathf.RoundToInt(this.def.projectile.GetDamageAmount(1, null) + (pwrVal * 6) * this.arcaneDmg);
                DamageInfo dinfo        = new DamageInfo(this.def.projectile.damageDef, DamageAmount, 1, this.ExactRotation.eulerAngles.y, this.launcher, null, this.equipmentDef, DamageInfo.SourceCategory.ThingOrUnknown);
                hitThing.TakeDamage(dinfo);
                if (Rand.Chance(.6f))
                {
                    DamageInfo dinfo2 = new DamageInfo(DamageDefOf.Stun, DamageAmount / 4, 1, this.ExactRotation.eulerAngles.y, this.launcher, null, this.equipmentDef, DamageInfo.SourceCategory.ThingOrUnknown);
                    hitThing.TakeDamage(dinfo2);
                }

                bool flag2 = this.canStartFire && Rand.Range(0f, 1f) > this.startFireChance;
                if (flag2)
                {
                    hitThing.TryAttachFire(0.05f);
                }
                Pawn hitTarget;
                bool flag3 = (hitTarget = (hitThing as Pawn)) != null;
                if (flag3)
                {
                    this.PostImpactEffects(this.launcher as Pawn, hitTarget);
                    FleckMaker.ThrowMicroSparks(this.destination, base.Map);
                    FleckMaker.Static(this.destination, base.Map, FleckDefOf.ShotHit_Dirt, 1f);
                }
            }
            else
            {
                FleckMaker.Static(this.ExactPosition, base.Map, FleckDefOf.ShotHit_Dirt, 1f);
                FleckMaker.ThrowMicroSparks(this.ExactPosition, base.Map);
            }
            for (int i = 0; i <= verVal; i++)
            {
                SoundInfo info = SoundInfo.InMap(new TargetInfo(base.Position, base.Map, false), MaintenanceType.None);
                SoundDefOf.Thunder_OnMap.PlayOneShot(info);
            }
            CellRect cellRect = CellRect.CenteredOn(hitThing.Position, 2);

            cellRect.ClipInsideMap(map);
            for (int i = 0; i < Rand.Range(verVal, verVal * 4); i++)
            {
                IntVec3 randomCell = cellRect.RandomCell;
                this.StaticExplosion(randomCell, map, 0.4f);
            }
        }
        protected override void ScatterAt(IntVec3 loc, Map map, GenStepParams parms, int stackCount = 1)
        {
            var randomInRange             = ShrinesCountX.RandomInRange;
            var randomInRange2            = ShrinesCountZ.RandomInRange;
            var randomInRange3            = ExtraHeightRange.RandomInRange;
            var standardAncientShrineSize = SymbolResolver_AncientShrinesGroupMedieval.StandardAncientShrineSize;
            var num2 = (randomInRange * standardAncientShrineSize.x) + (randomInRange - 1);
            var num3 = (randomInRange2 * standardAncientShrineSize.z) + (randomInRange2 - 1);
            var num4 = num2 + 2;
            var num5 = num3 + 2 + randomInRange3;
            var rect = new CellRect(loc.x, loc.z, num4, num5);

            rect.ClipInsideMap(map);
            if (rect.Width != num4 || rect.Height != num5)
            {
                return;
            }

            foreach (var c in rect.Cells)
            {
                var list = map.thingGrid.ThingsListAt(c);
                foreach (var thing in list)
                {
                    if (thing.def == ThingDefOf.AncientCryptosleepCasket)
                    {
                        return;
                    }
                }
            }

            if (!CanPlaceAncientBuildingInRange(rect, map))
            {
                return;
            }

            var resolveParams = default(ResolveParams);

            resolveParams.sketch       = new Sketch();
            resolveParams.monumentSize = new IntVec2(num2, num3);
            SketchGen.Generate(SketchResolverDefOf.MonumentRuin, resolveParams).Spawn(map, rect.CenterCell, null,
                                                                                      Sketch.SpawnPosType.Unchanged, Sketch.SpawnMode.Normal, false, false, null, false, false,
                                                                                      delegate(SketchEntity entity, IntVec3 cell)
            {
                var result = false;
                foreach (var b in entity.OccupiedRect.AdjacentCells)
                {
                    var c2 = cell + b;
                    if (!c2.InBounds(map))
                    {
                        continue;
                    }

                    var edifice = c2.GetEdifice(map);
                    if (edifice != null && edifice.def.building.isNaturalRock)
                    {
                        continue;
                    }

                    result = true;
                    break;
                }

                return(result);
            });

            var nextSignalTagID     = Find.UniqueIDsManager.GetNextSignalTagID();
            var signalTag           = "ancientTempleApproached-" + nextSignalTagID;
            var signalAction_Letter = (SignalAction_Letter)ThingMaker.MakeThing(ThingDefOf.SignalAction_Letter);

            signalAction_Letter.signalTag = signalTag;
            signalAction_Letter.letter    = LetterMaker.MakeLetter("LetterLabelAncientShrineWarning".Translate(),
                                                                   "AncientShrineWarning".Translate(), LetterDefOf.NeutralEvent, new TargetInfo(rect.CenterCell, map));
            GenSpawn.Spawn(signalAction_Letter, rect.CenterCell, map);
            var rectTrigger = (RectTrigger)ThingMaker.MakeThing(ThingDefOf.RectTrigger);

            rectTrigger.signalTag         = signalTag;
            rectTrigger.Rect              = rect.ExpandedBy(1).ClipInsideMap(map);
            rectTrigger.destroyIfUnfogged = true;
            GenSpawn.Spawn(rectTrigger, rect.CenterCell, map);
        }
        public static AcceptanceReport CanPlaceBlueprintAt(BuildableDef entDef, IntVec3 center, Rot4 rot, Map map, bool godMode = false, Thing thingToIgnore = null)
        {
            CellRect cellRect = GenAdj.OccupiedRect(center, rot, entDef.Size);

            CellRect.CellRectIterator iterator = cellRect.GetIterator();
            while (!iterator.Done())
            {
                IntVec3 current = iterator.Current;
                if (!current.InBounds(map))
                {
                    return(new AcceptanceReport("OutOfBounds".Translate()));
                }
                if (current.InNoBuildEdgeArea(map) && !DebugSettings.godMode)
                {
                    return("TooCloseToMapEdge".Translate());
                }
                iterator.MoveNext();
            }
            if (center.Fogged(map))
            {
                return("CannotPlaceInUndiscovered".Translate());
            }
            List <Thing> thingList = center.GetThingList(map);

            for (int i = 0; i < thingList.Count; i++)
            {
                Thing thing = thingList[i];
                if (thing != thingToIgnore && thing.Position == center && thing.Rotation == rot)
                {
                    if (thing.def == entDef)
                    {
                        return(new AcceptanceReport("IdenticalThingExists".Translate()));
                    }
                    if (thing.def.entityDefToBuild == entDef)
                    {
                        if (thing is Blueprint)
                        {
                            return(new AcceptanceReport("IdenticalBlueprintExists".Translate()));
                        }
                        return(new AcceptanceReport("IdenticalThingExists".Translate()));
                    }
                }
            }
            ThingDef thingDef = entDef as ThingDef;

            if (thingDef != null && thingDef.hasInteractionCell)
            {
                IntVec3 c = ThingUtility.InteractionCellWhenAt(thingDef, center, rot, map);
                if (!c.InBounds(map))
                {
                    return(new AcceptanceReport("InteractionSpotOutOfBounds".Translate()));
                }
                List <Thing> list = map.thingGrid.ThingsListAtFast(c);
                for (int j = 0; j < list.Count; j++)
                {
                    if (list[j] != thingToIgnore)
                    {
                        if (list[j].def.passability == Traversability.Impassable)
                        {
                            return(new AcceptanceReport("InteractionSpotBlocked".Translate(list[j].LabelNoCount).CapitalizeFirst()));
                        }
                        Blueprint blueprint = list[j] as Blueprint;
                        if (blueprint != null && blueprint.def.entityDefToBuild.passability == Traversability.Impassable)
                        {
                            return(new AcceptanceReport("InteractionSpotWillBeBlocked".Translate(blueprint.LabelNoCount).CapitalizeFirst()));
                        }
                    }
                }
            }
            if (entDef.passability != 0)
            {
                foreach (IntVec3 item in GenAdj.CellsAdjacentCardinal(center, rot, entDef.Size))
                {
                    if (item.InBounds(map))
                    {
                        thingList = item.GetThingList(map);
                        for (int k = 0; k < thingList.Count; k++)
                        {
                            Thing    thing2 = thingList[k];
                            ThingDef thingDef2;
                            if (thing2 != thingToIgnore)
                            {
                                thingDef2 = null;
                                Blueprint blueprint2 = thing2 as Blueprint;
                                if (blueprint2 != null)
                                {
                                    ThingDef thingDef3 = blueprint2.def.entityDefToBuild as ThingDef;
                                    if (thingDef3 != null)
                                    {
                                        thingDef2 = thingDef3;
                                        goto IL_0316;
                                    }
                                    continue;
                                }
                                thingDef2 = thing2.def;
                                goto IL_0316;
                            }
                            continue;
IL_0316:
                            if (thingDef2.hasInteractionCell && cellRect.Contains(ThingUtility.InteractionCellWhenAt(thingDef2, thing2.Position, thing2.Rotation, thing2.Map)))
                            {
                                return(new AcceptanceReport("WouldBlockInteractionSpot".Translate(entDef.label, thingDef2.label).CapitalizeFirst()));
                            }
                        }
                    }
                }
            }
            TerrainDef terrainDef = entDef as TerrainDef;

            if (terrainDef != null)
            {
                if (map.terrainGrid.TerrainAt(center) == terrainDef)
                {
                    return(new AcceptanceReport("TerrainIsAlready".Translate(terrainDef.label)));
                }
                if (map.designationManager.DesignationAt(center, DesignationDefOf.SmoothFloor) != null)
                {
                    return(new AcceptanceReport("SpaceBeingSmoothed".Translate()));
                }
            }
            if (!GenConstruct.CanBuildOnTerrain(entDef, center, map, rot, thingToIgnore))
            {
                return(new AcceptanceReport("TerrainCannotSupport".Translate()));
            }
            if (!godMode)
            {
                CellRect.CellRectIterator iterator2 = cellRect.GetIterator();
                while (!iterator2.Done())
                {
                    thingList = iterator2.Current.GetThingList(map);
                    for (int l = 0; l < thingList.Count; l++)
                    {
                        Thing thing3 = thingList[l];
                        if (thing3 != thingToIgnore && !GenConstruct.CanPlaceBlueprintOver(entDef, thing3.def))
                        {
                            return(new AcceptanceReport("SpaceAlreadyOccupied".Translate()));
                        }
                    }
                    iterator2.MoveNext();
                }
            }
            if (entDef.PlaceWorkers != null)
            {
                for (int m = 0; m < entDef.PlaceWorkers.Count; m++)
                {
                    AcceptanceReport result = entDef.PlaceWorkers[m].AllowsPlacing(entDef, center, rot, map, thingToIgnore);
                    if (!result.Accepted)
                    {
                        return(result);
                    }
                }
            }
            return(AcceptanceReport.WasAccepted);
        }
Exemple #18
0
        protected override void Impact(Thing hitThing)
        {
            Map map = base.Map;

            //base.Impact(hitThing);
            GenClamor.DoClamor(this, 2.1f, ClamorDefOf.Impact);
            if (!initialized)
            {
                SpawnThings spawnThing = new SpawnThings();
                pawn = this.launcher as Pawn;
                MagicPowerSkill        pwr         = pawn.GetComp <CompAbilityUserMagic>().MagicData.MagicPowerSkill_SummonElemental.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_SummonElemental_pwr");
                MagicPowerSkill        ver         = pawn.GetComp <CompAbilityUserMagic>().MagicData.MagicPowerSkill_SummonElemental.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_SummonElemental_ver");
                ModOptions.SettingsRef settingsRef = new ModOptions.SettingsRef();
                pwrVal = pwr.level;
                verVal = ver.level;
                if (pawn.story.traits.HasTrait(TorannMagicDefOf.Faceless))
                {
                    MightPowerSkill mpwr = pawn.GetComp <CompAbilityUserMight>().MightData.MightPowerSkill_Mimic.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Mimic_pwr");
                    MightPowerSkill mver = pawn.GetComp <CompAbilityUserMight>().MightData.MightPowerSkill_Mimic.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Mimic_ver");
                    pwrVal = mpwr.level;
                    verVal = mver.level;
                }
                if (settingsRef.AIHardMode && !pawn.IsColonist)
                {
                    pwrVal = 3;
                    verVal = 3;
                }
                CellRect cellRect = CellRect.CenteredOn(this.Position, 1);
                cellRect.ClipInsideMap(map);

                IntVec3       centerCell = cellRect.CenterCell;
                System.Random random     = new System.Random();
                random = new System.Random();

                duration += verVal * 900;
                duration  = Mathf.RoundToInt(duration * pawn.GetComp <CompAbilityUserMagic>().arcaneDmg);

                int rnd = GenMath.RoundRandom(random.Next(0, 8));
                if (rnd < 2)
                {
                    spawnThing.factionDef = TorannMagicDefOf.TM_ElementalFaction;
                    spawnThing.spawnCount = 1;
                    spawnThing.temporary  = false;

                    if (pwrVal == 3)
                    {
                        for (int i = 0; i < 2; i++)
                        {
                            spawnThing.def     = TorannMagicDefOf.TM_Earth_ElementalR;
                            spawnThing.kindDef = PawnKindDef.Named("TM_Earth_Elemental");
                            SingleSpawnLoop(spawnThing, centerCell, map);
                        }
                        spawnThing.def     = TorannMagicDefOf.TM_GreaterEarth_ElementalR;
                        spawnThing.kindDef = PawnKindDef.Named("TM_GreaterEarth_Elemental");
                    }
                    else if (pwrVal == 2)
                    {
                        for (int i = 0; i < 2; i++)
                        {
                            spawnThing.def     = TorannMagicDefOf.TM_LesserEarth_ElementalR;
                            spawnThing.kindDef = PawnKindDef.Named("TM_LesserEarth_Elemental");
                            SingleSpawnLoop(spawnThing, centerCell, map);
                        }
                        spawnThing.def     = TorannMagicDefOf.TM_GreaterEarth_ElementalR;
                        spawnThing.kindDef = PawnKindDef.Named("TM_GreaterEarth_Elemental");
                    }
                    else if (pwrVal == 1)
                    {
                        for (int i = 0; i < 2; i++)
                        {
                            spawnThing.def     = TorannMagicDefOf.TM_LesserEarth_ElementalR;
                            spawnThing.kindDef = PawnKindDef.Named("TM_LesserEarth_Elemental");
                            SingleSpawnLoop(spawnThing, centerCell, map);
                        }
                        spawnThing.def     = TorannMagicDefOf.TM_Earth_ElementalR;
                        spawnThing.kindDef = PawnKindDef.Named("TM_Earth_Elemental");
                    }
                    else
                    {
                        for (int i = 0; i < 1; i++)
                        {
                            spawnThing.def     = TorannMagicDefOf.TM_LesserEarth_ElementalR;
                            spawnThing.kindDef = PawnKindDef.Named("TM_LesserEarth_Elemental");
                            SingleSpawnLoop(spawnThing, centerCell, map);
                        }
                        spawnThing.def     = TorannMagicDefOf.TM_LesserEarth_ElementalR;
                        spawnThing.kindDef = PawnKindDef.Named("TM_LesserEarth_Elemental");
                    }
                    MoteMaker.ThrowSmoke(centerCell.ToVector3(), map, pwrVal);
                    MoteMaker.ThrowMicroSparks(centerCell.ToVector3(), map);
                    SoundDefOf.Ambient_AltitudeWind.sustainFadeoutTime.Equals(30.0f);
                }
                else if (rnd >= 2 && rnd < 4)
                {
                    spawnThing.factionDef = TorannMagicDefOf.TM_ElementalFaction;
                    spawnThing.spawnCount = 1;
                    spawnThing.temporary  = false;

                    if (pwrVal == 3)
                    {
                        for (int i = 0; i < 2; i++)
                        {
                            spawnThing.def     = TorannMagicDefOf.TM_Fire_ElementalR;
                            spawnThing.kindDef = PawnKindDef.Named("TM_Fire_Elemental");
                            SingleSpawnLoop(spawnThing, centerCell, map);
                        }
                        spawnThing.def     = TorannMagicDefOf.TM_GreaterFire_ElementalR;
                        spawnThing.kindDef = PawnKindDef.Named("TM_GreaterFire_Elemental");
                    }
                    else if (pwrVal == 2)
                    {
                        for (int i = 0; i < 2; i++)
                        {
                            spawnThing.def     = TorannMagicDefOf.TM_LesserFire_ElementalR;
                            spawnThing.kindDef = PawnKindDef.Named("TM_LesserFire_Elemental");
                            SingleSpawnLoop(spawnThing, centerCell, map);
                        }
                        spawnThing.def     = TorannMagicDefOf.TM_GreaterFire_ElementalR;
                        spawnThing.kindDef = PawnKindDef.Named("TM_GreaterFire_Elemental");
                    }
                    else if (pwrVal == 1)
                    {
                        for (int i = 0; i < 2; i++)
                        {
                            spawnThing.def     = TorannMagicDefOf.TM_LesserFire_ElementalR;
                            spawnThing.kindDef = PawnKindDef.Named("TM_LesserFire_Elemental");
                            SingleSpawnLoop(spawnThing, centerCell, map);
                        }
                        spawnThing.def     = TorannMagicDefOf.TM_Fire_ElementalR;
                        spawnThing.kindDef = PawnKindDef.Named("TM_Fire_Elemental");
                    }
                    else
                    {
                        for (int i = 0; i < 1; i++)
                        {
                            spawnThing.def     = TorannMagicDefOf.TM_LesserFire_ElementalR;
                            spawnThing.kindDef = PawnKindDef.Named("TM_LesserFire_Elemental");
                            SingleSpawnLoop(spawnThing, centerCell, map);
                        }
                        spawnThing.def     = TorannMagicDefOf.TM_LesserFire_ElementalR;
                        spawnThing.kindDef = PawnKindDef.Named("TM_LesserFire_Elemental");
                    }
                    MoteMaker.ThrowSmoke(centerCell.ToVector3(), map, pwrVal);
                    MoteMaker.ThrowMicroSparks(centerCell.ToVector3(), map);
                    MoteMaker.ThrowFireGlow(centerCell, map, pwrVal);
                    MoteMaker.ThrowHeatGlow(centerCell, map, pwrVal);
                }
                else if (rnd >= 4 && rnd < 6)
                {
                    spawnThing.factionDef = TorannMagicDefOf.TM_ElementalFaction;
                    spawnThing.spawnCount = 1;
                    spawnThing.temporary  = false;

                    if (pwrVal == 3)
                    {
                        for (int i = 0; i < 2; i++)
                        {
                            spawnThing.def     = TorannMagicDefOf.TM_Water_ElementalR;
                            spawnThing.kindDef = PawnKindDef.Named("TM_Water_Elemental");
                            SingleSpawnLoop(spawnThing, centerCell, map);
                        }
                        spawnThing.def     = TorannMagicDefOf.TM_GreaterWater_ElementalR;
                        spawnThing.kindDef = PawnKindDef.Named("TM_GreaterWater_Elemental");
                    }
                    else if (pwrVal == 2)
                    {
                        for (int i = 0; i < 2; i++)
                        {
                            spawnThing.def     = TorannMagicDefOf.TM_LesserWater_ElementalR;
                            spawnThing.kindDef = PawnKindDef.Named("TM_LesserWater_Elemental");
                            SingleSpawnLoop(spawnThing, centerCell, map);
                        }
                        spawnThing.def     = TorannMagicDefOf.TM_GreaterWater_ElementalR;
                        spawnThing.kindDef = PawnKindDef.Named("TM_GreaterWater_Elemental");
                    }
                    else if (pwrVal == 1)
                    {
                        for (int i = 0; i < 2; i++)
                        {
                            spawnThing.def     = TorannMagicDefOf.TM_LesserWater_ElementalR;
                            spawnThing.kindDef = PawnKindDef.Named("TM_LesserWater_Elemental");
                            SingleSpawnLoop(spawnThing, centerCell, map);
                        }
                        spawnThing.def     = TorannMagicDefOf.TM_Water_ElementalR;
                        spawnThing.kindDef = PawnKindDef.Named("TM_Water_Elemental");
                    }
                    else
                    {
                        for (int i = 0; i < 1; i++)
                        {
                            spawnThing.def     = TorannMagicDefOf.TM_LesserWater_ElementalR;
                            spawnThing.kindDef = PawnKindDef.Named("TM_LesserWater_Elemental");
                            SingleSpawnLoop(spawnThing, centerCell, map);
                        }
                        spawnThing.def     = TorannMagicDefOf.TM_LesserWater_ElementalR;
                        spawnThing.kindDef = PawnKindDef.Named("TM_LesserWater_Elemental");
                    }
                    MoteMaker.ThrowSmoke(centerCell.ToVector3(), map, pwrVal);
                    SoundDefOf.Ambient_AltitudeWind.sustainFadeoutTime.Equals(30.0f);
                    MoteMaker.ThrowTornadoDustPuff(centerCell.ToVector3(), map, pwrVal, Color.blue);
                    MoteMaker.ThrowTornadoDustPuff(centerCell.ToVector3(), map, pwrVal, Color.blue);
                    MoteMaker.ThrowTornadoDustPuff(centerCell.ToVector3(), map, pwrVal, Color.blue);
                }
                else
                {
                    spawnThing.factionDef = TorannMagicDefOf.TM_ElementalFaction;
                    spawnThing.spawnCount = 1;
                    spawnThing.temporary  = false;

                    if (pwrVal == 3)
                    {
                        for (int i = 0; i < 2; i++)
                        {
                            spawnThing.def     = TorannMagicDefOf.TM_LesserWind_ElementalR;
                            spawnThing.kindDef = PawnKindDef.Named("TM_Wind_Elemental");
                            SingleSpawnLoop(spawnThing, centerCell, map);
                        }
                        spawnThing.def     = TorannMagicDefOf.TM_GreaterWind_ElementalR;
                        spawnThing.kindDef = PawnKindDef.Named("TM_GreaterWind_Elemental");
                    }
                    else if (pwrVal == 2)
                    {
                        for (int i = 0; i < 2; i++)
                        {
                            spawnThing.def     = TorannMagicDefOf.TM_LesserWind_ElementalR;
                            spawnThing.kindDef = PawnKindDef.Named("TM_LesserWind_Elemental");
                            SingleSpawnLoop(spawnThing, centerCell, map);
                        }
                        spawnThing.def     = TorannMagicDefOf.TM_GreaterWind_ElementalR;
                        spawnThing.kindDef = PawnKindDef.Named("TM_GreaterWind_Elemental");
                    }
                    else if (pwrVal == 1)
                    {
                        for (int i = 0; i < 2; i++)
                        {
                            spawnThing.def     = TorannMagicDefOf.TM_LesserWind_ElementalR;
                            spawnThing.kindDef = PawnKindDef.Named("TM_LesserWind_Elemental");
                            SingleSpawnLoop(spawnThing, centerCell, map);
                        }
                        spawnThing.def     = TorannMagicDefOf.TM_Wind_ElementalR;
                        spawnThing.kindDef = PawnKindDef.Named("TM_Wind_Elemental");
                    }
                    else
                    {
                        for (int i = 0; i < 1; i++)
                        {
                            spawnThing.def     = TorannMagicDefOf.TM_LesserWind_ElementalR;
                            spawnThing.kindDef = PawnKindDef.Named("TM_LesserWind_Elemental");
                            SingleSpawnLoop(spawnThing, centerCell, map);
                        }
                        spawnThing.def     = TorannMagicDefOf.TM_LesserWind_ElementalR;
                        spawnThing.kindDef = PawnKindDef.Named("TM_LesserWind_Elemental");
                    }
                    MoteMaker.ThrowSmoke(centerCell.ToVector3(), map, 1 + (pwrVal * 2));
                    SoundDefOf.Ambient_AltitudeWind.sustainFadeoutTime.Equals(30.0f);
                    MoteMaker.ThrowTornadoDustPuff(centerCell.ToVector3(), map, pwrVal, Color.white);
                }

                SingleSpawnLoop(spawnThing, centerCell, map);

                this.age         = this.duration;
                this.initialized = true;
            }
            Destroy();
        }
        public void TerrainChanged(CellRect rect)
        {
            SectionTerrain st;
            if (!SectionTerrains.TryGetValue(rect, out st))
            {
                st = new SectionTerrain(rect);
                SectionTerrains.Add(rect, st);
            }

            st.TerrainChanged();
        }
        public static void GenerateRoomFromLayout(List <string> layoutList, CellRect roomRect, Map map, StructureLayoutDef rld, bool generateConduit = true)
        {
            bool parentFaction = map.ParentFaction != null;

            if (rld.roofGrid != null)
            {
                GenerateRoofGrid(rld.roofGrid, roomRect, map);
            }

            List <string> allSymbList = new List <string>();

            foreach (string str in layoutList)
            {
                allSymbList.AddRange(str.Split(','));
            }

            int l = 0;

            foreach (IntVec3 cell in roomRect)
            {
                if (l < allSymbList.Count && allSymbList[l] != ".")
                {
                    SymbolDef temp = DefDatabase <SymbolDef> .GetNamedSilentFail(allSymbList[l]);

                    Thing thing;
                    if (temp != null)
                    {
                        if (temp.isTerrain && temp.terrainDef != null)
                        {
                            GenerateTerrainAt(map, cell, temp.terrainDef);
                        }
                        else if (temp.pawnKindDefNS != null && CGO.factionSettlement?.shouldRuin == false)
                        {
                            if (temp.lordJob != null)
                            {
                                Lord lord = CreateNewLord(temp.lordJob, map, cell);
                                for (int i = 0; i < temp.numberToSpawn; i++)
                                {
                                    Pawn pawn = temp.spawnPartOfFaction ? PawnGenerator.GeneratePawn(temp.pawnKindDefNS, map.ParentFaction) : PawnGenerator.GeneratePawn(temp.pawnKindDefNS);
                                    if (pawn != null)
                                    {
                                        if (temp.isSlave && parentFaction)
                                        {
                                            pawn.guest.SetGuestStatus(map.ParentFaction, GuestStatus.Prisoner);
                                        }

                                        GenSpawn.Spawn(pawn, cell, map, WipeMode.FullRefund);
                                        lord.AddPawn(pawn);
                                    }
                                }
                            }
                            else
                            {
                                for (int i = 0; i < temp.numberToSpawn; i++)
                                {
                                    Pawn pawn = temp.spawnPartOfFaction ? PawnGenerator.GeneratePawn(temp.pawnKindDefNS, map.ParentFaction) : PawnGenerator.GeneratePawn(temp.pawnKindDefNS);
                                    if (pawn != null)
                                    {
                                        if (temp.isSlave && parentFaction)
                                        {
                                            pawn.guest.SetGuestStatus(map.ParentFaction, GuestStatus.Prisoner);
                                        }
                                        GenSpawn.Spawn(pawn, cell, map, WipeMode.FullRefund);
                                    }
                                }
                            }
                        }
                        else if (temp.thingDef?.category == ThingCategory.Item && cell.Walkable(map))
                        {
                            thing            = ThingMaker.MakeThing(temp.thingDef, temp.stuffDef ?? (temp.thingDef.stuffCategories?.Count > 0 ? GenStuff.RandomStuffFor(temp.thingDef) : null));
                            thing.stackCount = Mathf.Clamp(Rand.RangeInclusive(1, temp.thingDef.stackLimit), 1, 75);

                            CompQuality quality = thing.TryGetComp <CompQuality>();
                            quality?.SetQuality(QualityUtility.GenerateQualityBaseGen(), ArtGenerationContext.Outsider);

                            GenSpawn.Spawn(thing, cell, map, WipeMode.FullRefund);
                            thing.SetForbidden(true, false);
                        }
                        else if (temp.thingDef != null)
                        {
                            thing = ThingMaker.MakeThing(temp.thingDef, temp.thingDef.CostStuffCount > 0 ? (temp.stuffDef ?? temp.thingDef.defaultStuff ?? ThingDefOf.WoodLog) : null);

                            CompRefuelable refuelable = thing.TryGetComp <CompRefuelable>();
                            refuelable?.Refuel(refuelable.Props.fuelCapacity);

                            CompPowerBattery battery = thing.TryGetComp <CompPowerBattery>();
                            battery?.AddEnergy(battery.Props.storedEnergyMax);

                            if (thing is Building_CryptosleepCasket cryptosleepCasket && Rand.Value < temp.chanceToContainPawn)
                            {
                                Pawn pawn = GeneratePawnForContainer(temp, map);
                                if (!cryptosleepCasket.TryAcceptThing(pawn))
                                {
                                    pawn.Destroy();
                                }
                            }
                            else if (thing is Building_CorpseCasket corpseCasket && Rand.Value < temp.chanceToContainPawn)
                            {
                                Pawn pawn = GeneratePawnForContainer(temp, map);
                                if (!corpseCasket.TryAcceptThing(pawn))
                                {
                                    pawn.Destroy();
                                }
                            }
                            else if (thing is Building_Crate crate)
                            {
                                List <Thing> thingList = new List <Thing>();
                                if (map.ParentFaction == Faction.OfPlayer && temp.thingSetMakerDefForPlayer != null)
                                {
                                    thingList = temp.thingSetMakerDefForPlayer.root.Generate(new ThingSetMakerParams());
                                }
                                else if (temp.thingSetMakerDef != null)
                                {
                                    thingList = temp.thingSetMakerDef.root.Generate(new ThingSetMakerParams());
                                }

                                foreach (Thing t in thingList)
                                {
                                    t.stackCount = Math.Min((int)(t.stackCount * temp.crateStackMultiplier), t.def.stackLimit);
                                }

                                thingList.ForEach(t =>
                                {
                                    if (!crate.TryAcceptThing(t, false))
                                    {
                                        t.Destroy();
                                    }
                                });
                            }

                            if (thing.def.category == ThingCategory.Pawn && CGO.factionSettlement?.shouldRuin == true)
                            {
                                l++;
                                continue;
                            }
                            else if (cell.GetFirstMineable(map) is Mineable m && thing.def.designationCategory == DesignationCategoryDefOf.Security)
                            {
                                l++;
                                continue;
                            }
                            else if (thing.def.category == ThingCategory.Plant && cell.GetTerrain(map).fertility > 0.5 && cell.Walkable(map)) // If it's a plant
                            {
                                Plant plant = thing as Plant;
                                plant.Growth = temp.plantGrowth; // apply the growth
                                GenSpawn.Spawn(plant, cell, map, WipeMode.VanishOrMoveAside);
                            }
                            else if (thing.def.category == ThingCategory.Building)
                            {
                                if (!cell.GetTerrain(map).affordances.Contains(TerrainAffordanceDefOf.Heavy))
                                {
                                    if (thing.def.building.isNaturalRock)
                                    {
                                        TerrainDef t = DefDatabase <TerrainDef> .GetNamedSilentFail($"{thing.def.defName}_Rough");

                                        map.terrainGrid.SetTerrain(cell, t ?? TerrainDefOf.Soil);
                                        foreach (IntVec3 intVec3 in CellRect.CenteredOn(cell, 1))
                                        {
                                            if (!intVec3.GetTerrain(map).BuildableByPlayer)
                                            {
                                                map.terrainGrid.SetTerrain(intVec3, t ?? TerrainDefOf.Soil);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        map.terrainGrid.SetTerrain(cell, TerrainDefOf.Bridge);
                                    }
                                }

                                if (thing.def.rotatable)
                                {
                                    GenSpawn.Spawn(thing, cell, map, new Rot4(temp.rotation.AsInt), WipeMode.VanishOrMoveAside);
                                }
                                else
                                {
                                    GenSpawn.Spawn(thing, cell, map, WipeMode.VanishOrMoveAside);
                                }

                                if (parentFaction)
                                {
                                    thing.SetFactionDirect(map.ParentFaction);
                                }
                            }

                            if (generateConduit && rld.spawnConduits && !thing.def.mineable && (thing.def.passability == Traversability.Impassable || thing.def.IsDoor) && map.ParentFaction?.def.techLevel >= TechLevel.Industrial) // Add power cable under all impassable
                            {
                                Thing c = ThingMaker.MakeThing(ThingDefOf.PowerConduit);
                                if (parentFaction)
                                {
                                    c.SetFactionDirect(map.ParentFaction);
                                }
                                GenSpawn.Spawn(c, cell, map, WipeMode.FullRefund);
                            }
                            // Handle mortar and mortar pawns
                            if (thing?.def?.building?.buildingTags?.Count > 0)
                            {
                                if (thing.def.building.IsMortar && thing.def.category == ThingCategory.Building && thing.def.building.buildingTags.Contains("Artillery_MannedMortar") && thing.def.HasComp(typeof(CompMannable)) && parentFaction)
                                {
                                    // Spawn pawn
                                    Lord singlePawnLord          = LordMaker.MakeNewLord(map.ParentFaction, new LordJob_ManTurrets(), map, null);
                                    PawnGenerationRequest value  = new PawnGenerationRequest(map.ParentFaction.RandomPawnKind(), map.ParentFaction, PawnGenerationContext.NonPlayer, map.Tile, mustBeCapableOfViolence: true, inhabitant: true);
                                    ResolveParams         rpPawn = new ResolveParams
                                    {
                                        faction = map.ParentFaction,
                                        singlePawnGenerationRequest = new PawnGenerationRequest?(value),
                                        rect           = CellRect.SingleCell(thing.InteractionCell),
                                        singlePawnLord = singlePawnLord
                                    };
                                    BaseGen.symbolStack.Push("pawn", rpPawn);
                                    // Spawn shells
                                    ThingDef shellDef = TurretGunUtility.TryFindRandomShellDef(thing.def, false, true, map.ParentFaction.def.techLevel, false, 250f);
                                    if (shellDef != null)
                                    {
                                        ResolveParams rpShell = new ResolveParams
                                        {
                                            faction               = map.ParentFaction,
                                            singleThingDef        = shellDef,
                                            singleThingStackCount = Rand.RangeInclusive(8, Math.Min(12, shellDef.stackLimit))
                                        };
                                        BaseGen.symbolStack.Push("thing", rpShell);
                                    }
                                }
                            }
                        }
 static void ClearAnythingInOutpostArea()
 {
     CellRect rect = new CellRect(outpostData.areaSouthWestOrigin.x - 1, outpostData.areaSouthWestOrigin.z - 1, areaSideLength + 2, areaSideLength + 2);
     foreach (IntVec3 cell in rect.Cells)
     {
         Find.RoofGrid.SetRoof(cell, null);
         List<Thing> thingList = cell.GetThingList();
         for (int j = thingList.Count - 1; j >= 0; j--)
         {
             Thing thing = thingList[j];
             if (thing.def.destroyable)
             {
                 thing.Destroy(DestroyMode.Vanish);
             }
         }
         Find.Map.terrainGrid.RemoveTopLayer(cell);
         TerrainDef terrain = Find.TerrainGrid.TerrainAt(cell);
         if ((terrain == TerrainDef.Named("Marsh"))
             || (terrain == TerrainDef.Named("Mud"))
             || (terrain == TerrainDef.Named("WaterShallow")))
         {
             Find.TerrainGrid.SetTerrain(cell, TerrainDefOf.Soil);
         }
     }
 }
Exemple #22
0
        protected override void Impact(Thing hitThing)
        {
            Map map = base.Map;

            GenClamor.DoClamor(this, 2.1f, ClamorDefOf.Impact);
            //base.Impact(hitThing);
            ThingDef def    = this.def;
            Pawn     victim = hitThing as Pawn;
            Thing    item   = hitThing as Thing;
            IntVec3  arg_pos_1;

            Pawn pawn = this.launcher as Pawn;
            CompAbilityUserMagic comp = pawn.GetComp <CompAbilityUserMagic>();
            MagicPowerSkill      pwr  = pawn.GetComp <CompAbilityUserMagic>().MagicData.MagicPowerSkill_SummonPylon.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_SummonPylon_pwr");
            MagicPowerSkill      ver  = pawn.GetComp <CompAbilityUserMagic>().MagicData.MagicPowerSkill_SummonPylon.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_SummonPylon_ver");

            verVal = ver.level;
            pwrVal = pwr.level;
            if (pawn.story.traits.HasTrait(TorannMagicDefOf.Faceless))
            {
                MightPowerSkill mpwr = pawn.GetComp <CompAbilityUserMight>().MightData.MightPowerSkill_Mimic.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Mimic_pwr");
                MightPowerSkill mver = pawn.GetComp <CompAbilityUserMight>().MightData.MightPowerSkill_Mimic.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Mimic_ver");
                pwrVal = mpwr.level;
                verVal = mver.level;
            }
            CellRect cellRect = CellRect.CenteredOn(base.Position, 1);

            cellRect.ClipInsideMap(map);
            IntVec3 centerCell = cellRect.CenterCell;

            if (!this.primed)
            {
                duration += (verVal * 7200);
                duration  = (int)(duration * comp.arcaneDmg);
                arg_pos_1 = centerCell;

                if ((arg_pos_1.IsValid && arg_pos_1.Standable(map)))
                {
                    AbilityUser.SpawnThings tempPod = new SpawnThings();
                    IntVec3 shiftPos = centerCell;
                    centerCell.x++;

                    if (pwrVal == 1)
                    {
                        tempPod.def = ThingDef.Named("DefensePylon_I");
                    }
                    else if (pwrVal == 2)
                    {
                        tempPod.def = ThingDef.Named("DefensePylon_II");
                    }
                    else if (pwrVal == 3)
                    {
                        tempPod.def = ThingDef.Named("DefensePylon_III");
                    }
                    else
                    {
                        tempPod.def = ThingDef.Named("DefensePylon");
                    }
                    tempPod.spawnCount = 1;
                    try
                    {
                        this.SingleSpawnLoop(tempPod, shiftPos, map);
                    }
                    catch
                    {
                        comp.Mana.CurLevel += comp.ActualManaCost(TorannMagicDefOf.TM_SummonPylon);
                        this.age            = this.duration;
                        Log.Message("TM_Exception".Translate(
                                        pawn.LabelShort,
                                        this.def.defName
                                        ));
                    }

                    this.primed = true;
                }
                else
                {
                    Messages.Message("InvalidSummon".Translate(), MessageTypeDefOf.RejectInput);
                    comp.Mana.GainNeed(comp.ActualManaCost(TorannMagicDefOf.TM_SummonExplosive));
                    this.duration = 0;
                }
            }
            this.age = this.duration;
            Destroy();
        }
        public override void DoEffect(Pawn usedBy)
        {
            if (this.target != null && !this.GetTargetingParameters().CanTarget(this.target))
            {
                return;
            }
            base.DoEffect(usedBy);
            if (this.parent.Stuff == null)
            {
                this.parent.SetStuffDirect(ThingDefOf.Cloth);
            }

            CellRect cellRect     = new CellRect(this.targetPos.x - 2, this.targetPos.z - 2, 5, 4);
            double   hitpoints    = (double)this.parent.HitPoints / 10;
            int      wallsToPlace = (int)Math.Floor(hitpoints);
            //int wallsToPlace = 49;
            List <IntVec3> everything = new List <IntVec3>();

            everything.AddRange(this.wallCells);
            everything.AddRange(this.doorCells);


            foreach (IntVec3 current in everything)
            {
                if (!GenConstruct.CanPlaceBlueprintAt(ThingDef.Named("TentWall"), current, Rot4.North, usedBy.Map, false, null).Accepted)
                {
                    Messages.Message("Tent placement blocked. Please deploy on a suitable space.", MessageSound.RejectInput);
                    return;
                }

                if (current.GetFirstItem(usedBy.Map) != null || current.GetFirstPawn(usedBy.Map) != null || current.GetFirstHaulable(usedBy.Map) != null)
                {
                    Messages.Message("Tent placement blocked. Please deploy on a suitable space.", MessageSound.RejectInput);
                    return;
                }
                Building building = current.GetFirstBuilding(usedBy.Map);
                if (building != null)
                {
                    if (building.def.IsEdifice())
                    {
                        Messages.Message("Tent placement blocked by a item, pawn or a building. Please deploy on a suitable space.", MessageSound.RejectInput);
                        return;
                    }
                }
            }
            foreach (IntVec3 current in this.wallCells)
            {
                if (usedBy.Map.roofGrid.RoofAt(current) == null)
                {
                    usedBy.Map.roofGrid.SetRoof(current, RoofDefOf.RoofConstructed);
                }
            }
            foreach (IntVec3 current in this.doorCells)
            {
                if (usedBy.Map.roofGrid.RoofAt(current) == null)
                {
                    usedBy.Map.roofGrid.SetRoof(current, RoofDefOf.RoofConstructed);
                }
            }
            foreach (IntVec3 current in this.roofCells)
            {
                if (usedBy.Map.roofGrid.RoofAt(current) == null)
                {
                    usedBy.Map.roofGrid.SetRoof(current, RoofDefOf.RoofConstructed);
                }
            }

            if (usedBy.Map.roofGrid.RoofAt(supportCell) == null)
            {
                usedBy.Map.roofGrid.SetRoof(supportCell, RoofDefOf.RoofConstructed);
            }


            if (wallsToPlace < wallCells.Count + doorCells.Count)
            {
                Messages.Message("Damaged tent deployed. Some walls will be missing.", MessageSound.Negative);
            }
            int wallsPlaced = 0;

            this.GetPlacements(this.targetPos);

            foreach (IntVec3 current in this.wallCells)
            {
                if (wallsPlaced < wallsToPlace)
                {
                    TrySpawnWall(current, usedBy);
                    wallsPlaced++;
                }
            }

            foreach (IntVec3 DoorPos in this.doorCells)
            {
                if (wallsPlaced < wallsToPlace)
                {
                    Thing door = ThingMaker.MakeThing(ThingDef.Named("TentDoor"), this.parent.Stuff);
                    door.SetFaction(usedBy.Faction, null);
                    door.Rotation = Building_Door.DoorRotationAt(DoorPos, usedBy.Map);
                    GenSpawn.Spawn(door, DoorPos, usedBy.Map);
                    wallsPlaced++;
                }
            }


            this.parent.Destroy(DestroyMode.Vanish);
            SoundDefOf.DesignatePlaceBuilding.PlayOneShotOnCamera();
            Thing tent = ThingMaker.MakeThing(ThingDef.Named("TentDeployed"), this.parent.Stuff);

            tent.SetFaction(usedBy.Faction, null);
            tent.TryGetComp <CompPackTent>().tentName   = this.parent.def.defName;
            tent.TryGetComp <CompPackTent>().placingRot = this.placingRot;
            GenSpawn.Spawn(tent, this.supportCell, usedBy.Map);

            return;
        }
        public bool TryFindCEShootLineFromTo(IntVec3 root, LocalTargetInfo targ, out ShootLine resultingLine)
        {
            if (targ.HasThing && targ.Thing.Map != this.caster.Map)
            {
                resultingLine = default(ShootLine);
                return(false);
            }
            if (this.verbProps.MeleeRange)
            {
                resultingLine = new ShootLine(root, targ.Cell);
                return(ReachabilityImmediate.CanReachImmediate(root, targ, this.caster.Map, PathEndMode.Touch, null));
            }
            CellRect cellRect = (!targ.HasThing) ? CellRect.SingleCell(targ.Cell) : targ.Thing.OccupiedRect();
            float    num      = cellRect.ClosestDistSquaredTo(root);

            if (num > this.verbProps.range * this.verbProps.range || num < this.verbProps.minRange * this.verbProps.minRange)
            {
                resultingLine = new ShootLine(root, targ.Cell);
                return(false);
            }
            //if (!this.verbProps.NeedsLineOfSight) This method doesn't consider the currently loaded projectile
            if (ProjectileDef.projectile.flyOverhead)
            {
                resultingLine = new ShootLine(root, targ.Cell);
                return(true);
            }
            if (this.CasterIsPawn)
            {
                IntVec3 dest;
                if (this.CanHitFromCellIgnoringRange(root, targ, out dest))
                {
                    resultingLine = new ShootLine(root, dest);
                    return(true);
                }
                ShootLeanUtility.LeanShootingSourcesFromTo(root, cellRect.ClosestCellTo(root), this.caster.Map, tempLeanShootSources);
                for (int i = 0; i < tempLeanShootSources.Count; i++)
                {
                    IntVec3 intVec = tempLeanShootSources[i];
                    if (this.CanHitFromCellIgnoringRange(intVec, targ, out dest))
                    {
                        resultingLine = new ShootLine(intVec, dest);
                        return(true);
                    }
                }
            }
            else
            {
                CellRect.CellRectIterator iterator = this.caster.OccupiedRect().GetIterator();
                while (!iterator.Done())
                {
                    IntVec3 current = iterator.Current;
                    IntVec3 dest;
                    if (this.CanHitFromCellIgnoringRange(current, targ, out dest))
                    {
                        resultingLine = new ShootLine(current, dest);
                        return(true);
                    }
                    iterator.MoveNext();
                }
            }
            resultingLine = new ShootLine(root, targ.Cell);
            return(false);
        }
        protected override void Impact(Thing hitThing)
        {
            Map map = base.Map;

            base.Impact(hitThing);
            ThingDef def    = this.def;
            Pawn     victim = hitThing as Pawn;

            Pawn pawn = this.launcher as Pawn;
            CompAbilityUserMagic comp = pawn.GetComp <CompAbilityUserMagic>();

            pwr = pawn.GetComp <CompAbilityUserMagic>().MagicData.MagicPowerSkill_LightningCloud.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_LightningCloud_pwr");
            ver = pawn.GetComp <CompAbilityUserMagic>().MagicData.MagicPowerSkill_LightningCloud.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_LightningCloud_ver");
            ModOptions.SettingsRef settingsRef = new ModOptions.SettingsRef();
            pwrVal = pwr.level;
            verVal = ver.level;
            if (pawn.story.traits.HasTrait(TorannMagicDefOf.Faceless))
            {
                MightPowerSkill mpwr = pawn.GetComp <CompAbilityUserMight>().MightData.MightPowerSkill_Mimic.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Mimic_pwr");
                MightPowerSkill mver = pawn.GetComp <CompAbilityUserMight>().MightData.MightPowerSkill_Mimic.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Mimic_ver");
                pwrVal = mpwr.level;
                verVal = mver.level;
            }
            this.arcaneDmg = comp.arcaneDmg;
            if (settingsRef.AIHardMode && !pawn.IsColonist)
            {
                pwrVal = 3;
                verVal = 3;
            }
            radius = (int)this.def.projectile.explosionRadius + (1 * verVal);

            CellRect cellRect = CellRect.CenteredOn(base.Position, radius - 3);

            cellRect.ClipInsideMap(map);
            IntVec3 randomCell = cellRect.RandomCell;

            duration = 900 + (verVal * 120);

            if (this.primed == true)
            {
                if (((this.shockDelay + this.lastStrike) < this.age))
                {
                    for (int i = 0; i < 4; i++)
                    {
                        randomCell = cellRect.RandomCell;
                        if (randomCell.InBounds(map))
                        {
                            victim = randomCell.GetFirstPawn(map);
                            if (victim != null)
                            {
                                damageEntities(victim, Mathf.RoundToInt((this.def.projectile.GetDamageAmount(1, null) + pwrVal) * this.arcaneDmg));
                            }
                        }
                    }

                    Vector3 loc2 = base.Position.ToVector3Shifted();
                    Vector3 loc  = randomCell.ToVector3Shifted();

                    bool rand1 = Rand.Range(0, 100) < 3;
                    bool rand2 = Rand.Range(0, 100) < 16;
                    if (rand1)
                    {
                        MoteMaker.ThrowSmoke(loc2, map, radius);
                        SoundDefOf.Ambient_AltitudeWind.sustainFadeoutTime.Equals(30.0f);
                    }
                    if (rand2)
                    {
                        MoteMaker.ThrowSmoke(loc, map, 4f);
                    }

                    MoteMaker.ThrowMicroSparks(loc, map);
                    MoteMaker.ThrowLightningGlow(loc, map, 2f);

                    strikeInt++;
                    this.lastStrike = this.age;
                    this.shockDelay = Rand.Range(1, 3);

                    bool flag1 = this.age <= duration;
                    if (!flag1)
                    {
                        this.primed = false;
                    }
                }
            }
        }
        //private bool WallHasDoor(CellRect rect, Rot4 dir)
        //{
        //    Map map = BaseGen.globalSettings.map;
        //    foreach (IntVec3 current in rect.GetEdgeCells(dir))
        //    {
        //        if (current.GetDoor(map) != null)
        //        {
        //            return true;
        //        }
        //    }
        //    return false;
        //}

        private bool TryFindRandomDoorCell(CellRect rect, Rot4 dir, out IntVec3 found)
        {
            Map map = BaseGen.globalSettings.map;

            if (dir == Rot4.North)
            {
                if (rect.Width <= 2)
                {
                    found = IntVec3.Invalid;
                    return(false);
                }
                if (!Rand.TryRangeInclusiveWhere(rect.minX + 1, rect.maxX - 1, delegate(int x)
                {
                    IntVec3 c = new IntVec3(x, 0, rect.maxZ + 1);
                    return(c.InBounds(map) && c.Walkable(map) && !c.Fogged(map));
                }, out int newX))
                {
                    found = IntVec3.Invalid;
                    return(false);
                }
                found = new IntVec3(newX, 0, rect.maxZ);
                return(true);
            }
            else if (dir == Rot4.South)
            {
                if (rect.Width <= 2)
                {
                    found = IntVec3.Invalid;
                    return(false);
                }
                if (!Rand.TryRangeInclusiveWhere(rect.minX + 1, rect.maxX - 1, delegate(int x)
                {
                    IntVec3 c = new IntVec3(x, 0, rect.minZ - 1);
                    return(c.InBounds(map) && c.Walkable(map) && !c.Fogged(map));
                }, out int newX2))
                {
                    found = IntVec3.Invalid;
                    return(false);
                }
                found = new IntVec3(newX2, 0, rect.minZ);
                return(true);
            }
            else if (dir == Rot4.West)
            {
                if (rect.Height <= 2)
                {
                    found = IntVec3.Invalid;
                    return(false);
                }
                if (!Rand.TryRangeInclusiveWhere(rect.minZ + 1, rect.maxZ - 1, delegate(int z)
                {
                    IntVec3 c = new IntVec3(rect.minX - 1, 0, z);
                    return(c.InBounds(map) && c.Walkable(map) && !c.Fogged(map));
                }, out int newZ))
                {
                    found = IntVec3.Invalid;
                    return(false);
                }
                found = new IntVec3(rect.minX, 0, newZ);
                return(true);
            }
            else
            {
                if (rect.Height <= 2)
                {
                    found = IntVec3.Invalid;
                    return(false);
                }
                if (!Rand.TryRangeInclusiveWhere(rect.minZ + 1, rect.maxZ - 1, delegate(int z)
                {
                    IntVec3 c = new IntVec3(rect.maxX + 1, 0, z);
                    return(c.InBounds(map) && c.Walkable(map) && !c.Fogged(map));
                }, out int newZ2))
                {
                    found = IntVec3.Invalid;
                    return(false);
                }
                found = new IntVec3(rect.maxX, 0, newZ2);
                return(true);
            }
        }
        protected override void Impact(Thing hitThing)
        {
            Map map = base.Map;

            base.Impact(hitThing);

            if (!initialized)
            {
                SpawnThings spawnThing = new SpawnThings();
                pawn = this.launcher as Pawn;
                comp = pawn.GetComp <CompAbilityUserMagic>();
                MagicPowerSkill        pwr         = pawn.GetComp <CompAbilityUserMagic>().MagicData.MagicPowerSkill_SummonMinion.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_SummonMinion_pwr");
                MagicPowerSkill        ver         = pawn.GetComp <CompAbilityUserMagic>().MagicData.MagicPowerSkill_SummonMinion.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_SummonMinion_ver");
                ModOptions.SettingsRef settingsRef = new ModOptions.SettingsRef();
                pwrVal = pwr.level;
                verVal = ver.level;
                if (settingsRef.AIHardMode && !pawn.IsColonist)
                {
                    pwrVal = 3;
                    verVal = 3;
                }
                CellRect cellRect = CellRect.CenteredOn(this.Position, 1);
                cellRect.ClipInsideMap(map);

                IntVec3       centerCell = cellRect.CenterCell;
                System.Random random     = new System.Random();
                random = new System.Random();

                duration += (verVal * durationMultiplier);
                duration  = (int)(duration * comp.arcaneDmg);

                spawnThing.factionDef = TorannMagicDefOf.TM_SummonedFaction;
                spawnThing.spawnCount = 1;
                spawnThing.temporary  = false;

                if (pwrVal >= 2)
                {
                    for (int i = 0; i < pwrVal - 1; i++)
                    {
                        spawnThing.def     = TorannMagicDefOf.TM_GreaterMinionR;
                        spawnThing.kindDef = PawnKindDef.Named("TM_GreaterMinion");
                        SingleSpawnLoop(spawnThing, centerCell, map);
                    }
                    MoteMaker.ThrowSmoke(centerCell.ToVector3(), map, 2 + pwrVal);
                    MoteMaker.ThrowMicroSparks(centerCell.ToVector3(), map);
                    MoteMaker.ThrowHeatGlow(centerCell, map, 2 + pwrVal);
                }
                else
                {
                    for (int i = 0; i < pwrVal + 1; i++)
                    {
                        spawnThing.def     = TorannMagicDefOf.TM_MinionR;
                        spawnThing.kindDef = PawnKindDef.Named("TM_Minion");

                        SingleSpawnLoop(spawnThing, centerCell, map);
                    }
                    MoteMaker.ThrowSmoke(centerCell.ToVector3(), map, 1 + pwrVal);
                    MoteMaker.ThrowMicroSparks(centerCell.ToVector3(), map);
                    MoteMaker.ThrowHeatGlow(centerCell, map, 1 + pwrVal);
                }

                SoundDefOf.Ambient_AltitudeWind.sustainFadeoutTime.Equals(30.0f);
                this.initialized = true;
            }
            else
            {
                this.age = this.duration;
            }
        }
Exemple #28
0
        private void ResolveOption(int roomsPerRowX, int pathwayWidthX, int roomsPerRowZ, int pathwayWidthZ, ResolveParams rp)
        {
            Map      map       = BaseGen.globalSettings.map;
            int      roomSize  = GetRoomSize(roomsPerRowX, pathwayWidthX, rp.rect.Width);
            int      roomSize2 = GetRoomSize(roomsPerRowZ, pathwayWidthZ, rp.rect.Height);
            ThingDef thingDef  = null;

            if (pathwayWidthX >= 3)
            {
                thingDef = ((rp.faction != null && (int)rp.faction.def.techLevel < 4) ? ThingDefOf.TorchLamp : ThingDefOf.StandingLamp);
            }
            TerrainDef floorDef = rp.pathwayFloorDef ?? BaseGenUtility.RandomBasicFloorDef(rp.faction);
            int        num      = roomSize;

            for (int i = 0; i < roomsPerRowX - 1; i++)
            {
                CellRect      rect          = new CellRect(rp.rect.minX + num, rp.rect.minZ, pathwayWidthX, rp.rect.Height);
                ResolveParams resolveParams = rp;
                resolveParams.rect             = rect;
                resolveParams.floorDef         = floorDef;
                resolveParams.streetHorizontal = false;
                BaseGen.symbolStack.Push("street", resolveParams);
                num += roomSize + pathwayWidthX;
            }
            int num2 = roomSize2;

            for (int j = 0; j < roomsPerRowZ - 1; j++)
            {
                CellRect      rect2          = new CellRect(rp.rect.minX, rp.rect.minZ + num2, rp.rect.Width, pathwayWidthZ);
                ResolveParams resolveParams2 = rp;
                resolveParams2.rect             = rect2;
                resolveParams2.floorDef         = floorDef;
                resolveParams2.streetHorizontal = true;
                BaseGen.symbolStack.Push("street", resolveParams2);
                num2 += roomSize2 + pathwayWidthZ;
            }
            num  = 0;
            num2 = 0;
            children.Clear();
            for (int k = 0; k < roomsPerRowX; k++)
            {
                for (int l = 0; l < roomsPerRowZ; l++)
                {
                    Child child = new Child();
                    child.rect  = new CellRect(rp.rect.minX + num, rp.rect.minZ + num2, roomSize, roomSize2);
                    child.gridX = k;
                    child.gridY = l;
                    children.Add(child);
                    num2 += roomSize2 + pathwayWidthZ;
                }
                num += roomSize + pathwayWidthX;
                num2 = 0;
            }
            MergeRandomChildren();
            children.Shuffle();
            for (int m = 0; m < children.Count; m++)
            {
                if (thingDef != null)
                {
                    IntVec3 c = new IntVec3(children[m].rect.maxX + 1, 0, children[m].rect.maxZ);
                    if (rp.rect.Contains(c) && c.Standable(map))
                    {
                        ResolveParams resolveParams3 = rp;
                        resolveParams3.rect           = CellRect.SingleCell(c);
                        resolveParams3.singleThingDef = thingDef;
                        BaseGen.symbolStack.Push("thing", resolveParams3);
                    }
                }
                ResolveParams resolveParams4 = rp;
                resolveParams4.rect = children[m].rect;
                BaseGen.symbolStack.Push("basePart_outdoors", resolveParams4);
            }
        }
Exemple #29
0
        protected CellRect CalculateDestinationRect(LocalTargetInfo dest, PathEndMode peMode)
        {
            CellRect result = (dest.HasThing && peMode != PathEndMode.OnCell) ? dest.Thing.OccupiedRect() : CellRect.SingleCell(dest.Cell);

            if (peMode == PathEndMode.Touch)
            {
                result = result.ExpandedBy(1);
            }
            return(result);
        }
Exemple #30
0
        private IEnumerable <IntVec3> GetCarrierSpots()
        {
            // Should only be called right after blueprint creation

            int            countCarriers = Info.pawnsWithRole[CarnivalRole.Carrier].Count;
            int            countSpots    = 0;
            List <IntVec3> spots         = new List <IntVec3>();
            CellRect       searchRect    = CellRect.CenteredOn(
                ((LordToilData_SetupCarnival)data).blueprints
                .Where(b => b.def.defName.StartsWith("Carn_TentLodge"))
                .Select(b => b.Position)
                .Average(),
                8
                );

            for (int i = 0; i < 50; i++)
            {
                // Try to find initial spot
                IntVec3 randomCell = searchRect.RandomCell;
                if (Map.reachability.CanReach(randomCell, Info.setupCentre, PathEndMode.OnCell, TraverseMode.NoPassClosedDoors, Danger.Deadly) &&
                    !randomCell.GetThingList(this.Map).Any(t => t is Blueprint))
                {
                    spots.Add(randomCell);
                    countSpots++;
                    break;
                }
            }

            if (countSpots == 0)
            {
                goto Error;
            }

            byte attempts         = 0;
            byte directionalTries = 0;

            while (attempts < 75 && countSpots < countCarriers)
            {
                IntVec3 lastSpot = spots.Last();
                IntVec3 newSpot  = new IntVec3(lastSpot.x, lastSpot.y, lastSpot.z);
                IntVec3 offset;

                if (countSpots % 4 == 0)
                {
                    // New row
                    directionalTries++;
                }

                offset = directionalTries.ToIntVec3(1) * 3;

                newSpot += offset;

                if (!spots.Contains(newSpot) &&
                    Map.reachability.CanReach(newSpot, Info.setupCentre, PathEndMode.OnCell, TraverseMode.NoPassClosedDoors, Danger.Deadly) &&
                    !newSpot.GetThingList(this.Map).Any(t => t is Blueprint))
                {
                    // Spot found
                    spots.Add(newSpot);
                    if (countSpots % 4 == 0)
                    {
                        // New row
                        directionalTries++;
                    }
                    countSpots++;
                }
                else if (directionalTries < 3)
                {
                    // No spot, increment direction to try
                    directionalTries++;
                }
                else
                {
                    // No spot, reset direction to try and find new starting spot

                    if (spots.Any())
                    {
                        // Try to find next spots close to other spots
                        searchRect = CellRect.CenteredOn(spots.Average(), 8);
                    }

                    for (int i = 0; i < 50; i++)
                    {
                        IntVec3 randomCell = searchRect.RandomCell;
                        if (Map.reachability.CanReach(randomCell, Info.setupCentre, PathEndMode.OnCell, TraverseMode.NoPassClosedDoors, Danger.Deadly) &&
                            !randomCell.GetThingList(this.Map).Any(t => t is Blueprint))
                        {
                            spots.Add(randomCell);
                            countSpots++;
                            break;
                        }
                    }
                    directionalTries = 0;
                }

                // Whether or not a spot was found, increment attempts to avoid infinite looping
                attempts++;
            }

Error:

            for (int i = 0; i < countSpots && i < countCarriers; i++)
            {
                // Add calculated spots to rememberedPositions
                Info.rememberedPositions.Add(Info.pawnsWithRole[CarnivalRole.Carrier][i], spots[i]);
                yield return(spots[i]);
            }

            if (countSpots != countCarriers)
            {
                Log.Error("[Carnivale] Not enough spots found for carnival carriers to chill. countSpots=" + countSpots + ", countCarriers=" + countCarriers);
            }
        }
Exemple #31
0
        protected override bool TryCastShot()
        {
            bool flag10 = false;

            this.TargetsAoE.Clear();
            this.UpdateTargets();
            int  shotsPerBurst = this.ShotsPerBurst;
            bool flag2         = this.UseAbilityProps.AbilityTargetCategory != AbilityTargetCategory.TargetAoE && this.TargetsAoE.Count > 1;

            if (flag2)
            {
                this.TargetsAoE.RemoveRange(0, this.TargetsAoE.Count - 1);
            }
            for (int i = 0; i < this.TargetsAoE.Count; i++)
            {
                bool?flag3    = this.TryLaunchProjectile(this.verbProps.defaultProjectile, this.TargetsAoE[i]);
                bool hasValue = flag3.HasValue;
                if (hasValue)
                {
                    bool flag4 = flag3 == true;
                    if (flag4)
                    {
                        flag10 = true;
                    }
                    bool flag5 = flag3 == false;
                    if (flag5)
                    {
                        flag10 = false;
                    }
                }
            }

            CellRect cellRect = CellRect.CenteredOn(this.currentTarget.Cell, 1);
            Map      map      = caster.Map;

            cellRect.ClipInsideMap(map);

            IntVec3      centerCell      = cellRect.CenterCell;
            Thing        summonableThing = new Thing();
            FlyingObject summonablePawn  = new FlyingObject();
            Pawn         victim          = null;
            //dinfo.SetAmount(10);
            //dinfo.SetWeaponHediff(TorannMagicDefOf.TM_GrapplingHook);

            bool pflag = true;

            summonableThing = centerCell.GetFirstPawn(map);
            if (summonableThing == null)
            {
                pflag = false;
                //miss
            }
            else
            {
                pVect   = summonableThing.TrueCenter();
                pVect.x = base.caster.TrueCenter().x;
                pVect.z = base.caster.TrueCenter().z;
                pVect.y = 0f;
                victim  = summonableThing as Pawn;
                if (victim != null)
                {
                    if (!victim.IsColonist && !victim.IsPrisoner && !victim.Faction.HostileTo(this.CasterPawn.Faction) && victim.Faction != null && victim.RaceProps.Humanlike)
                    {
                        //Faction faction = victim.Faction;
                        //faction.TrySetRelationKind(this.CasterPawn.Faction, FactionRelationKind.Ally, false, null);
                        //FactionRelation fr = new FactionRelation();
                        //fr.baseGoodwill = -100;
                        //fr.kind = FactionRelationKind.Hostile;
                        //faction.SetRelation(fr);
                    }
                }
            }
            bool result;
            bool arg_40_0;

            if (this.currentTarget != null && base.caster != null)
            {
                IntVec3 arg_29_0 = this.currentTarget.Cell;
                arg_40_0 = this.caster.Position.IsValid;
            }
            else
            {
                arg_40_0 = false;
            }
            bool flag = arg_40_0;

            if (flag)
            {
                if (summonableThing != null)
                {
                    if (pflag)
                    {
                        DamageInfo dinfo2 = new DamageInfo(DamageDefOf.Stun, 10, 10, -1, this.CasterPawn, null, null, DamageInfo.SourceCategory.ThingOrUnknown, victim);
                        if (!victim.RaceProps.Humanlike || victim.Faction == this.CasterPawn.Faction)
                        {
                            if (ModCheck.Validate.GiddyUp.Core_IsInitialized())
                            {
                                ModCheck.GiddyUp.ForceDismount(victim);
                            }
                            victim.Position = base.Caster.Position;
                            victim.Notify_Teleported();
                            victim.TakeDamage(dinfo2);
                            //summonablePawn = (FlyingObject)GenSpawn.Spawn(ThingDef.Named("TM_SummonedPawn"), summonableThing.Position, summonableThing.Map);
                            //summonablePawn.impactDamage = dinfo2;
                            //summonablePawn.Launch(base.caster, new LocalTargetInfo(pVect.ToIntVec3()), summonableThing);
                        }
                        else if (victim.RaceProps.Humanlike && victim.Faction != this.CasterPawn.Faction && Rand.Chance(TM_Calc.GetSpellSuccessChance(this.CasterPawn, victim, true)))
                        {
                            if (ModCheck.Validate.GiddyUp.Core_IsInitialized())
                            {
                                ModCheck.GiddyUp.ForceDismount(victim);
                            }
                            victim.Position = base.Caster.Position;
                            victim.Notify_Teleported();
                            victim.TakeDamage(dinfo2);
                            //summonablePawn = (FlyingObject)GenSpawn.Spawn(ThingDef.Named("TM_SummonedPawn"), summonableThing.Position, summonableThing.Map);
                            //summonablePawn.impactDamage = dinfo2;
                            //summonablePawn.Launch(base.caster, new LocalTargetInfo(pVect.ToIntVec3()), summonableThing);
                        }
                        else
                        {
                            MoteMaker.ThrowText(victim.DrawPos, victim.Map, "TM_ResistedSpell".Translate(), -1);
                        }
                    }
                    else
                    {
                        //miss
                    }
                    result = true;
                }
            }
            else
            {
                Log.Warning("failed to TryCastShot");
            }
            //this.burstShotsLeft = 0;
            //this.ability.TicksUntilCasting = (int)base.UseAbilityProps.SecondsToRecharge * 60;
            this.PostCastShot(flag10, out flag10);
            return(flag);
        }
 public static void DebugDraw()
 {
     if (DebugViewSettings.drawInfestationChance)
     {
         if (tmpCachedInfestationChanceCellColors == null)
         {
             tmpCachedInfestationChanceCellColors = new List <Pair <IntVec3, float> >();
         }
         if (Time.frameCount % 8 == 0)
         {
             tmpCachedInfestationChanceCellColors.Clear();
             Map      currentMap      = Find.CurrentMap;
             CellRect currentViewRect = Find.CameraDriver.CurrentViewRect;
             currentViewRect.ClipInsideMap(currentMap);
             currentViewRect = currentViewRect.ExpandedBy(1);
             CalculateTraversalDistancesToUnroofed(currentMap);
             CalculateClosedAreaSizeGrid(currentMap);
             CalculateDistanceToColonyBuildingGrid(currentMap);
             float num  = 0.001f;
             int   num2 = 0;
             while (true)
             {
                 int     num3 = num2;
                 IntVec3 size = currentMap.Size;
                 if (num3 >= size.z)
                 {
                     break;
                 }
                 int num4 = 0;
                 while (true)
                 {
                     int     num5  = num4;
                     IntVec3 size2 = currentMap.Size;
                     if (num5 >= size2.x)
                     {
                         break;
                     }
                     IntVec3 cell    = new IntVec3(num4, 0, num2);
                     float   scoreAt = GetScoreAt(cell, currentMap);
                     if (scoreAt > num)
                     {
                         num = scoreAt;
                     }
                     num4++;
                 }
                 num2++;
             }
             int num6 = 0;
             while (true)
             {
                 int     num7  = num6;
                 IntVec3 size3 = currentMap.Size;
                 if (num7 >= size3.z)
                 {
                     break;
                 }
                 int num8 = 0;
                 while (true)
                 {
                     int     num9  = num8;
                     IntVec3 size4 = currentMap.Size;
                     if (num9 >= size4.x)
                     {
                         break;
                     }
                     IntVec3 intVec = new IntVec3(num8, 0, num6);
                     if (currentViewRect.Contains(intVec))
                     {
                         float scoreAt2 = GetScoreAt(intVec, currentMap);
                         if (!(scoreAt2 <= 7.5f))
                         {
                             float second = GenMath.LerpDouble(7.5f, num, 0f, 1f, scoreAt2);
                             tmpCachedInfestationChanceCellColors.Add(new Pair <IntVec3, float>(intVec, second));
                         }
                     }
                     num8++;
                 }
                 num6++;
             }
         }
         for (int i = 0; i < tmpCachedInfestationChanceCellColors.Count; i++)
         {
             IntVec3 first   = tmpCachedInfestationChanceCellColors[i].First;
             float   second2 = tmpCachedInfestationChanceCellColors[i].Second;
             CellRenderer.RenderCell(first, SolidColorMaterials.SimpleSolidColorMaterial(new Color(0f, 0f, 1f, second2)));
         }
     }
     else
     {
         tmpCachedInfestationChanceCellColors = null;
     }
 }
        public override void Tick()
        {
            base.Tick();
            age++;
            if (this.ticksToImpact >= 0)
            {
                DrawEffects(this.ExactPosition, base.Map);
            }
            this.ticksToImpact--;
            this.ticksFollowingImpact--;
            base.Position = this.ExactPosition.ToIntVec3();
            bool flag = !this.ExactPosition.InBounds(base.Map);

            if (flag)
            {
                this.ticksToImpact++;
                this.Destroy(DestroyMode.Vanish);
            }
            else
            {
                bool flag2 = this.ticksToImpact <= 0 && !impacted;
                if (flag2)
                {
                    bool flag3 = this.DestinationCell.InBounds(base.Map);
                    if (flag3)
                    {
                        base.Position = this.DestinationCell;
                    }
                    this.ImpactSomething();
                }
            }

            if (this.impacted)
            {
                if (this.ticksFollowingImpact > 0 && Find.TickManager.TicksGame % 5 == 0)
                {
                    CellRect cellRect = CellRect.CenteredOn(base.Position, 2);
                    cellRect.ClipInsideMap(base.Map);
                    IntVec3 spreadingDarknessCell;
                    if (!(cellRect.CenterCell.GetTerrain(base.Map).passability == Traversability.Impassable) && !cellRect.CenterCell.IsValid || !cellRect.CenterCell.InBounds(base.Map))
                    {
                        this.ticksFollowingImpact = -1;
                    }
                    for (int i = 0; i < 2; i++)
                    {
                        spreadingDarknessCell = cellRect.RandomCell;
                        if (spreadingDarknessCell.IsValid && spreadingDarknessCell.InBounds(base.Map))
                        {
                            GenExplosion.DoExplosion(spreadingDarknessCell, base.Map, .4f, TMDamageDefOf.DamageDefOf.TM_DeathBolt, this.launcher as Pawn, Mathf.RoundToInt((Rand.Range(.4f * this.def.projectile.damageAmountBase, .8f * this.def.projectile.damageAmountBase) + (3f * pwrVal)) * this.arcaneDmg), this.def.projectile.soundExplode, def, null, null, 0f, 1, false, null, 0f, 0, 0.0f, true);
                            TM_MoteMaker.ThrowDiseaseMote(base.Position.ToVector3Shifted(), base.Map, .6f);
                            if (powered)
                            {
                                TM_MoteMaker.ThrowBoltMote(base.Position.ToVector3Shifted(), base.Map, 0.3f);
                            }
                        }
                    }
                }

                if (this.ticksFollowingImpact < 0)
                {
                    this.Destroy(DestroyMode.Vanish);
                }
            }
        }
        public void SearchForTargets(IntVec3 center, float radius)
        {
            Pawn     curPawnTarg = null;
            Building curBldgTarg = null;
            IntVec3  curCell;
            IEnumerable <IntVec3> targets = GenRadial.RadialCellsAround(center, radius, true);

            for (int i = 0; i < targets.Count(); i++)
            {
                curCell = targets.ToArray <IntVec3>()[i];
                if (curCell.InBounds(base.Map) && curCell.IsValid)
                {
                    curPawnTarg = curCell.GetFirstPawn(base.Map);
                    curBldgTarg = curCell.GetFirstBuilding(base.Map);
                }

                if (curPawnTarg != null && curPawnTarg != launcher)
                {
                    bool newTarg = false;
                    if (this.age > this.lastStrike + (this.maxStrikeDelay - (int)Rand.Range(0 + (pwrVal * 20), 40 + (pwrVal * 15))))
                    {
                        if (Rand.Chance(.1f))
                        {
                            newTarg = true;
                        }
                        if (newTarg)
                        {
                            CellRect cellRect = CellRect.CenteredOn(curCell, 2);
                            cellRect.ClipInsideMap(base.Map);
                            DrawStrike(center, curPawnTarg.Position.ToVector3());
                            for (int k = 0; k < Rand.Range(1, 8); k++)
                            {
                                IntVec3 randomCell = cellRect.RandomCell;
                                GenExplosion.DoExplosion(randomCell, base.Map, Rand.Range(.4f, .8f), TMDamageDefOf.DamageDefOf.TM_Lightning, this.launcher, Rand.Range(3 + 3 * pwrVal, 7 + 5 * pwrVal), SoundDefOf.Thunder_OnMap, null, null, null, 0f, 1, false, null, 0f, 1, 0.1f, true);
                            }
                            GenExplosion.DoExplosion(curPawnTarg.Position, base.Map, 1f, TMDamageDefOf.DamageDefOf.TM_Lightning, this.launcher, Rand.Range(3 + 3 * pwrVal, 7 + 5 * pwrVal), SoundDefOf.Thunder_OffMap, null, null, null, 0f, 1, false, null, 0f, 1, 0.1f, true);
                            this.lastStrike = this.age;
                        }
                    }
                }
                if (curBldgTarg != null)
                {
                    bool newTarg = false;
                    if (this.age > this.lastStrikeBldg + (this.maxStrikeDelayBldg - (int)Rand.Range(0 + (pwrVal * 10), (pwrVal * 15))))
                    {
                        if (Rand.Chance(.1f))
                        {
                            newTarg = true;
                        }
                        if (newTarg)
                        {
                            CellRect cellRect = CellRect.CenteredOn(curCell, 1);
                            cellRect.ClipInsideMap(base.Map);
                            DrawStrike(center, curBldgTarg.Position.ToVector3());
                            for (int k = 0; k < Rand.Range(1, 8); k++)
                            {
                                IntVec3 randomCell = cellRect.RandomCell;
                                GenExplosion.DoExplosion(randomCell, base.Map, Rand.Range(.2f, .6f), TMDamageDefOf.DamageDefOf.TM_Lightning, this.launcher, Rand.Range(3 + 3 * pwrVal, 7 + 5 * pwrVal), SoundDefOf.Thunder_OffMap, null, null, null, 0f, 1, false, null, 0f, 1, 0.1f, true);
                            }
                            GenExplosion.DoExplosion(curBldgTarg.Position, base.Map, 1f, TMDamageDefOf.DamageDefOf.TM_Lightning, this.launcher, Rand.Range(5 + 5 * pwrVal, 10 + 10 * pwrVal), SoundDefOf.Thunder_OffMap, null, null, null, 0f, 1, false, null, 0f, 1, 0.1f, true);
                            this.lastStrikeBldg = this.age;
                        }
                    }
                }
                targets.GetEnumerator().MoveNext();
            }
            DrawStrikeFading();
            age++;
        }
        public static void GenerateSamSiteZone(IntVec3 areaSouthWestOrigin, int zoneAbs, int zoneOrd, ref OG_OutpostData outpostData)
        {
            IntVec3 origin = Zone.GetZoneOrigin(areaSouthWestOrigin, zoneAbs, zoneOrd);

            // Spawn SAM site surrounded by sandbags.
            IntVec3 samSitePosition = origin + new IntVec3(Genstep_GenerateOutpost.zoneSideCenterOffset, 0, Genstep_GenerateOutpost.zoneSideCenterOffset);
            OG_Common.TrySpawnThingAt(OG_Util.SamSiteDef, null, samSitePosition, false, Rot4.Invalid, ref outpostData);
            CellRect sandbagRect = new CellRect(origin.x + 3, origin.z + 3, 5, 5);
            foreach (IntVec3 cell in sandbagRect.Cells)
            {
                if ((cell.x == sandbagRect.minX) || (cell.x == sandbagRect.maxX) || (cell.z == sandbagRect.minZ) || (cell.z == sandbagRect.maxZ))
                {
                    OG_Common.TrySpawnThingAt(ThingDefOf.Sandbags, null, cell, false, Rot4.Invalid, ref outpostData);
                }
            }
            for (int rotationAsInt = Rot4.North.AsInt; rotationAsInt <= Rot4.West.AsInt; rotationAsInt++)
            {
                IntVec3 sandbagPosition = samSitePosition + new IntVec3(0, 0, 3).RotatedBy(new Rot4(rotationAsInt));
                OG_Common.TrySpawnThingAt(ThingDefOf.Sandbags, null, sandbagPosition, false, Rot4.Invalid, ref outpostData);
                foreach (IntVec3 cell in GenAdj.CellsAdjacent8Way(sandbagPosition))
                {
                    Find.TerrainGrid.SetTerrain(cell, TerrainDefOf.Concrete);
                }
            }

            // Generate concrete ground.
            CellRect concreteRect = new CellRect(origin.x + 2, origin.z + 2, 7, 7);
            foreach (IntVec3 cell in concreteRect.Cells)
            {
                Find.TerrainGrid.SetTerrain(cell, TerrainDefOf.Concrete);
            }
        }
Exemple #36
0
        private bool TryFindSpawnCell(CellRect rect, out IntVec3 result)
        {
            Map map = BaseGen.globalSettings.map;

            return(CellFinder.TryFindRandomCellInsideWith(rect, (IntVec3 c) => c.Standable(map) && !c.Roofed(map) && !BaseGenUtility.AnyDoorAdjacentCardinalTo(c, map) && c.GetFirstItem(map) == null && !GenSpawn.WouldWipeAnythingWith(c, Rot4.North, ThingDefOf.Campfire, map, (Thing x) => x.def.category == ThingCategory.Building), out result));
        }
        public static void GenerateOutpost(OG_OutpostData outpostDataParameter)
        {
            outpostData = outpostDataParameter;
            outpostData.triggerIntrusion = null;
            outpostData.outpostThingList = new List<Thing>();

            // Reset zoneMap.
            for (int zoneOrd = 0; zoneOrd < verticalZonesNumber; zoneOrd++)
            {
                for (int zoneAbs = 0; zoneAbs < horizontalZonesNumber; zoneAbs++)
                {
                    zoneMap[zoneOrd, zoneAbs] = new ZoneProperties(ZoneType.NotYetGenerated, Rot4.North, Rot4.North);
                }
            }
            // Clear the whole area and remove any roof.
            CellRect rect = new CellRect(outpostData.areaSouthWestOrigin.x - 1, outpostData.areaSouthWestOrigin.z - 1, areaSideLength + 2, areaSideLength + 2);
            foreach (IntVec3 cell in rect.Cells)
            {
                Find.RoofGrid.SetRoof(cell, null);
                List<Thing> thingList = cell.GetThingList();
                for (int j = thingList.Count - 1; j >= 0; j--)
                {
                    Thing thing = thingList[j];
                    if (thing.def.destroyable)
                    {
                        thing.Destroy(DestroyMode.Vanish);
                    }
                }
            }
            // Create the intrusion trigger.
            outpostData.triggerIntrusion = (TriggerIntrusion)ThingMaker.MakeThing(ThingDef.Named("TriggerIntrusion"));
            GenSpawn.Spawn(outpostData.triggerIntrusion, rect.CenterCell);

            GenerateOutpostLayout();
            
            // TODO: debug. Display the generated layout.
            /*for (int zoneOrd = 0; zoneOrd < verticalZonesNumber; zoneOrd++)
            {
                for (int zoneAbs = 0; zoneAbs < horizontalZonesNumber; zoneAbs++)
                {
                    ZoneProperties zone = zoneMap[zoneOrd, zoneAbs];
                    Log.Message("Layout: zoneMap[" + zoneOrd + "," + zoneAbs + "] => " + zone.zoneType.ToString() + "," + zone.rotation.ToString() + "," + zone.linkedZoneRelativeRotation.ToString());
                }
            }*/
            GenerateOutpostZones(outpostData.areaSouthWestOrigin);
            
            IntVec3 mainRoomZoneOrigin = Zone.GetZoneOrigin(outpostData.areaSouthWestOrigin, mainRoomZoneAbs, mainRoomZoneOrd);
            OG_Common.GenerateSas(mainRoomZoneOrigin + new IntVec3(5, 0, 10), Rot4.North, 3, smallRoomWallOffset * 2, ref outpostData);
            OG_Common.GenerateSas(mainRoomZoneOrigin + new IntVec3(10, 0, 5), Rot4.East, 3, smallRoomWallOffset * 2, ref outpostData);
            OG_Common.GenerateSas(mainRoomZoneOrigin + new IntVec3(5, 0, 0), Rot4.South, 3, smallRoomWallOffset * 2, ref outpostData);
            OG_Common.GenerateSas(mainRoomZoneOrigin + new IntVec3(0, 0, 5), Rot4.West, 3, smallRoomWallOffset * 2, ref outpostData);
            
            // Generate laser fences.
            OG_LaserFence.GenerateLaserFence(zoneMap, ref outpostData);
            // Generate battle remains.
            OG_WarfieldEffects.GenerateWarfieldEffects(zoneMap, horizontalZonesNumber, verticalZonesNumber, outpostData);
            // Damage outpost to reflect its history.
            OG_RuinEffects.GenerateRuinEffects(ref outpostData);
            // Don't generate permanent inhabitants for small outposts. Those are just used as a shack by exploration teams.

            // Initialize command console data.
            outpostData.outpostThingList = OG_Util.RefreshThingList(outpostData.outpostThingList);
            commandConsole.outpostThingList = outpostData.outpostThingList.ListFullCopy<Thing>();
            commandConsole.dropZoneCenter = outpostData.dropZoneCenter;
            // Initialize intrusion trigger data.
            outpostData.triggerIntrusion.commandConsole = commandConsole;

            SendWelcomeLetter(outpostData);
        }
        public static Building_OutpostCommandConsole GenerateBigRoomCommandRoom(IntVec3 areaSouthWestOrigin, int zoneAbs, int zoneOrd, Rot4 rotation, ref OG_OutpostData outpostData)
        {
            Building_OutpostCommandConsole commandConsole = null;

            IntVec3 origin = Zone.GetZoneOrigin(areaSouthWestOrigin, zoneAbs, zoneOrd);
            IntVec3 rotatedOrigin = Zone.GetZoneRotatedOrigin(areaSouthWestOrigin, zoneAbs, zoneOrd, rotation);

            OG_Common.GenerateEmptyRoomAt(rotatedOrigin, Genstep_GenerateOutpost.zoneSideSize, Genstep_GenerateOutpost.zoneSideSize, rotation, TerrainDefOf.Concrete, TerrainDef.Named("CarpetDark"), ref outpostData);

            // Spawn doors.
            OG_Common.SpawnDoorAt(rotatedOrigin + new IntVec3(5, 0, 10).RotatedBy(rotation), ref outpostData);
            OG_Common.SpawnDoorAt(rotatedOrigin + new IntVec3(10, 0, 5).RotatedBy(rotation), ref outpostData);
            OG_Common.SpawnDoorAt(rotatedOrigin + new IntVec3(5, 0, 0).RotatedBy(rotation), ref outpostData);
            OG_Common.SpawnDoorAt(rotatedOrigin + new IntVec3(0, 0, 5).RotatedBy(rotation), ref outpostData);
            
            // Spawn weapon racks.
            Building_Storage rack = OG_Common.TrySpawnThingAt(ThingDefOf.EquipmentRack, ThingDefOf.Steel, rotatedOrigin + new IntVec3(2, 0, 1).RotatedBy(rotation), true, new Rot4(Rot4.North.AsInt + rotation.AsInt), ref outpostData) as Building_Storage;
            OG_Common.TrySpawnWeaponOnRack(rack);
            rack.GetStoreSettings().filter.SetAllow(ThingCategoryDef.Named("WeaponsMelee"), false);
            rack.GetStoreSettings().Priority = StoragePriority.Critical;
            rack = OG_Common.TrySpawnThingAt(ThingDefOf.EquipmentRack, ThingDefOf.Steel, rotatedOrigin + new IntVec3(1, 0, 3).RotatedBy(rotation), true, new Rot4(Rot4.East.AsInt + rotation.AsInt), ref outpostData) as Building_Storage;
            OG_Common.TrySpawnWeaponOnRack(rack);
            rack.GetStoreSettings().filter.SetAllow(ThingCategoryDef.Named("WeaponsMelee"), false);
            rack.GetStoreSettings().Priority = StoragePriority.Critical;

            // Spawn lamps.
            OG_Common.TrySpawnLampAt(rotatedOrigin + new IntVec3(1, 0, 1).RotatedBy(rotation), Color.white, ref outpostData);
            OG_Common.TrySpawnLampAt(rotatedOrigin + new IntVec3(9, 0, 9).RotatedBy(rotation), Color.white, ref outpostData);

            // Spawn table and stools.
            OG_Common.TrySpawnThingAt(ThingDef.Named("Stool"), ThingDefOf.Steel, rotatedOrigin + new IntVec3(7, 0, 1).RotatedBy(rotation), true, new Rot4(Rot4.East.AsInt + rotation.AsInt), ref outpostData);
            OG_Common.TrySpawnThingAt(ThingDef.Named("Stool"), ThingDefOf.Steel, rotatedOrigin + new IntVec3(8, 0, 3).RotatedBy(rotation), true, new Rot4(Rot4.South.AsInt + rotation.AsInt), ref outpostData);
            OG_Common.TrySpawnThingAt(ThingDef.Named("TableShort"), ThingDefOf.Steel, rotatedOrigin + new IntVec3(8, 0, 1).RotatedBy(rotation), true, new Rot4(Rot4.North.AsInt + rotation.AsInt), ref outpostData);

            // Spawn outpost command console, battery and spare parts cabinet.
            OG_Common.TrySpawnThingAt(ThingDefOf.Battery, null, rotatedOrigin + new IntVec3(1, 0, 9).RotatedBy(rotation), true, new Rot4(Rot4.South.AsInt + rotation.AsInt), ref outpostData);
            OG_Common.TrySpawnThingAt(OG_Util.SparePartsCabinetDef, null, rotatedOrigin + new IntVec3(1, 0, 7).RotatedBy(rotation), true, new Rot4(Rot4.East.AsInt + rotation.AsInt), ref outpostData);
            OG_Common.SpawnResourceAt(ThingDefOf.Component, 10, rotatedOrigin + new IntVec3(1, 0, 7).RotatedBy(rotation), true);
            OG_Common.SpawnResourceAt(ThingDefOf.Component, 10, rotatedOrigin + new IntVec3(1, 0, 6).RotatedBy(rotation), true);
            commandConsole = OG_Common.TrySpawnThingAt(OG_Util.OutpostCommandConsoleDef, null, rotatedOrigin + new IntVec3(3, 0, 9).RotatedBy(rotation), true, new Rot4(Rot4.South.AsInt + rotation.AsInt), ref outpostData) as Building_OutpostCommandConsole;

            // Spawn workbenches.
            OG_Common.TrySpawnThingAt(ThingDef.Named("TableMachining"), null, rotatedOrigin + new IntVec3(7, 0, 9).RotatedBy(rotation), true, new Rot4(Rot4.North.AsInt + rotation.AsInt), ref outpostData);
            OG_Common.TrySpawnThingAt(ThingDef.Named("ElectricSmithy"), null, rotatedOrigin + new IntVec3(9, 0, 7).RotatedBy(rotation), true, new Rot4(Rot4.East.AsInt + rotation.AsInt), ref outpostData);

            // Spawn heaters and coolers.
            OG_Common.TrySpawnHeaterAt(rotatedOrigin + new IntVec3(1, 0, 4).RotatedBy(rotation), ref outpostData);
            OG_Common.TrySpawnHeaterAt(rotatedOrigin + new IntVec3(4, 0, 1).RotatedBy(rotation), ref outpostData);
            OG_Common.SpawnCoolerAt(rotatedOrigin + new IntVec3(0, 0, 1).RotatedBy(rotation), new Rot4(Rot4.West.AsInt + rotation.AsInt), ref outpostData);
            OG_Common.SpawnCoolerAt(rotatedOrigin + new IntVec3(1, 0, 0).RotatedBy(rotation), new Rot4(Rot4.South.AsInt + rotation.AsInt), ref outpostData);

            // Spawn floor and tactical computer.
            for (int xOffset = 0; xOffset <= 10; xOffset++)
            {
                Find.TerrainGrid.SetTerrain(rotatedOrigin + new IntVec3(xOffset, 0, 5).RotatedBy(rotation), TerrainDef.Named("PavedTile"));
            }
            for (int zOffset = 0; zOffset <= 10; zOffset++)
            {
                Find.TerrainGrid.SetTerrain(rotatedOrigin + new IntVec3(5, 0, zOffset).RotatedBy(rotation), TerrainDef.Named("PavedTile"));
            }
            CellRect rect = new CellRect(origin.x + 3, origin.z + 3, 5, 5);
            foreach (IntVec3 cell in rect)
            {
                Find.TerrainGrid.SetTerrain(cell, TerrainDef.Named("PavedTile"));
            }
            foreach (IntVec3 cell in rect.ContractedBy(1))
            {
                Find.TerrainGrid.SetTerrain(cell, TerrainDef.Named("CarpetRed"));
            }
            if (OG_Util.IsModActive("Misc. Incidents"))
            {
                OG_Common.TrySpawnThingAt(ThingDef.Named("TacticalComputer"), null, rotatedOrigin + new IntVec3(5, 0, 5).RotatedBy(rotation), true, new Rot4(Rot4.North.AsInt + rotation.AsInt), ref outpostData);
            }

            return commandConsole;
        }
        protected override bool CanScatterAt(IntVec3 loc)
        {
            int mountainousBorderCells = 0;
            int mountainousBorderCellsThreshold = 0;
            int aquaticCells = 0;
            int aquaticCellsThreshold = 0;

            if (base.CanScatterAt(loc) == false)
            {
                return false;
            }
            
            int minFreeAreaSideSize = 1;
            switch (this.outpostData.size)
            {
                case OG_OutpostSize.SmallOutpost:
                    minFreeAreaSideSize = OG_SmallOutpost.areaSideLength;
                    break;
                case OG_OutpostSize.BigOutpost:
                    minFreeAreaSideSize = OG_BigOutpost.areaSideLength;
                    break;
            }
            CellRect outpostArea = new CellRect(loc.x, loc.z, minFreeAreaSideSize, minFreeAreaSideSize);
            mountainousBorderCellsThreshold = (2 * outpostArea.Width + 2 * outpostArea.Height) / 4;
            aquaticCellsThreshold = outpostArea.Area / 100;
            foreach (IntVec3 cell in outpostArea)
            {
                // Only for border cells: too close from edge or crossing an existing structure (potentially a shrine).
                if ((cell.x == outpostArea.minX)
                    || (cell.x == outpostArea.maxX)
                    || (cell.z == outpostArea.minZ)
                    || (cell.z == outpostArea.maxZ))
                {
                    if (cell.CloseToEdge(20))
                    {
                        return false;
                    }

                    Building building = cell.GetEdifice();
                    if (building != null)
                    {
                        mountainousBorderCells++;
                        if (mountainousBorderCells > mountainousBorderCellsThreshold)
                        {
                            return false;
                        }
                    }
                }
                TerrainDef terrain = Find.TerrainGrid.TerrainAt(cell);
                if (terrain == TerrainDef.Named("WaterDeep"))
                {
                    return false;
                }
                if ((terrain == TerrainDef.Named("Marsh"))
                    || (terrain == TerrainDef.Named("Mud"))
                    || (terrain == TerrainDef.Named("WaterShallow")))
                {
                    aquaticCells++;
                    if (aquaticCells > aquaticCellsThreshold)
                    {
                        return false;
                    }
                }
                List<Thing> thingList = cell.GetThingList();
                foreach (Thing thing in thingList)
                {
                    if (thing.def.destroyable == false)
                    {
                        return false;
                    }
                }
            }
            // TODO: debug.
            //Log.Message("Valid spawn point found! Mountainous cells/threshold, aquatic cells/threshold = " + mountainousBorderCells + "/" + mountainousBorderCellsThreshold + ", " + aquaticCells + "/" + aquaticCellsThreshold);
            return true;
        }
        public void TryStartUseJob(Pawn user)
        {
            Find.DesignatorManager.Deselect();
            if (!user.CanReserveAndReach(this.parent, PathEndMode.Touch, Danger.Deadly, 1))
            {
                return;
            }
            if (!user.CanReach(this.targetPos, PathEndMode.Touch, Danger.Deadly))
            {
                return;
            }
            if (this.parent.HitPoints <= 0)
            {
                Messages.Message("Cannot place a fully damaged tent.", MessageSound.RejectInput);
                return;
            }

            CellRect       cellRect   = new CellRect(this.targetPos.x - 2, this.targetPos.z - 2, 5, 4);
            List <IntVec3> everything = new List <IntVec3>();

            everything.AddRange(this.wallCells);
            everything.AddRange(this.doorCells);


            foreach (IntVec3 current in everything)
            {
                if (!GenConstruct.CanPlaceBlueprintAt(ThingDefOf.Wall, current, Rot4.North, user.Map, false, null).Accepted)
                {
                    Messages.Message("Tent placement blocked. Please deploy on a suitable space.", MessageSound.RejectInput);
                    return;
                }

                if (current.GetFirstItem(user.Map) != null || current.GetFirstPawn(user.Map) != null || current.GetFirstHaulable(user.Map) != null)
                {
                    Messages.Message("Tent placement blocked by a item, pawn or a building. Please deploy on a suitable space.", MessageSound.RejectInput);
                    return;
                }

                Building building = current.GetFirstBuilding(user.Map);
                if (building != null)
                {
                    if (building.def.IsEdifice())
                    {
                        Messages.Message("Tent placement blocked by a item, pawn or a building. Please deploy on a suitable space.", MessageSound.RejectInput);
                        return;
                    }
                }
                Plant plant = current.GetPlant(user.Map);
                if (plant != null)
                {
                    if (plant.def.plant.IsTree)
                    {
                        Messages.Message("Tent placement blocked by a tree. Please deploy on a suitable space.", MessageSound.RejectInput);
                        return;
                    }
                }
            }
            Job job = new Job(DefDatabase <JobDef> .GetNamed("DeployTent", true), this.parent, this.targetInfo1);

            user.jobs.TryTakeOrderedJob(job);
        }
        private static bool TargetValidator(IntVec3 c, Map map, CompTargetable_Tent t)
        {
            if (!c.InBounds(map) || !c.Standable(map))
            {
                return(false);
            }
            if (!c.Walkable(map))
            {
                return(false);
            }

            t.HandleRotation();
            t.GetPlacements(c);
            CellRect       cellRect   = new CellRect(c.x - 2, c.z - 2, 5, 4);
            List <IntVec3> clist      = new List <IntVec3>();
            Color          color      = new Color(1f, 1f, 1f, 0.4f);
            List <IntVec3> everything = new List <IntVec3>();

            everything.AddRange(t.wallCells);
            everything.AddRange(t.doorCells);


            foreach (IntVec3 current in everything)
            {
                if (!current.InBounds(map))
                {
                    return(false);
                }
                if (!GenConstruct.CanPlaceBlueprintAt(ThingDefOf.Wall, current, Rot4.North, map, false, null).Accepted)
                {
                    color = new Color(1f, 0f, 0f, 0.4f);
                }

                if (current.GetFirstItem(map) != null || current.GetFirstPawn(map) != null || current.GetFirstHaulable(map) != null)
                {
                    color = new Color(1f, 0f, 0f, 0.4f);
                }
                Building building = current.GetFirstBuilding(map);
                if (building != null)
                {
                    if (building.def.IsEdifice())
                    {
                        color = new Color(1f, 0f, 0f, 0.4f);
                    }
                }
                Plant plant = current.GetPlant(map);
                if (plant != null)
                {
                    if (plant.def.plant.IsTree)
                    {
                        color = new Color(1f, 0f, 0f, 0.4f);
                    }
                }
            }
            foreach (IntVec3 doorCell in t.doorCells)
            {
                GhostDrawer.DrawGhostThing(doorCell, t.placingRot, ThingDef.Named("TentDoor"), null, color, AltitudeLayer.Blueprint);
            }


            GenDraw.DrawFieldEdges(t.wallCells, color);

            return(true);
        }
Exemple #42
0
 public static void GenerateEmptyRoomAt(IntVec3 rotatedOrigin,
     int width,
     int height,
     Rot4 rotation,
     TerrainDef defaultFloorDef,
     TerrainDef interiorFloorDef,
     ref OG_OutpostData outpostData)
 {
     CellRect rect = new CellRect(rotatedOrigin.x, rotatedOrigin.z, width, height);
     if (rotation == Rot4.North)
     {
         rect = new CellRect(rotatedOrigin.x, rotatedOrigin.z, width, height);
     }
     else if (rotation == Rot4.East)
     {
         rect = new CellRect(rotatedOrigin.x, rotatedOrigin.z - width + 1, height, width);
     }
     else if (rotation == Rot4.South)
     {
         rect = new CellRect(rotatedOrigin.x - width + 1, rotatedOrigin.z - height + 1, width, height);
     }
     else
     {
         rect = new CellRect(rotatedOrigin.x - height + 1, rotatedOrigin.z, height, width);
     }
     // Generate 4 walls and power conduits.
     foreach (IntVec3 cell in rect.Cells)
     {
         if ((cell.x == rect.minX) || (cell.x == rect.maxX) || (cell.z == rect.minZ) || (cell.z == rect.maxZ))
         {
             OG_Common.TrySpawnWallAt(cell, ref outpostData);
             OG_Common.SpawnFireproofPowerConduitAt(cell, ref outpostData);
         }
     }
     // Trigger to unfog area when a pawn enters the room.
     SpawnRectTriggerUnfogArea(rect, ref outpostData.triggerIntrusion);
     // Generate roof.
     foreach (IntVec3 cell in rect.Cells)
     {
         Find.RoofGrid.SetRoof(cell, OG_Util.IronedRoofDef);
     }
     // Generate room default floor.
     if (defaultFloorDef != null)
     {
         foreach (IntVec3 cell in rect.ExpandedBy(1).Cells)
         {
             TerrainDef terrain = Find.TerrainGrid.TerrainAt(cell);
             if (terrain != TerrainDef.Named("PavedTile")) // Don't recover already spawned paved tile.
             {
                 Find.TerrainGrid.SetTerrain(cell, defaultFloorDef);
             }
         }
     }
     // Generate room interior floor.
     if (interiorFloorDef != null)
     {
         foreach (IntVec3 cell in rect.ContractedBy(1).Cells)
         {
             Find.TerrainGrid.SetTerrain(cell, interiorFloorDef);
         }
     }
 }