Exemplo n.º 1
0
        /// <summary>
        /// preform the requested transform
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        protected override MergedPawns TransformImpl(TransformationRequest request)
        {
            Pawn  firstPawn  = request.originals[0];
            Pawn  secondPawn = request.originals[1];
            float averageAge = firstPawn.ageTracker.AgeBiologicalYearsFloat
                               + secondPawn.ageTracker.AgeBiologicalYearsFloat;

            averageAge /= 2;


            float newAge = averageAge * request.outputDef.race.race.lifeExpectancy / firstPawn.RaceProps.lifeExpectancy;

            Faction faction = request.forcedFaction ?? Faction.OfPlayer;

            var pRequest = FormerHumanUtilities.CreateMergedAnimalRequest(request.outputDef, request.originals, faction);



            Pawn meldToSpawn = PawnGenerator.GeneratePawn(pRequest);

            HediffDef hediffToAdd = HediffDef.Named(FORMER_HUMAN_HEDIFF); //make sure hediff is added before spawning meld

            //make them count as former humans
            var tracker = meldToSpawn.GetSapienceTracker();

            if (tracker == null)
            {
                Log.Error($"{meldToSpawn.def.defName} is a meld but does not have a former human tracker!");
            }
            else
            {
                GiveTransformedPawnSapienceState(meldToSpawn, 1);
            }



            Hediff hediff = HediffMaker.MakeHediff(hediffToAdd, meldToSpawn);

            hediff.Severity = Rand.Range(request.minSeverity, request.maxSeverity);
            meldToSpawn.health.AddHediff(hediff);

            Pawn_NeedsTracker needs = meldToSpawn.needs;

            needs.food.CurLevel = firstPawn.needs.food.CurLevel;
            needs.rest.CurLevel = firstPawn.needs.rest.CurLevel;
            meldToSpawn.training.SetWantedRecursive(TrainableDefOf.Obedience, true);
            meldToSpawn.training.Train(TrainableDefOf.Obedience, null, true);
            meldToSpawn.Name = firstPawn.Name;
            var meld = (Pawn)GenSpawn.Spawn(meldToSpawn, firstPawn.PositionHeld, firstPawn.MapHeld);

            for (var i = 0; i < 10; i++)
            {
                IntermittentMagicSprayer.ThrowMagicPuffDown(meld.Position.ToVector3(), meld.MapHeld);
                IntermittentMagicSprayer.ThrowMagicPuffUp(meld.Position.ToVector3(), meld.MapHeld);
            }

            meld.SetFaction(Faction.OfPlayer);

            ReactionsHelper.OnPawnsMerged(firstPawn, firstPawn.IsPrisoner, secondPawn, secondPawn.IsPrisoner, meld);
            MergedPawnUtilities.TransferToMergedPawn(request.originals, meld);
            //apply any other post tf effects
            ApplyPostTfEffects(request.originals[0], meld, request);

            TransformerUtility.CleanUpHumanPawnPostTf(firstPawn, null);
            TransformerUtility.CleanUpHumanPawnPostTf(secondPawn, null);

            var inst = new MergedPawns(request.transformedTick)
            {
                originals          = request.originals.ToList(), //we want to make a copy here
                meld               = meld,
                mutagenDef         = def,
                factionResponsible = Faction.OfPlayer
            };

            return(inst);
        }
Exemplo n.º 2
0
        public void SingleSpawnLoop(SpawnThings spawnables, IntVec3 position, Map map)
        {
            bool flag = spawnables.def != null;

            if (flag)
            {
                Faction faction = pawn.Faction;
                bool    flag2   = spawnables.def.race != null;
                if (flag2)
                {
                    bool flag3 = spawnables.kindDef == null;
                    if (flag3)
                    {
                        Log.Error("Missing kinddef");
                    }
                    else
                    {
                        newPawn = (TMPawnSummoned)PawnGenerator.GeneratePawn(spawnables.kindDef, faction);
                        newPawn.validSummoning = true;
                        newPawn.Spawner        = this.Caster;
                        newPawn.Temporary      = true;
                        newPawn.TicksToDestroy = Mathf.RoundToInt(1800 * this.arcaneDmg);

                        try
                        {
                            GenSpawn.Spawn(newPawn, position, map);
                            CompLeaper comp = newPawn.GetComp <CompLeaper>();
                            comp.explosionRadius += ((verVal * .2f) * this.arcaneDmg);
                        }
                        catch
                        {
                            Log.Message("TM_Exception".Translate(
                                            pawn.LabelShort,
                                            this.def.defName
                                            ));
                            this.Destroy(DestroyMode.Vanish);
                        }
                        if (newPawn.Faction != null && newPawn.Faction != Faction.OfPlayer)
                        {
                            Lord lord = null;
                            if (newPawn.Map.mapPawns.SpawnedPawnsInFaction(faction).Any((Pawn p) => p != newPawn))
                            {
                                Predicate <Thing> validator = (Thing p) => p != newPawn && ((Pawn)p).GetLord() != null;
                                Pawn p2 = (Pawn)GenClosest.ClosestThing_Global(newPawn.Position, newPawn.Map.mapPawns.SpawnedPawnsInFaction(faction), 99999f, validator, null);
                                lord = p2.GetLord();
                            }
                            bool flag4 = lord == null;
                            if (flag4)
                            {
                                LordJob_DefendPoint lordJob = new LordJob_DefendPoint(newPawn.Position);
                                lord = LordMaker.MakeNewLord(faction, lordJob, map, null);
                            }
                            lord.AddPawn(newPawn);
                        }
                    }
                }
                else
                {
                    Log.Message("Missing race");
                }
            }
        }
Exemplo n.º 3
0
        public static void Resurrect(Pawn pawn)
        {
            if (!pawn.Dead)
            {
                Log.Error("Tried to resurrect a pawn who is not dead: " + pawn.ToStringSafe <Pawn>());
                return;
            }
            if (pawn.Discarded)
            {
                Log.Error("Tried to resurrect a discarded pawn: " + pawn.ToStringSafe <Pawn>());
                return;
            }
            Corpse  corpse = pawn.Corpse;
            bool    flag   = false;
            IntVec3 loc    = IntVec3.Invalid;
            Map     map    = null;

            if (corpse != null)
            {
                flag             = corpse.Spawned;
                loc              = corpse.Position;
                map              = corpse.Map;
                corpse.InnerPawn = null;
                corpse.Destroy(DestroyMode.Vanish);
            }
            if (flag && pawn.IsWorldPawn())
            {
                Find.WorldPawns.RemovePawn(pawn);
            }
            pawn.ForceSetStateToUnspawned();
            PawnComponentsUtility.CreateInitialComponents(pawn);
            pawn.health.Notify_Resurrected();
            if (pawn.Faction != null && pawn.Faction.IsPlayer)
            {
                if (pawn.workSettings != null)
                {
                    pawn.workSettings.EnableAndInitialize();
                }
                Find.Storyteller.intenderPopulation.Notify_PopulationGained();
            }
            if (flag)
            {
                GenSpawn.Spawn(pawn, loc, map);
                for (int i = 0; i < 10; i++)
                {
                    MoteMaker.ThrowAirPuffUp(pawn.DrawPos, map);
                }
                if (pawn.Faction != null && pawn.Faction != Faction.OfPlayer && pawn.HostileTo(Faction.OfPlayer))
                {
                    LordMaker.MakeNewLord(pawn.Faction, new LordJob_AssaultColony(pawn.Faction, true, true, false, false, true), pawn.Map, Gen.YieldSingle <Pawn>(pawn));
                }
                if (pawn.apparel != null)
                {
                    List <Apparel> wornApparel = pawn.apparel.WornApparel;
                    for (int j = 0; j < wornApparel.Count; j++)
                    {
                        wornApparel[j].Notify_PawnResurrected();
                    }
                }
            }
        }
        protected override void Impact(Thing hitThing)
        {
            base.Impact(hitThing);

            Log.Message("about to attemp to load the def variables..", true);
            int  limitGunValue = Def.limitGunValue;
            int  effectRadius  = Def.effectRadius;
            bool excludeOpGuns = Def.excludeOpGuns;
            bool spawnFewMelee = Def.spawnFewMelee;

            Log.Message("If you are reading this, the def variables sucessfully got read and loaded", true);
            int itemDefArraySize = DefDatabase <ThingDef> .DefCount;

            Log.Message("the number of item defs in the thing def database is: " + itemDefArraySize, true);
            Log.Message("About to sort through " + itemDefArraySize + " things in DefDatabase<ThingDef>.All", true);
            List <ThingDef> listOfThings = new List <ThingDef>();
            int             thingsCount  = 0;

            foreach (ThingDef currentThing in DefDatabase <ThingDef> .AllDefs)
            {
                if (currentThing.IsWithinCategory(ThingCategoryDefOf.Weapons))
                {
                    //Log.Message("- " + currentThing.label, true);

                    /*I don't understand lists, have never used them in a real world scenario to accomplish anything meaningful so I
                     * really hope that this doesn't cause a zillion null exceptions in Rimworld*/
                    if (!currentThing.label.Contains("Unfinished") && !currentThing.label.Contains("uranium") && !currentThing.label.Contains("unfinished") && !currentThing.label.Contains("Psychic") && !currentThing.label.Contains("subpersona") && !currentThing.label.Contains("turret"))
                    {
                        if (limitGunValue == 0 || currentThing.BaseMarketValue < limitGunValue)
                        {
                            listOfThings.Add(currentThing);
                            thingsCount++;
                        }
                        //Log.Message("- " + currentThing.label, true);
                    }
                }
            }

            //strangely, there are some items NOT contained in the thing def database. My list only excludes buildings and some other pointless junk
            //I can add the excluded things in manually. Most of them are in the already decalred in the ThingDefOf class

            //Log.Message("Done. wrote " + thingsCount + " things to a bigass list", true);


            //ok on to the other shit
            if (hitThing != null || base.Position != null) //Fancy way to declare a variable inside an if statement. - Thanks Erdelf.
            {
                //Log.Warning("hitThing = " + hitThing.ToString(), true);
                var rand = Rand.Value; // This is a random percentage between 0% and 100%
                //GenExplosion.DoExplosion(hitThing.Position, hitThing.Map, 3.9f, DamageDefOf.Bomb, this, 15, 0);
                //GenClamor.DoClamor(this, 3.9f, ClamorDefOf.Impact);

                int hitPosX; // = hitThing.Position.x;
                int hitPosY; // = hitThing.Position.y;
                int hitPosZ; // = hitThing.Position.z;
                if (hitThing == null)
                {
                    hitPosX = base.Position.x;
                    hitPosY = base.Position.y;
                    hitPosZ = base.Position.z;
                }
                else
                {
                    hitPosX = hitThing.Position.x;
                    hitPosY = hitThing.Position.y;
                    hitPosZ = hitThing.Position.z;
                }
                //Log.Message("about to spawn a zillion items in for loop 1", true);
                for (int g = -effectRadius; g < effectRadius; g++)
                {
                    for (int i = -effectRadius; i < effectRadius; i++)
                    {
                        //Random r2 = new Random();
                        //int r2Int = r2.Next(0, 34);
                        IntVec3  positionWhatever  = new IntVec3(hitPosX + i, hitPosY, hitPosZ + g);
                        ThingDef thingyWhateverFoo = listOfThings.RandomElement <ThingDef>();
                        Thing    thingThatsAboutToBeSpawned;
                        int      numThingsToSpawn = 1;

                        if (!thingyWhateverFoo.IsRangedWeapon)
                        {
                            //bool meleeOK;
                            if (new Random().Next(0, 1000) < 50 && spawnFewMelee == true)
                            {
                                //cool. do nothing then
                            }
                            else
                            {
                                //bool foundRanged = false;
                                while (!thingyWhateverFoo.IsRangedWeapon)
                                {
                                    thingyWhateverFoo = listOfThings.RandomElement <ThingDef>();
                                }
                            }
                        }

                        if (thingyWhateverFoo.MadeFromStuff)
                        {
                            thingThatsAboutToBeSpawned = ThingMaker.MakeThing(thingyWhateverFoo, ThingDefOf.Steel);
                            numThingsToSpawn           = 1;
                        }
                        else
                        {
                            thingThatsAboutToBeSpawned = ThingMaker.MakeThing(thingyWhateverFoo);
                            //numThingsToSpawn = Math.Abs(Math.Abs(g) - 5) + Math.Abs(Math.Abs(i) - 5);
                            numThingsToSpawn = 1;
                        }
                        int qtyMult = 1;

                        if (!MiscCrap.IsBuilingHere(this.launcher.Map, positionWhatever))
                        {
                            for (int b = 0; b < numThingsToSpawn * qtyMult; b++)
                            {
                                //Log.Message("r2Int = " + r2Int, true);

                                //don't spawn over a building. This causes it to deconstruct once you save and reload
                                if (thingyWhateverFoo.MadeFromStuff)
                                {
                                    GenSpawn.Spawn(thingThatsAboutToBeSpawned, positionWhatever, this.launcher.Map);
                                }
                                else
                                {
                                    GenSpawn.Spawn(thingyWhateverFoo, positionWhatever, this.launcher.Map);
                                }
                            }
                        }
                    }
                }
                //Log.Message("done", true);
            }

            /*else if (this.launcher.Map != null)
             * {
             *  GenExplosion.DoExplosion(this.Position, this.launcher.Map, 3.9f, DamageDefOf.Bomb, this, 1, 0);
             *  GenClamor.DoClamor(this, 3.9f, ClamorDefOf.Impact);
             *
             *  int hitPosX = this.Position.x;
             *  int hitPosY = this.Position.y;
             *  for (int g = -5; g < 5; g++)
             *  {
             *      for (int i = -5; i < 5; i++)
             *      {
             *          Random r3 = new Random();
             *          int r3Int = r3.Next(0, 34);
             *          IntVec3 positionWhatever = new IntVec3(this.Position.x + i, this.Position.y, this.Position.z + g);
             *          int beersToMake = Math.Abs(Math.Abs(g) - 5) + Math.Abs(Math.Abs(i) - 5);
             *          for (int b = 0; b < beersToMake; b++)
             *          {
             *              GenSpawn.Spawn(thingArray[r3Int], positionWhatever, this.launcher.Map);
             *          }
             *      }
             *  }
             * }*/
        }
Exemplo n.º 5
0
        protected override bool TryExecuteWorker(IncidentParms parms)
        {
            Map map = (Map)parms.target;
            List <TargetInfo> list        = new List <TargetInfo>();
            List <Thing>      list3       = ThingSetMakerDefOf.Meteorite.root.Generate();
            ThingDef          shipPartDef = def?.mechClusterBuilding;
            IntVec3           intVec      = FindDropPodLocation(map, (IntVec3 spot) => CanPlaceAt(spot));

            if (intVec == IntVec3.Invalid)
            {
                return(false);
            }
            float       points = Mathf.Max(parms.points * 0.9f, 300f);
            List <Pawn> list2  = PawnGroupMakerUtility.GeneratePawns(new PawnGroupMakerParms
            {
                groupKind = PawnGroupKindDefOf.Combat,
                tile      = map.Tile,
                faction   = Faction.OfMechanoids,
                points    = points
            }).ToList();
            Thing thing = ThingMaker.MakeThing(shipPartDef);

            thing.SetFaction(Faction.OfMechanoids);
            LordMaker.MakeNewLord(Faction.OfMechanoids, new LordJob_SleepThenMechanoidsDefend(new List <Thing>
            {
                thing
            }, Faction.OfMechanoids, 28f, intVec, canAssaultColony: false, isMechCluster: false), map, list2);
            DropPodUtility.DropThingsNear(intVec, map, list2.Cast <Thing>());
            foreach (Pawn item in list2)
            {
                item.TryGetComp <CompCanBeDormant>()?.ToSleep();
            }
            list.AddRange(list2.Select((Pawn p) => new TargetInfo(p)));
            GenSpawn.Spawn(SkyfallerMaker.MakeSkyfaller(ThingDefOf.MeteoriteIncoming, thing), intVec, map);
            list.Add(new TargetInfo(intVec, map));
            SendStandardLetter(parms, list);
            return(true);

            bool CanPlaceAt(IntVec3 loc)
            {
                CellRect cellRect = GenAdj.OccupiedRect(loc, Rot4.North, shipPartDef.Size);

                if (loc.Fogged(map) || !cellRect.InBounds(map))
                {
                    return(false);
                }
                if (!DropCellFinder.SkyfallerCanLandAt(loc, map, shipPartDef.Size))
                {
                    return(false);
                }
                foreach (IntVec3 item2 in cellRect)
                {
                    RoofDef roof = item2.GetRoof(map);
                    if (roof != null && roof.isNatural)
                    {
                        return(false);
                    }
                }
                return(GenConstruct.CanBuildOnTerrain(shipPartDef, loc, map, Rot4.North));
            }
        }
Exemplo n.º 6
0
 private void ShowLaserVisually(IntVec3 position)
 {
     LaserDrillVisual _LaserDrillVisual = (LaserDrillVisual)GenSpawn.Spawn(ThingDef.Named("LaserDrillVisual"), position, parent.Map, WipeMode.Vanish);
 }
        protected virtual void Impact(Thing hitThing)
        {
            bool flag = hitThing == null;

            if (flag)
            {
                Pawn pawn;
                bool flag2 = (pawn = (base.Position.GetThingList(base.Map).FirstOrDefault((Thing x) => x == this.assignedTarget) as Pawn)) != null;
                if (flag2)
                {
                    hitThing = pawn;
                }
            }
            bool hasValue = this.impactDamage.HasValue;

            if (hasValue)
            {
                for (int i = 0; i < this.timesToDamage; i++)
                {
                    bool flag3 = this.damageLaunched;
                    if (flag3)
                    {
                        this.flyingThing.TakeDamage(this.impactDamage.Value);
                    }
                    else
                    {
                        hitThing.TakeDamage(this.impactDamage.Value);
                    }
                }
                bool flag4 = this.explosion;
                if (flag4)
                {
                    GenExplosion.DoExplosion(base.Position, base.Map, 0.9f, DamageDefOf.Stun, this, -1, 0, null, null, null, null, null, 0f, 1, false, null, 0f, 1, 0f, false);
                }
            }
            try
            {
                SoundDefOf.Ambient_AltitudeWind.sustainFadeoutTime.Equals(30.0f);
                this.FireExplosion(pwrVal, verVal, base.Position, base.Map, (1.2f + (float)(verVal * .8f)));
                if (!pawn.IsColonist)
                {
                    this.FireExplosion(3, 3, base.Position, base.Map, (1.2f + (float)(3 * .8f)));
                }
                MoteMaker.ThrowSmoke(pawn.Position.ToVector3(), base.Map, (0.8f + (float)(verVal * .8f)));

                for (int i = 0; i < (2 + verVal); i++)
                {
                    expCell1 = GetNewPos(expCell1, this.origin.x <= this.DestinationCell.x, this.origin.z <= this.DestinationCell.z, false, 0, 0, xProb, 1 - xProb);
                    MoteMaker.ThrowSmoke(expCell1.ToVector3(), base.Map, 1.6f);
                    expCell2 = GetNewPos(expCell2, this.origin.x <= this.DestinationCell.x, this.origin.z <= this.DestinationCell.z, false, 0, 0, 1 - xProb, xProb);
                    MoteMaker.ThrowSmoke(expCell2.ToVector3(), base.Map, 1.6f);
                }
                for (int i = 0; i < (4 + (3 * verVal)); i++)
                {
                    CellRect cellRect = CellRect.CenteredOn(expCell1, (1 + verVal));
                    cellRect.ClipInsideMap(base.Map);
                    IntVec3 randomCell = cellRect.RandomCell;
                    this.FireExplosion(pwrVal, verVal, randomCell, base.Map, .4f);
                    cellRect   = CellRect.CenteredOn(expCell2, (1 + verVal));
                    randomCell = cellRect.RandomCell;
                    this.FireExplosion(pwrVal, verVal, randomCell, base.Map, .4f);
                }

                GenSpawn.Spawn(this.flyingThing, base.Position, base.Map);
                ModOptions.Constants.SetPawnInFlight(false);
                Pawn p = this.flyingThing as Pawn;
                RemoveInvul(p);
                if (p.IsColonist)
                {
                    p.drafter.Drafted = true;
                    CameraJumper.TryJumpAndSelect(p);
                }
                this.Destroy(DestroyMode.Vanish);
            }
            catch
            {
                GenSpawn.Spawn(this.flyingThing, base.Position, base.Map);
                ModOptions.Constants.SetPawnInFlight(false);
                Pawn p = this.flyingThing as Pawn;
                RemoveInvul(p);
                if (p.IsColonist)
                {
                    p.drafter.Drafted = true;
                }
                this.Destroy(DestroyMode.Vanish);
            }
        }
        static bool Prefix(ref SignalAction_Ambush __instance, SignalArgs args)
        {
            Map map = __instance.Map;

            if (__instance.points <= 0f)
            {
                return(false);
            }
            List <Pawn> list = new List <Pawn>();

            foreach (Pawn item in (IEnumerable <Pawn>)GenerateAmbushPawnsInfo.Invoke(__instance, new object[] { }))
            {
                // Skip out if the pawn isn't suitable for the map
                if (!map.PawnKindCanEnter(item.kindDef))
                {
                    Find.WorldPawns.PassToWorld(item);
                    break;
                }

                IntVec3 result;
                if (__instance.spawnPawnsOnEdge)
                {
                    // Changed to CellFinderExtended
                    if (!CellFinderExtended.TryFindRandomEdgeCellWith((IntVec3 x) => x.Standable(map) && !x.Fogged(map) && map.reachability.CanReachColony(x), map, item.kindDef, CellFinder.EdgeRoadChance_Ignore, out result))
                    {
                        Find.WorldPawns.PassToWorld(item);
                        break;
                    }
                }
                // TODO: PawnKind aware find cell around
                else if (!SiteGenStepUtility.TryFindSpawnCellAroundOrNear(__instance.spawnAround, __instance.spawnNear, map, out result))
                {
                    Find.WorldPawns.PassToWorld(item);
                    break;
                }
                GenSpawn.Spawn(item, result, map);
                if (!__instance.spawnPawnsOnEdge)
                {
                    for (int i = 0; i < 10; i++)
                    {
                        MoteMaker.ThrowAirPuffUp(item.DrawPos, map);
                    }
                }
                list.Add(item);
            }
            if (!list.Any())
            {
                return(false);
            }
            if (__instance.ambushType == SignalActionAmbushType.Manhunters)
            {
                for (int j = 0; j < list.Count; j++)
                {
                    list[j].mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.ManhunterPermanent);
                }
            }
            else
            {
                Faction faction = list[0].Faction;
                LordMaker.MakeNewLord(faction, new LordJob_AssaultColony(faction), map, list);
            }
            if (!__instance.spawnPawnsOnEdge)
            {
                for (int k = 0; k < list.Count; k++)
                {
                    list[k].jobs.StartJob(JobMaker.MakeJob(JobDefOf.Wait, 120));
                    list[k].Rotation = Rot4.Random;
                }
            }
            Find.LetterStack.ReceiveLetter("LetterLabelAmbushInExistingMap".Translate(), "LetterAmbushInExistingMap".Translate(Faction.OfPlayer.def.pawnsPlural).CapitalizeFirst(), LetterDefOf.ThreatBig, list[0]);
            return(false);
        }
        private bool TryFindSpawnCell(CellRect rect, ThingDef thingDef, Rot4 rot, bool mustReachMapEdge, out IntVec3 spawnCell)
        {
            Map     map    = BaseGen.globalSettings.map;
            IntVec3 center = IntVec3.Zero;
            IntVec2 size   = thingDef.size;

            GenAdj.AdjustForRotation(ref center, ref size, rot);
            CellRect             rect2         = CellRect.Empty;
            TraverseParms        traverseParms = TraverseParms.For(TraverseMode.PassDoors);
            Predicate <CellRect> basePredicate = (CellRect x) => x.Cells.All((IntVec3 y) => y.Standable(map)) && !GenSpawn.WouldWipeAnythingWith(x, thingDef, map, (Thing z) => z.def.category == ThingCategory.Building) && (thingDef.category != ThingCategory.Item || x.CenterCell.GetFirstItem(map) == null) && (!mustReachMapEdge || map.reachability.CanReachMapEdge(x.CenterCell, traverseParms));
            bool flag = false;

            if (thingDef.category == ThingCategory.Building)
            {
                flag = rect.TryFindRandomInnerRectTouchingEdge(size, out rect2, (CellRect x) => basePredicate(x) && !BaseGenUtility.AnyDoorAdjacentCardinalTo(x, map) && GenConstruct.TerrainCanSupport(x, map, thingDef));
                if (!flag)
                {
                    flag = rect.TryFindRandomInnerRectTouchingEdge(size, out rect2, (CellRect x) => basePredicate(x) && !BaseGenUtility.AnyDoorAdjacentCardinalTo(x, map));
                }
            }
            if (!flag && !rect.TryFindRandomInnerRectTouchingEdge(size, out rect2, basePredicate))
            {
                spawnCell = IntVec3.Invalid;
                return(false);
            }
            foreach (IntVec3 item in rect2)
            {
                if (GenAdj.OccupiedRect(item, rot, thingDef.size) == rect2)
                {
                    spawnCell = item;
                    return(true);
                }
            }
            Log.Error("We found a valid rect but we couldn't find the root position. This should never happen.");
            spawnCell = IntVec3.Invalid;
            return(false);
        }
Exemplo n.º 10
0
        public void TryLaunch(int destinationTile, TransportPodsArrivalAction arrivalAction, Caravan cafr = null)
        {
            if (cafr == null && !this.parent.Spawned)
            {
                Log.Error("Tried to launch " + (object)this.parent + ", but it's unspawned.");
            }
            else
            {
                if (this.parent.Spawned && !this.LoadingInProgressOrReadyToLaunch || (!this.AllInGroupConnectedToFuelingPort || !this.AllFuelingPortSourcesInGroupHaveAnyFuel))
                {
                    return;
                }
                if (cafr == null)
                {
                    Map map = this.parent.Map;
                    int num = Find.WorldGrid.TraversalDistanceBetween(map.Tile, destinationTile, true, int.MaxValue);
                    if (num > this.MaxLaunchDistance)
                    {
                        return;
                    }
                    this.Transporter.TryRemoveLord(map);
                    int             groupId           = this.Transporter.groupID;
                    float           amount            = Mathf.Max(CompLaunchableSRTS.FuelNeededToLaunchAtDist((float)num, this.BaseFuelPerTile), 1f);
                    CompTransporter comp1             = this.FuelingPortSource.TryGetComp <CompTransporter>();
                    Building        fuelingPortSource = this.FuelingPortSource;
                    if (fuelingPortSource != null)
                    {
                        fuelingPortSource.TryGetComp <CompRefuelable>().ConsumeFuel(amount);
                    }
                    ThingOwner directlyHeldThings = comp1.GetDirectlyHeldThings();

                    // Neceros Edit
                    Thing thing = ThingMaker.MakeThing(ThingDef.Named(parent.def.defName), (ThingDef)null);
                    thing.SetFactionDirect(Faction.OfPlayer);
                    thing.Rotation = this.FuelingPortSource.Rotation;
                    CompRefuelable comp2 = thing.TryGetComp <CompRefuelable>();
                    comp2.GetType().GetField("fuel", BindingFlags.Instance | BindingFlags.NonPublic).SetValue((object)comp2, (object)fuelingPortSource.TryGetComp <CompRefuelable>().Fuel);
                    comp2.TargetFuelLevel = fuelingPortSource.TryGetComp <CompRefuelable>().TargetFuelLevel;
                    thing.stackCount      = 1;
                    directlyHeldThings.TryAddOrTransfer(thing, true);

                    // Neceros Edit
                    ActiveDropPod activeDropPod = (ActiveDropPod)ThingMaker.MakeThing(ThingDef.Named(parent.def.defName + "_Active"), null);
                    activeDropPod.Contents = new ActiveDropPodInfo();
                    activeDropPod.Contents.innerContainer.TryAddRangeOrTransfer((IEnumerable <Thing>)directlyHeldThings, true, true);

                    // Neceros Edit
                    SRTSLeaving srtsLeaving = (SRTSLeaving)SkyfallerMaker.MakeSkyfaller(ThingDef.Named(parent.def.defName + "_Leaving"), (Thing)activeDropPod);
                    srtsLeaving.rotation        = this.FuelingPortSource.Rotation;
                    srtsLeaving.groupID         = groupId;
                    srtsLeaving.destinationTile = destinationTile;
                    srtsLeaving.arrivalAction   = arrivalAction;
                    comp1.CleanUpLoadingVars(map);
                    IntVec3 position = fuelingPortSource.Position;
                    SRTSStatic.SRTSDestroy((Thing)fuelingPortSource, DestroyMode.Vanish);
                    GenSpawn.Spawn((Thing)srtsLeaving, position, map, WipeMode.Vanish);
                    CameraJumper.TryHideWorld();
                }
                else
                {
                    int num = Find.WorldGrid.TraversalDistanceBetween(this.carr.Tile, destinationTile, true, int.MaxValue);
                    if (num > this.MaxLaunchDistance)
                    {
                        return;
                    }
                    float amount = Mathf.Max(CompLaunchableSRTS.FuelNeededToLaunchAtDist((float)num, this.BaseFuelPerTile), 1f);
                    if (this.FuelingPortSource != null)
                    {
                        this.FuelingPortSource.TryGetComp <CompRefuelable>().ConsumeFuel(amount);
                    }
                    ThingOwner <Pawn> directlyHeldThings = (ThingOwner <Pawn>)cafr.GetDirectlyHeldThings();
                    Thing             thing = null;
                    foreach (Pawn pawn in directlyHeldThings.InnerListForReading)
                    {
                        Pawn_InventoryTracker inventory = pawn.inventory;
                        for (int index = 0; index < inventory.innerContainer.Count; ++index)
                        {
                            // Neceros Edit
                            if (inventory.innerContainer[index].TryGetComp <CompLaunchableSRTS>() != null)
                            {
                                thing = inventory.innerContainer[index];
                                inventory.innerContainer[index].holdingOwner.Remove(inventory.innerContainer[index]);
                                break;
                            }
                        }
                    }
                    /*Add caravan items to SRTS - SmashPhil */
                    foreach (Pawn p in directlyHeldThings.InnerListForReading)
                    {
                        p.inventory.innerContainer.InnerListForReading.ForEach(x => AddThingsToSRTS(x));
                        p.inventory.innerContainer.Clear();
                    }

                    ThingOwner <Thing> thingOwner = new ThingOwner <Thing>();
                    foreach (Pawn pawn in directlyHeldThings.AsEnumerable <Pawn>().ToList <Pawn>())
                    {
                        thingOwner.TryAddOrTransfer((Thing)pawn, true);
                    }
                    if (thing != null && thing.holdingOwner == null)
                    {
                        thingOwner.TryAddOrTransfer(thing, false);
                    }

                    // Neceros Edit
                    ActiveDropPod activeDropPod = (ActiveDropPod)ThingMaker.MakeThing(ThingDef.Named(parent.def.defName + "_Active"), (ThingDef)null);
                    activeDropPod.Contents = new ActiveDropPodInfo();
                    activeDropPod.Contents.innerContainer.TryAddRangeOrTransfer((IEnumerable <Thing>)thingOwner, true, true);
                    activeDropPod.Contents.innerContainer.TryAddRangeOrTransfer((IEnumerable <Thing>)thingsInsideShip, true, true);
                    thingsInsideShip.Clear();

                    cafr.RemoveAllPawns();
                    if (!cafr.Destroyed)
                    {
                        cafr.Destroy();
                    }
                    TravelingSRTS travelingTransportPods = (TravelingSRTS)WorldObjectMaker.MakeWorldObject(DefDatabase <WorldObjectDef> .GetNamed("TravelingSRTS", true));
                    travelingTransportPods.Tile = cafr.Tile;
                    travelingTransportPods.SetFaction(Faction.OfPlayer);
                    travelingTransportPods.destinationTile = destinationTile;
                    travelingTransportPods.arrivalAction   = arrivalAction;
                    travelingTransportPods.flyingThing     = this.parent;
                    Find.WorldObjects.Add((WorldObject)travelingTransportPods);
                    travelingTransportPods.AddPod(activeDropPod.Contents, true);
                    activeDropPod.Contents = (ActiveDropPodInfo)null;
                    activeDropPod.Destroy(DestroyMode.Vanish);
                    Find.WorldTargeter.StopTargeting();
                }
            }
        }
Exemplo n.º 11
0
        //bool validTarg;

        //public override bool CanHitTargetFrom(IntVec3 root, LocalTargetInfo targ)
        //{
        //    if (targ.Thing != null && targ.Thing == this.caster)
        //    {
        //        return this.verbProps.targetParams.canTargetSelf;
        //    }
        //    if (targ.IsValid && targ.CenterVector3.InBounds(base.CasterPawn.Map) && !targ.Cell.Fogged(base.CasterPawn.Map) && targ.Cell.Walkable(base.CasterPawn.Map))
        //    {
        //        if ((root - targ.Cell).LengthHorizontal < this.verbProps.range)
        //        {
        //            ShootLine shootLine;
        //            validTarg = this.TryFindShootLineFromTo(root, targ, out shootLine);
        //        }
        //        else
        //        {
        //            validTarg = false;
        //        }
        //    }
        //    else
        //    {
        //        validTarg = false;
        //    }
        //    return validTarg;
        //}

        public virtual void Effect()
        {
            LocalTargetInfo t    = this.TargetsAoE[0];
            bool            flag = t.Cell != default(IntVec3);

            if (flag)
            {
                Pawn casterPawn = base.CasterPawn;
                //this.Ability.PostAbilityAttempt();
                if (ModCheck.Validate.GiddyUp.Core_IsInitialized())
                {
                    ModCheck.GiddyUp.ForceDismount(base.CasterPawn);
                }

                LongEventHandler.QueueLongEvent(delegate
                {
                    FlyingObject_PsionicStorm flyingObject = (FlyingObject_PsionicStorm)GenSpawn.Spawn(ThingDef.Named("FlyingObject_PsionicStorm"), this.CasterPawn.Position, this.CasterPawn.Map);
                    flyingObject.Launch(this.CasterPawn, t.Cell, this.CasterPawn, this);
                }, "LaunchingFlyer", false, null);
            }
        }
        public override void Notify_PawnDied()
        {
            IntVec3 spawnLoc = !base.Pawn.Dead ? base.parent.pawn.Position : base.parent.pawn.PositionHeld;
            Map     spawnMap = !base.Pawn.Dead ? base.parent.pawn.Map : base.parent.pawn.MapHeld;

            this.Pawn.def.race.deathActionWorkerClass = typeof(DeathActionWorker_Simple);
            bool fullterm = this.parent.CurStageIndex > this.parent.def.stages.Count - 3;

            if (!fullterm || bursted || spawnMap == null || spawnLoc == null)
            {
                return;
            }
            else
            {
                bursted = true;
                if (spawnMap == null || spawnLoc == null)
                {
                    return;
                }
                else
                {
                    if (countToSpawn == 0)
                    {
                        countToSpawn++;
                    }
                    for (int i = 0; i < countToSpawn; i++)
                    {
                        Pawn pawn = XenomorphSpawnRequest();
                        //    Log.Message(string.Format("Xenomorph to hatch: {0}", pawn.LabelShortCap));
                        pawn.ageTracker.AgeBiologicalTicks    = 0;
                        pawn.ageTracker.AgeChronologicalTicks = 0;
                        Comp_Xenomorph _Xenomorph = pawn.TryGetComp <Comp_Xenomorph>();
                        if (_Xenomorph != null)
                        {
                            _Xenomorph.host = base.parent.pawn.kindDef;
                        }
                        GenSpawn.Spawn(pawn, spawnLoc, spawnMap, 0);
                    }
                    Vector3 vector = spawnLoc.ToVector3Shifted();
                    for (int i = 0; i < 101; i++)
                    {
                        if (Rand.MTBEventOccurs(DustMoteSpawnMTB, 2f, 3.TicksToSeconds()))
                        {
                            MoteMaker.ThrowDustPuffThick(new Vector3(vector.x, 0f, vector.z)
                            {
                                y = AltitudeLayer.MoteOverhead.AltitudeFor()
                            }, spawnMap, 1.5f, HostBloodColour);
                        }
                        if (i == 100)
                        {
                        }
                        if (i % 10 == 0)
                        {
                            FilthMaker.TryMakeFilth(spawnLoc + GenAdj.AdjacentCellsAndInside.RandomElement(), this.Pawn.MapHeld, this.Pawn.RaceProps.BloodDef, this.Pawn.LabelIndefinite(), 1);
                        }
                    }
                    ThingDef motedef = DefDatabase <ThingDef> .GetNamedSilentFail("Mote_BlastExtinguisher");

                    MoteMaker.ThrowExplosionCell(spawnLoc, MyMap, motedef, HostBloodColour);
                    // GenAdj.AdjacentCellsAndInside[i];
                    for (int i2 = 0; i2 < GenAdj.AdjacentCellsAndInside.Length; i2++)
                    {
                        FilthMaker.TryMakeFilth(spawnLoc + GenAdj.AdjacentCellsAndInside[i2], this.Pawn.MapHeld, this.Pawn.RaceProps.BloodDef, this.Pawn.LabelIndefinite(), 1);
                    }
                    string text = TranslatorFormattedStringExtensions.Translate("Xeno_Chestburster_Emerge", base.parent.pawn.LabelShort, this.parent.Part.LabelShort);
                    MoteMaker.ThrowText(spawnLoc.ToVector3(), spawnMap, text, 5f);

                    if (!PlayerKnowledgeDatabase.IsComplete(XenomorphConceptDefOf.RRY_Concept_Chestbursters) && MyMap != null)
                    {
                        LessonAutoActivator.TeachOpportunity(XenomorphConceptDefOf.RRY_Concept_Chestbursters, OpportunityType.Important);
                    }
                    Pawn.health.AddHediff(DefDatabase <HediffDef> .GetNamedSilentFail("RRY_PostBurstWound"), this.parent.Part);
                    Pawn.health.RemoveHediff(this.parent);
                }
            }
        }
Exemplo n.º 13
0
        protected virtual void Impact(Thing hitThing)
        {
            bool flag = hitThing == null;

            if (flag)
            {
                Pawn pawn;
                bool flag2 = (pawn = (base.Position.GetThingList(base.Map).FirstOrDefault((Thing x) => x == this.assignedTarget) as Pawn)) != null;
                if (flag2)
                {
                    hitThing = pawn;
                }
            }
            bool hasValue = this.impactDamage.HasValue;

            if (hasValue)
            {
                hitThing.TakeDamage(this.impactDamage.Value);
            }
            try
            {
                SoundDefOf.Ambient_AltitudeWind.sustainFadeoutTime.Equals(30.0f);

                GenSpawn.Spawn(this.flyingThing, base.Position, base.Map);
                Thing p = this.flyingThing;
                if (this.flyingThing is Pawn)
                {
                    if (this.earlyImpact)
                    {
                        damageEntities(p, this.impactForce, DamageDefOf.Blunt);
                        damageEntities(p, 2 * this.impactForce, DamageDefOf.Stun);
                    }
                }
                else if (flyingThing.def.thingCategories != null && (flyingThing.def.thingCategories.Contains(ThingCategoryDefOf.Chunks) || flyingThing.def.thingCategories.Contains(ThingCategoryDef.Named("StoneChunks"))))
                {
                    float   radius = 3f;
                    Vector3 center = this.ExactPosition;
                    if (this.earlyImpact)
                    {
                        bool    wallFlag90neg = false;
                        IntVec3 wallCheck     = (center + (Quaternion.AngleAxis(-90, Vector3.up) * this.direction)).ToIntVec3();
                        MoteMaker.ThrowMicroSparks(wallCheck.ToVector3Shifted(), base.Map);
                        wallFlag90neg = wallCheck.Walkable(base.Map);

                        wallCheck = (center + (Quaternion.AngleAxis(90, Vector3.up) * this.direction)).ToIntVec3();
                        MoteMaker.ThrowMicroSparks(wallCheck.ToVector3Shifted(), base.Map);
                        bool wallFlag90 = wallCheck.Walkable(base.Map);

                        if ((!wallFlag90 && !wallFlag90neg) || (wallFlag90 && wallFlag90neg))
                        {
                            //fragment energy bounces in reverse direction of travel
                            center = center + ((Quaternion.AngleAxis(180, Vector3.up) * this.direction) * 3);
                        }
                        else if (wallFlag90)
                        {
                            center = center + ((Quaternion.AngleAxis(90, Vector3.up) * this.direction) * 3);
                        }
                        else if (wallFlag90neg)
                        {
                            center = center + ((Quaternion.AngleAxis(-90, Vector3.up) * this.direction) * 3);
                        }
                    }

                    int num = GenRadial.NumCellsInRadius(radius);
                    for (int i = 0; i < num / 2; i++)
                    {
                        IntVec3 intVec = center.ToIntVec3() + GenRadial.RadialPattern[Rand.Range(1, num)];
                        if (intVec.IsValid && intVec.InBounds(base.Map))
                        {
                            Vector3 moteDirection = TM_Calc.GetVector(this.ExactPosition.ToIntVec3(), intVec);
                            TM_MoteMaker.ThrowGenericMote(ThingDef.Named("Mote_Rubble"), this.ExactPosition, base.Map, Rand.Range(.3f, .5f), .2f, .02f, .05f, Rand.Range(-100, 100), 12f, (Quaternion.AngleAxis(90, Vector3.up) * moteDirection).ToAngleFlat(), 0);
                            GenExplosion.DoExplosion(intVec, base.Map, .4f, DamageDefOf.Blunt, pawn, Rand.Range(14, 22), 0, SoundDefOf.Pawn_Melee_Punch_HitBuilding, null, null, null, ThingDef.Named("Filth_RubbleRock"), .6f, 1, false, null, 0f, 1, 0, false);
                            MoteMaker.ThrowSmoke(intVec.ToVector3Shifted(), base.Map, Rand.Range(.6f, 1f));
                        }
                    }
                    damageEntities(p, 305, DamageDefOf.Blunt);
                }
                this.Destroy(DestroyMode.Vanish);
            }
            catch
            {
                GenSpawn.Spawn(this.flyingThing, base.Position, base.Map);
                Pawn p = this.flyingThing as Pawn;

                this.Destroy(DestroyMode.Vanish);
            }
        }
Exemplo n.º 14
0
        public override void Generate(Map map, GenStepParams parms)
        {
            //Log.Error("running");
            List <ThingDef> source = (from x in DefDatabase <ThingDef> .AllDefsListForReading
                                      where x.category == ThingCategory.Plant && x.GetCompProperties <CompProperties_WaterPlant>() != null &&
                                      x.GetCompProperties <CompProperties_WaterPlant>().allowedBiomes.Contains(map.Biome.defName)
                                      select x).ToList <ThingDef>();

            //Log.Error("1");
            if (source == null || source.Count == 0)
            {
                return;
            }
            //Log.Error(source[0].defName);
            foreach (IntVec3 c in map.AllCells)
            {
                ThingDef source2 = source[Rand.RangeInclusive(0, source.Count - 1)];
                if (c.GetEdifice(map) == null && c.GetCover(map) == null && c.GetFirstBuilding(map) == null)
                {
                    if (source2.GetCompProperties <CompProperties_WaterPlant>().allowedTiles.Contains(c.GetTerrain(map)))
                    {
                        if (Rand.Chance(source2.GetCompProperties <CompProperties_WaterPlant>().spawnChance))
                        {
                            Plant plant = (Plant)ThingMaker.MakeThing(source2, null);
                            plant.Growth = Rand.Range(0.07f, 1f);
                            if (plant.def.plant.LimitedLifespan)
                            {
                                plant.Age = Rand.Range(0, Mathf.Max(plant.def.plant.LifespanTicks - 50, 0));
                            }
                            GenSpawn.Spawn(plant, c, map);
                        }
                    }
                    else
                    {
                        if (source2.GetCompProperties <CompProperties_WaterPlant>().growNearWater)
                        {
                            bool flag = false;
                            for (int i = c.x - 1; i < c.x + 2; i++)
                            {
                                for (int j = c.z - 1; j < c.z + 2; j++)
                                {
                                    IntVec3 temp = new IntVec3(i, 0, j);
                                    if (temp.InBounds(map) && source2.GetCompProperties <CompProperties_WaterPlant>().allowedTiles.Contains(temp.GetTerrain(map)) && !IsWater(temp, map) && !(temp.GetTerrain(map).defName == "Marsh"))
                                    {
                                        if (Rand.Chance(source2.GetCompProperties <CompProperties_WaterPlant>().spawnChance))
                                        {
                                            Plant plant = (Plant)ThingMaker.MakeThing(source2, null);
                                            plant.Growth = Rand.Range(0.07f, 1f);
                                            if (plant.def.plant.LimitedLifespan)
                                            {
                                                plant.Age = Rand.Range(0, Mathf.Max(plant.def.plant.LifespanTicks - 50, 0));
                                            }
                                            GenSpawn.Spawn(plant, c, map);
                                            flag = true;
                                        }
                                    }
                                    if (flag)
                                    {
                                        break;
                                    }
                                }
                                if (flag)
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 15
0
        public override void Tick()
        {
            //Base Tick
            base.Tick();
            //Return if not Spawnd
            if (!this.Spawned)
            {
                return;
            }


            //Should not draw much performence...
            //To enhance performence we could add "this.IsHashIntervalTick(60)"
            if (spawnedDrones.Count > 0 && compPowerTrader?.PowerOn == false)
            {
                for (int i = spawnedDrones.Count - 1; i >= 0; i--)
                {
                    spawnedDrones[i].jobs.StartJob(new Job(PRFDefOf.PRFDrone_ReturnToStation, this), JobCondition.InterruptForced);
                }
                //return as there is nothing to do if its off....
                return;
            }


            //Update the Allowed Area Range on Power Change
            if (this.IsHashIntervalTick(60))
            {
                //Update the Range
                Update_droneAllowedArea_forDrones(droneAllowedArea);

                //TODO add cell calc
                cashed_GetCoverageCells = StationRangecells.ToList();
            }

            //Search for Job
            if (this.IsHashIntervalTick(60 + additionJobSearchTickDelay) && DronesLeft > 0 && !lockdown && compPowerTrader?.PowerOn != false)
            {
                //The issue appears to be 100% with TryGiveJob
                Job job = TryGiveJob();

                if (job != null)
                {
                    additionJobSearchTickDelay = 0; //Reset to 0 - found a job -> may find more
                    job.playerForced           = true;
                    job.expiryInterval         = -1;
                    //MakeDrone takes about 1ms
                    Pawn_Drone drone = MakeDrone();
                    GenSpawn.Spawn(drone, Position, Map);
                    drone.jobs.StartJob(job);
                }
                else
                {
                    //Experimental Delay
                    //Add delay (limit to 300) i am well aware that this can be higher that 300 with the current code
                    if (additionJobSearchTickDelay < 300)
                    {
                        //Exponential delay
                        additionJobSearchTickDelay = (additionJobSearchTickDelay + 1) * 2;
                    }
                }
            }
        }
Exemplo n.º 16
0
        private static void DropToWorldObjectDo(WorldObject place, List <ThingEntry> things, string from, string text)
        {
            GlobalTargetInfo ti = new GlobalTargetInfo(place);
            var factionPirate   = SessionClientController.Data.FactionPirate;

            if (MainHelper.DebugMode)
            {
                Loger.Log("Mail================================================= {");
            }

            if (place is Settlement && ((Settlement)place).Map != null)
            {
                var map  = ((Settlement)place).Map;
                var cell = GameUtils.GetTradeCell(map);
                ti = new GlobalTargetInfo(cell, map);
                Thing thinXZ;
                foreach (var thing in things)
                {
                    if (MainHelper.DebugMode)
                    {
                        Loger.Log("Mail------------------------------------------------- {" + Environment.NewLine
                                  + thing.Data + Environment.NewLine
                                  + "Mail------------------------------------------------- }" + Environment.NewLine);
                    }
                    var thin = GameUtils.PrepareSpawnThingEntry(thing, factionPirate);

                    if (MainHelper.DebugMode)
                    {
                        Loger.Log("Spawn...");
                    }
                    if (thin is Pawn)
                    {
                        GenSpawn.Spawn((Pawn)thin, cell, map);
                    }
                    else
                    {
                        GenDrop.TryDropSpawn(thin, cell, map, ThingPlaceMode.Near, out thinXZ, null);
                    }
                    if (MainHelper.DebugMode)
                    {
                        Loger.Log("Spawn...OK");
                    }
                }
            }
            else if (place is Caravan)
            {
                var pawns = (place as Caravan).PawnsListForReading;
                foreach (var thing in things)
                {
                    /*
                     * thing.SetFaction(factionColonistLoadID, factionPirateLoadID);
                     * var thin = thing.CreateThing(false);
                     */
                    var thin = GameUtils.PrepareSpawnThingEntry(thing, factionPirate);

                    if (thin is Pawn)
                    {
                        (place as Caravan).AddPawn(thin as Pawn, true);
                        GameUtils.SpawnSetupOnCaravan(thin as Pawn);
                    }
                    else
                    {
                        var p = CaravanInventoryUtility.FindPawnToMoveInventoryTo(thin, pawns, null);
                        if (p != null)
                        {
                            p.inventory.innerContainer.TryAdd(thin, true);
                        }
                    }
                }
            }

            if (MainHelper.DebugMode)
            {
                Loger.Log("Mail================================================= }");
            }

            Find.LetterStack.ReceiveLetter("OCity_UpdateWorld_Trade".Translate()
                                           , text
                                           , LetterDefOf.PositiveEvent
                                           , ti
                                           , null);
        }
Exemplo n.º 17
0
        private static Gizmo GetSquadTeleGizmo(Pawn pawn)
        {
            // Log.Warning("YES");
            var command_Target = new Command_TargetPlus {
                defaultLabel = "ChronoTeleport".Translate()
            };


            var tp = new TargetingParameters
            {
                canTargetBuildings = false,
                canTargetFires     = false,
                canTargetLocations = true,
                canTargetPawns     = false,
                canTargetSelf      = false
            };

            command_Target.disabled        = pawn.stances.stunner.Stunned || !pawn.drafter.Drafted;
            command_Target.targetingParams = tp;
            command_Target.hotKey          = KeyBindingDefOf.Misc4;
            command_Target.icon            = ContentFinder <Texture2D> .Get("ra2/Things/Misc/ChTeleport");

            command_Target.aimIcon = ContentFinder <Texture2D> .Get("ra2/Things/Misc/ChTeleport");

            command_Target.action = delegate(LocalTargetInfo target)
            {
                var enumerable = Find.Selector.SelectedObjects.Where(x =>
                                                                     x is Pawn {
                    IsColonistPlayerControlled: true, Drafted: true
                }).Cast <Pawn>();

                var tmpPawns  = enumerable.ToList();
                var tmpPawns2 = new List <Pawn>();
                foreach (var pawn2 in tmpPawns)
                {
                    {
                        var casterPawn = pawn2;
                        var map        = pawn2.Map;

                        var thi = map.thingGrid.ThingsAt(target.Cell);
                        foreach (var th in thi)
                        {
                            if (th is not Building)
                            {
                                continue;
                            }

                            Messages.Message("ChronoNotToBuild".Translate(), MessageTypeDefOf.RejectInput);
                            return;
                        }

                        FleckMaker.ThrowExplosionCell(target.Cell, map, FleckDefOf.ExplosionFlash, new Color(1, 1, 1));
                        // MoteMaker.ThrowExplosionCell(target.Cell, map, ThingDefOf.Mote_ExplosionFlash, new UnityEngine.Color(1,1,1));
                        // for (int asd = 0; asd < 60; asd++)
                        FleckMaker.ThrowExplosionCell(casterPawn.Position, map, FleckDefOf.ExplosionFlash,
                                                      new Color(1f, 1, 1));
                        var dist = Math.Sqrt(Math.Pow(casterPawn.Position.x - target.Cell.x, 2) +
                                             Math.Pow(casterPawn.Position.z - target.Cell.z, 2));
                        if (dist < 20)
                        {
                            dist = 20;
                        }


                        pawn2.DeSpawn();
                        GenSpawn.Spawn(casterPawn, target.Cell, map);

                        casterPawn.drafter.Drafted = true;
                        tmpPawns2.Add(casterPawn);

                        DefDatabase <SoundDef> .GetNamed("ra2_Chrono_move").PlayOneShot(casterPawn);

                        DefDatabase <SoundDef> .GetNamed("ra2_Chrono_movesay").PlayOneShotOnCamera();

                        var dinfo = new DamageInfo(DamageDefOf.Stun, (int)(dist * 0.1), -1, 1, null, null,
                                                   casterPawn.equipment.Primary.def, DamageInfo.SourceCategory.ThingOrUnknown, casterPawn);
                        casterPawn.TakeDamage(dinfo);
                    }
                }

                foreach (var pps in tmpPawns2)
                {
                    Find.Selector.SelectedObjects.Add(pps);
                }
            };
Exemplo n.º 18
0
        public override void Tick()
        {
            //base.Tick();
            this.ticksToImpact--;
            bool flag = !this.ExactPosition.InBounds(base.Map) || base.Position.DistanceToEdge(base.Map) <= 1;

            if (this.stage > 0 && this.stage < 4 && this.nextAttackTick < Find.TickManager.TicksGame)
            {
                IntVec3 targetVariation = this.targetCells.RandomElement();
                float   angle           = (Quaternion.AngleAxis(90, Vector3.up) * GetVector(this.ExactPosition, targetVariation.ToVector3Shifted())).ToAngleFlat();
                Vector3 drawPos         = this.ExactPosition + (GetVector(this.ExactPosition, targetVariation.ToVector3Shifted()) * .5f);
                TM_MoteMaker.ThrowGenericMote(ThingDef.Named("Mote_PsiBlastStart"), drawPos, base.Map, Rand.Range(.4f, .6f), Rand.Range(.0f, .05f), 0f, .1f, 0, 0, 0, angle);                      //throw psi blast start
                TM_MoteMaker.ThrowGenericMote(ThingDef.Named("Mote_PsiBlastEnd"), drawPos, base.Map, Rand.Range(.4f, .8f), Rand.Range(.0f, .1f), .2f, .3f, 0, Rand.Range(1f, 1.5f), angle, angle); //throw psi blast end
                this.TryLaunchProjectile(ThingDef.Named("TM_Projectile_PsionicBlast"), targetVariation);
                this.nextAttackTick = Find.TickManager.TicksGame + Mathf.RoundToInt(Rand.Range(attackFrequencyLow, attackFrequencyHigh) * (1 - .1f * this.verVal));
            }
            if (flag)
            {
                this.ticksToImpact++;
                base.Position = this.ExactPosition.ToIntVec3();
                GenSpawn.Spawn(this.flyingThing, base.Position, base.Map);
                ModOptions.Constants.SetPawnInFlight(false);
                Pawn p = this.flyingThing as Pawn;
                if (p.IsColonist)
                {
                    p.drafter.Drafted = true;
                    CameraJumper.TryJumpAndSelect(p);
                }
                this.Destroy(DestroyMode.Vanish);
            }
            else
            {
                base.Position = this.ExactPosition.ToIntVec3();
                MoteMaker.ThrowDustPuff(base.Position, base.Map, Rand.Range(0.8f, 1.2f));
                bool flag2 = this.ticksToImpact <= 0;
                if (flag2)
                {
                    if (this.stage == 0)
                    {
                        CalculateCurvePoints(this.nearApex, this.farApex, 90);
                        this.origin = this.curvePoints[this.destinationCurvePoint];
                        this.destinationCurvePoint++;
                        this.destination    = this.curvePoints[this.destinationCurvePoint];
                        this.speed          = this.circleFlightSpeed;
                        this.ticksToImpact  = this.StartingTicksToImpact;
                        this.nextAttackTick = Find.TickManager.TicksGame + Mathf.RoundToInt(Rand.Range(attackFrequencyLow, attackFrequencyHigh) * (1 - .1f * this.verVal));
                        this.stage          = 1;
                    }
                    else if (this.stage == 1)
                    {
                        if ((this.curvePoints.Count() - 1) > this.destinationCurvePoint)
                        {
                            this.origin = this.curvePoints[this.destinationCurvePoint];
                            this.destinationCurvePoint++;
                            this.destination   = this.curvePoints[this.destinationCurvePoint];
                            this.ticksToImpact = this.StartingTicksToImpact;
                        }
                        else
                        {
                            this.origin = this.curvePoints[this.destinationCurvePoint];
                            CalculateCurvePoints(this.origin, this.nearApex, 90);
                            this.destinationCurvePoint++;
                            this.destination   = this.curvePoints[this.destinationCurvePoint];
                            this.ticksToImpact = this.StartingTicksToImpact;
                            this.stage         = 2;
                        }
                    }
                    else if (this.stage == 2)
                    {
                        if ((this.curvePoints.Count() - 1) > this.destinationCurvePoint)
                        {
                            this.origin = this.curvePoints[this.destinationCurvePoint];
                            this.destinationCurvePoint++;
                            this.destination   = this.curvePoints[this.destinationCurvePoint];
                            this.ticksToImpact = this.StartingTicksToImpact;
                        }
                        else
                        {
                            this.origin        = this.curvePoints[this.destinationCurvePoint];
                            this.destination   = this.nearApex;
                            this.ticksToImpact = this.StartingTicksToImpact;
                            //this.speed = 15;
                            this.stage = 3;
                        }
                    }
                    else if (this.stage == 3)
                    {
                        this.speed         = 25f;
                        this.origin        = this.nearApex;
                        this.destination   = this.trueOrigin;
                        this.ticksToImpact = this.StartingTicksToImpact;
                        this.stage         = 4;
                    }
                    else
                    {
                        bool flag3 = this.DestinationCell.InBounds(base.Map);
                        if (flag3)
                        {
                            base.Position = this.DestinationCell;
                        }
                        this.ImpactSomething();
                    }
                }
            }
        }
        protected override bool TryExecuteWorker(IncidentParms parms)
        {
            var map        = parms.target as Map;
            var closestCat = TryGetClosestCatOnMap(map);

            var guardianProps = def.GetModExtension <GuardianProperties>();

            if (closestCat == null)
            {
                return(true);
            }

            //Transform Cat
            //Generate guardian
            var newGuardian = PawnGenerator.GeneratePawn(new PawnGenerationRequest(
                                                             guardianProps.guardianDef, Faction.OfPlayer, PawnGenerationContext.NonPlayer, -1, true, false,
                                                             false, false, false,
                                                             true, 0f, false, true, true, false, false, false, false, false, 0, 0, null, 0, null, null, null, null,
                                                             null, closestCat.ageTracker.AgeBiologicalYears, closestCat.ageTracker.AgeChronologicalYears,
                                                             closestCat.gender));

            //Transfer over family trees and relations to guardian from old cat.
            var oldRelations = closestCat.relations;
            var newRelations = newGuardian.relations;

            //Transfer over relations.
            var relationList = new List <DirectPawnRelation>(oldRelations.DirectRelations);

            foreach (var relation in relationList)
            {
                newRelations.AddDirectRelation(relation.def, relation.otherPawn);
                oldRelations.RemoveDirectRelation(relation);
            }

            //Fully train.
            foreach (var trainableDef in DefDatabase <TrainableDef> .AllDefs)
            {
                for (var step = 0; step < trainableDef.steps; step++)
                {
                    newGuardian.training.Train(trainableDef, null);
                }
            }

            //Make a new name.
            if (closestCat.Name != null)
            {
                newGuardian.Name = closestCat.gender == Gender.Male
                    ? new NameSingle(NameGenerator.GenerateName(RulePackDef.Named("NamerAnimalGenericMale")))
                    : new NameSingle(NameGenerator.GenerateName(RulePackDef.Named("NamerAnimalGenericFemale")));
            }

            //Dump inventory, if any.
            closestCat.inventory.DropAllNearPawn(closestCat.Position);

            Letter letter = LetterMaker.MakeLetter(
                "Cults_BastGuardianTransformationLabel".Translate(closestCat.Name?.ToStringShort),
                "Cults_BastGuardianTransformationDescription".Translate(closestCat.Name?.ToStringFull),
                LetterDefOf.PositiveEvent, new GlobalTargetInfo(newGuardian));

            //Remove old cat.
            var catPosition = closestCat.Position;

            closestCat.Destroy();

            //Spawn in guardian.
            GenSpawn.Spawn(newGuardian, catPosition, map);
            MoteMaker.MakePowerBeamMote(catPosition, map);

            Current.Game.letterStack.ReceiveLetter(letter);

            return(true);
        }
Exemplo n.º 20
0
        protected override bool TryCastShot()
        {
            bool result = false;
            bool flag   = false;

            if (this.currentTarget != null && base.CasterPawn != null)
            {
                IntVec3 arg_29_0 = this.currentTarget.Cell;
                Vector3 vector   = this.currentTarget.CenterVector3;
                flag = this.currentTarget.Cell.IsValid && vector.InBounds(base.CasterPawn.Map) && this.currentTarget.Thing != null && this.currentTarget.Thing is Pawn;
            }

            if (flag)
            {
                Pawn    p                 = this.CasterPawn;
                Pawn    targetPawn        = this.currentTarget.Thing as Pawn;
                Map     map               = this.CasterPawn.Map;
                IntVec3 cell              = this.CasterPawn.Position;
                bool    draftFlag         = this.CasterPawn.Drafted;
                CompAbilityUserMagic comp = p.TryGetComp <CompAbilityUserMagic>();
                if (comp != null)
                {
                    pwrVal = comp.MagicData.MagicPowerSkill_ShadowWalk.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_ShadowWalk_pwr").level;
                    verVal = comp.MagicData.MagicPowerSkill_ShadowWalk.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_ShadowWalk_ver").level;
                }
                try
                {
                    if (this.CasterPawn.IsColonist)
                    {
                        ModOptions.Constants.SetPawnInFlight(true);
                        this.CasterPawn.DeSpawn();
                        GenSpawn.Spawn(p, this.currentTarget.Cell, map);
                        p.drafter.Drafted = draftFlag;
                        CameraJumper.TryJumpAndSelect(p);
                        ModOptions.Constants.SetPawnInFlight(false);
                    }
                    else
                    {
                        ModOptions.Constants.SetPawnInFlight(true);
                        this.CasterPawn.DeSpawn();
                        GenSpawn.Spawn(p, this.currentTarget.Cell, map);
                        ModOptions.Constants.SetPawnInFlight(false);
                    }
                    if (pwrVal > 0)
                    {
                        HealthUtility.AdjustSeverity(p, TorannMagicDefOf.TM_ShadowCloakHD, .5f);
                        HediffComp_Disappears hdComp = p.health.hediffSet.GetFirstHediffOfDef(TorannMagicDefOf.TM_ShadowCloakHD).TryGetComp <HediffComp_Disappears>();
                        if (hdComp != null)
                        {
                            hdComp.ticksToDisappear = 60 + (60 * pwrVal);
                        }
                    }
                    if (verVal > 0)
                    {
                        TM_Action.DoAction_HealPawn(p, p, 1 + verVal, 6 + verVal);
                        if (targetPawn.Faction != null && targetPawn.Faction == p.Faction)
                        {
                            if (verVal > 1)
                            {
                                TM_Action.DoAction_HealPawn(p, targetPawn, verVal, 4 + verVal);
                            }
                            if (verVal > 2)
                            {
                                HealthUtility.AdjustSeverity(targetPawn, TorannMagicDefOf.TM_ShadowCloakHD, .5f);
                                HediffComp_Disappears hdComp = targetPawn.health.hediffSet.GetFirstHediffOfDef(TorannMagicDefOf.TM_ShadowCloakHD).TryGetComp <HediffComp_Disappears>();
                                if (hdComp != null)
                                {
                                    hdComp.ticksToDisappear = 180;
                                }
                                ThingDef fog = TorannMagicDefOf.Fog_Shadows;
                                fog.gas.expireSeconds.min = 4;
                                fog.gas.expireSeconds.max = 4;
                                GenExplosion.DoExplosion(p.Position, p.Map, 2, TMDamageDefOf.DamageDefOf.TM_Toxin, caster, 0, 0, TMDamageDefOf.DamageDefOf.TM_Toxin.soundExplosion, null, null, null, fog, 1f, 1, false, null, 0f, 0, 0.0f, false);
                            }
                        }
                    }
                    for (int i = 0; i < 6; i++)
                    {
                        Vector3 rndPos = p.DrawPos;
                        rndPos.x += Rand.Range(-1.5f, 1.5f);
                        rndPos.z += Rand.Range(-1.5f, 1.5f);
                        TM_MoteMaker.ThrowGenericMote(TorannMagicDefOf.Mote_ShadowCloud, rndPos, p.Map, Rand.Range(.8f, 1.2f), .6f, .05f, Rand.Range(.7f, 1f), Rand.Range(-40, 40), Rand.Range(0, 1f), Rand.Range(0, 360), Rand.Range(0, 360));
                    }
                }
                catch
                {
                    if (!this.CasterPawn.Spawned)
                    {
                        GenSpawn.Spawn(p, cell, map);
                        Log.Message("Exception occured when trying to blink - recovered pawn at position ability was used from.");
                    }
                }

                result = true;
            }
            else
            {
                Messages.Message("InvalidTargetLocation".Translate(), MessageTypeDefOf.RejectInput);
            }
            this.burstShotsLeft = 0;
            return(result);
        }
Exemplo n.º 21
0
        public void SpawnRadiationMote()
        {
            if (linked == null)
            {
                return;
            }


            CompPropertiesIrradiator moteProps = MoteProps;

            if (moteProps?.motes == null || !moteProps.motes.Any())
            {
                return;
            }

            var def = moteProps.motes.RandomElement();

            if (def.skip)
            {
                return;
            }

            if (def.speed.max < 0.5f)
            {
                if (Rand.RangeInclusive(0, 5) > linked.Position.DistanceTo(parent.Position))
                {
                    return;
                }
            }

            MoteRadiation moteThrown = ThingMaker.MakeThing(def.mote, null) as MoteRadiation;

            if (moteThrown == null)
            {
                return;
            }

            Vector3 origin      = parent.ExactPosition();
            Vector3 destination = linked.ExactPosition();

            origin.y = destination.y;
            Vector3 sideways = (destination - origin).normalized.RotatedBy(90);

            origin      += sideways * Rand.Range(-def.initialSpread, def.initialSpread);
            destination += sideways * Rand.Range(-def.spread, def.spread);

            float positionPercent = Mathf.Sqrt(Rand.Range(0f, 1f));
            float position        = def.offset.LerpThroughRange(positionPercent);
            float scale           = def.scaleRange.RandomInRange;

            Vector3 dir         = destination - origin;
            Vector3 startOffset = dir * position;
            float   angle       = startOffset.AngleFlat();

            moteThrown.exactPosition = origin + startOffset;
            moteThrown.exactRotation = angle;
            moteThrown.reflectAt     = motesReflectAt;
            moteThrown.reflectChance = def.reflectChance;

            Rot4 rot = Rotation();

            if (rot.IsHorizontal)
            {
                moteThrown.deathLocation      = linked.ExactPosition().x;
                moteThrown.isHorizontal       = true;
                moteThrown.reflectIndex       = rot == Rot4.West ? 0 : motesReflectAt.Count() - 1;
                moteThrown.reflectIndexChange = rot == Rot4.West ? 1 : -1;
            }
            else
            {
                moteThrown.deathLocation      = linked.ExactPosition().z;
                moteThrown.isHorizontal       = false;
                moteThrown.reflectIndex       = rot == Rot4.North ? 0 : motesReflectAt.Count() - 1;
                moteThrown.reflectIndexChange = rot == Rot4.North ? 1 : -1;
            }


            moteThrown.exactScale = new Vector3(scale, scale, scale);
            moteThrown.SetVelocity(angle, def.speed.RandomInRange);
            GenSpawn.Spawn(moteThrown, parent.Position, parent.Map, WipeMode.Vanish);
        }
Exemplo n.º 22
0
        protected virtual (bool success, Vector3 launchPos, float angle) TryCastShotInternal()
        {
            if (currentTarget.HasThing && currentTarget.Thing.Map != caster.Map)
            {
                return(false, Vector3.zero, 0);
            }
            ThingDef projectile = Projectile;

            if (projectile == null)
            {
                return(false, Vector3.zero, 0);
            }
            ShootLine shootLine;
            bool      flag = TryFindShootLineFromTo(caster.Position, currentTarget, out shootLine);

            if (verbProps.stopBurstWithoutLos && !flag)
            {
                return(false, Vector3.zero, 0);
            }
            if (EquipmentSource != null)
            {
                CompChangeableProjectile comp = EquipmentSource.GetComp <CompChangeableProjectile>();
                if (comp != null)
                {
                    comp.Notify_ProjectileLaunched();
                }
                CompReloadable comp2 = EquipmentSource.GetComp <CompReloadable>();
                if (comp2 != null)
                {
                    comp2.UsedOnce();
                }
            }
            Thing        launcher     = caster;
            Thing        equipment    = EquipmentSource;
            CompMannable compMannable = caster.TryGetComp <CompMannable>();

            if (compMannable != null && compMannable.ManningPawn != null)
            {
                launcher  = compMannable.ManningPawn;
                equipment = caster;
            }
            Vector3    launchPos   = caster.DrawPos;
            float      angle       = launchPos.AngleToPoint(currentTarget.CenterVector3);
            Projectile projectile2 = (Projectile)GenSpawn.Spawn(projectile, shootLine.Source, caster.Map, WipeMode.Vanish);

            if (caster.def.GetModExtension <ProjectilePropertiesDefModExtension>() is ProjectilePropertiesDefModExtension projectileProps)
            {
                projectile2.AllComps.Insert(0, new CompTurretProjectileProperties(CasterTWC)
                {
                    speed    = projectileProps.speed > 0 ? projectileProps.speed : projectile2.def.projectile.speed,
                    hitflag  = projectileProps.projectileHitFlag,
                    hitflags = projectileProps.hitFlagDef
                });
            }
            if (verbProps.forcedMissRadius > 0.5f)
            {
                float num = VerbUtility.CalculateAdjustedForcedMiss(verbProps.forcedMissRadius, currentTarget.Cell - caster.Position);
                if (num > 0.5f)
                {
                    int max  = GenRadial.NumCellsInRadius(num);
                    int num2 = Rand.Range(0, max);
                    if (num2 > 0)
                    {
                        IntVec3 c = currentTarget.Cell + GenRadial.RadialPattern[num2];
                        launchPos += new Vector3(VerbProps.shootOffset.x, 0, VerbProps.shootOffset.y).RotatedBy(angle);
                        ThrowDebugText("ToRadius");
                        ThrowDebugText("Rad\nDest", c);
                        ProjectileHitFlags projectileHitFlags = ProjectileHitFlags.NonTargetWorld;
                        if (Rand.Chance(0.5f))
                        {
                            projectileHitFlags = ProjectileHitFlags.All;
                        }
                        if (!canHitNonTargetPawnsNow)
                        {
                            projectileHitFlags &= ~ProjectileHitFlags.NonTargetPawns;
                        }
                        projectile2.Launch(launcher, launchPos, c, currentTarget, projectileHitFlags, equipment, null);
                        return(true, launchPos, angle);
                    }
                }
            }
            ShotReport shotReport            = ShotReport.HitReportFor(caster, this, currentTarget);
            Thing      randomCoverToMissInto = shotReport.GetRandomCoverToMissInto();
            ThingDef   targetCoverDef        = (randomCoverToMissInto != null) ? randomCoverToMissInto.def : null;

            if (!Rand.Chance(shotReport.AimOnTargetChance_IgnoringPosture))
            {
                shootLine.ChangeDestToMissWild(shotReport.AimOnTargetChance_StandardTarget);
                ThrowDebugText("ToWild" + (canHitNonTargetPawnsNow ? "\nchntp" : ""));
                ThrowDebugText("Wild\nDest", shootLine.Dest);
                ProjectileHitFlags projectileHitFlags2 = ProjectileHitFlags.NonTargetWorld;
                if (Rand.Chance(0.5f) && canHitNonTargetPawnsNow)
                {
                    projectileHitFlags2 |= ProjectileHitFlags.NonTargetPawns;
                }
                launchPos += new Vector3(VerbProps.shootOffset.x, 0, VerbProps.shootOffset.y).RotatedBy(angle);
                projectile2.Launch(launcher, launchPos, shootLine.Dest, currentTarget, projectileHitFlags2, equipment, targetCoverDef);
                return(true, launchPos, angle);
            }
            if (currentTarget.Thing != null && currentTarget.Thing.def.category == ThingCategory.Pawn && !Rand.Chance(shotReport.PassCoverChance))
            {
                ThrowDebugText("ToCover" + (canHitNonTargetPawnsNow ? "\nchntp" : ""));
                ThrowDebugText("Cover\nDest", randomCoverToMissInto.Position);
                ProjectileHitFlags projectileHitFlags3 = ProjectileHitFlags.NonTargetWorld;
                if (canHitNonTargetPawnsNow)
                {
                    projectileHitFlags3 |= ProjectileHitFlags.NonTargetPawns;
                }
                launchPos += new Vector3(VerbProps.shootOffset.x, 0, VerbProps.shootOffset.y).RotatedBy(angle);
                projectile2.Launch(launcher, launchPos, randomCoverToMissInto, currentTarget, projectileHitFlags3, equipment, targetCoverDef);
                return(true, launchPos, angle);
            }
            ProjectileHitFlags projectileHitFlags4 = ProjectileHitFlags.IntendedTarget;

            if (canHitNonTargetPawnsNow)
            {
                projectileHitFlags4 |= ProjectileHitFlags.NonTargetPawns;
            }
            if (!currentTarget.HasThing || currentTarget.Thing.def.Fillage == FillCategory.Full)
            {
                projectileHitFlags4 |= ProjectileHitFlags.NonTargetWorld;
            }
            ThrowDebugText("ToHit" + (canHitNonTargetPawnsNow ? "\nchntp" : ""));

            if (currentTarget.Thing != null)
            {
                angle      = launchPos.AngleToPoint(currentTarget.CenterVector3);
                launchPos += new Vector3(VerbProps.shootOffset.x, 0, VerbProps.shootOffset.y).RotatedBy(angle);
                projectile2.Launch(launcher, launchPos, currentTarget, currentTarget, projectileHitFlags4, equipment, targetCoverDef);
                ThrowDebugText("Hit\nDest", currentTarget.Cell);
            }
            else
            {
                angle      = launchPos.AngleToPoint(shootLine.Dest.ToVector3Shifted());
                launchPos += new Vector3(VerbProps.shootOffset.x, 0, VerbProps.shootOffset.y).RotatedBy(angle);
                projectile2.Launch(launcher, launchPos, shootLine.Dest, currentTarget, projectileHitFlags4, equipment, targetCoverDef);
                ThrowDebugText("Hit\nDest", shootLine.Dest);
            }
            return(true, launchPos, angle);
        }
Exemplo n.º 23
0
        public static bool Spawn(ref Thing __result,
                                 Thing newThing,
                                 IntVec3 loc,
                                 Map map,
                                 Rot4 rot,
                                 WipeMode wipeMode        = WipeMode.Vanish,
                                 bool respawningAfterLoad = false)
        {
            if (map == null)
            {
                Log.Error("Tried to spawn " + newThing.ToStringSafe <Thing>() + " in a null map.", false);
                __result = (Thing)null;
                return(false);
            }
            if (!loc.InBounds(map))
            {
                Log.Error("Tried to spawn " + newThing.ToStringSafe <Thing>() + " out of bounds at " + (object)loc + ".", false);
                __result = (Thing)null;
                return(false);
            }
            if (null != newThing)
            {
                if (null != newThing.def)
                {
                    if (newThing.def.randomizeRotationOnSpawn)
                    {
                        rot = Rot4.Random;
                    }
                    CellRect occupiedRect = GenAdj.OccupiedRect(loc, rot, newThing.def.Size);
                    if (!occupiedRect.InBounds(map))
                    {
                        Log.Error("Tried to spawn " + newThing.ToStringSafe <Thing>() + " out of bounds at " + (object)loc + " (out of bounds because size is " + (object)newThing.def.Size + ").", false);
                        __result = (Thing)null;
                        return(false);
                    }
                    if (newThing.Spawned)
                    {
                        Log.Error("Tried to spawn " + (object)newThing + " but it's already spawned.", false);
                        __result = newThing;
                        return(false);
                    }
                    switch (wipeMode)
                    {
                    case WipeMode.Vanish:
                        GenSpawn.WipeExistingThings(loc, rot, (BuildableDef)newThing.def, map, DestroyMode.Vanish);
                        break;

                    case WipeMode.FullRefund:
                        GenSpawn.WipeAndRefundExistingThings(loc, rot, (BuildableDef)newThing.def, map);
                        break;

                    case WipeMode.VanishOrMoveAside:
                        GenSpawn.CheckMoveItemsAside(loc, rot, newThing.def, map);
                        GenSpawn.WipeExistingThings(loc, rot, (BuildableDef)newThing.def, map, DestroyMode.Vanish);
                        break;
                    }
                    if (newThing.def.category == ThingCategory.Item)
                    {
                        foreach (IntVec3 intVec3 in occupiedRect)
                        {
                            foreach (Thing thing in intVec3.GetThingList(map).ToList <Thing>())
                            {
                                if (thing != newThing && thing.def.category == ThingCategory.Item)
                                {
                                    thing.DeSpawn(DestroyMode.Vanish);
                                    if (!GenPlace.TryPlaceThing(thing, intVec3, map, ThingPlaceMode.Near, (Action <Thing, int>)null, (Predicate <IntVec3>)(x => !occupiedRect.Contains(x)), new Rot4()))
                                    {
                                        thing.Destroy(DestroyMode.Vanish);
                                    }
                                }
                            }
                        }
                    }
                    newThing.Rotation = rot;
                    newThing.Position = loc;
                    if (newThing.holdingOwner != null)
                    {
                        newThing.holdingOwner.Remove(newThing);
                    }
                    newThing.SpawnSetup(map, respawningAfterLoad);
                    if (newThing.Spawned && newThing.stackCount == 0)
                    {
                        Log.Error("Spawned thing with 0 stackCount: " + (object)newThing, false);
                        newThing.Destroy(DestroyMode.Vanish);
                        __result = (Thing)null;
                        return(false);
                    }
                    if (newThing.def.passability == Traversability.Impassable)
                    {
                        foreach (IntVec3 c in occupiedRect)
                        {
                            foreach (Thing thing in c.GetThingList(map).ToList <Thing>())
                            {
                                if (thing != newThing && thing is Pawn pawn)
                                {
                                    pawn.pather.TryRecoverFromUnwalkablePosition(false);
                                }
                            }
                        }
                    }
                }
            }
            __result = newThing;
            return(false);
        }
Exemplo n.º 24
0
        public void SingleSpawnLoop(SpawnThings spawnables, IntVec3 position, Map map)
        {
            bool flag = spawnables.def != null;

            if (flag)
            {
                Faction faction = this.sustainerPawn.Faction;
                bool    flag2   = spawnables.def.race != null;
                if (flag2)
                {
                    bool flag3 = spawnables.kindDef == null;
                    if (flag3)
                    {
                        Log.Error("Missing kinddef");
                    }
                    else
                    {
                        newPawn = (TMPawnSummoned)PawnGenerator.GeneratePawn(spawnables.kindDef, faction);
                        newPawn.validSummoning = true;
                        newPawn.Temporary      = false;
                        //if (newPawn.Faction != Faction.OfPlayerSilentFail)
                        //{
                        //    newPawn.SetFaction(this.Caster.Faction, null);
                        //}
                        try
                        {
                            GenSpawn.Spawn(newPawn, position, map, Rot4.North, WipeMode.Vanish, false);
                            //GenPlace.TryPlaceThing(newPawn, position, map, ThingPlaceMode.Near, null, null);
                            CompSentinel compSentinel = newPawn.TryGetComp <CompSentinel>();
                            compSentinel.target        = this.hostilePawn;
                            compSentinel.sentinelLoc   = position;
                            compSentinel.rotation      = this.Rotation;
                            compSentinel.sustainerPawn = this.sustainerPawn;
                        }
                        catch
                        {
                            Log.Message("TM_Exception".Translate(
                                            "sentinel building",
                                            this.def.defName
                                            ));
                            this.Destroy(DestroyMode.Vanish);
                        }

                        if (newPawn.Faction != null && newPawn.Faction != Faction.OfPlayer)
                        {
                            try
                            {
                                Lord lord = null;
                                if (newPawn.Map.mapPawns.SpawnedPawnsInFaction(faction).Any((Pawn p) => p != newPawn))
                                {
                                    Predicate <Thing> validator = (Thing p) => p != newPawn && ((Pawn)p).GetLord() != null;
                                    Pawn p2 = (Pawn)GenClosest.ClosestThing_Global(newPawn.Position, newPawn.Map.mapPawns.SpawnedPawnsInFaction(faction), 99999f, validator, null);
                                    lord = p2.GetLord();
                                }
                                bool flag4 = lord == null;
                                if (flag4)
                                {
                                    LordJob_DefendPoint lordJob = new LordJob_DefendPoint(newPawn.Position);
                                    lord = LordMaker.MakeNewLord(faction, lordJob, map, null);
                                }
                                lord.AddPawn(newPawn);
                            }
                            catch (NullReferenceException ex)
                            {
                                //
                            }
                        }
                    }
                }
                else
                {
                    Log.Message("Missing race");
                }
            }
        }
        public override void DoEffect(Pawn usedBy)
        {
            if (this.target != null && !this.GetTargetingParameters().CanTarget(this.target))
            {
                return;
            }
            base.DoEffect(usedBy);
            if (this.parent.Stuff == null)
            {
                this.parent.SetStuffDirect(ThingDefOf.Cloth);
            }

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

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


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

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

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


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

            this.getPlacements(this.targetPos);

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

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


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

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

            return;
        }
        public void SingleSpawnLoop(SpawnThings spawnables, IntVec3 position, Map map)
        {
            bool flag = spawnables.def != null;

            if (flag)
            {
                Faction faction = pawn.Faction;
                bool    flag2   = spawnables.def.race != null;
                if (flag2)
                {
                    bool flag3 = spawnables.kindDef == null;
                    if (flag3)
                    {
                        Log.Error("Missing kinddef");
                    }
                    else
                    {
                        newPawn = (TMPawnSummoned)PawnGenerator.GeneratePawn(spawnables.kindDef, faction);
                        newPawn.validSummoning = true;
                        newPawn.Spawner        = this.Caster;
                        newPawn.Temporary      = true;
                        newPawn.TicksToDestroy = this.duration;
                        //if (newPawn.Faction != Faction.OfPlayerSilentFail)
                        //{
                        //    newPawn.SetFaction(this.Caster.Faction, null);
                        //}
                        try
                        {
                            GenSpawn.Spawn(newPawn, position, map, Rot4.North, WipeMode.Vanish, false);
                            //GenPlace.TryPlaceThing(newPawn, position, map, ThingPlaceMode.Near, null, null);
                        }
                        catch
                        {
                            pawn.GetComp <CompAbilityUserMagic>().Mana.CurLevel += pawn.GetComp <CompAbilityUserMagic>().ActualManaCost(TorannMagicDefOf.TM_SummonElemental);
                            Log.Message("TM_Exception".Translate(
                                            pawn.LabelShort,
                                            this.def.defName
                                            ));
                            this.Destroy(DestroyMode.Vanish);
                        }
                        if (newPawn.Faction != null && newPawn.Faction != Faction.OfPlayer)
                        {
                            Lord lord = null;
                            if (newPawn.Map.mapPawns.SpawnedPawnsInFaction(faction).Any((Pawn p) => p != newPawn))
                            {
                                Predicate <Thing> validator = (Thing p) => p != newPawn && ((Pawn)p).GetLord() != null;
                                Pawn p2 = (Pawn)GenClosest.ClosestThing_Global(newPawn.Position, newPawn.Map.mapPawns.SpawnedPawnsInFaction(faction), 99999f, validator, null);
                                lord = p2.GetLord();
                            }
                            bool flag4 = lord == null;
                            if (flag4)
                            {
                                LordJob_DefendPoint lordJob = new LordJob_DefendPoint(newPawn.Position);
                                lord = LordMaker.MakeNewLord(faction, lordJob, map, null);
                            }
                            else
                            {
                                try
                                {
                                    //PawnDuty duty = this.pawn.mindState.duty;
                                    newPawn.mindState.duty = new PawnDuty(DutyDefOf.Defend);
                                }
                                catch
                                {
                                    Log.Message("error attempting to assign a duty to elemental");
                                }
                            }
                            lord.AddPawn(newPawn);
                        }
                    }
                }
                else
                {
                    Log.Message("Missing race");
                }
            }
        }
        /// <summary>
        ///     Tries to revert the given pawn.
        /// </summary>
        /// <param name="transformedPawn">The transformed pawn.</param>
        /// <returns></returns>
        public override bool TryRevert(Pawn transformedPawn)
        {
            Tuple <TransformedPawn, TransformedStatus> status = GameComp.GetTransformedPawnContaining(transformedPawn);

            if (status != null)
            {
                if (status.Item2 != TransformedStatus.Transformed)
                {
                    return(false);
                }
                if (status.Item1 is TransformedPawnSingle inst)
                {
                    if (TryRevertImpl(inst))
                    {
                        GameComp.RemoveInstance(inst);
                        return(true);
                    }
                    else
                    {
                        Log.Warning($"could not revert original pawn instance {inst}");
                    }
                }
                else
                {
                    Log.Warning($"{nameof(SimpleMechaniteMutagen)} received \"{status.Item1?.GetType()?.Name ??"NULL"}\" but was expecting \"{nameof(TransformedPawnSingle)}\"");
                }
                return(false);
            }
            else
            {
                Log.Warning($"unable to find status for transformed pawn {transformedPawn.ThingID}");
            }

            Hediff formerHuman =
                transformedPawn.health.hediffSet.hediffs.FirstOrDefault(h => h.def == TfHediffDefOf.TransformedHuman);

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

            PawnGenerationRequest request = TransformerUtility.GenerateRandomPawnFromAnimal(transformedPawn);



            Pawn pawnTf = PawnGenerator.GeneratePawn(request);

            pawnTf.needs.food.CurLevel = transformedPawn.needs.food.CurLevel;
            pawnTf.needs.rest.CurLevel = transformedPawn.needs.rest.CurLevel;
            Log.Message($"going to spawn {pawnTf.Name} {pawnTf.KindLabel}");
            var spawned = (Pawn)GenSpawn.Spawn(pawnTf, transformedPawn.GetCorrectPosition(), transformedPawn.GetCorrectMap());

            spawned.equipment.DestroyAllEquipment();
            spawned.apparel.DestroyAll();

            if (transformedPawn.Name is NameTriple nT)
            {
                spawned.Name = nT; //give the new random pawn the same name as the former human
            }


            for (var i = 0; i < 10; i++)
            {
                IntermittentMagicSprayer.ThrowMagicPuffDown(spawned.GetCorrectPosition().ToVector3(), spawned.GetCorrectMap());
                IntermittentMagicSprayer.ThrowMagicPuffUp(spawned.GetCorrectPosition().ToVector3(), spawned.GetCorrectMap());
            }


            AddReversionThought(spawned, formerHuman.CurStageIndex);



            transformedPawn.Destroy();
            return(true);
        }
Exemplo n.º 28
0
        public static void GenerateOutpost(OG_OutpostData outpostDataParameter)
        {
            outpostData = outpostDataParameter;
            outpostData.triggerIntrusion = null;
            outpostData.outpostThingList = new List <Thing>();

            // Reset zoneMap.
            for (int zoneOrd = 0; zoneOrd < verticalZonesNumber; zoneOrd++)
            {
                for (int zoneAbs = 0; zoneAbs < horizontalZonesNumber; zoneAbs++)
                {
                    zoneMap[zoneOrd, zoneAbs] = new ZoneProperties(ZoneType.NotYetGenerated, Rot4.North, Rot4.North);
                }
            }
            // Clear the whole area and remove any roof.
            CellRect rect = new CellRect(outpostData.areaSouthWestOrigin.x - 1, outpostData.areaSouthWestOrigin.z - 1, areaSideLength + 2, areaSideLength + 2);

            foreach (IntVec3 cell in rect.Cells)
            {
                Find.RoofGrid.SetRoof(cell, null);
                List <Thing> thingList = cell.GetThingList();
                for (int j = thingList.Count - 1; j >= 0; j--)
                {
                    Thing thing = thingList[j];
                    if (thing.def.destroyable)
                    {
                        thing.Destroy(DestroyMode.Vanish);
                    }
                }
            }
            // Create the intrusion trigger.
            outpostData.triggerIntrusion = (TriggerIntrusion)ThingMaker.MakeThing(ThingDef.Named("TriggerIntrusion"));
            GenSpawn.Spawn(outpostData.triggerIntrusion, rect.Center);

            GenerateOutpostLayout();

            // TODO: debug. Display the generated layout.

            /*for (int zoneOrd = 0; zoneOrd < verticalZonesNumber; zoneOrd++)
             * {
             *  for (int zoneAbs = 0; zoneAbs < horizontalZonesNumber; zoneAbs++)
             *  {
             *      ZoneProperties zone = zoneMap[zoneOrd, zoneAbs];
             *      Log.Message("Layout: zoneMap[" + zoneOrd + "," + zoneAbs + "] => " + zone.zoneType.ToString() + "," + zone.rotation.ToString() + "," + zone.linkedZoneRelativeRotation.ToString());
             *  }
             * }*/
            GenerateOutpostZones(outpostData.areaSouthWestOrigin);

            IntVec3 mainRoomZoneOrigin = Zone.GetZoneOrigin(outpostData.areaSouthWestOrigin, mainRoomZoneAbs, mainRoomZoneOrd);

            OG_Common.GenerateSas(mainRoomZoneOrigin + new IntVec3(5, 0, 10), Rot4.North, 3, smallRoomWallOffset * 2, ref outpostData);
            OG_Common.GenerateSas(mainRoomZoneOrigin + new IntVec3(10, 0, 5), Rot4.East, 3, smallRoomWallOffset * 2, ref outpostData);
            OG_Common.GenerateSas(mainRoomZoneOrigin + new IntVec3(5, 0, 0), Rot4.South, 3, smallRoomWallOffset * 2, ref outpostData);
            OG_Common.GenerateSas(mainRoomZoneOrigin + new IntVec3(0, 0, 5), Rot4.West, 3, smallRoomWallOffset * 2, ref outpostData);

            // Generate laser fences.
            OG_LaserFence.GenerateLaserFence(zoneMap, ref outpostData);
            // Generate battle remains.
            OG_WarfieldEffects.GenerateWarfieldEffects(zoneMap, horizontalZonesNumber, verticalZonesNumber, outpostData);
            // Damage outpost to reflect its history.
            OG_RuinEffects.GenerateRuinEffects(ref outpostData);
            // Don't generate permanent inhabitants for small outposts. Those are just used as a shack by exploration teams.

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

            SendWelcomeLetter(outpostData);
        }
Exemplo n.º 29
0
        public static BomberSkyfaller SpawnSkyfaller(ThingDef skyfaller, ThingDef innerThing, IntVec3 pos, Map map)
        {
            BomberSkyfaller thing = BomberSkyfallerMaker.MakeSkyfaller(skyfaller, innerThing);

            return((BomberSkyfaller)GenSpawn.Spawn(thing, pos, map, WipeMode.Vanish));
        }
Exemplo n.º 30
0
        /// <summary>
        ///     Tries to revert the given pawn.
        /// </summary>
        /// <param name="transformedPawn">The transformed pawn.</param>
        /// <returns></returns>
        public override bool TryRevert(Pawn transformedPawn)
        {
            if (transformedPawn == null)
            {
                throw new ArgumentNullException(nameof(transformedPawn));
            }

            var pawnStatus = GameComp.GetTransformedPawnContaining(transformedPawn);
            var sState     = transformedPawn.GetSapienceState();

            if (sState == null)
            {
                return(false);
            }
            if (pawnStatus != null)
            {
                if (pawnStatus.Value.status != TransformedStatus.Transformed)
                {
                    return(false);
                }
                if (pawnStatus.Value.pawn is MergedPawns merged)
                {
                    if (sState.StateDef != def.transformedSapienceState)
                    {
                        return(false);
                    }

                    if (TryRevertImpl(merged))
                    {
                        GameComp.RemoveInstance(merged);
                        return(true);
                    }
                }

                return(false);
            }


            if (sState.StateDef == def.transformedSapienceState)
            {
                ThoughtDef thoughtDef = null;

                for (var i = 0; i < 2; i++)
                {
                    PawnGenerationRequest request = TransformerUtility.GenerateRandomPawnFromAnimal(transformedPawn);
                    Pawn pawnTf = PawnGenerator.GeneratePawn(request);
                    pawnTf.needs.food.CurLevel = transformedPawn.needs.food.CurInstantLevel;
                    pawnTf.needs.rest.CurLevel = transformedPawn.needs.rest.CurLevel;

                    var spawnedPawn = (Pawn)GenSpawn.Spawn(pawnTf, transformedPawn.PositionHeld, transformedPawn.MapHeld);
                    spawnedPawn.apparel.DestroyAll();
                    spawnedPawn.equipment.DestroyAllEquipment();
                    for (var j = 0; j < 10; j++)
                    {
                        IntermittentMagicSprayer.ThrowMagicPuffDown(spawnedPawn.Position.ToVector3(), spawnedPawn.MapHeld);
                        IntermittentMagicSprayer.ThrowMagicPuffUp(spawnedPawn.Position.ToVector3(), spawnedPawn.MapHeld);
                    }

                    _scratchArray[i] = spawnedPawn;
                }
                PawnRelationDef relationDef;
                bool            relationIsMergeMate = thoughtDef == def.revertedThoughtGood;
                relationDef = relationIsMergeMate ? TfRelationDefOf.MergeMate : TfRelationDefOf.ExMerged;
                _scratchArray[0].relations.AddDirectRelation(relationDef, _scratchArray[1]);

                CheckForBrainDamage(transformedPawn, _scratchArray[0], _scratchArray[1]);
                transformedPawn.Destroy();



                return(true);
            }

            return(false);
        }