public override void PostSpawnSetup(bool respawningAfterLoad)
        {
            base.PostSpawnSetup(respawningAfterLoad);

            if (this.parent.Map != null)
            {
                CellRect rect = GenAdj.OccupiedRect(parent.Position, parent.Rotation, IntVec2.One);
                rect = rect.ExpandedBy(5);
                foreach (IntVec3 current in rect.Cells)
                {
                    if (current.InBounds(parent.Map))
                    {
                        List <Thing> list = parent.Map.thingGrid.ThingsListAt(current);
                        for (int i = 0; i < list.Count; i++)
                        {
                            if (list[i].TryGetComp <CompGlower>() != null)
                            {
                                list[i].Kill();
                            }
                        }
                    }
                }
            }
        }
Exemple #2
0
        private void SpawnTrigger(CellRect rectToDefend, IntVec3 root, Map map, GenStepParams parms)
        {
            int      nextSignalTagID = Find.UniqueIDsManager.GetNextSignalTagID();
            string   signalTag       = "ambushActivated-" + nextSignalTagID;
            CellRect rect;

            if (root.IsValid)
            {
                rect = CellRect.CenteredOn(root, 17);
            }
            else
            {
                rect = rectToDefend.ExpandedBy(12);
            }
            SignalAction_Ambush signalAction_Ambush = this.MakeAmbushSignalAction(rectToDefend, root, parms);

            signalAction_Ambush.signalTag = signalTag;
            GenSpawn.Spawn(signalAction_Ambush, rect.CenterCell, map, WipeMode.Vanish);
            RectTrigger rectTrigger = this.MakeRectTrigger();

            rectTrigger.signalTag = signalTag;
            rectTrigger.Rect      = rect;
            GenSpawn.Spawn(rectTrigger, rect.CenterCell, map, WipeMode.Vanish);
        }
Exemple #3
0
 protected virtual void HitRoof()
 {
     if (def.skyfaller.hitRoof)
     {
         CellRect cr = this.OccupiedRect();
         if (cr.Cells.Any((IntVec3 x) => x.Roofed(base.Map)))
         {
             RoofDef roof = cr.Cells.First((IntVec3 x) => x.Roofed(base.Map)).GetRoof(base.Map);
             if (!roof.soundPunchThrough.NullOrUndefined())
             {
                 roof.soundPunchThrough.PlayOneShot(new TargetInfo(base.Position, base.Map));
             }
             RoofCollapserImmediate.DropRoofInCells(cr.ExpandedBy(1).ClipInsideMap(base.Map).Cells.Where(delegate(IntVec3 c)
             {
                 if (!c.InBounds(base.Map))
                 {
                     return(false);
                 }
                 if (cr.Contains(c))
                 {
                     return(true);
                 }
                 if (c.GetFirstPawn(base.Map) != null)
                 {
                     return(false);
                 }
                 Building edifice = c.GetEdifice(base.Map);
                 if (edifice != null && edifice.def.holdsRoof)
                 {
                     return(false);
                 }
                 return(true);
             }), base.Map);
         }
     }
 }
        private void FindNearbyGlowers(CellRect rect)
        {
            Map map = BaseGen.globalSettings.map;

            nearbyGlowers.Clear();
            rect = rect.ExpandedBy(4);
            rect = rect.ClipInsideMap(map);
            foreach (IntVec3 item in rect)
            {
                Region region = item.GetRegion(map);
                if (region != null && region.Room.PsychologicallyOutdoors)
                {
                    List <Thing> thingList = item.GetThingList(map);
                    for (int i = 0; i < thingList.Count; i++)
                    {
                        CompGlower compGlower = thingList[i].TryGetComp <CompGlower>();
                        if (compGlower != null)
                        {
                            nearbyGlowers.Add(compGlower);
                        }
                    }
                }
            }
        }
Exemple #5
0
        public static void DynamicDrawManagerPostfix(DynamicDrawManager __instance)
        {
            Map map      = Traverse.Create(__instance).Field("map").GetValue <Map>();
            var ZTracker = Current.Game.GetComponent <ZLevelsManager>();

            foreach (var map2 in ZTracker.GetAllMaps(map.Tile)
                     .OrderBy(x => ZTracker.GetZIndexFor(x)))
            {
                int curLevel  = ZTracker.GetZIndexFor(map);
                int baseLevel = ZTracker.GetZIndexFor(map2);

                if (curLevel > baseLevel && baseLevel >= 0)
                {
                    HashSet <Thing> drawThings = Traverse.Create(map2.dynamicDrawManager).Field("drawThings").GetValue <HashSet <Thing> >();

                    if (!DebugViewSettings.drawThingsDynamic)
                    {
                        return;
                    }
                    Traverse.Create(__instance).Field("drawingNow").SetValue(true);
                    try
                    {
                        bool[]   fogGrid  = map2.fogGrid.fogGrid;
                        CellRect cellRect = Find.CameraDriver.CurrentViewRect;
                        cellRect.ClipInsideMap(map2);
                        cellRect = cellRect.ExpandedBy(1);
                        CellIndices cellIndices = map2.cellIndices;
                        foreach (Thing thing in drawThings)
                        {
                            IntVec3 position = thing.Position;
                            if (position.GetTerrain(map) == ZLevelsDefOf.ZL_OutsideTerrain)
                            {
                                if ((cellRect.Contains(position) || thing.def.drawOffscreen)
                                    //&& (!fogGrid[cellIndices.CellToIndex(position)]
                                    //|| thing.def.seeThroughFog)
                                    && (thing.def.hideAtSnowDepth >= 1f ||
                                        map2.snowGrid.GetDepth(position) <= thing.def.hideAtSnowDepth))
                                {
                                    try
                                    {
                                        if (thing.Graphic is Graphic_Mote || thing.Graphic is Graphic_Linked)
                                        {
                                        }
                                        else if (thing.Graphic is Graphic_LinkedCornerFiller ||
                                                 thing.Graphic is Graphic_RandomRotated)
                                        {
                                            thing.Draw();
                                        }
                                        else if (thing is Pawn pawn)
                                        {
                                            var newRenderer = new PawnRendererScaled(pawn);
                                            pawn.Drawer.renderer.graphics.ResolveAllGraphics();
                                            newRenderer.graphics.nakedGraphic      = pawn.Drawer.renderer.graphics.nakedGraphic;
                                            newRenderer.graphics.headGraphic       = pawn.Drawer.renderer.graphics.headGraphic;
                                            newRenderer.graphics.hairGraphic       = pawn.Drawer.renderer.graphics.hairGraphic;
                                            newRenderer.graphics.rottingGraphic    = pawn.Drawer.renderer.graphics.rottingGraphic;
                                            newRenderer.graphics.dessicatedGraphic = pawn.Drawer.renderer.graphics.dessicatedGraphic;
                                            newRenderer.graphics.apparelGraphics   = pawn.Drawer.renderer.graphics.apparelGraphics;
                                            newRenderer.graphics.packGraphic       = pawn.Drawer.renderer.graphics.packGraphic;
                                            newRenderer.graphics.flasher           = pawn.Drawer.renderer.graphics.flasher;
                                            newRenderer.RenderPawnAt(thing.DrawPos, curLevel, baseLevel);
                                        }
                                        else
                                        {
                                            Vector2 drawSize = thing.Graphic.drawSize;
                                            drawSize.x *= 1f - (((float)(curLevel) - (float)baseLevel) / 5f);
                                            drawSize.y *= 1f - (((float)(curLevel) - (float)baseLevel) / 5f);
                                            var newGraphic = thing.Graphic.GetCopy(drawSize);
                                            newGraphic.Draw(thing.DrawPos, thing.Rotation, thing);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Log.Error(string.Concat(new object[]
                                        {
                                            "Exception drawing ",
                                            thing,
                                            ": ",
                                            ex.ToString()
                                        }), false);
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception arg)
                    {
                        Log.Error("Exception drawing dynamic things: " + arg, false);
                    }
                    Traverse.Create(__instance).Field("drawingNow").SetValue(false);
                }
            }
        }
Exemple #6
0
        private static void RecalcRootLocY(ref Vector3 rootLoc, Pawn pawn, CompBodyAnimator compAnimator)
        {
            Vector3  loc      = rootLoc;
            CellRect viewRect = Find.CameraDriver.CurrentViewRect;

            viewRect = viewRect.ExpandedBy(1);

            List <Pawn> pawns = new List <Pawn>();

            foreach (Pawn otherPawn in pawn.Map.mapPawns.AllPawnsSpawned)
            {
                if (!viewRect.Contains(otherPawn.Position))
                {
                    continue;
                }
                if (otherPawn == pawn)
                {
                    continue;
                }
                if (otherPawn.DrawPos.x < loc.x - 0.5f)
                {
                    continue;
                }

                if (otherPawn.DrawPos.x > loc.x + 0.5f)
                {
                    continue;
                }

                if (otherPawn.DrawPos.z >= loc.z)
                {
                    continue;
                }                                               // ignore above

                pawns.Add(otherPawn);
            }
            // pawns = pawn.Map.mapPawns.AllPawnsSpawned
            //                .Where(
            //                       otherPawn => _viewRect.Contains(otherPawn.Position) &&
            //                       otherPawn != pawn &&
            //                                    otherPawn.DrawPos.x >= loc.x - 1 &&
            //                                    otherPawn.DrawPos.x <= loc.x + 1 &&
            //                                    otherPawn.DrawPos.z <= loc.z).ToList();
            //  List<Pawn> leftOfPawn = pawns.Where(other => other.DrawPos.x <= loc.x).ToList();
            bool flag = compAnimator != null;

            if (!pawns.NullOrEmpty())
            {
                float pawnOffset = YOffsetPawns * pawns.Count;
                loc.y -= pawnOffset;
                if (flag)
                {
                    compAnimator.DrawOffsetY = pawnOffset;
                }
                //   loc.y -= 0.1f * leftOfPawn.Count;
            }
            else
            {
                if (flag)
                {
                    compAnimator.DrawOffsetY = 0f;
                }
            }
            rootLoc = loc;
        }
        public static bool TryFindSpectatorCellFor(Pawn p, CellRect spectateRect, Map map, out IntVec3 cell, SpectateRectSide allowedSides = SpectateRectSide.All, int margin = 1, List <IntVec3> extraDisallowedCells = null)
        {
            spectateRect.ClipInsideMap(map);
            if (spectateRect.Area == 0 || allowedSides == SpectateRectSide.None)
            {
                cell = IntVec3.Invalid;
                return(false);
            }
            CellRect            rectWithMargin = spectateRect.ExpandedBy(margin).ClipInsideMap(map);
            Predicate <IntVec3> predicate      = delegate(IntVec3 x)
            {
                if (!x.InBounds(map))
                {
                    return(false);
                }
                if (!x.Standable(map))
                {
                    return(false);
                }
                if (x.Fogged(map))
                {
                    return(false);
                }
                if (rectWithMargin.Contains(x))
                {
                    return(false);
                }
                if ((x.z <= rectWithMargin.maxZ || (allowedSides & SpectateRectSide.Up) != SpectateRectSide.Up) && (x.x <= rectWithMargin.maxX || (allowedSides & SpectateRectSide.Right) != SpectateRectSide.Right) && (x.z >= rectWithMargin.minZ || (allowedSides & SpectateRectSide.Down) != SpectateRectSide.Down) && (x.x >= rectWithMargin.minX || (allowedSides & SpectateRectSide.Left) != SpectateRectSide.Left))
                {
                    return(false);
                }
                IntVec3 intVec3 = spectateRect.ClosestCellTo(x);
                if ((float)intVec3.DistanceToSquared(x) > 210.25f)
                {
                    return(false);
                }
                if (!GenSight.LineOfSight(intVec3, x, map, true, null, 0, 0))
                {
                    return(false);
                }
                if (x.GetThingList(map).Find((Thing y) => y is Pawn && y != p) != null)
                {
                    return(false);
                }
                if (p != null)
                {
                    if (!p.CanReserveAndReach(x, PathEndMode.OnCell, Danger.Some, 1, -1, null, false))
                    {
                        return(false);
                    }
                    Building edifice = x.GetEdifice(map);
                    if (edifice != null && edifice.def.category == ThingCategory.Building && edifice.def.building.isSittable && !p.CanReserve(edifice, 1, -1, null, false))
                    {
                        return(false);
                    }
                    if (x.IsForbidden(p))
                    {
                        return(false);
                    }
                    if (x.GetDangerFor(p, map) != Danger.None)
                    {
                        return(false);
                    }
                }
                if (extraDisallowedCells != null && extraDisallowedCells.Contains(x))
                {
                    return(false);
                }
                if (!SpectatorCellFinder.CorrectlyRotatedChairAt(x, map, spectateRect))
                {
                    int num = 0;
                    for (int k = 0; k < GenAdj.AdjacentCells.Length; k++)
                    {
                        IntVec3 x2 = x + GenAdj.AdjacentCells[k];
                        if (SpectatorCellFinder.CorrectlyRotatedChairAt(x2, map, spectateRect))
                        {
                            num++;
                        }
                    }
                    if (num >= 3)
                    {
                        return(false);
                    }
                    int num2 = SpectatorCellFinder.DistanceToClosestChair(x, new IntVec3(-1, 0, 0), map, 4, spectateRect);
                    if (num2 >= 0)
                    {
                        int num3 = SpectatorCellFinder.DistanceToClosestChair(x, new IntVec3(1, 0, 0), map, 4, spectateRect);
                        if (num3 >= 0 && Mathf.Abs(num2 - num3) <= 1)
                        {
                            return(false);
                        }
                    }
                    int num4 = SpectatorCellFinder.DistanceToClosestChair(x, new IntVec3(0, 0, 1), map, 4, spectateRect);
                    if (num4 >= 0)
                    {
                        int num5 = SpectatorCellFinder.DistanceToClosestChair(x, new IntVec3(0, 0, -1), map, 4, spectateRect);
                        if (num5 >= 0 && Mathf.Abs(num4 - num5) <= 1)
                        {
                            return(false);
                        }
                    }
                }
                return(true);
            };

            if (p != null && predicate(p.Position) && SpectatorCellFinder.CorrectlyRotatedChairAt(p.Position, map, spectateRect))
            {
                cell = p.Position;
                return(true);
            }
            for (int i = 0; i < 1000; i++)
            {
                IntVec3 intVec = rectWithMargin.CenterCell + GenRadial.RadialPattern[i];
                if (predicate(intVec))
                {
                    if (!SpectatorCellFinder.CorrectlyRotatedChairAt(intVec, map, spectateRect))
                    {
                        for (int j = 0; j < 90; j++)
                        {
                            IntVec3 intVec2 = intVec + GenRadial.RadialPattern[j];
                            if (SpectatorCellFinder.CorrectlyRotatedChairAt(intVec2, map, spectateRect) && predicate(intVec2))
                            {
                                cell = intVec2;
                                return(true);
                            }
                        }
                    }
                    cell = intVec;
                    return(true);
                }
            }
            cell = IntVec3.Invalid;
            return(false);
        }
Exemple #8
0
        public static void DynamicDrawManagerPostfix(DynamicDrawManager __instance, Map ___map, ref bool ___drawingNow)
        {
            var ZTracker = ZUtils.ZTracker;
            int curLevel = ZTracker.GetZIndexFor(___map);

            if (curLevel > 0)
            {
                foreach (var map2 in ZTracker.GetAllMaps(___map.Tile))                //.OrderBy(x => ZTracker.GetZIndexFor(x)))
                {
                    int baseLevel = ZTracker.GetZIndexFor(map2);
                    if (curLevel > baseLevel && baseLevel >= 0)
                    {
                        ___drawingNow = true;
                        bool[]   fogGrid  = map2.fogGrid.fogGrid;
                        CellRect cellRect = Find.CameraDriver.CurrentViewRect;
                        cellRect.ClipInsideMap(map2);
                        cellRect = cellRect.ExpandedBy(1);
                        CellIndices cellIndices = map2.cellIndices;
                        foreach (Thing thing in map2.dynamicDrawManager.drawThings)
                        {
                            IntVec3 position  = thing.Position;
                            IntVec3 position2 = position + new IntVec3(0, 0, -1);
                            if (position.GetTerrain(___map) == ZLevelsDefOf.ZL_OutsideTerrain ||
                                position2.InBounds(___map) && position.GetTerrain(___map) != ZLevelsDefOf.ZL_OutsideTerrain &&
                                position2.GetTerrain(___map) == ZLevelsDefOf.ZL_OutsideTerrain)
                            {
                                if ((cellRect.Contains(position) || thing.def.drawOffscreen)
                                    //&& (!fogGrid[cellIndices.CellToIndex(position)]
                                    //|| thing.def.seeThroughFog)
                                    && (thing.def.hideAtSnowDepth >= 1f ||
                                        map2.snowGrid.GetDepth(position) <= thing.def.hideAtSnowDepth))
                                {
                                    DrawPos_Patch.ChangeDrawPos = true;
                                    DrawPos_Patch.zLevelOffset  = (baseLevel - curLevel) / 3.5f;
                                    DrawPos_Patch.yLevelOffset  = baseLevel - curLevel;
                                    try
                                    {
                                        var graphicType = thing.Graphic.GetType();
                                        if (graphicType == typeof(Graphic_Mote))
                                        {
                                        }
                                        else if (graphicType == typeof(Graphic_LinkedCornerFiller) || graphicType == typeof(Graphic_RandomRotated) || graphicType == typeof(Graphic_Linked))
                                        {
                                            thing.Draw();
                                        }
                                        else if (thing is Pawn pawn)
                                        {
                                            DrawPos_Patch.ChangeDrawPos = false;
                                            var newDrawPos = thing.DrawPos;
                                            newDrawPos.z += (baseLevel - curLevel) / 2f;
                                            newDrawPos.y -= baseLevel - curLevel;
                                            newDrawPos.y -= 4.1f;
                                            if (cachedPawnRenderers.ContainsKey(pawn))
                                            {
                                                cachedPawnRenderers[pawn].RenderPawnAt(newDrawPos, curLevel, baseLevel);
                                            }
                                            else
                                            {
                                                var newRenderer = new PawnRendererScaled(pawn, pawn.Drawer.renderer.wiggler);
                                                pawn.Drawer.renderer.graphics.ResolveAllGraphics();
                                                newRenderer.graphics.nakedGraphic      = pawn.Drawer.renderer.graphics.nakedGraphic;
                                                newRenderer.graphics.headGraphic       = pawn.Drawer.renderer.graphics.headGraphic;
                                                newRenderer.graphics.hairGraphic       = pawn.Drawer.renderer.graphics.hairGraphic;
                                                newRenderer.graphics.rottingGraphic    = pawn.Drawer.renderer.graphics.rottingGraphic;
                                                newRenderer.graphics.dessicatedGraphic = pawn.Drawer.renderer.graphics.dessicatedGraphic;
                                                newRenderer.graphics.apparelGraphics   = pawn.Drawer.renderer.graphics.apparelGraphics;
                                                newRenderer.graphics.packGraphic       = pawn.Drawer.renderer.graphics.packGraphic;
                                                newRenderer.graphics.flasher           = pawn.Drawer.renderer.graphics.flasher;
                                                newRenderer.RenderPawnAt(newDrawPos, curLevel, baseLevel);
                                                cachedPawnRenderers[pawn] = newRenderer;
                                            }
                                        }
                                        else if (thing is Corpse corpse)
                                        {
                                            DrawPos_Patch.ChangeDrawPos = false;
                                            var newDrawPos = thing.DrawPos;
                                            newDrawPos.z += (baseLevel - curLevel) / 2f;
                                            newDrawPos.y -= baseLevel - curLevel;
                                            newDrawPos.y -= 4f;
                                            if (cachedCorpseRenderers.ContainsKey(corpse.InnerPawn))
                                            {
                                                cachedCorpseRenderers[corpse.InnerPawn].RenderPawnAt(newDrawPos, curLevel, baseLevel);
                                            }
                                            else
                                            {
                                                var newRenderer = new PawnRendererScaled(corpse.InnerPawn, corpse.InnerPawn.Drawer.renderer.wiggler);
                                                corpse.InnerPawn.Drawer.renderer.graphics.ResolveAllGraphics();
                                                newRenderer.graphics.nakedGraphic      = corpse.InnerPawn.Drawer.renderer.graphics.nakedGraphic;
                                                newRenderer.graphics.headGraphic       = corpse.InnerPawn.Drawer.renderer.graphics.headGraphic;
                                                newRenderer.graphics.hairGraphic       = corpse.InnerPawn.Drawer.renderer.graphics.hairGraphic;
                                                newRenderer.graphics.rottingGraphic    = corpse.InnerPawn.Drawer.renderer.graphics.rottingGraphic;
                                                newRenderer.graphics.dessicatedGraphic = corpse.InnerPawn.Drawer.renderer.graphics.dessicatedGraphic;
                                                newRenderer.graphics.apparelGraphics   = corpse.InnerPawn.Drawer.renderer.graphics.apparelGraphics;
                                                newRenderer.graphics.packGraphic       = corpse.InnerPawn.Drawer.renderer.graphics.packGraphic;
                                                newRenderer.graphics.flasher           = corpse.InnerPawn.Drawer.renderer.graphics.flasher;
                                                newRenderer.RenderPawnAt(newDrawPos, curLevel, baseLevel);
                                                cachedCorpseRenderers[corpse.InnerPawn] = newRenderer;
                                            }
                                        }
                                        else if (thing.def.projectile == null && !thing.def.IsDoor)
                                        {
                                            Vector2 drawSize = thing.Graphic.drawSize;
                                            drawSize.x *= 1f - (((float)(curLevel) - (float)baseLevel) / 5f);
                                            drawSize.y *= 1f - (((float)(curLevel) - (float)baseLevel) / 5f);
                                            var newGraphic = thing.Graphic.GetCopy(drawSize);
                                            newGraphic.Draw(thing.DrawPos, thing.Rotation, thing);
                                        }
                                        else
                                        {
                                            if (thing is Building_Door door)
                                            {
                                                DrawPos_Patch.ChangeDrawPos = false;
                                                DrawDoor(door, baseLevel, curLevel);
                                            }
                                            else
                                            {
                                                thing.Draw();
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Log.Error(string.Concat(new object[]
                                        {
                                            "Exception drawing ",
                                            thing,
                                            ": ",
                                            ex.ToString()
                                        }), false);
                                    }
                                    DrawPos_Patch.ChangeDrawPos = false;
                                }
                            }
                        }
                        ___drawingNow = false;
                    }
                }
            }
        }
Exemple #9
0
        public override void MapComponentTick()
        {
            base.MapComponentTick();

            var currentPawns = new List <Pawn>();
            var checkedPawns = new List <Pawn>();

            CellRect _viewRect = Find.CameraDriver.CurrentViewRect;

            _viewRect = _viewRect.ExpandedBy(1);

            foreach (Pawn pawn in this.map.mapPawns.AllPawnsSpawned)
            {
                if (!_viewRect.Contains(pawn.Position))
                {
                    continue;
                }
                currentPawns.Add(pawn);
            }
            if (currentPawns.NullOrEmpty() || currentPawns.Count > 32)
            {
                return;
            }
            // top to bottom
            int minX = currentPawns.Min(x => x.Position.x);
            int maxX = currentPawns.Max(x => x.Position.x);
            int minZ = currentPawns.Min(x => x.Position.z);
            int maxZ = currentPawns.Max(x => x.Position.z);
            //  Log.Message(minX + " - " + maxX + " - " + minZ + " - " + maxZ);
            Dictionary <IntVec3, List <Pawn> > pawnsOn = new Dictionary <IntVec3, List <Pawn> >();
            var checkedGrid = new List <IntVec3>();
            int currentZ    = maxZ;

            while (currentZ > minZ)
            {
                currentZ--;

                int currentX = minX;

                while (currentX < maxX)
                {
                    currentX++;

                    if (currentPawns.Count == checkedPawns.Count)
                    {
                        break;
                    }
                    IntVec3 currentCell = new IntVec3(currentX, 0, currentZ);

                    if (checkedGrid.Contains(currentCell))
                    {
                        continue;
                    }

                    // start with the topmost pawn
                    List <Pawn> pawnsOnCell = currentPawns.FindAll(x => x.Position.x == currentX && x.Position.z == currentZ);

                    if (pawnsOnCell.NullOrEmpty())
                    {
                        continue;
                    }

                    checkedGrid.Add(currentCell);
                    pawnsOn.Add(currentCell, pawnsOnCell);
                    checkedPawns.AddRange(pawnsOnCell);
                }
            }

            // string log = "FS values: ";
            foreach (KeyValuePair <IntVec3, List <Pawn> > x in pawnsOn)
            {
                IntVec3     y = x.Key;
                List <Pawn> z = x.Value;
                //        log += "\n vector at: " + y;
                foreach (Pawn p in z)
                {
                    //          log += "\n" + p.LabelCap + " - " + p.Position;
                }
            }
            //    Log.Message(log);
        }
Exemple #10
0
        private void MakeBlueprintRoom(CellRect mapRect, Map map, MapGeneratorBlueprintDef blueprint, ThingDef stuffDef)
        {
            blueprint.buildingData = CleanUpBlueprintData(blueprint.buildingData);
            blueprint.floorData    = CleanUpBlueprintData(blueprint.floorData);
            blueprint.pawnData     = CleanUpBlueprintData(blueprint.pawnData);
            blueprint.itemData     = CleanUpBlueprintData(blueprint.itemData);

            if (blueprint.buildingData == null && blueprint.floorData == null)
            {
                Log.ErrorOnce(string.Format("After cleaning the BlueprintData and FloorData of blueprint {0} -> both are null, nothing will be done!", blueprint.defName), 313001);
                return;
            }

            IntVec3 spawnBaseCell = new IntVec3(mapRect.BottomLeft.x, mapRect.TopRight.y, mapRect.TopRight.z);
            IntVec3 spawnCell;

            foreach (IntVec3 cell in mapRect)
            {
                // Check all cells and abort if there is something indestructible found
                if (!CheckCell(cell, map))
                {
                    return;
                }
            }

            allSpawnedPawns = null;
            try
            {
                // Work through blueprint. Note: top-left to bottom-right
                for (int zn = 0; zn < blueprint.size.z; zn++)
                {
                    for (int x = 0; x < blueprint.size.x; x++)
                    {
                        //// map can be clipped, don't work with the clipped parts
                        //if (x > mapRect.Width - 1 || zn > mapRect.Height - 1)
                        //    continue;

                        spawnCell = spawnBaseCell + new IntVec3(x, 0, -zn);

                        int         itemPos     = x + blueprint.size.x * zn;
                        ThingDef    thingDef    = TryGetThingDefFromBuildingData(blueprint, itemPos);
                        Rot4        thingRot    = TryGetRotationFromBuildingData(blueprint, itemPos);
                        TerrainDef  terrainDef  = TryGetTerrainDefFromFloorData(blueprint, itemPos);
                        PawnKindDef pawnKindDef = TryGetPawnKindDefFromPawnData(blueprint, itemPos);
                        ThingDef    itemDef     = TryGetItemDefFromItemData(blueprint, itemPos);

                        List <Thing> list = map.thingGrid.ThingsListAt(spawnCell);
                        for (int i = 0; i < list.Count; i++)
                        {
                            if (list[i].def == thingDef)
                            {
                                continue;
                            }
                        }

                        //Only clear the space, if something will be made here
                        if (thingDef != null || terrainDef != null || pawnKindDef != null || itemDef != null)
                        {
                            ClearCell(spawnCell, map);
                        }

                        if ((blueprint.canHaveHoles ||
                             (MapGenerator_ModSettings.createAllNonPawnBPsWithHoles && (blueprint.pawnLegend == null || blueprint.pawnLegend.Count <= 0))) &&
                            Rand.Value < MapGenerator_ModSettings.chanceForHoles)
                        {
                            continue;
                        }

                        // If placed on water, increase the hole chance, if no pawns are to be placed!
                        if (spawnCell.GetTerrain(map).defName.ToLower().Contains("water") &&
                            (blueprint.pawnLegend == null || blueprint.pawnLegend.Count <= 0) &&
                            Rand.Value < MapGenerator_ModSettings.chanceForHolesOnWater)
                        {
                            continue;
                        }

                        TrySetCellAs(spawnCell, map, thingDef, thingRot, stuffDef, terrainDef, pawnKindDef, itemDef, blueprint);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Warning("Misc. MapGenerator -- Error with blueprint '" + blueprint.defName + "'. Placement position at " +
                            mapRect.CenterCell.ToString() + " on a map of the size " + map.Size.ToString() + "\n" +
                            ex.Message + "\n" + ex.StackTrace);
            }


            // If pawns are spawned, place ancient shrine trigger
            if (allSpawnedPawns != null && allSpawnedPawns.Count > 0)
            {
                int    nextSignalTagID = Find.UniqueIDsManager.GetNextSignalTagID();
                string signalTag       = "ancientTempleApproached-" + nextSignalTagID;
                SignalAction_Letter signalAction_Letter = (SignalAction_Letter)ThingMaker.MakeThing(ThingDefOf.SignalAction_Letter, null);
                signalAction_Letter.signalTag = signalTag;
                signalAction_Letter.letter    = LetterMaker.MakeLetter("LetterLabelAncientShrineWarning".Translate(), "AncientShrineWarning".Translate(), LetterDefOf.NeutralEvent, new TargetInfo(mapRect.CenterCell, map, false));
                GenSpawn.Spawn(signalAction_Letter, mapRect.CenterCell, map);
                RectTrigger rectTrigger = (RectTrigger)ThingMaker.MakeThing(ThingDefOf.RectTrigger, null);
                rectTrigger.signalTag         = signalTag;
                rectTrigger.Rect              = mapRect.ExpandedBy(1).ClipInsideMap(map);
                rectTrigger.destroyIfUnfogged = true;
                GenSpawn.Spawn(rectTrigger, mapRect.CenterCell, map);
            }

            // also if pawns are spawned make the appropriate LordJob
            LordJob lordJob;

            if (allSpawnedPawns != null && allSpawnedPawns.Count > 0)
            {
                if (blueprint.factionSelection == FactionSelection.friendly)
                {
                    lordJob = new LordJob_AssistColony(allSpawnedPawns[0].Faction, allSpawnedPawns[0].Position);
                }
                else
                {
                    if (Rand.Value < 0.5f)
                    {
                        lordJob = new LordJob_DefendPoint(allSpawnedPawns[0].Position);
                    }
                    else
                    {
                        lordJob = new LordJob_AssaultColony(allSpawnedPawns[0].Faction, false, false, false, false, false);
                    }
                }
                LordMaker.MakeNewLord(allSpawnedPawns[0].Faction, lordJob, map, allSpawnedPawns);

                allSpawnedPawns = null;
            }
        }
Exemple #11
0
        public static void MakeColony(params ColonyMakerFlag[] flags)
        {
            bool godMode = DebugSettings.godMode;

            DebugSettings.godMode            = true;
            Thing.allowDestroyNonDestroyable = true;
            if (Autotests_ColonyMaker.usedCells == null)
            {
                Autotests_ColonyMaker.usedCells = new BoolGrid(Autotests_ColonyMaker.Map);
            }
            else
            {
                Autotests_ColonyMaker.usedCells.ClearAndResizeTo(Autotests_ColonyMaker.Map);
            }
            IntVec3 center  = Autotests_ColonyMaker.Map.Center;
            int     minX    = center.x - 50;
            IntVec3 center2 = Autotests_ColonyMaker.Map.Center;

            Autotests_ColonyMaker.overRect = new CellRect(minX, center2.z - 50, 100, 100);
            Autotests_ColonyMaker.DeleteAllSpawnedPawns();
            GenDebug.ClearArea(Autotests_ColonyMaker.overRect, Find.VisibleMap);
            if (flags.Contains(ColonyMakerFlag.Animals))
            {
                foreach (PawnKindDef item in from k in DefDatabase <PawnKindDef> .AllDefs
                         where k.RaceProps.Animal
                         select k)
                {
                    CellRect cellRect = default(CellRect);
                    if (Autotests_ColonyMaker.TryGetFreeRect(6, 3, out cellRect))
                    {
                        cellRect = cellRect.ContractedBy(1);
                        foreach (IntVec3 item2 in cellRect)
                        {
                            Autotests_ColonyMaker.Map.terrainGrid.SetTerrain(item2, TerrainDefOf.Concrete);
                        }
                        GenSpawn.Spawn(PawnGenerator.GeneratePawn(item, null), cellRect.Cells.ElementAt(0), Autotests_ColonyMaker.Map);
                        IntVec3 intVec = cellRect.Cells.ElementAt(1);
                        Pawn    p      = (Pawn)GenSpawn.Spawn(PawnGenerator.GeneratePawn(item, null), intVec, Autotests_ColonyMaker.Map);
                        HealthUtility.DamageUntilDead(p);
                        Corpse       thing        = (Corpse)intVec.GetThingList(Find.VisibleMap).First((Thing t) => t is Corpse);
                        CompRottable compRottable = thing.TryGetComp <CompRottable>();
                        if (compRottable != null)
                        {
                            compRottable.RotProgress += 1200000f;
                        }
                        if (item.RaceProps.leatherDef != null)
                        {
                            GenSpawn.Spawn(item.RaceProps.leatherDef, cellRect.Cells.ElementAt(2), Autotests_ColonyMaker.Map);
                        }
                        if (item.RaceProps.meatDef != null)
                        {
                            GenSpawn.Spawn(item.RaceProps.meatDef, cellRect.Cells.ElementAt(3), Autotests_ColonyMaker.Map);
                        }
                        continue;
                    }
                    return;
                }
            }
            if (flags.Contains(ColonyMakerFlag.ConduitGrid))
            {
                Designator_Build designator_Build = new Designator_Build(ThingDefOf.PowerConduit);
                for (int i = Autotests_ColonyMaker.overRect.minX; i < Autotests_ColonyMaker.overRect.maxX; i++)
                {
                    for (int j = Autotests_ColonyMaker.overRect.minZ; j < Autotests_ColonyMaker.overRect.maxZ; j += 7)
                    {
                        designator_Build.DesignateSingleCell(new IntVec3(i, 0, j));
                    }
                }
                for (int l = Autotests_ColonyMaker.overRect.minZ; l < Autotests_ColonyMaker.overRect.maxZ; l++)
                {
                    for (int m = Autotests_ColonyMaker.overRect.minX; m < Autotests_ColonyMaker.overRect.maxX; m += 7)
                    {
                        designator_Build.DesignateSingleCell(new IntVec3(m, 0, l));
                    }
                }
            }
            if (flags.Contains(ColonyMakerFlag.PowerPlants))
            {
                List <ThingDef> list = new List <ThingDef>();
                list.Add(ThingDefOf.SolarGenerator);
                list.Add(ThingDefOf.WindTurbine);
                List <ThingDef> list2 = list;
                int             num   = 0;
                while (num < 8)
                {
                    if (Autotests_ColonyMaker.TryMakeBuilding(list2[num % list2.Count]) != null)
                    {
                        num++;
                        continue;
                    }
                    Log.Message("Could not make solar generator.");
                    break;
                }
            }
            if (flags.Contains(ColonyMakerFlag.Batteries))
            {
                for (int n = 0; n < 6; n++)
                {
                    Thing thing2 = Autotests_ColonyMaker.TryMakeBuilding(ThingDefOf.Battery);
                    if (thing2 == null)
                    {
                        Log.Message("Could not make battery.");
                        break;
                    }
                    ((Building_Battery)thing2).GetComp <CompPowerBattery>().AddEnergy(999999f);
                }
            }
            if (flags.Contains(ColonyMakerFlag.WorkTables))
            {
                IEnumerable <ThingDef> enumerable = from def in DefDatabase <ThingDef> .AllDefs
                                                    where typeof(Building_WorkTable).IsAssignableFrom(def.thingClass)
                                                    select def;
                foreach (ThingDef item3 in enumerable)
                {
                    Thing thing3 = Autotests_ColonyMaker.TryMakeBuilding(item3);
                    if (thing3 == null)
                    {
                        Log.Message("Could not make worktable: " + item3.defName);
                        break;
                    }
                    Building_WorkTable building_WorkTable = thing3 as Building_WorkTable;
                    if (building_WorkTable != null)
                    {
                        foreach (RecipeDef allRecipe in building_WorkTable.def.AllRecipes)
                        {
                            building_WorkTable.billStack.AddBill(allRecipe.MakeNewBill());
                        }
                    }
                }
            }
            if (flags.Contains(ColonyMakerFlag.AllBuildings))
            {
                IEnumerable <ThingDef> enumerable2 = from def in DefDatabase <ThingDef> .AllDefs
                                                     where def.category == ThingCategory.Building && def.designationCategory != null
                                                     select def;
                foreach (ThingDef item4 in enumerable2)
                {
                    if (item4 != ThingDefOf.PowerConduit)
                    {
                        Thing thing4 = Autotests_ColonyMaker.TryMakeBuilding(item4);
                        if (thing4 == null)
                        {
                            Log.Message("Could not make building: " + item4.defName);
                            break;
                        }
                    }
                }
            }
            CellRect rect = default(CellRect);

            if (!Autotests_ColonyMaker.TryGetFreeRect(33, 33, out rect))
            {
                Log.Error("Could not get wallable rect");
            }
            rect = rect.ContractedBy(1);
            if (flags.Contains(ColonyMakerFlag.AllItems))
            {
                List <ThingDef> itemDefs = (from def in DefDatabase <ThingDef> .AllDefs
                                            where DebugThingPlaceHelper.IsDebugSpawnable(def) && def.category == ThingCategory.Item
                                            select def).ToList();
                Autotests_ColonyMaker.FillWithItems(rect, itemDefs);
            }
            else if (flags.Contains(ColonyMakerFlag.ItemsRawFood))
            {
                List <ThingDef> list3 = new List <ThingDef>();
                list3.Add(ThingDefOf.RawPotatoes);
                Autotests_ColonyMaker.FillWithItems(rect, list3);
            }
            if (flags.Contains(ColonyMakerFlag.Filth))
            {
                foreach (IntVec3 item5 in rect)
                {
                    GenSpawn.Spawn(ThingDefOf.FilthDirt, item5, Autotests_ColonyMaker.Map);
                }
            }
            if (flags.Contains(ColonyMakerFlag.ItemsWall))
            {
                CellRect         cellRect2         = rect.ExpandedBy(1);
                Designator_Build designator_Build2 = new Designator_Build(ThingDefOf.Wall);
                designator_Build2.SetStuffDef(ThingDefOf.WoodLog);
                foreach (IntVec3 edgeCell in cellRect2.EdgeCells)
                {
                    designator_Build2.DesignateSingleCell(edgeCell);
                }
            }
            if (flags.Contains(ColonyMakerFlag.ColonistsMany))
            {
                Autotests_ColonyMaker.MakeColonists(15, Autotests_ColonyMaker.overRect.CenterCell);
            }
            else if (flags.Contains(ColonyMakerFlag.ColonistOne))
            {
                Autotests_ColonyMaker.MakeColonists(1, Autotests_ColonyMaker.overRect.CenterCell);
            }
            if (flags.Contains(ColonyMakerFlag.Fire))
            {
                CellRect cellRect3 = default(CellRect);
                if (!Autotests_ColonyMaker.TryGetFreeRect(30, 30, out cellRect3))
                {
                    Log.Error("Could not get free rect for fire.");
                }
                ThingDef plantTreeOak = ThingDefOf.PlantTreeOak;
                foreach (IntVec3 item6 in cellRect3)
                {
                    GenSpawn.Spawn(plantTreeOak, item6, Autotests_ColonyMaker.Map);
                }
                foreach (IntVec3 item7 in cellRect3)
                {
                    IntVec3 current9 = item7;
                    if (current9.x % 7 == 0 && current9.z % 7 == 0)
                    {
                        GenExplosion.DoExplosion(current9, Find.VisibleMap, 3.9f, DamageDefOf.Flame, null, -1, null, null, null, null, 0f, 1, false, null, 0f, 1, 0f, false);
                    }
                }
            }
            if (flags.Contains(ColonyMakerFlag.ColonistsHungry))
            {
                Autotests_ColonyMaker.DoToColonists(0.4f, delegate(Pawn col)
                {
                    col.needs.food.CurLevel = Mathf.Max(0f, Rand.Range(-0.05f, 0.05f));
                });
            }
            if (flags.Contains(ColonyMakerFlag.ColonistsTired))
            {
                Autotests_ColonyMaker.DoToColonists(0.4f, delegate(Pawn col)
                {
                    col.needs.rest.CurLevel = Mathf.Max(0f, Rand.Range(-0.05f, 0.05f));
                });
            }
            if (flags.Contains(ColonyMakerFlag.ColonistsInjured))
            {
                Autotests_ColonyMaker.DoToColonists(0.4f, delegate(Pawn col)
                {
                    DamageDef def2 = (from d in DefDatabase <DamageDef> .AllDefs
                                      where d.externalViolence
                                      select d).RandomElement();
                    col.TakeDamage(new DamageInfo(def2, 10, -1f, null, null, null, DamageInfo.SourceCategory.ThingOrUnknown));
                });
            }
            if (flags.Contains(ColonyMakerFlag.ColonistsDiseased))
            {
                foreach (HediffDef item8 in from d in DefDatabase <HediffDef> .AllDefs
                         where d.hediffClass != typeof(Hediff_AddedPart) && (d.HasComp(typeof(HediffComp_Immunizable)) || d.HasComp(typeof(HediffComp_GrowthMode)))
                         select d)
                {
                    Pawn     pawn      = PawnGenerator.GeneratePawn(Faction.OfPlayer.def.basicMemberKind, Faction.OfPlayer);
                    CellRect cellRect4 = default(CellRect);
                    Autotests_ColonyMaker.TryGetFreeRect(1, 1, out cellRect4);
                    GenSpawn.Spawn(pawn, cellRect4.CenterCell, Autotests_ColonyMaker.Map);
                    pawn.health.AddHediff(item8, null, null);
                }
            }
            if (flags.Contains(ColonyMakerFlag.Beds))
            {
                IEnumerable <ThingDef> source = from def in DefDatabase <ThingDef> .AllDefs
                                                where def.thingClass == typeof(Building_Bed)
                                                select def;
                int freeColonistsCount = Autotests_ColonyMaker.Map.mapPawns.FreeColonistsCount;
                int num2 = 0;
                while (num2 < freeColonistsCount)
                {
                    if (Autotests_ColonyMaker.TryMakeBuilding(source.RandomElement()) != null)
                    {
                        num2++;
                        continue;
                    }
                    Log.Message("Could not make beds.");
                    break;
                }
            }
            if (flags.Contains(ColonyMakerFlag.Stockpiles))
            {
                Designator_ZoneAddStockpile_Resources designator_ZoneAddStockpile_Resources = new Designator_ZoneAddStockpile_Resources();
                IEnumerator enumerator11 = Enum.GetValues(typeof(StoragePriority)).GetEnumerator();
                try
                {
                    while (enumerator11.MoveNext())
                    {
                        StoragePriority priority  = (StoragePriority)enumerator11.Current;
                        CellRect        cellRect5 = default(CellRect);
                        Autotests_ColonyMaker.TryGetFreeRect(7, 7, out cellRect5);
                        cellRect5 = cellRect5.ContractedBy(1);
                        designator_ZoneAddStockpile_Resources.DesignateMultiCell(cellRect5.Cells);
                        Zone_Stockpile zone_Stockpile = (Zone_Stockpile)Autotests_ColonyMaker.Map.zoneManager.ZoneAt(cellRect5.CenterCell);
                        zone_Stockpile.settings.Priority = priority;
                    }
                }
                finally
                {
                    IDisposable disposable;
                    if ((disposable = (enumerator11 as IDisposable)) != null)
                    {
                        disposable.Dispose();
                    }
                }
            }
            if (flags.Contains(ColonyMakerFlag.GrowingZones))
            {
                Zone_Growing dummyZone = new Zone_Growing(Autotests_ColonyMaker.Map.zoneManager);
                foreach (ThingDef item9 in from d in DefDatabase <ThingDef> .AllDefs
                         where d.plant != null && GenPlant.CanSowOnGrower(d, dummyZone)
                         select d)
                {
                    CellRect cellRect6 = default(CellRect);
                    if (!Autotests_ColonyMaker.TryGetFreeRect(6, 6, out cellRect6))
                    {
                        Log.Error("Could not get growing zone rect.");
                    }
                    cellRect6 = cellRect6.ContractedBy(1);
                    foreach (IntVec3 item10 in cellRect6)
                    {
                        Autotests_ColonyMaker.Map.terrainGrid.SetTerrain(item10, TerrainDefOf.Soil);
                    }
                    Designator_ZoneAdd_Growing designator_ZoneAdd_Growing = new Designator_ZoneAdd_Growing();
                    designator_ZoneAdd_Growing.DesignateMultiCell(cellRect6.Cells);
                    Zone_Growing zone_Growing = (Zone_Growing)Autotests_ColonyMaker.Map.zoneManager.ZoneAt(cellRect6.CenterCell);
                    zone_Growing.SetPlantDefToGrow(item9);
                }
                dummyZone.Delete();
            }
            Autotests_ColonyMaker.ClearAllHomeArea();
            Autotests_ColonyMaker.FillWithHomeArea(Autotests_ColonyMaker.overRect);
            DebugSettings.godMode            = godMode;
            Thing.allowDestroyNonDestroyable = false;
        }
 public Stencil Expand(int amount)
 {
     return(new Stencil(map, pos, rot, bounds.ExpandedBy(amount)));
 }
Exemple #13
0
        public override void PassingParameters(ResolveParams rp)
        {
            string defChair = "DiningChair";
            string defLamp  = "Jecrell_GasLamp";

            ThingDef lampDef      = Cthulhu.Utility.IsIndustrialAgeLoaded() ? ThingDef.Named(defLamp) : ThingDefOf.TorchLamp;
            ThingDef lampStuffDef = Cthulhu.Utility.IsIndustrialAgeLoaded() ? ThingDefOf.Steel : null;

            Map      map      = BaseGen.globalSettings.map;
            bool     @bool    = Rand.Bool;
            bool     hasLamp  = false;
            ThingDef thingDef = ThingDefOf.Bed;
            ThingDef chairDef = ThingDef.Named(defChair);

            foreach (IntVec3 current in rp.rect)
            {
                if (@bool)
                {
                    if (current.x % 3 != 0 || current.z % 3 != 0)
                    {
                        continue;
                    }
                }
                else if (current.x % 3 != 0 || current.z % 3 != 0)
                {
                    continue;
                }
                Rot4 rot = (!@bool) ? Rot4.South : Rot4.West;
                if (!GenSpawn.WouldWipeAnythingWith(current, rot, thingDef, map, (Thing x) => x.def.category == ThingCategory.Building))
                {
                    bool flag = false;
                    foreach (IntVec3 current2 in GenAdj.CellsOccupiedBy(current, rot, thingDef.Size))
                    {
                        if (BaseGenUtility.AnyDoorAdjacentCardinalTo(current2, map))
                        {
                            flag = true;
                            break;
                        }
                    }
                    if (!flag)
                    {
                        ///Bed
                        ThingDef stuff = null;
                        if (thingDef.MadeFromStuff)
                        {
                            stuff = ThingDefOf.WoodLog;
                        }
                        Thing thing = ThingMaker.MakeThing(thingDef, stuff);
                        thing.SetFaction(rp.faction, null);
                        GenSpawn.Spawn(thing, current, map, rot);

                        if (thing != null)
                        {
                            if (thing.Spawned && thing.Position.InBounds(map))
                            {
                                CellRect thingRect = thing.OccupiedRect();
                                if (thingRect != null)
                                {
                                    thingRect = thingRect.ExpandedBy(1);
                                    List <IntVec3> possibleCells = new List <IntVec3>();
                                    possibleCells.AddRange(thingRect.GetEdgeCells(Rot4.North));
                                    possibleCells.AddRange(thingRect.GetEdgeCells(Rot4.South));
                                    possibleCells.AddRange(thingRect.GetEdgeCells(Rot4.East));
                                    possibleCells.AddRange(thingRect.GetEdgeCells(Rot4.West));
                                    possibleCells.Remove(Cthulhu.Utility.GetCornerPos(thingRect, 0));
                                    possibleCells.Remove(Cthulhu.Utility.GetCornerPos(thingRect, 1));
                                    possibleCells.Remove(Cthulhu.Utility.GetCornerPos(thingRect, 2));
                                    possibleCells.Remove(Cthulhu.Utility.GetCornerPos(thingRect, 3));

                                    IntVec3 spawnPos = IntVec3.Invalid;
                                    spawnPos = possibleCells.FirstOrDefault((IntVec3 x) => x.InBounds(map) && x.Walkable(map));
                                    if (spawnPos != null)
                                    {
                                        possibleCells.Remove(spawnPos);
                                        Thing thing2 = ThingMaker.MakeThing(chairDef, stuff);
                                        thing2.SetFaction(rp.faction, null);
                                        GenSpawn.Spawn(thing2, spawnPos, map, rot.Opposite);
                                    }
                                    if (!hasLamp)
                                    {
                                        hasLamp  = true;
                                        spawnPos = possibleCells.FirstOrDefault((IntVec3 x) => x.InBounds(map) && x.Walkable(map));
                                        if (spawnPos != null)
                                        {
                                            possibleCells.Remove(spawnPos);
                                            Thing thing3 = ThingMaker.MakeThing(lampDef, lampStuffDef);
                                            thing3.SetFaction(rp.faction, null);
                                            GenSpawn.Spawn(thing3, spawnPos, map, rot.Opposite);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            //List<int> corners = new List<int>() { 0, 1, 2, 3 };
            //foreach (int corner in corners.InRandomOrder<int>())
            //{
            //    IntVec3 loc = Cthulhu.Utility.GetCornerPos(rp.rect.ContractedBy(1), corner);
            //    if (!GenSpawn.WouldWipeAnythingWith(loc, Rot4.South, lampDef, map, (Thing x) => x.def.category == ThingCategory.Building))
            //    {
            //        ThingDef singleThingDef3 = (Cthulhu.Utility.IsIndustrialAgeLoaded()) ? lampDef : ThingDefOf.TorchLamp;
            //        Thing thing3 = ThingMaker.MakeThing(singleThingDef3, ThingDefOf.Steel);
            //        GenSpawn.Spawn(thing3, loc, map);
            //        break;
            //    }
            //}
        }
 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 CompTick()
        {
            base.CompTick();

            if (this.parent.IsHashIntervalTick(7500))
            {
                float num = this.parent.Map.glowGrid.GameGlowAt(this.parent.Position, false);

                if (num < 0.5)
                {
                    CellRect rect = GenAdj.OccupiedRect(parent.Position, parent.Rotation, IntVec2.One);
                    rect = rect.ExpandedBy(3);
                    IntVec3 current = rect.Cells.RandomElement();

                    while (current == this.parent.Position)
                    {
                        current = rect.Cells.RandomElement();
                    }
                    bool         buildingFound = false;
                    List <Thing> list          = parent.Map.thingGrid.ThingsListAt(current);
                    for (int i = 0; i < list.Count; i++)
                    {
                        if ((list[i].def == InternalDefOf.GR_FleshGrowth_Building) || list[i].def.IsDoor)
                        {
                            buildingFound = true;
                        }
                    }


                    if (!buildingFound)
                    {
                        Room room = current.GetRoom(this.parent.Map);
                        if (current.InBounds(parent.Map) && room?.OutdoorsForWork == false)
                        {
                            Thing thing = ThingMaker.MakeThing(InternalDefOf.GR_FleshGrowth_Building, null);
                            thing.Rotation = Rot4.North;
                            thing.Position = current;

                            thing.SpawnSetup(parent.Map, false);
                        }
                    }
                }
            }
            if (this.parent.IsHashIntervalTick(30000))
            {
                if (this.parent.Map.listerThings.ThingsOfDef(InternalDefOf.GR_FleshFlies.race).Count < 40)
                {
                    Pawn pawn = PawnGenerator.GeneratePawn(new PawnGenerationRequest(InternalDefOf.GR_FleshFlies, null, fixedBiologicalAge: 1, fixedChronologicalAge: 1,
                                                                                     newborn: false, forceGenerateNewPawn: true));
                    IntVec3 near = CellFinder.StandableCellNear(this.parent.Position, this.parent.Map, 1f);

                    if (near.InBounds(parent.Map))
                    {
                        GenSpawn.Spawn(pawn, near, this.parent.Map);

                        pawn.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.ManhunterPermanent, null, true, false, null, false);
                        pawn.health.AddHediff(InternalDefOf.GR_GreaterScaria);
                    }
                }
            }
        }
Exemple #16
0
        /// <summary>
        /// Catch All for vehicle related Things spawned in. Handles GodMode placing of vehicle buildings, corrects immovable spawn locations, and registers air defenses
        /// </summary>
        /// <param name="newThing"></param>
        /// <param name="loc"></param>
        /// <param name="map"></param>
        /// <param name="rot"></param>
        /// <param name="__result"></param>
        /// <param name="wipeMode"></param>
        /// <param name="respawningAfterLoad"></param>
        /// <returns></returns>
        public static bool RegisterThingSpawned(Thing newThing, ref IntVec3 loc, Map map, Rot4 rot, Thing __result, WipeMode wipeMode, bool respawningAfterLoad)
        {
            if (newThing.def is VehicleBuildDef def)
            {
                if (!VehicleMod.settings.debug.debugSpawnVehicleBuildingGodMode && newThing.HitPoints == newThing.MaxHitPoints)
                {
                    VehiclePawn vehiclePawn = VehicleSpawner.GenerateVehicle(def.thingToSpawn, newThing.Faction);                    // (VehiclePawn)PawnGenerator.GeneratePawn(def.thingToSpawn);

                    if (def.soundBuilt != null)
                    {
                        def.soundBuilt.PlayOneShot(new TargetInfo(loc, map, false));
                    }
                    VehiclePawn vehicleSpawned = (VehiclePawn)GenSpawn.Spawn(vehiclePawn, loc, map, rot, WipeMode.FullRefund, false);
                    vehicleSpawned.Rename();
                    __result = vehicleSpawned;
                    AchievementsHelper.TriggerVehicleConstructionEvent(vehicleSpawned);
                    return(false);
                }
            }
            else if (newThing is VehiclePawn vehicle)
            {
                bool standable = true;
                foreach (IntVec3 c in vehicle.PawnOccupiedCells(loc, rot))
                {
                    if (!c.InBounds(map) || (vehicle.IsBoat() ? GenGridVehicles.Impassable(c, map) : GenGrid.Impassable(c, map)))
                    {
                        standable = false;
                        break;
                    }
                }
                bool validator(IntVec3 c)
                {
                    foreach (IntVec3 c2 in vehicle.PawnOccupiedCells(c, rot))
                    {
                        if (vehicle.IsBoat() ? GenGridVehicles.Impassable(c, map) : GenGrid.Impassable(c, map))
                        {
                            return(false);
                        }
                    }
                    return(true);
                }

                if (standable)
                {
                    return(true);
                }
                if (!CellFinder.TryFindRandomCellNear(loc, map, 20, validator, out IntVec3 newLoc, 100))
                {
                    Log.Error($"Unable to find location to spawn {newThing.LabelShort} after 100 attempts. Aborting spawn.");
                    return(false);
                }
                loc = newLoc;
            }
            else if (newThing is Pawn pawn && !pawn.Dead)
            {
                try
                {
                    var positionManager = map.GetCachedMapComponent <VehiclePositionManager>();
                    if (positionManager.PositionClaimed(loc))
                    {
                        VehiclePawn inPlaceVehicle = positionManager.ClaimedBy(loc);
                        CellRect    occupiedRect   = inPlaceVehicle.OccupiedRect().ExpandedBy(1);
                        Rand.PushState();
                        for (int i = 0; i < 3; i++)
                        {
                            IntVec3 newLoc = occupiedRect.EdgeCells.Where(c => GenGrid.InBounds(c, map) && GenGrid.Standable(c, map)).RandomElementWithFallback(inPlaceVehicle.Position);
                            if (occupiedRect.EdgeCells.Contains(newLoc))
                            {
                                loc = newLoc;
                                break;
                            }
                            occupiedRect = occupiedRect.ExpandedBy(1);
                        }
                        Rand.PopState();
                    }
                }
                catch (Exception ex)
                {
                    Log.Error($"Pawn {newThing.Label} could not be readjusted for spawn location. Exception={ex.Message}");
                }
            }
Exemple #17
0
        public override void PassingParameters(ResolveParams rp)
        {
            string defChair = "DiningChair";
            string defLamp  = "Jecrell_GasLamp";

            ThingDef lampDef      = Cthulhu.Utility.IsIndustrialAgeLoaded() ? ThingDef.Named(defLamp) : ThingDefOf.TorchLamp;
            ThingDef lampStuffDef = Cthulhu.Utility.IsIndustrialAgeLoaded() ? ThingDefOf.Steel : null;

            Map      map      = BaseGen.globalSettings.map;
            bool     @bool    = Rand.Bool;
            bool     hasLamp  = false;
            ThingDef thingDef = ThingDefOf.SleepingSpot;
            ThingDef chairDef = ThingDef.Named(defChair);

            foreach (IntVec3 current in rp.rect)
            {
                if (@bool)
                {
                    if (current.x % 3 != 0 || current.z % 3 != 0)
                    {
                        continue;
                    }
                }
                else if (current.x % 3 != 0 || current.z % 3 != 0)
                {
                    continue;
                }
                Rot4 rot = (!@bool) ? Rot4.South : Rot4.West;
                if (!GenSpawn.WouldWipeAnythingWith(current, rot, thingDef, map, (Thing x) => x.def.category == ThingCategory.Building))
                {
                    bool flag = false;
                    foreach (IntVec3 current2 in GenAdj.CellsOccupiedBy(current, rot, thingDef.Size))
                    {
                        if (BaseGenUtility.AnyDoorAdjacentCardinalTo(current2, map))
                        {
                            flag = true;
                            break;
                        }
                    }
                    if (!flag)
                    {
                        ///Bed
                        ThingDef stuff = null;
                        if (thingDef.MadeFromStuff)
                        {
                            stuff = ThingDefOf.WoodLog;
                        }
                        Thing thing = ThingMaker.MakeThing(thingDef, stuff);
                        thing.SetFaction(rp.faction, null);

                        GenSpawn.Spawn(thing, current, map, rot);

                        if (thing != null)
                        {
                            if (thing.Spawned && thing.Position.InBounds(map))
                            {
                                CellRect thingRect = thing.OccupiedRect();
                                if (thingRect != null)
                                {
                                    thingRect = thingRect.ExpandedBy(1);
                                    List <IntVec3> possibleCells = new List <IntVec3>();
                                    possibleCells.AddRange(thingRect.GetEdgeCells(Rot4.North));
                                    possibleCells.AddRange(thingRect.GetEdgeCells(Rot4.South));
                                    possibleCells.AddRange(thingRect.GetEdgeCells(Rot4.East));
                                    possibleCells.AddRange(thingRect.GetEdgeCells(Rot4.West));
                                    possibleCells.Remove(Cthulhu.Utility.GetCornerPos(thingRect, 0));
                                    possibleCells.Remove(Cthulhu.Utility.GetCornerPos(thingRect, 1));
                                    possibleCells.Remove(Cthulhu.Utility.GetCornerPos(thingRect, 2));
                                    possibleCells.Remove(Cthulhu.Utility.GetCornerPos(thingRect, 3));

                                    IntVec3 spawnPos = IntVec3.Invalid;
                                    spawnPos = possibleCells.InRandomOrder <IntVec3>().FirstOrDefault((IntVec3 x) => x.InBounds(map) && x.Walkable(map));
                                    if (spawnPos != null)
                                    {
                                        possibleCells.Remove(spawnPos);
                                        Thing thing2 = ThingMaker.MakeThing(chairDef, ThingDefOf.WoodLog);
                                        thing2.SetFaction(rp.faction, null);
                                        GenSpawn.Spawn(thing2, spawnPos, map, rot.Opposite);
                                    }
                                    if (!hasLamp)
                                    {
                                        hasLamp  = true;
                                        spawnPos = possibleCells.FirstOrDefault((IntVec3 x) => x.InBounds(map) && x.Walkable(map));
                                        if (spawnPos != null)
                                        {
                                            possibleCells.Remove(spawnPos);
                                            Thing thing3 = ThingMaker.MakeThing(lampDef, lampStuffDef);
                                            thing3.SetFaction(rp.faction, null);
                                            GenSpawn.Spawn(thing3, spawnPos, map, rot.Opposite);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            //if (!Cthulhu.Utility.IsCosmicHorrorsLoaded())
            //{
            PawnGroupKindDef    groupKind           = rp.pawnGroupKindDef ?? PawnGroupKindDefOf.Combat;
            PawnGroupMakerParms pawnGroupMakerParms = new PawnGroupMakerParms()
            {
                faction = (from x in Find.FactionManager.AllFactions
                           where x.HostileTo(rp.faction) && x.def.pawnGroupMakers != null &&
                           x.def.pawnGroupMakers.Count > 0 &&
                           x.def.humanlikeFaction &&
                           IsCosmicHorrorFaction(x) == false &&
                           (x.def.pawnGroupMakers.FirstOrDefault((PawnGroupMaker y) => y.kindDef == PawnGroupKindDefOf.Combat) != null)
                           select x).RandomElement <Faction>(),
                tile   = map.Tile,
                points = 5000,
                generateFightersOnly = false,
            };
            int num = 0;

            foreach (Pawn current in PawnGroupMakerUtility.GeneratePawns(pawnGroupMakerParms, true))
            {
                num++;
                ResolveParams resolveParams = rp;
                resolveParams.singlePawnToSpawn = current;
                BaseGen.symbolStack.Push("pawn", resolveParams);
                if (num == 3)
                {
                    break;
                }
            }
            //}
            //else
            //{
            //    Faction tempFaction = Find.FactionManager.AllFactions.InRandomOrder<Faction>().FirstOrDefault((Faction z) => IsCosmicHorrorFaction(z));
            //    PawnGroupKindDef groupKind = rp.pawnGroupKindDef ?? PawnGroupKindDefOf.Combat;
            //    PawnGroupMakerParms pawnGroupMakerParms = new PawnGroupMakerParms()
            //    {
            //        faction = tempFaction,
            //        map = map,
            //        points = 5000,
            //        generateFightersOnly = false,
            //        generateMeleeOnly = false
            //    };
            //    int num = 0;
            //    foreach (Pawn current in PawnGroupMakerUtility.GeneratePawns(groupKind, pawnGroupMakerParms, true))
            //    {
            //        num++;
            //        ResolveParams resolveParams = rp;
            //        resolveParams.singlePawnToSpawn = current;
            //        resolveParams.singlePawnLord = null;
            //        BaseGen.symbolStack.Push("pawn", resolveParams);
            //        if (num == 3) break;
            //    }
            //}

            //List<int> corners = new List<int>() { 0, 1, 2, 3 };
            //foreach (int corner in corners.InRandomOrder<int>())
            //{
            //    IntVec3 loc = Cthulhu.Utility.GetCornerPos(rp.rect.ContractedBy(1), corner);
            //    if (!GenSpawn.WouldWipeAnythingWith(loc, Rot4.South, lampDef, map, (Thing x) => x.def.category == ThingCategory.Building))
            //    {
            //        ThingDef singleThingDef3 = (Cthulhu.Utility.IsIndustrialAgeLoaded()) ? lampDef : ThingDefOf.TorchLamp;
            //        Thing thing3 = ThingMaker.MakeThing(singleThingDef3, ThingDefOf.Steel);
            //        GenSpawn.Spawn(thing3, loc, map);
            //        break;
            //    }
            //}
        }
        public override void CompTick()
        {
            base.CompTick();

            if (AnimalBehaviours_Settings.flagCorpseDecayingEffect)
            {
                tickCounter++;

                //Only check every 2 rare ticks (8 seconds)
                if (tickCounter > Props.tickInterval)
                {
                    Pawn pawn = this.parent as Pawn;

                    //Null map check
                    if (pawn.Map != null)
                    {
                        //Check on radius
                        CellRect rect = GenAdj.OccupiedRect(pawn.Position, pawn.Rotation, IntVec2.One);
                        rect = rect.ExpandedBy(Props.radius);

                        foreach (IntVec3 current in rect.Cells)
                        {
                            if (current.InBounds(pawn.Map))
                            {
                                HashSet <Thing> hashSet = new HashSet <Thing>(current.GetThingList(pawn.Map));
                                if (hashSet != null)
                                {
                                    foreach (Thing thingInCell in hashSet)
                                    {
                                        Corpse corpse = thingInCell as Corpse;
                                        //If anything in those cells was a corpse
                                        if (corpse != null)
                                        {
                                            //A FLESHY corpse, no mechanoid munching
                                            if (corpse.InnerPawn.def.race.IsFlesh)
                                            {
                                                //Damage the corpse, and feed the animal
                                                corpse.HitPoints         -= 5;
                                                pawn.needs.food.CurLevel += Props.nutritionGained;

                                                //This is for achievements
                                                if (ModLister.HasActiveModWithName("Alpha Animals") && (pawn.Faction == Faction.OfPlayer) && (corpse.InnerPawn.def.race.Humanlike))
                                                {
                                                    pawn.health.AddHediff(HediffDef.Named("AA_CorpseFeast"));
                                                }

                                                //If the corpse can rot, do it
                                                CompRottable compRottable = corpse.TryGetComp <CompRottable>();
                                                if (compRottable.Stage == RotStage.Fresh)
                                                {
                                                    compRottable.RotProgress += 100000;
                                                }
                                                //If the corpse reaches 0 HP, destroy it, and spawn corpse bile
                                                if (corpse.HitPoints < 0)
                                                {
                                                    corpse.Destroy(DestroyMode.Vanish);
                                                    for (int i = 0; i < 20; i++)
                                                    {
                                                        IntVec3 c;
                                                        CellFinder.TryFindRandomReachableCellNear(pawn.Position, pawn.Map, 2, TraverseParms.For(TraverseMode.NoPassClosedDoors, Danger.Deadly, false), null, null, out c);
                                                        FilthMaker.TryMakeFilth(c, pawn.Map, ThingDefOf.Filth_CorpseBile, pawn.LabelIndefinite(), 1, FilthSourceFlags.None);
                                                        SoundDef.Named(Props.corpseSound).PlayOneShot(new TargetInfo(pawn.Position, pawn.Map, false));
                                                    }
                                                }
                                                FilthMaker.TryMakeFilth(current, pawn.Map, ThingDefOf.Filth_CorpseBile, pawn.LabelIndefinite(), 1, FilthSourceFlags.None);
                                                flagOnce = true;
                                            }
                                        }
                                    }
                                }
                            }
                            if (flagOnce)
                            {
                                flagOnce = false; break;
                            }
                        }
                    }
                    tickCounter = 0;
                }
            }
        }
Exemple #19
0
        protected override void ScatterAt(IntVec3 loc, Map map, int stackCount = 1)
        {
            // Once a mapcenter blueprint is placed, don't do anything more
            if (mapCenterBlueprintUsed)
            {
                return;
            }

            // After 5 min reset the saved cells!
            if (usedCells_lastChange.AddMinutes(5) < DateTime.UtcNow)
            {
                usedCells.Clear();
                usedCells_lastChange = DateTime.UtcNow;
            }

            // update the usedSpots
            if (usedSpots != null && usedSpots.Count > 0)
            {
                foreach (IntVec3 usedSpot in usedSpots)
                {
                    usedCells.Add(usedSpot);
                }
                usedCells_lastChange = DateTime.UtcNow;
            }

            MapGeneratorBlueprintDef blueprint;

            // Safety: only use blueprints where the size is smaller than the map size  => Safety really needed?
            blueprint = DefDatabase <MapGeneratorBlueprintDef> .AllDefsListForReading
                        .RandomElementByWeight((MapGeneratorBlueprintDef b) => b.chance);


            if (!blueprint.mapCenterBlueprint && blueprint.pawnLegend != null && blueprint.pawnLegend.Count > 0)
            {
                // Check if the loc is near the spawn location
                IntVec2  nogoCenter     = new IntVec2(Find.World.info.initialMapSize.x / 2, Find.World.info.initialMapSize.z / 2);
                CellRect nogoCenterRect = new CellRect(nogoCenter.x, nogoCenter.z, 1, 1);
                nogoCenterRect = nogoCenterRect.ExpandedBy(20);
                if (nogoCenterRect.Contains(loc))
                {
                    // If loc is near the center, find new blueprint that doesn't contain any pawns
                    blueprint = DefDatabase <MapGeneratorBlueprintDef> .AllDefsListForReading
                                .Where(b => (b.pawnLegend == null || b.pawnLegend.Count == 0))
                                .RandomElementByWeight((MapGeneratorBlueprintDef b) => b.chance);
                }
            }
            if (blueprint == null)
            {
                return;
            }

            // if the blueprint is a map center blueprint, set the loc so that the center is at the map center
            if (blueprint.mapCenterBlueprint)
            {
                loc = new IntVec3(map.Center.x - (blueprint.size.x / 2), map.Center.y, map.Center.z - (blueprint.size.z / 2));
                mapCenterBlueprintUsed = true;
            }

            // place a blueprint ruin
            //ScatterBlueprintAt(loc, map, blueprint, ref selectedWallStuff, this.usedSpots);
            ScatterBlueprintAt(loc, map, blueprint, ref selectedWallStuff, usedCells);

            // reset
            selectedWallStuff = null;
        }
        public override void Resolve(ResolveParams rp)
        {
            ThingDef thingDef = (from d in DefDatabase <ThingDef> .AllDefs
                                 where d.IsStuff && d.stuffProps.CanMake(ThingDefOf.Wall) && d.stuffProps.categories.Contains(StuffCategoryDefOf.Stony) && d != ThingDef.Named("Jade")
                                 select d).ToList <ThingDef>().RandomElementByWeight((ThingDef x) => 3f + 1f / x.BaseMarketValue);

            rp.wallStuff = thingDef;
            rp.floorDef  = BaseGenUtility.CorrespondingTerrainDef(thingDef, true);
            int num = Rand.RangeInclusive(30, 40);

            for (int i = 0; i < num; i++)
            {
                int           minX          = Rand.RangeInclusive(rp.rect.minX, rp.rect.maxX - 1);
                int           minZ          = Rand.RangeInclusive(rp.rect.minZ, rp.rect.maxZ - 1);
                ResolveParams resolveParams = rp;
                resolveParams.rect = new CellRect(minX, minZ, Rand.RangeInclusive(1, 3), Rand.RangeInclusive(1, 3));
                BaseGen.symbolStack.Push("pathOfDestruction", resolveParams, null);
            }
            for (int j = 0; j < Rand.RangeInclusive(2, 5); j++)
            {
                int           minX2          = Rand.RangeInclusive(rp.rect.minX + 4, rp.rect.maxX - 10);
                int           minZ2          = Rand.RangeInclusive(rp.rect.minZ + 4, rp.rect.maxZ - 10);
                ResolveParams resolveParams2 = rp;
                resolveParams2.rect = new CellRect(minX2, minZ2, Rand.RangeInclusive(5, 8), Rand.RangeInclusive(5, 8));
                BaseGen.symbolStack.Push("emptyRoom", resolveParams2, null);
            }
            ResolveParams resolveParams3 = rp;

            resolveParams3.rect = resolveParams3.rect.ContractedBy(21);
            ResolveParams resolveParams4 = resolveParams3;

            resolveParams4.rect.Width  = (int)(0.25 * (double)resolveParams3.rect.Width);
            resolveParams4.rect.Height = resolveParams4.rect.Width;
            for (int k = 0; k < 4; k++)
            {
                BaseGen.symbolStack.Push("roomWithDoor", resolveParams4, null);
                resolveParams4.rect = new CellRect(resolveParams4.rect.minX, resolveParams4.rect.maxZ, resolveParams4.rect.Width, resolveParams4.rect.Height);
            }
            resolveParams3.SetCustom <char[]>("hasDoor", new char[]
            {
                'N'
            }, false);
            BaseGen.symbolStack.Push("roomWithDoor", resolveParams3, null);
            ResolveParams resolveParams5 = rp;

            resolveParams5.rect = rp.rect.ContractedBy(5);
            ResolveParams resolveParams6 = resolveParams5;

            for (int l = 0; l < 25; l++)
            {
                int width  = Rand.RangeInclusive(4, 6);
                int height = Rand.RangeInclusive(4, 7);
                if (resolveParams6.rect.minX > resolveParams5.rect.maxX - 3)
                {
                    break;
                }
                resolveParams6.rect = new CellRect(resolveParams6.rect.minX, resolveParams5.rect.minZ, width, height);
                if (Rand.Chance(0.15f))
                {
                    resolveParams6.rect.minX = resolveParams6.rect.minX + 3;
                }
                else
                {
                    char c = (!Rand.Chance(0.1f)) ? 'N' : 'W';
                    resolveParams6.SetCustom <char[]>("hasDoor", new char[]
                    {
                        c
                    }, false);
                    BaseGen.symbolStack.Push("roomWithDoor", resolveParams6, null);
                    resolveParams6.rect.minX = resolveParams6.rect.maxX;
                }
            }
            resolveParams6 = resolveParams5;
            for (int m = 0; m < 25; m++)
            {
                int width2 = Rand.RangeInclusive(4, 6);
                int num2   = Rand.RangeInclusive(4, 7);
                if (resolveParams6.rect.minX > resolveParams5.rect.maxX - 3)
                {
                    break;
                }
                resolveParams6.rect = new CellRect(resolveParams6.rect.minX, resolveParams5.rect.maxZ + 1 - num2, width2, num2);
                if (Rand.Chance(0.15f))
                {
                    resolveParams6.rect.minX = resolveParams6.rect.minX + 3;
                }
                else
                {
                    char c2 = (!Rand.Chance(0.1f)) ? 'S' : 'W';
                    resolveParams6.SetCustom <char[]>("hasDoor", new char[]
                    {
                        c2
                    }, false);
                    BaseGen.symbolStack.Push("roomWithDoor", resolveParams6, null);
                    resolveParams6.rect.minX = resolveParams6.rect.maxX;
                }
            }
            resolveParams6           = resolveParams5;
            resolveParams6.rect.minZ = resolveParams6.rect.minZ + 4;
            for (int n = 0; n < 25; n++)
            {
                int width3  = Rand.RangeInclusive(4, 6);
                int height2 = Rand.RangeInclusive(4, 7);
                if (resolveParams6.rect.minZ > resolveParams5.rect.maxZ - 4)
                {
                    break;
                }
                resolveParams6.rect = new CellRect(resolveParams5.rect.minX, resolveParams6.rect.minZ, width3, height2);
                if (Rand.Chance(0.15f))
                {
                    resolveParams6.rect.minZ = resolveParams6.rect.minZ + 3;
                }
                else
                {
                    char c3 = (!Rand.Chance(0.1f)) ? 'E' : 'S';
                    resolveParams6.SetCustom <char[]>("hasDoor", new char[]
                    {
                        c3
                    }, false);
                    BaseGen.symbolStack.Push("roomWithDoor", resolveParams6, null);
                    resolveParams6.rect.minZ = resolveParams6.rect.maxZ;
                }
            }
            resolveParams6           = resolveParams5;
            resolveParams6.rect.minZ = resolveParams6.rect.minZ + 4;
            for (int num3 = 0; num3 < 25; num3++)
            {
                int num4    = Rand.RangeInclusive(4, 6);
                int height3 = Rand.RangeInclusive(4, 7);
                if (resolveParams6.rect.minZ > resolveParams5.rect.maxZ - 4)
                {
                    break;
                }
                resolveParams6.rect = new CellRect(resolveParams5.rect.maxX + 1 - num4, resolveParams6.rect.minZ, num4, height3);
                if (Rand.Chance(0.15f))
                {
                    resolveParams6.rect.minZ = resolveParams6.rect.minZ + 3;
                }
                else
                {
                    char c4 = (!Rand.Chance(0.1f)) ? 'W' : 'S';
                    resolveParams6.SetCustom <char[]>("hasDoor", new char[]
                    {
                        c4
                    }, false);
                    BaseGen.symbolStack.Push("roomWithDoor", resolveParams6, null);
                    resolveParams6.rect.minZ = resolveParams6.rect.maxZ;
                }
            }
            ResolveParams resolveParams10;
            ResolveParams resolveParams9;
            ResolveParams resolveParams8;
            ResolveParams resolveParams7 = resolveParams8 = (resolveParams9 = (resolveParams10 = rp));
            CellRect      cellRect       = new CellRect(rp.rect.maxX, rp.rect.maxZ, 1, 1);

            resolveParams8.rect = cellRect.ExpandedBy(4);
            CellRect cellRect2 = new CellRect(rp.rect.minX, rp.rect.maxZ, 1, 1);

            resolveParams7.rect = cellRect2.ExpandedBy(4);
            CellRect cellRect3 = new CellRect(rp.rect.maxX, rp.rect.minZ, 1, 1);

            resolveParams9.rect = cellRect3.ExpandedBy(4);
            CellRect cellRect4 = new CellRect(rp.rect.minX, rp.rect.minZ, 1, 1);

            resolveParams10.rect = cellRect4.ExpandedBy(4);
            resolveParams8.SetCustom <char[]>("hasDoor", new char[]
            {
                'S',
                'W'
            }, false);
            resolveParams7.SetCustom <char[]>("hasDoor", new char[]
            {
                'S',
                'E'
            }, false);
            resolveParams9.SetCustom <char[]>("hasDoor", new char[]
            {
                'N',
                'W'
            }, false);
            resolveParams10.SetCustom <char[]>("hasDoor", new char[]
            {
                'N',
                'E'
            }, false);
            BaseGen.symbolStack.Push("roomWithDoor", resolveParams8, null);
            BaseGen.symbolStack.Push("roomWithDoor", resolveParams7, null);
            BaseGen.symbolStack.Push("roomWithDoor", resolveParams9, null);
            BaseGen.symbolStack.Push("roomWithDoor", resolveParams10, null);
            ResolveParams resolveParams11 = rp;

            resolveParams11.rect = resolveParams11.rect.ContractedBy(3);
            BaseGen.symbolStack.Push("edgeShields", resolveParams11, null);
            ResolveParams resolveParams12 = rp;

            BaseGen.symbolStack.Push("doors", resolveParams12, null);
            BaseGen.symbolStack.Push("edgeWalls", resolveParams12, null);
            BaseGen.symbolStack.Push("floor", resolveParams12, null);
        }
Exemple #21
0
 public override void CompTick()
 {
     //null map check
     if (this.parent.Map != null)
     {
         tickCounter++;
         //Only do every electroRate ticks
         if (tickCounter >= electroRate)
         {
             Pawn     pawn = this.parent as Pawn;
             CellRect rect = GenAdj.OccupiedRect(pawn.Position, pawn.Rotation, IntVec2.One);
             rect = rect.ExpandedBy(electroRadius);
             List <Building> batteriesInRange = new List <Building>();
             foreach (IntVec3 current in rect.Cells)
             {
                 if (current.InBounds(pawn.Map))
                 {
                     Building edifice = current.GetEdifice(pawn.Map);
                     //If any buildings were found in the requested area
                     if (edifice != null)
                     {
                         //Check their defNames, and see if they are in the list of provided batteries
                         //in the XML. They can be modded batteries. Example nice list of modded batteries:
                         //< li > Battery </ li >
                         //< li > Battery_Silver </ li >
                         //< li > Battery_Gold </ li >
                         //< li > Battery_Plasteel </ li >
                         //< li > Battery_Uranium </ li >
                         //< li > Battery_Advanced </ li >
                         //< li > Battery_Vanometric </ li >
                         //< li > Battery4k </ li >
                         //< li > Battery16k </ li >
                         //< li > Battery64k </ li >
                         //< li > Battery256k </ li >
                         //< li > ChargeBack_Battery_Prototype </ li >
                         //< li > ChargeBack_Battery </ li >
                         //< li > SpeedCharge_Battery </ li >
                         //< li > ResonanceCell_Battery </ li >
                         //< li > VoidCell_Battery </ li >
                         //< li > VFE_LargeBattery </ li >
                         //< li > VFE_SmallBattery </ li >
                         //< li > VFE_AdvancedBattery </ li >
                         //< li > VFE_LargeAdvancedBattery </ li >
                         foreach (string defNameOfBattery in Props.batteriesToAffect)
                         {
                             if (edifice.def.defName == defNameOfBattery)
                             {
                                 batteriesInRange.Add(edifice);
                             }
                         }
                     }
                 }
             }
             //If any battery was found
             if (batteriesInRange.Count > 0)
             {
                 //Affect a random one if more than one was found
                 Building batteryToAffect = batteriesInRange.RandomElement();
                 MoteMaker.ThrowMicroSparks(batteryToAffect.Position.ToVector3(), batteryToAffect.Map);
                 foreach (CompPowerBattery current2 in batteryToAffect.GetComps <CompPowerBattery>())
                 {
                     //Add 1 energy. The rate it fills is thus defined by electroRate
                     current2.AddEnergy((float)1);
                     break;
                 }
             }
             tickCounter = 0;
         }
     }
 }
Exemple #22
0
        public static SpectateRectSide FindSingleBestSide_NewTemp(CellRect spectateRect, Map map, SpectateRectSide allowedSides = SpectateRectSide.All, int margin = 1, Func <IntVec3, SpectateRectSide, int, float> scoreOffset = null)
        {
            for (int i = 0; i < scorePerSide.Length; i++)
            {
                scorePerSide[i] = 0f;
            }
            usedCells.Clear();
            int      num      = 30;
            CellRect cellRect = spectateRect.ExpandedBy(margin).ClipInsideMap(map);

            for (int j = 0; j < num; j++)
            {
                if (!TryFindSpectatorCellFor(null, spectateRect, map, out var cell, allowedSides, margin, usedCells))
                {
                    break;
                }
                usedCells.Add(cell);
                SpectateRectSide spectateRectSide = SpectateRectSide.None;
                if (cell.z > cellRect.maxZ)
                {
                    spectateRectSide |= SpectateRectSide.Up;
                }
                if (cell.x > cellRect.maxX)
                {
                    spectateRectSide |= SpectateRectSide.Right;
                }
                if (cell.z < cellRect.minZ)
                {
                    spectateRectSide |= SpectateRectSide.Down;
                }
                if (cell.x < cellRect.minX)
                {
                    spectateRectSide |= SpectateRectSide.Left;
                }
                float    num2 = Mathf.Lerp(1f, 0.35f, (float)j / (float)num);
                float    num3 = num2 + (scoreOffset?.Invoke(cell, spectateRectSide, j) ?? 0f);
                Building correctlyRotatedChairAt = GetCorrectlyRotatedChairAt(cell, map, spectateRect);
                foreach (SpectateRectSide allSelectedItem in spectateRectSide.GetAllSelectedItems <SpectateRectSide>())
                {
                    if (allSelectedItem.ValidSingleSide() && allowedSides.HasFlag(allSelectedItem))
                    {
                        scorePerSide[allSelectedItem.AsInt()] += num3;
                        if (correctlyRotatedChairAt != null && correctlyRotatedChairAt.Rotation == allSelectedItem.AsRot4())
                        {
                            scorePerSide[allSelectedItem.AsInt()] += 1.2f * num2;
                        }
                    }
                }
            }
            float num4 = 0f;
            int   num5 = -1;

            for (int k = 0; k < scorePerSide.Length; k++)
            {
                if (scorePerSide[k] != 0f && (num5 <0 || scorePerSide[k]> num4))
                {
                    num5 = k;
                    num4 = scorePerSide[k];
                }
            }
            usedCells.Clear();
            return(num5.ToSpectatorSide());
        }
Exemple #23
0
        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;
            IntVec2 standardAncientShrineSize = SymbolResolver_AncientShrinesGroupMedieval.StandardAncientShrineSize;
            var     num  = 1;
            var     num2 = (randomInRange * standardAncientShrineSize.x) + ((randomInRange - 1) * num);
            var     num3 = (randomInRange2 * standardAncientShrineSize.z) + ((randomInRange2 - 1) * num);
            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 (IntVec3 c in rect.Cells)
            {
                List <Thing> list = map.thingGrid.ThingsListAt(c);
                for (var i = 0; i < list.Count; i++)
                {
                    if (list[i].def == ThingDefOf.AncientCryptosleepCasket)
                    {
                        return;
                    }
                }
            }
            if (!CanPlaceAncientBuildingInRange(rect, map))
            {
                return;
            }
            var resolveParams = default(RimWorld.SketchGen.ResolveParams);

            resolveParams.sketch       = new Sketch();
            resolveParams.monumentSize = new IntVec2?(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 (IntVec3 b in entity.OccupiedRect.AdjacentCells)
                {
                    IntVec3 c2 = cell + b;
                    if (c2.InBounds(map))
                    {
                        Building edifice = c2.GetEdifice(map);
                        if (edifice == null || !edifice.def.building.isNaturalRock)
                        {
                            result = true;
                            break;
                        }
                    }
                }
                return(result);
            }, null);

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

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

            rectTrigger.signalTag         = signalTag;
            rectTrigger.Rect              = rect.ExpandedBy(1).ClipInsideMap(map);
            rectTrigger.destroyIfUnfogged = true;
            GenSpawn.Spawn(rectTrigger, rect.CenterCell, map);
        }
        // Token: 0x06000004 RID: 4 RVA: 0x00002428 File Offset: 0x00000628
        private void MakeBlueprintRoom(CellRect mapRect, MapGeneratorBlueprintDef blueprint, Map map, ThingDef stuffDef)
        {
            blueprint.buildingData = CleanUpBlueprintData(blueprint.buildingData);
            blueprint.floorData    = CleanUpBlueprintData(blueprint.floorData);
            blueprint.pawnData     = CleanUpBlueprintData(blueprint.pawnData);
            blueprint.itemData     = CleanUpBlueprintData(blueprint.itemData);
            if (blueprint.buildingData == null && blueprint.floorData == null)
            {
                Log.ErrorOnce(
                    $"After cleaning the BlueprintData and FloorData of blueprint {blueprint.defName} -> both are null, nothing will be done!",
                    313001);
            }
            else
            {
                var a = new IntVec3(mapRect.BottomLeft.x, mapRect.TopRight.y, mapRect.TopRight.z);
                foreach (var c in mapRect)
                {
                    if (!CheckCell(c, map))
                    {
                        return;
                    }
                }

                allSpawnedPawns = null;
                for (var i = 0; i < blueprint.size.z; i++)
                {
                    for (var j = 0; j < blueprint.size.x; j++)
                    {
                        var c2          = a + new IntVec3(j, 0, -i);
                        var itemPos     = j + (blueprint.size.x * i);
                        var thingDef    = TryGetThingDefFromBuildingData(blueprint, itemPos);
                        var thingRot    = TryGetRotationFromBuildingData(blueprint, itemPos);
                        var terrainDef  = TryGetTerrainDefFromFloorData(blueprint, itemPos);
                        var pawnKindDef = TryGetPawnKindDefFromPawnData(blueprint, itemPos);
                        var thingDef2   = TryGetItemDefFromItemData(blueprint, itemPos);
                        var list        = map.thingGrid.ThingsListAt(c2);
                        foreach (var thing in list)
                        {
                            if (thing.def == thingDef)
                            {
                            }
                        }

                        if (thingDef != null || terrainDef != null || pawnKindDef != null || thingDef2 != null)
                        {
                            ClearCell(c2, map);
                        }

                        if (!(blueprint.canHaveHoles && Rand.Value < 0.08f))
                        {
                            TrySetCellAs(c2, thingDef, thingRot, map, stuffDef, terrainDef, pawnKindDef, thingDef2,
                                         blueprint);
                        }
                    }
                }

                if (allSpawnedPawns != null && allSpawnedPawns.Count > 0)
                {
                    var rectTrigger = (RectTrigger)ThingMaker.MakeThing(ThingDefOf.RectTrigger);
                    rectTrigger.Rect = mapRect.ExpandedBy(1).ClipInsideMap(map);
                    //rectTrigger.letter = new Letter(Translator.Translate("LetterLabelAncientShrineWarning"), Translator.Translate("AncientShrineWarning"), 1, mapRect.CenterCell);
                    rectTrigger.destroyIfUnfogged = false;
                    GenSpawn.Spawn(rectTrigger, mapRect.CenterCell, map);
                }

                if (allSpawnedPawns == null || allSpawnedPawns.Count <= 0)
                {
                    return;
                }

                LordJob lordJob;
                if (blueprint.factionSelection == FactionSelection.friendly)
                {
                    lordJob = new LordJob_AssistColony(allSpawnedPawns[0].Faction, allSpawnedPawns[0].Position);
                }
                else
                {
                    if (Rand.Value < 0.5f)
                    {
                        lordJob = new LordJob_DefendPoint(allSpawnedPawns[0].Position);
                    }
                    else
                    {
                        lordJob = new LordJob_AssaultColony(allSpawnedPawns[0].Faction, false, false);
                    }
                }

                LordMaker.MakeNewLord(allSpawnedPawns[0].Faction, lordJob, map, allSpawnedPawns);
                allSpawnedPawns = null;
            }
        }
        public static SpectateRectSide FindSingleBestSide(CellRect spectateRect, Map map, SpectateRectSide allowedSides = SpectateRectSide.All, int margin = 1)
        {
            for (int i = 0; i < SpectatorCellFinder.scorePerSide.Length; i++)
            {
                SpectatorCellFinder.scorePerSide[i] = 0f;
            }
            SpectatorCellFinder.usedCells.Clear();
            int      num      = 30;
            CellRect cellRect = spectateRect.ExpandedBy(margin).ClipInsideMap(map);

            for (int j = 0; j < num; j++)
            {
                IntVec3 intVec;
                if (!SpectatorCellFinder.TryFindSpectatorCellFor(null, spectateRect, map, out intVec, allowedSides, margin, SpectatorCellFinder.usedCells))
                {
                    break;
                }
                SpectatorCellFinder.usedCells.Add(intVec);
                float    num2 = Mathf.Lerp(1f, 0.35f, (float)j / (float)num);
                float    num3 = num2;
                Building correctlyRotatedChairAt = SpectatorCellFinder.GetCorrectlyRotatedChairAt(intVec, map, spectateRect);
                if (intVec.z > cellRect.maxZ && (allowedSides & SpectateRectSide.Up) == SpectateRectSide.Up)
                {
                    SpectatorCellFinder.scorePerSide[0] += num3;
                    if (correctlyRotatedChairAt != null && correctlyRotatedChairAt.Rotation == Rot4.South)
                    {
                        SpectatorCellFinder.scorePerSide[0] += 1.2f * num2;
                    }
                }
                if (intVec.x > cellRect.maxX && (allowedSides & SpectateRectSide.Right) == SpectateRectSide.Right)
                {
                    SpectatorCellFinder.scorePerSide[1] += num3;
                    if (correctlyRotatedChairAt != null && correctlyRotatedChairAt.Rotation == Rot4.West)
                    {
                        SpectatorCellFinder.scorePerSide[1] += 1.2f * num2;
                    }
                }
                if (intVec.z < cellRect.minZ && (allowedSides & SpectateRectSide.Down) == SpectateRectSide.Down)
                {
                    SpectatorCellFinder.scorePerSide[2] += num3;
                    if (correctlyRotatedChairAt != null && correctlyRotatedChairAt.Rotation == Rot4.North)
                    {
                        SpectatorCellFinder.scorePerSide[2] += 1.2f * num2;
                    }
                }
                if (intVec.x < cellRect.minX && (allowedSides & SpectateRectSide.Left) == SpectateRectSide.Left)
                {
                    SpectatorCellFinder.scorePerSide[3] += num3;
                    if (correctlyRotatedChairAt != null && correctlyRotatedChairAt.Rotation == Rot4.East)
                    {
                        SpectatorCellFinder.scorePerSide[3] += 1.2f * num2;
                    }
                }
            }
            float num4 = 0f;
            int   num5 = -1;

            for (int k = 0; k < SpectatorCellFinder.scorePerSide.Length; k++)
            {
                if (SpectatorCellFinder.scorePerSide[k] != 0f)
                {
                    if (num5 < 0 || SpectatorCellFinder.scorePerSide[k] > num4)
                    {
                        num5 = k;
                        num4 = SpectatorCellFinder.scorePerSide[k];
                    }
                }
            }
            SpectatorCellFinder.usedCells.Clear();
            switch (num5)
            {
            case 0:
                return(SpectateRectSide.Up);

            case 1:
                return(SpectateRectSide.Right);

            case 2:
                return(SpectateRectSide.Down);

            case 3:
                return(SpectateRectSide.Left);

            default:
                return(SpectateRectSide.None);
            }
        }
Exemple #26
0
        protected override void ScatterAt(IntVec3 c, Map map, GenStepParams parms, int stackCount = 1)
        {
            Log.Message("Horrors: Initiating Hive Spawn");
            var noiseArray = new double[map.Size.x, map.Size.z];

            var caveNoise = GeneratePerlinNoiseForCaves(map);

            Log.Message("Horrors: Noise Generated Successfully");

            Log.Message("Horrors: Stepping through noise grid");
            for (var i = 0; i < map.Size.x; i++)
            {
                for (var n = 0; n < map.Size.z; n++)
                {
                    noiseArray[i, n] = caveNoise.layeredNoise(Convert.ToDouble(i) / 10, Convert.ToDouble(n) / 10);
                }
            }

            Log.Message("Horrors: Digging out tunnels");
            for (var i = 0; i < map.Size.x; i++)
            {
                for (var n = 0; n < map.Size.z; n++)
                {
                    var loc = new IntVec3(i, 0, n);

                    if (CoverUtility.TotalSurroundingCoverScore(loc, map) > 0.2)
                    {
                        GenSpawn.Spawn(ThingDef.Named("HorrorWeb"), loc, map);
                    }

                    if (!(noiseArray[i, n] > 0.5))
                    {
                        continue;
                    }

                    if (loc.GetEdifice(map) != null)
                    {
                        loc.GetEdifice(map).Destroy(DestroyMode.KillFinalize);
                    }

                    if (map.fogGrid.IsFogged(loc))
                    {
                        map.fogGrid.Unfog(loc);
                    }

                    // map.terrainGrid.SetTerrain(loc, TerrainDef.Named("FloorWebs"));
                }
            }

            Log.Message("Horrors: Generating Hive Rect");
            var     rect = new CellRect(0, 0, 0, 0);
            Faction faction;

            if (map.info.parent?.Faction == null || map.info.parent.Faction == Faction.OfPlayer)
            {
                faction = Find.FactionManager.RandomEnemyFaction();
            }
            else
            {
                faction = map.info.parent.Faction;
            }

            rect = rect.ExpandedBy(4);

            rect.ClipInsideMap(map);
            var resolveParams = default(ResolveParams);

            resolveParams.rect         = rect;
            resolveParams.faction      = faction;
            BaseGen.globalSettings.map = map;

            Log.Message("Horrors: Validating Spawns");

            bool Validator(IntVec3 p)
            {
                return(DropCellFinder.IsGoodDropSpot(p, map, true, true));
            }

            // Pawns
            var queenPawn = PawnGenerator.GeneratePawn(PawnKindDef.Named("Pirate"), faction);

            Log.Message("Horrors: Spawning Sinkhole");
            CellFinder.TryFindRandomCellNear(map.Center, map, 20, Validator, out var cellReturned);
            GenSpawn.Spawn(ThingDef.Named("SinkHole"), map.Center, map);

            Log.Message("Horrors: Spawning Sinkhole");
            CellFinder.TryFindRandomCellNear(map.Center, map, 20, Validator, out cellReturned);
            GenSpawn.Spawn(ThingDef.Named("SinkHole"), cellReturned, map);

            Log.Message("Horrors: Spawning Sinkhole");
            CellFinder.TryFindRandomCellNear(map.Center, map, 20, Validator, out cellReturned);
            GenSpawn.Spawn(ThingDef.Named("SinkHole"), cellReturned, map);

            Log.Message("Horrors: Spawning Sinkhole");
            CellFinder.TryFindRandomCellNear(map.Center, map, 20, Validator, out cellReturned);
            GenSpawn.Spawn(ThingDef.Named("SinkHole"), cellReturned, map);

            Log.Message("Horrors: Spawning Sinkhole");
            CellFinder.TryFindRandomCellNear(map.Center, map, 20, Validator, out cellReturned);

            var queen = GenSpawn.Spawn(queenPawn, cellReturned, map);

            var pawnToSpawn = PawnGenerator.GeneratePawn(PawnKindDef.Named("BroodLord"), faction);

            GenSpawn.Spawn(pawnToSpawn, cellReturned, map);
            pawnToSpawn.training.Train(TrainableDefOf.Obedience, (Pawn)queen);
        }
Exemple #27
0
 public Stencil Expand(int amount)
 {
     return(new Stencil(map, pos, rot, bounds.ExpandedBy(amount).ClipInsideMap(map)));
 }
        public static SpectateRectSide FindSingleBestSide(CellRect spectateRect, Map map, SpectateRectSide allowedSides = SpectateRectSide.All, int margin = 1)
        {
            for (int i = 0; i < SpectatorCellFinder.scorePerSide.Length; i++)
            {
                SpectatorCellFinder.scorePerSide[i] = 0f;
            }
            SpectatorCellFinder.usedCells.Clear();
            int      num      = 30;
            CellRect cellRect = spectateRect.ExpandedBy(margin).ClipInsideMap(map);
            int      num2     = 0;
            IntVec3  intVec   = default(IntVec3);

            while (num2 < num && SpectatorCellFinder.TryFindSpectatorCellFor((Pawn)null, spectateRect, map, out intVec, allowedSides, margin, SpectatorCellFinder.usedCells))
            {
                SpectatorCellFinder.usedCells.Add(intVec);
                float    num3 = Mathf.Lerp(1f, 0.35f, (float)num2 / (float)num);
                float    num4 = num3;
                Building correctlyRotatedChairAt = SpectatorCellFinder.GetCorrectlyRotatedChairAt(intVec, map, spectateRect);
                if (intVec.z > cellRect.maxZ && (allowedSides & SpectateRectSide.Up) == SpectateRectSide.Up)
                {
                    SpectatorCellFinder.scorePerSide[0] += num4;
                    if (correctlyRotatedChairAt != null && correctlyRotatedChairAt.Rotation == Rot4.South)
                    {
                        SpectatorCellFinder.scorePerSide[0] += (float)(1.2000000476837158 * num3);
                    }
                }
                if (intVec.x > cellRect.maxX && (allowedSides & SpectateRectSide.Right) == SpectateRectSide.Right)
                {
                    SpectatorCellFinder.scorePerSide[1] += num4;
                    if (correctlyRotatedChairAt != null && correctlyRotatedChairAt.Rotation == Rot4.West)
                    {
                        SpectatorCellFinder.scorePerSide[1] += (float)(1.2000000476837158 * num3);
                    }
                }
                if (intVec.z < cellRect.minZ && (allowedSides & SpectateRectSide.Down) == SpectateRectSide.Down)
                {
                    SpectatorCellFinder.scorePerSide[2] += num4;
                    if (correctlyRotatedChairAt != null && correctlyRotatedChairAt.Rotation == Rot4.North)
                    {
                        SpectatorCellFinder.scorePerSide[2] += (float)(1.2000000476837158 * num3);
                    }
                }
                if (intVec.x < cellRect.minX && (allowedSides & SpectateRectSide.Left) == SpectateRectSide.Left)
                {
                    SpectatorCellFinder.scorePerSide[3] += num4;
                    if (correctlyRotatedChairAt != null && correctlyRotatedChairAt.Rotation == Rot4.East)
                    {
                        SpectatorCellFinder.scorePerSide[3] += (float)(1.2000000476837158 * num3);
                    }
                }
                num2++;
            }
            float num5 = 0f;
            int   num6 = -1;

            for (int j = 0; j < SpectatorCellFinder.scorePerSide.Length; j++)
            {
                if (SpectatorCellFinder.scorePerSide[j] != 0.0 && (num6 <0 || SpectatorCellFinder.scorePerSide[j]> num5))
                {
                    num6 = j;
                    num5 = SpectatorCellFinder.scorePerSide[j];
                }
            }
            SpectatorCellFinder.usedCells.Clear();
            switch (num6)
            {
            case 0:
                return(SpectateRectSide.Up);

            case 1:
                return(SpectateRectSide.Right);

            case 2:
                return(SpectateRectSide.Down);

            case 3:
                return(SpectateRectSide.Left);

            default:
                return(SpectateRectSide.None);
            }
        }
Exemple #29
0
        public static void ClearThingsFor(Map map, IntVec3 spot, IntVec2 size, Rot4 rot, int expandedBy = 0, bool cutPlants = true, bool teleportHaulables = true)
        {
            if (!cutPlants && !teleportHaulables)
            {
                return;
            }

            CellRect removeCells = GenAdj.OccupiedRect(spot, rot, size).ExpandedBy(expandedBy);
            CellRect moveToCells = removeCells.ExpandedBy(2).ClipInsideMap(map);

            foreach (IntVec3 cell in removeCells)
            {
                if (cutPlants)
                {
                    Plant plant = cell.GetPlant(map);
                    if (plant != null && plant.def.plant.harvestWork >= 200f) // from GenConstruct.BlocksFramePlacement()
                    {
                        Designation des = new Designation(plant, DesignationDefOf.CutPlant);
                        map.designationManager.AddDesignation(des);

                        plant.SetForbiddenIfOutsideHomeArea(); // does nothing
                    }
                }

                if (teleportHaulables)
                {
                    Thing haulable = cell.GetFirstHaulable(map);
                    if (haulable != null)
                    {
                        IntVec3 moveToSpot = haulable.Position;
                        IntVec3 tempSpot;
                        for (int i = 0; i < 50; i++)
                        {
                            if (i < 15)
                            {
                                tempSpot = moveToCells.EdgeCells.RandomElement();
                            }
                            else
                            {
                                tempSpot = moveToCells.RandomCell;
                            }

                            if (!removeCells.Contains(tempSpot))
                            {
                                if (tempSpot.Standable(map))
                                {
                                    moveToSpot = tempSpot;
                                    break;
                                }
                            }
                        }
                        if (moveToSpot == haulable.Position)
                        {
                            Log.Error("Found no spot to teleport " + haulable + " to.");
                            continue;
                        }

                        // Teleport the f****r
                        //haulable.Position = moveToSpot;
                        GenPlace.TryMoveThing(haulable, moveToSpot, map);
                    }
                }
            }
        }
Exemple #30
0
        private void SpawnRoofOver(Thing thing)
        {
            CellRect cellRect = thing.OccupiedRect();
            bool     flag     = true;

            CellRect.CellRectIterator iterator = cellRect.GetIterator();
            while (!iterator.Done())
            {
                if (!iterator.Current.Roofed(thing.Map))
                {
                    flag = false;
                    break;
                }
                iterator.MoveNext();
            }
            if (flag)
            {
                return;
            }
            int      num       = 0;
            CellRect cellRect2 = cellRect.ExpandedBy(2);

            CellRect.CellRectIterator iterator2 = cellRect2.GetIterator();
            while (!iterator2.Done())
            {
                if (iterator2.Current.InBounds(thing.Map) && iterator2.Current.GetRoofHolderOrImpassable(thing.Map) != null)
                {
                    num++;
                }
                iterator2.MoveNext();
            }
            if (num < 2)
            {
                ThingDef stuff = Rand.Element <ThingDef>(ThingDefOf.WoodLog, ThingDefOf.Steel);
                foreach (IntVec3 intVec in cellRect2.Corners)
                {
                    if (intVec.InBounds(thing.Map))
                    {
                        if (intVec.Standable(thing.Map))
                        {
                            if (intVec.GetFirstItem(thing.Map) == null && intVec.GetFirstBuilding(thing.Map) == null && intVec.GetFirstPawn(thing.Map) == null)
                            {
                                if (!GenAdj.CellsAdjacent8Way(new TargetInfo(intVec, thing.Map, false)).Any((IntVec3 x) => !x.InBounds(thing.Map) || !x.Walkable(thing.Map)))
                                {
                                    if (intVec.SupportsStructureType(thing.Map, ThingDefOf.Wall.terrainAffordanceNeeded))
                                    {
                                        Thing thing2 = ThingMaker.MakeThing(ThingDefOf.Wall, stuff);
                                        GenSpawn.Spawn(thing2, intVec, thing.Map, WipeMode.Vanish);
                                        thing2.SetFaction(thing.Faction, null);
                                        num++;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (num > 0)
            {
                CellRect.CellRectIterator iterator3 = cellRect2.GetIterator();
                while (!iterator3.Done())
                {
                    if (iterator3.Current.InBounds(thing.Map) && !iterator3.Current.Roofed(thing.Map))
                    {
                        thing.Map.roofGrid.SetRoof(iterator3.Current, RoofDefOf.RoofConstructed);
                    }
                    iterator3.MoveNext();
                }
            }
        }