public override void Tick()
        {
            if (pawn.Map == null || pawn.InContainerEnclosed)
            {
                return;
            }

            if (relatedPawns == null)
            {
                relatedPawns = pawn.relations.RelatedPawns.ToList();
            }
            if (makeStartingPack)
            {
                MakeStartingPack();
            }

            if (pawn.IsHashIntervalTick(60))             // update per real second
            {
                if (!immuneToPackLoss)
                {
                    packLossStage = pawn.TryAddPackLossThought(relatedPawns, packLossStage);
                }

                UpdateResists();
                CheckBodyparts();
                UpdatePackHediffState(packHediffDef, relatedPawns);
                TryToTakeDownedOrDeadPawn(relatedPawns);
            }

            if (pawn.IsHashIntervalTick(2500) || pawnPosInQueue > -1)             // update per game hour
            {
                if (pawnPosInQueue > 0)
                {
                    pawnPosInQueue--;
                    return;
                }

                if (debug)
                {
                    Log.Message(pawn + " pawnPosInQueue = " + pawnPosInQueue);
                }

                TryToTakeDownedOrDeadPawn(relatedPawns);

                //Log.Message(pawn + " packmates count = " + relatedPawns.Count);
                relatedPawns = pawn.relations.RelatedPawns.ToList();
                //Log.Message(pawn + " packmates count = " + relatedPawns.Count);

                if (Rand.Chance(chanceToFilthPerHour))
                {
                    FilthMaker.MakeFilth(pawn.Position, pawn.Map, RimWorld.ThingDefOf.Filth_Dirt, pawn.LabelIndefinite(), 1);
                }

                UpdateRaceSpecificThoughts();
                TryMakeImmuneToPackLoss();
                UpdatePackHediff(relatedPawns);

                if (!pawn.Awake() || pawn.IsSlave())
                {
                    if (pawnPosInQueue == 0)
                    {
                        pawnPosInQueue = -1;
                    }
                    return;
                }

                if (TryRecruitAvaliPrisoner())
                {
                    return;
                }

                pawnTotalSkillCount = pawn.GetTotalSkillLevel();

                CheckPawnsInPack(relatedPawns);

                //if (debug) Log.Message(pawn + " packSize = " + pawnsInPack);
                //Log.Message("FreeColonists count = " + pawn.Map.mapPawns.FreeColonists.Count());

                //if (debug) Log.Message(pawn + " packSize = " + pawnsInPack);

                int currentPawnsInPack = pawnsInPack;
                TryMakePack();
                if (currentPawnsInPack < pawnsInPack)
                {
                    MakePawnKnowHisPackmates();
                    CheckPawnsInPack(relatedPawns);
                }

                if (pawnPosInQueue == 0)
                {
                    pawnPosInQueue = -1;
                }
            }
        }
Esempio n. 2
0
        protected void TrySpread()
        {
            IntVec3 intVec = base.Position;
            bool    flag;

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

            float chance;

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

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

            Rand.PopState();
            if (f)
            {
                if (!flag)
                {
                    CellRect startRect = CellRect.SingleCell(base.Position);
                    CellRect endRect   = CellRect.SingleCell(intVec);
                    if (!GenSight.LineOfSight(base.Position, intVec, base.Map, startRect, endRect, null))
                    {
                        return;
                    }
                    Spark spark;
                    if (this.def.projectile.damageDef == AdeptusDamageDefOf.OG_Chaos_Deamon_Warpfire)
                    {
                        spark = (Spark)GenSpawn.Spawn(AdeptusThingDefOf.OG_WarpSpark, base.Position, base.Map, WipeMode.Vanish);
                    }
                    else
                    {
                        spark = (Spark)GenSpawn.Spawn(ThingDefOf.Spark, base.Position, base.Map, WipeMode.Vanish);
                    }
                    spark.Launch(this, intVec, intVec, ProjectileHitFlags.All, null);
                }
                else
                {
                    if (this.def.projectile.damageDef == AdeptusDamageDefOf.OG_Chaos_Deamon_Warpfire)
                    {
                        WarpfireUtility.TryStartWarpfireIn(intVec, base.Map, 0.1f);
                    }
                    else
                    {
                        FireUtility.TryStartFireIn(intVec, base.Map, 0.1f);
                    }
                }
            }
        }
Esempio n. 3
0
        // Token: 0x0600219B RID: 8603 RVA: 0x000CBD34 File Offset: 0x000C9F34
        protected override bool TryCastShot()
        {
            if (this.currentTarget.HasThing && this.currentTarget.Thing.Map != this.caster.Map)
            {
                return(false);
            }
            ThingDef projectile = this.Projectile;

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

            if (this.verbProps.stopBurstWithoutLos && !flag)
            {
                return(false);
            }
            if (this.EquipmentSource != null)
            {
                CompChangeableProjectile comp = this.EquipmentSource.GetComp <CompChangeableProjectile>();
                if (comp != null)
                {
                    comp.Notify_ProjectileLaunched();
                }
            }
            Thing        launcher     = this.caster;
            Thing        equipment    = this.EquipmentSource;
            CompMannable compMannable = this.caster.TryGetComp <CompMannable>();

            if (compMannable != null && compMannable.ManningPawn != null)
            {
                launcher  = compMannable.ManningPawn;
                equipment = this.caster;
            }
            Vector3    drawPos     = this.caster.DrawPos;
            Projectile projectile2 = (Projectile)GenSpawn.Spawn(projectile, shootLine.Source, this.caster.Map, WipeMode.Vanish);

            if (this.verbProps.forcedMissRadius > 0.5f)
            {
                float num = VerbUtility.CalculateAdjustedForcedMiss(this.verbProps.forcedMissRadius, this.currentTarget.Cell - this.caster.Position);
                if (num > 0.5f)
                {
                    int max  = GenRadial.NumCellsInRadius(num);
                    int num2 = Rand.Range(0, max);
                    if (num2 > 0)
                    {
                        IntVec3 c = this.currentTarget.Cell + GenRadial.RadialPattern[num2];
                        this.ThrowDebugText("ToRadius");
                        this.ThrowDebugText("Rad\nDest", c);
                        ProjectileHitFlags projectileHitFlags = ProjectileHitFlags.NonTargetWorld;
                        if (Rand.Chance(0.5f))
                        {
                            projectileHitFlags = ProjectileHitFlags.All;
                        }
                        if (!this.canHitNonTargetPawnsNow)
                        {
                            projectileHitFlags &= ~ProjectileHitFlags.NonTargetPawns;
                        }
                        projectile2.Launch(launcher, drawPos, c, this.currentTarget, projectileHitFlags, equipment, null);
                        return(true);
                    }
                }
            }
            ShotReport shotReport            = ShotReport.HitReportFor(this.caster, this, this.currentTarget);
            Thing      randomCoverToMissInto = shotReport.GetRandomCoverToMissInto();
            ThingDef   targetCoverDef        = (randomCoverToMissInto != null) ? randomCoverToMissInto.def : null;

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

            if (this.canHitNonTargetPawnsNow)
            {
                projectileHitFlags4 |= ProjectileHitFlags.NonTargetPawns;
            }
            if (!this.currentTarget.HasThing || this.currentTarget.Thing.def.Fillage == FillCategory.Full)
            {
                projectileHitFlags4 |= ProjectileHitFlags.NonTargetWorld;
            }
            this.ThrowDebugText("ToHit" + (this.canHitNonTargetPawnsNow ? "\nchntp" : ""));
            if (this.currentTarget.Thing != null)
            {
                projectile2.Launch(launcher, drawPos, this.currentTarget, this.currentTarget, projectileHitFlags4, equipment, targetCoverDef);
                this.ThrowDebugText("Hit\nDest", this.currentTarget.Cell);
            }
            else
            {
                projectile2.Launch(launcher, drawPos, shootLine.Dest, this.currentTarget, projectileHitFlags4, equipment, targetCoverDef);
                this.ThrowDebugText("Hit\nDest", shootLine.Dest);
            }
            return(true);
        }
Esempio n. 4
0
 public static void Postfix_QualityUtility_GenerateQualityCreatedByPawn(QualityCategory __result, Pawn pawn, SkillDef relevantSkill)
 {
     if (__result >= QualityCategory.Legendary)
     {
         bool generatePlotArmor = (relevantSkill == SkillDefOf.Artistic) ?
                                  Rand.Chance(PlotArmorUtility.GenerateChanceFromLegendaryArt) : Rand.Chance(PlotArmorUtility.GenerateChanceFromLegendaryItem);
         if (generatePlotArmor)
         {
             ThingDef stuff     = GenStuff.RandomStuffByCommonalityFor(PR_ThingDefOf.Apparel_PlotArmor);
             Thing    plotArmor = ThingMaker.MakeThing(PR_ThingDefOf.Apparel_PlotArmor, stuff);
             plotArmor.TryGetComp <CompQuality>().SetQuality(QualityUtility.AllQualityCategories.RandomElement(), ArtGenerationContext.Colony);
             GenSpawn.Spawn(plotArmor, pawn.Position, pawn.Map);
             Messages.Message("PlotArmorCreated".Translate(pawn.LabelShort), plotArmor, MessageTypeDefOf.PositiveEvent);
         }
     }
 }
        public bool AddNewBaby(Pawn mother, Pawn father)
        {
            float  melanin;
            string lastname;

            if (xxx.is_human(mother))
            {
                if (xxx.is_human(father))
                {
                    melanin = ChildRelationUtility.GetRandomChildSkinColor(father.story?.melanin ?? 0f, mother.story?.melanin ?? 0f);
                    //melanin = (mother.story?.melanin ?? 0f + father.story?.melanin ?? 0f) / 2;
                    lastname = NameTriple.FromString(father.Name.ToStringFull).Last;
                }
                else
                {
                    melanin  = mother.story?.melanin ?? 0f;
                    lastname = NameTriple.FromString(mother.Name.ToStringFull).Last;
                }
            }
            else if (xxx.is_human(father))
            {
                melanin  = father.story?.melanin ?? 0f;
                lastname = NameTriple.FromString(father.Name.ToStringFull).Last;
            }
            else
            {
                melanin  = Rand.Range(0, 1.0f);
                lastname = "";
            }

            PawnGenerationRequest request = new PawnGenerationRequest(
                newborn: true,
                allowDowned: true,
                faction: mother.IsPrisoner ? null : mother.Faction,
                canGeneratePawnRelations: false,
                forceGenerateNewPawn: true,
                colonistRelationChanceFactor: 0,
                allowFood: false,
                allowAddictions: false,
                relationWithExtraPawnChanceFactor: 0,
                fixedMelanin: melanin,
                fixedLastName: lastname,
                kind: BabyPawnKindDecider(mother, father)
                //fixedIdeo: mother.Ideo,
                //forbidAnyTitle: true,
                //forceNoBackstory:true
                );

            int         division       = 1;
            HairDef     firsthair      = null;
            Color       firsthaircolor = Color.white;
            BodyTypeDef firstbody      = null;
            CrownType   firstcrown     = CrownType.Undefined;
            string      firstheadpath  = null;
            string      firstHARcrown  = null;

            while (Rand.Chance(Configurations.EnzygoticTwinsChance) && division < Configurations.MaxEnzygoticTwins)
            {
                division++;
            }
            for (int i = 0; i < division; i++)
            {
                Pawn baby = GenerateBaby(request, mother, father);
                if (division > 1)
                {
                    if (i == 0 && baby.story != null)
                    {
                        firsthair           = baby.story.hairDef;
                        firsthaircolor      = baby.story.hairColor;
                        request.FixedGender = baby.gender;
                        firstbody           = baby.story.bodyType;
                        firstcrown          = baby.story.crownType;
                        firstheadpath       = (string)baby.story.GetMemberValue("headGraphicPath");
                        if (firstheadpath == null)
                        {
                            Graphic_Multi head = GraphicDatabaseHeadRecords.GetHeadRandom(baby.gender, baby.story.SkinColor, baby.story.crownType, true);
                            if (head != null)
                            {
                                baby.story.SetMemberValue("headGraphicPath", head.GraphicPath);
                            }
                            firstheadpath = (string)baby.story.GetMemberValue("headGraphicPath");
                        }
                        if (Configurations.HARActivated && baby.IsHAR())
                        {
                            firstHARcrown = baby.GetHARCrown();
                        }
                    }
                    else
                    {
                        if (baby.story != null)
                        {
                            baby.story.hairDef   = firsthair;
                            baby.story.hairColor = firsthaircolor;
                            baby.story.bodyType  = firstbody;
                            baby.story.crownType = firstcrown;
                            baby.story.SetMemberValue("headGraphicPath", firstheadpath);

                            if (Configurations.HARActivated && baby.IsHAR())
                            {
                                baby.SetHARCrown(firstHARcrown);
                            }
                        }
                    }
                }

                if (baby != null)
                {
                    babies.Add(baby);
                }
            }



            return(true);
        }
Esempio n. 6
0
        private bool CheckIntercept(Thing interceptorThing, CompProjectileInterceptor interceptorComp, bool withDebug = false)
        {
            Vector3 shieldPosition = interceptorThing.Position.ToVector3ShiftedWithAltitude(0.5f);
            float   radius         = interceptorComp.Props.radius;
            float   blockRadius    = radius + def.projectile.SpeedTilesPerTick + 0.1f;

            var newExactPos = ExactPosition;

            if ((newExactPos - shieldPosition).sqrMagnitude > Mathf.Pow(blockRadius, 2))
            {
                return(false);
            }
            if (!interceptorComp.Active)
            {
                return(false);
            }

            if (interceptorComp.Props.interceptGroundProjectiles && def.projectile.flyOverhead)
            {
                return(false);
            }

            if (interceptorComp.Props.interceptAirProjectiles && !def.projectile.flyOverhead)
            {
                return(false);
            }

            if ((launcher == null || !launcher.HostileTo(interceptorThing)) && !((bool)interceptDebug.GetValue(interceptorComp)) && !interceptorComp.Props.interceptNonHostileProjectiles)
            {
                return(false);
            }
            if (!interceptorComp.Props.interceptOutgoingProjectiles && (shieldPosition - lastExactPos).sqrMagnitude <= Mathf.Pow((float)radius, 2))
            {
                return(false);
            }
            if (!IntersectLineSphericalOutline(shieldPosition, radius, lastExactPos, newExactPos))
            {
                return(false);
            }
            interceptAngleField.SetValue(interceptorComp, lastExactPos.AngleToFlat(interceptorThing.TrueCenter()));
            interceptTicksField.SetValue(interceptorComp, Find.TickManager.TicksGame);
            var areWeLucky = Rand.Chance((def.projectile as ProjectilePropertiesCE)?.empShieldBreakChance ?? 0);

            if (areWeLucky)
            {
                var firstEMPSecondaryDamage = (def.projectile as ProjectilePropertiesCE)?.secondaryDamage?.FirstOrDefault(sd => sd.def == DamageDefOf.EMP);
                if (def.projectile.damageDef == DamageDefOf.EMP)
                {
                    interceptBreakShield.Invoke(interceptorComp, new object[] { new DamageInfo(def.projectile.damageDef, def.projectile.damageDef.defaultDamage) });
                }
                else if (firstEMPSecondaryDamage != null)
                {
                    interceptBreakShield.Invoke(interceptorComp, new object[] { new DamageInfo(firstEMPSecondaryDamage.def, firstEMPSecondaryDamage.def.defaultDamage) });
                }
            }
            Effecter eff = new Effecter(EffecterDefOf.Interceptor_BlockedProjectile);

            eff.Trigger(new TargetInfo(newExactPos.ToIntVec3(), interceptorThing.Map, false), TargetInfo.Invalid);
            eff.Cleanup();
            return(true);
        }
        public override void Tick()
        {
            base.Tick();

            // Save the last known global target map. This is necessary for when targeting a pawn that is destroyed in a foreign map.
            // Note that this isn't a perfect fix: this isn't saved, so reloading the game will still cause a 'fake strike' where the laser will not spawn.
            if (globalTarget.IsValid && globalTarget.Map != null)
            {
                globalTargetMapLastKnown = globalTarget.Map;
            }

            if (globalTarget.HasThing && !globalTarget.ThingDestroyed)
                lastKnownThingLoc = globalTarget.Cell;
            else if (localTarget.HasThing && !localTarget.ThingDestroyed)
                lastKnownThingLoc = localTarget.Cell;

            beam?.Tick();

            if (!IsChargingUp && IsPoweringUp)
            {
                PoweringUpTicks++;

                if (PoweringUpTicks == TICKS_BEFORE_FIRING_LASER - 40 && Rand.Chance(EasterEggChance))
                {
                    DoEasterEgg();
                }

                if (PoweringUpTicks == TICKS_BEFORE_FIRING_LASER)
                {
                    StartFireLaser();
                }

                if (PoweringUpTicks == POWER_UP_TICKS)
                {
                    StartRealAttack();
                }
            }

            if (IsChargingUp)
            {
                BatComp.MaxStoredEnergy = CHARGE_WATT_DAYS;
                if (Math.Abs(BatComp.StoredEnergyPct - 1f) < 0.005f)
                {
                    // Now full on power!
                    IsChargingUp = false;
                    StartPowerUpSequence();
                }
            }
            else
            {
                BatComp.SetStoredEnergyPct(0f);
                BatComp.MaxStoredEnergy = 0;
            }
            if (IsOnCooldown)
            {
                CooldownTicks--;
            }

            if (soundSustainer != null)
            {
                if (soundSustainer.Ended)
                    soundSustainer = null;
                soundSustainer?.Maintain();
            }

            if (this.Spawned && !this.Destroyed)
                this.GunComp?.verbTracker?.VerbsTick();

            if(this.chargeEffect != null)
            {
                bool isActive = chargeEffect.gameObject.activeSelf;
                bool shouldBeActive = Find.CurrentMap == this.Map;

                if(isActive != shouldBeActive)
                    chargeEffect.gameObject.SetActive(shouldBeActive);
            }
        }
        protected override bool TryExecuteWorker(IncidentParms parms)
        {
            if (Settings.disableSkyMindSecurityStuff)
            {
                return(false);
            }

            List <Pawn> victims;
            var         cryptolockedThings = new List <string>();
            var         title = "";
            var         msg   = "";
            var         nbConnectedClients   = Utils.GCATPP.getNbThingsConnected();
            var         nbSurrogates         = Utils.GCATPP.getNbSurrogateAndroids();
            var         nbUnsecurisedClients = nbConnectedClients - Utils.GCATPP.getNbSlotSecurisedAvailable();

            LetterDef letter;

            var attackType = 1;
            var fee        = 0;


            if (nbSurrogates <= 0)
            {
                return(false);
            }


            if (nbUnsecurisedClients <= 0)
            {
                if (!Rand.Chance(Settings.riskSecurisedSecuritySystemGetVirus))
                {
                    return(false);
                }

                var nb = 0;


                nb = nbSurrogates / 2;
                nb = nb != 0 ? Rand.Range(1, nb + 1) : 1;

                letter = LetterDefOf.ThreatSmall;

                victims = Utils.GCATPP.getRandomSurrogateAndroids(nb);
                if (victims.Count == 0)
                {
                    return(false);
                }

                foreach (var v in victims)
                {
                    var csm = v.TryGetComp <CompSkyMind>();
                    var cas = v.TryGetComp <CompAndroidState>();
                    if (csm == null || cas == null)
                    {
                        continue;
                    }

                    csm.Infected = 4;


                    if (cas.surrogateController != null)
                    {
                        var cso = cas.surrogateController.TryGetComp <CompSurrogateOwner>();
                        cso?.disconnectControlledSurrogate(null);
                    }

                    var he = v.health.hediffSet.GetFirstHediffOfDef(Utils.hediffNoHost);
                    if (he != null)
                    {
                        v.health.RemoveHediff(he);
                    }

                    Utils.ignoredPawnNotifications = v;
                    Utils.VirusedRandomMentalBreak.RandomElement().Worker.TryStart(v, null, false);
                    Utils.ignoredPawnNotifications = null;
                }


                title = "ATPP_IncidentSurrogateHackingVirus".Translate();
                msg   = "ATPP_IncidentSurrogateHackingLiteDesc".Translate(nb);
            }
            else
            {
                letter = LetterDefOf.ThreatBig;

                attackType = Rand.Range(1, 4);

                var  nb   = 0;
                Lord lord = null;

                if (attackType != 3)
                {
                    nb = nbSurrogates / 2;
                    nb = nb != 0 ? Rand.Range(1, nb + 1) : 1;

                    var lordJob = new LordJob_AssaultColony(Faction.OfAncientsHostile, false, false, false, false, false);

                    lord = LordMaker.MakeNewLord(Faction.OfAncientsHostile, lordJob, Current.Game.CurrentMap);
                }
                else
                {
                    nb = nbSurrogates;
                }

                msg = "ATPP_IncidentSurrogateHackingHardDesc".Translate(nb) + "\n";

                switch (attackType)
                {
                case 1:
                    title = "ATPP_IncidentSurrogateHackingVirus".Translate();
                    msg  += "ATPP_IncidentVirusedDesc".Translate();
                    break;

                case 2:
                    title = "ATPP_IncidentSurrogateHackingExplosiveVirus".Translate();
                    msg  += "ATPP_IncidentVirusedExplosiveDesc".Translate();
                    break;

                case 3:
                    title = "ATPP_IncidentSurrogateHackingCryptolocker".Translate();
                    msg  += "ATPP_IncidentCryptolockerDesc".Translate();
                    break;
                }

                victims = Utils.GCATPP.getRandomSurrogateAndroids(nb);
                if (victims.Count != nb)
                {
                    return(false);
                }

                foreach (var v in victims)
                {
                    var csm = v.TryGetComp <CompSkyMind>();

                    v.mindState.canFleeIndividual = false;
                    csm.Infected = attackType;
                    if (v.jobs != null)
                    {
                        v.jobs.StopAll();
                        v.jobs.ClearQueuedJobs();
                    }

                    if (v.mindState != null)
                    {
                        v.mindState.Reset(true);
                    }


                    switch (attackType)
                    {
                    case 1:

                        if (lord != null)
                        {
                            lord.AddPawn(v);
                        }
                        break;

                    case 2:

                        if (lord != null)
                        {
                            lord.AddPawn(v);
                        }
                        break;

                    case 3:
                        cryptolockedThings.Add(v.GetUniqueLoadID());

                        switch (v.def.defName)
                        {
                        case Utils.M7:
                            fee += Settings.ransomCostT5;
                            break;

                        case Utils.HU:
                            fee += Settings.ransomCostT4;
                            break;

                        case Utils.T2:
                            fee += Settings.ransomCostT2;
                            break;

                        case Utils.T3:
                            fee += Settings.ransomCostT3;
                            break;

                        case Utils.T4:
                            fee += Settings.ransomCostT4;
                            break;

                        case Utils.T5:
                            fee += Settings.ransomCostT5;
                            break;

                        case Utils.T1:
                        default:
                            fee += Settings.ransomCostT1;
                            break;
                        }

                        break;
                    }

                    if (attackType != 1 && attackType != 2)
                    {
                        continue;
                    }

                    var shooting = v.skills.GetSkill(SkillDefOf.Shooting);
                    if (shooting != null && !shooting.TotallyDisabled)
                    {
                        shooting.levelInt = Rand.Range(3, 19);
                    }
                    var melee = v.skills.GetSkill(SkillDefOf.Melee);
                    if (melee != null && !melee.TotallyDisabled)
                    {
                        melee.levelInt = Rand.Range(3, 19);
                    }
                }
            }

            Find.LetterStack.ReceiveLetter(title, msg, letter, victims);


            if (attackType != 3)
            {
                return(true);
            }

            var faction = Find.FactionManager.RandomEnemyFaction();

            var ransom = (ChoiceLetter_RansomDemand)LetterMaker.MakeLetter(DefDatabase <LetterDef> .GetNamed("ATPP_CLPayCryptoRansom"));

            ransom.label              = "ATPP_CryptolockerNeedPayRansomTitle".Translate();
            ransom.text               = "ATPP_CryptolockerNeedPayRansom".Translate(faction.Name, fee);
            ransom.faction            = faction;
            ransom.radioMode          = true;
            ransom.fee                = fee;
            ransom.cryptolockedThings = cryptolockedThings;
            ransom.StartTimeout(60000);
            Find.LetterStack.ReceiveLetter(ransom);

            return(true);
        }
        public virtual bool CheckFail(ref Verb_Shoot __instance)
        {
            string msg        = string.Format("");
            Thing  gun        = __instance.EquipmentSource;
            bool   failed     = false;
            float  failChance = FailChance(gun, out string reliabilityString);

            if (failChance > 0f)
            {
                Rand.PushState();
                failed = Rand.Chance(failChance);
                Rand.PopState();
                if (Debug)
                {
                    Log.Message((GetsHot ? "Overheat" : "Jam") + " Chance: " + failChance + "% Result: " + (failed ? (GetsHot ? "Overheated" : "Jamed") : "Passed"));
                }
            }
            if (failed)
            {
                bool           stillFire         = true;
                bool           canDamageWeapon   = HotDamageWeapon || JamsDamageWeapon;
                MessageTypeDef msgDef            = GetsHot ? MessageTypeDefOf.NegativeHealthEvent : MessageTypeDefOf.SilentInput;
                float          extraWeaponDamage = HotDamageWeapon ? HotDamage : JamDamage;
                if (GetsHot)
                {
                    string    overheat     = "overheated";
                    string    causing      = "causing";
                    DamageDef damageDef    = __instance.Projectile.projectile.damageDef;
                    HediffDef HediffToAdd  = damageDef.hediff;
                    Pawn      launcherPawn = __instance.caster as Pawn;
                    Rand.PushState();
                    bool crit = Rand.Chance(GetsHotCritChance);
                    Rand.PopState();
                    bool critExplode = false;
                    if (crit)
                    {
                        overheat = "critically overheated";
                        if (GetsHotCritExplosion)
                        {
                            critExplode = Rand.Chance(GetsHotCritExplosionChance);
                            if (critExplode)
                            {
                                causing = "causing an explosion";
                                CriticalOverheatExplosion(__instance);
                            }
                        }
                    }
                    float ArmorPenetration = __instance.Projectile.projectile.GetArmorPenetration(__instance.EquipmentSource, null) * (crit ? 1f : 0.25f);
                    float DamageAmount     = __instance.Projectile.projectile.GetDamageAmount(__instance.EquipmentSource, null) * (crit ? 1f : 0.25f);
                    msg = string.Format("{0}'s {1} " + overheat + ". ({2} chance) " + causing + " {3} damage", __instance.caster.LabelCap, __instance.EquipmentSource.LabelCap, failChance.ToStringPercent(), DamageAmount);
                    float damageLeft = DamageAmount;
                    List <BodyPartTagDef> tagDefs = new List <BodyPartTagDef>()
                    {
                        BodyPartTagDefOf.ManipulationLimbDigit, BodyPartTagDefOf.ManipulationLimbSegment
                    };
                    List <BodyPartRecord> list = launcherPawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Outside, tagDefs).ToList <BodyPartRecord>();
                    if (!list.NullOrEmpty())
                    {
                        while (damageLeft > 0f && !list.NullOrEmpty())
                        {
                            Rand.PushState();
                            BodyPartRecord part = list.RandomElement();
                            list.Remove(part);
                            float maxPartDamage = Math.Min(damageLeft, launcherPawn.health.hediffSet.GetPartHealth(part));
                            float amount        = Rand.Range(1f, Math.Min(damageLeft, maxPartDamage));
                            Rand.PopState();
                            if (amount > 0)
                            {
                                /*
                                 * Hediff hediff = HediffMaker.MakeHediff(HediffToAdd, launcherPawn, part);
                                 * hediff.Severity = severity;
                                 * launcherPawn.health.AddHediff(hediff, part, null);
                                 */
                                DamageInfo info = new DamageInfo(damageDef, amount, ArmorPenetration, -1, __instance.EquipmentSource, part, __instance.EquipmentSource.def, DamageInfo.SourceCategory.ThingOrUnknown, __instance.CurrentTarget.Thing ?? null);
                                launcherPawn.TakeDamage(info);
                                damageLeft -= amount;
                            }
                        }
                    }
                }
                if (Jams)
                {
                    if (!__instance.GetsHot())
                    {
                        msg = string.Format("{0}'s {1} had a weapon jam. ({2} chance)", __instance.caster.LabelCap, __instance.EquipmentSource.LabelCap, failChance.ToStringPercent());
                    }
                    float defaultCooldownTime = __instance.verbProps.defaultCooldownTime * 2;
                    __instance.verbProps.defaultCooldownTime = defaultCooldownTime;
                    if (canDamageWeapon)
                    {
                        if (extraWeaponDamage != 0f)
                        {
                            if (__instance.EquipmentSource != null)
                            {
                                if (__instance.EquipmentSource.HitPoints - (int)extraWeaponDamage >= 0)
                                {
                                    __instance.EquipmentSource.HitPoints = __instance.EquipmentSource.HitPoints - (int)extraWeaponDamage;
                                }
                                else if (__instance.EquipmentSource.HitPoints - (int)extraWeaponDamage < 0)
                                {
                                    __instance.EquipmentSource.HitPoints = 0;
                                    __instance.EquipmentSource.Destroy();
                                }
                            }
                            if (__instance.HediffCompSource != null)
                            {
                                /*
                                 * if (__instance.HediffCompSource.parent.Part.HitPoints - (int)extraWeaponDamage >= 0)
                                 * {
                                 *  __instance.HediffCompSource.HitPoints = __instance.HediffCompSource.HitPoints - (int)extraWeaponDamage;
                                 * }
                                 * else if (__instance.HediffCompSource.HitPoints - (int)extraWeaponDamage < 0)
                                 * {
                                 *  __instance.HediffCompSource.HitPoints = 0;
                                 *  __instance.HediffCompSource.Destroy();
                                 * }
                                 */
                            }
                        }
                        else
                        {
                            if (__instance.EquipmentSource != null)
                            {
                                if (__instance.EquipmentSource.HitPoints > 0)
                                {
                                    __instance.EquipmentSource.HitPoints--;
                                }
                            }
                        }
                    }
                    if (__instance.EquipmentSource != null)
                    {
                        SpinningLaserGun spinner = __instance.EquipmentSource as SpinningLaserGun;
                        if (spinner != null)
                        {
                            spinner.state = SpinningLaserGunBase.State.Idle;
                            spinner.ReachRotationSpeed(0, 0);
                        }
                    }
                }
                Messages.Message(msg, msgDef);
            }
            return(failed);
        }
        protected override bool TryCastShot()
        {
            bool flag = false;

            this.TargetsAoE.Clear();
            //this.UpdateTargets();
            this.FindTargets();
            MagicPowerSkill ver = base.CasterPawn.GetComp <CompAbilityUserMagic>().MagicData.MagicPowerSkill_Rend.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_Rend_ver");

            verVal = ver.level;
            bool friendlyTarget = this.currentTarget != null && this.currentTarget.Thing != null && this.currentTarget.Thing.Faction != null && this.currentTarget.Thing.Faction == this.CasterPawn.Faction && this.currentTarget.Thing != this.CasterPawn;
            bool flag2          = (this.UseAbilityProps.AbilityTargetCategory != AbilityTargetCategory.TargetAoE && this.TargetsAoE.Count > 1) || friendlyTarget;

            if (flag2)
            {
                this.TargetsAoE.RemoveRange(0, this.TargetsAoE.Count - 1);
            }
            if (friendlyTarget)
            {
                Pawn pawn = this.currentTarget.Thing as Pawn;
                if (pawn != null && pawn.RaceProps.Humanlike && pawn.needs != null && pawn.needs.mood.thoughts != null)
                {
                    if (Rand.Chance(TM_Calc.GetSpellSuccessChance(this.CasterPawn, pawn, true)))
                    {
                        List <Thought_Memory> thoughts = pawn.needs.mood.thoughts.memories.Memories;
                        pawn.mindState.mentalStateHandler.TryStartMentalState(TorannMagicDefOf.WanderConfused, null, false, false, null, false);
                        for (int i = 0; i < thoughts.Count; i++)
                        {
                            pawn.needs.mood.thoughts.memories.RemoveMemory(thoughts[i]);
                            i--;
                        }
                        pawn.needs.mood.thoughts.memories.TryGainMemory(TorannMagicDefOf.TM_MemoryWipe, null);
                        Effects(pawn.Position);
                    }
                    else
                    {
                        MoteMaker.ThrowText(pawn.DrawPos, pawn.Map, "TM_ResistedSpell".Translate(), -1);
                    }
                }
            }
            else
            {
                for (int i = 0; i < this.TargetsAoE.Count; i++)
                {
                    Pawn newPawn = this.TargetsAoE[i].Thing as Pawn;
                    if (newPawn.RaceProps.IsFlesh && newPawn.RaceProps.Humanlike && newPawn.Faction != this.CasterPawn.Faction)
                    {
                        if (Rand.Chance(TM_Calc.GetSpellSuccessChance(this.CasterPawn, newPawn, true)))
                        {
                            TM_Action.DamageEntities(newPawn, null, 30, DamageDefOf.Stun, this.CasterPawn);
                            Effects(newPawn.Position);
                        }
                        else
                        {
                            MoteMaker.ThrowText(newPawn.DrawPos, newPawn.Map, "TM_ResistedSpell".Translate(), -1);
                        }
                    }
                }
            }
            this.PostCastShot(flag, out flag);
            return(flag);
        }
        private IEnumerable <DamageInfo> DamageInfosToApply(LocalTargetInfo target)
        {
            float            num = verbProps.AdjustedMeleeDamageAmount(this, CasterPawn);
            float            armorPenetration = verbProps.AdjustedArmorPenetration(this, CasterPawn);
            DamageDef        def = verbProps.meleeDamageDef;
            BodyPartGroupDef bodyPartGroupDef = null;
            HediffDef        hediffDef        = null;

            num = Rand.Range(num * 0.8f, num * 1.2f);
            if (CasterIsPawn)
            {
                bodyPartGroupDef = verbProps.AdjustedLinkedBodyPartsGroup(tool);
                if (num >= 1f)
                {
                    if (base.HediffCompSource != null)
                    {
                        hediffDef = base.HediffCompSource.Def;
                    }
                }
                else
                {
                    num = 1f;
                    def = DamageDefOf.Blunt;
                }
            }
            ThingDef   source     = (base.EquipmentSource == null) ? CasterPawn.def : base.EquipmentSource.def;
            Vector3    direction  = (target.Thing.Position - CasterPawn.Position).ToVector3();
            DamageInfo damageInfo = new DamageInfo(def, num, armorPenetration, -1f, caster, null, source);

            damageInfo.SetBodyRegion(BodyPartHeight.Undefined, BodyPartDepth.Outside);
            damageInfo.SetWeaponBodyPartGroup(bodyPartGroupDef);
            damageInfo.SetWeaponHediff(hediffDef);
            damageInfo.SetAngle(direction);
            yield return(damageInfo);

            if (tool != null && tool.extraMeleeDamages != null)
            {
                foreach (ExtraDamage extraMeleeDamage in tool.extraMeleeDamages)
                {
                    if (Rand.Chance(extraMeleeDamage.chance))
                    {
                        num        = extraMeleeDamage.amount;
                        num        = Rand.Range(num * 0.8f, num * 1.2f);
                        damageInfo = new DamageInfo(extraMeleeDamage.def, num, extraMeleeDamage.AdjustedArmorPenetration(this, CasterPawn), -1f, caster, null, source);
                        damageInfo.SetBodyRegion(BodyPartHeight.Undefined, BodyPartDepth.Outside);
                        damageInfo.SetWeaponBodyPartGroup(bodyPartGroupDef);
                        damageInfo.SetWeaponHediff(hediffDef);
                        damageInfo.SetAngle(direction);
                        yield return(damageInfo);
                    }
                }
            }
            if (surpriseAttack && ((verbProps.surpriseAttack != null && !verbProps.surpriseAttack.extraMeleeDamages.NullOrEmpty()) || (tool != null && tool.surpriseAttack != null && !tool.surpriseAttack.extraMeleeDamages.NullOrEmpty())))
            {
                IEnumerable <ExtraDamage> enumerable = Enumerable.Empty <ExtraDamage>();
                if (verbProps.surpriseAttack != null && verbProps.surpriseAttack.extraMeleeDamages != null)
                {
                    enumerable = enumerable.Concat(verbProps.surpriseAttack.extraMeleeDamages);
                }
                if (tool != null && tool.surpriseAttack != null && !tool.surpriseAttack.extraMeleeDamages.NullOrEmpty())
                {
                    enumerable = enumerable.Concat(tool.surpriseAttack.extraMeleeDamages);
                }
                foreach (ExtraDamage item in enumerable)
                {
                    int        num2 = GenMath.RoundRandom(item.AdjustedDamageAmount(this, CasterPawn));
                    float      armorPenetration2 = item.AdjustedArmorPenetration(this, CasterPawn);
                    DamageInfo damageInfo2       = new DamageInfo(item.def, num2, armorPenetration2, -1f, caster, null, source);
                    damageInfo2.SetBodyRegion(BodyPartHeight.Undefined, BodyPartDepth.Outside);
                    damageInfo2.SetWeaponBodyPartGroup(bodyPartGroupDef);
                    damageInfo2.SetWeaponHediff(hediffDef);
                    damageInfo2.SetAngle(direction);
                    yield return(damageInfo2);
                }
            }
        }
Esempio n. 12
0
        public override void CompTickRare()
        {
            base.CompTickRare();

            HeatDissipationCoefficient = parentArea * 0.1f;
            foreach (IntVec3 cell in GenAdj.CellsAdjacent8Way(parent))
            {
                float sum = 0;
                if (cell.GetCover(parent.Map) != null)
                {
                    sum = cell.GetCover(parent.Map).def.fillPercent;
                }
                HeatDissipationCoefficient += (1f - sum) * 0.2f;
            }
            //HeatDissipationCoefficient /= parent.def.size.x * parent.def.size.z;

            outSide = parent.GetRoom().UsesOutdoorTemperature;
            //if (outSide)
            //{
            //    heatStorage *= 0.9f;
            //}

            //if (energyStorage / energyStorageMax > 0.5)
            //{

            //精确一点,分多次计算
            float roomTemperature = parent.AmbientTemperature;

            for (remainderSec += 4.16666667f; remainderSec >= 1f; remainderSec--)
            {
                if (active)
                {
                    if (heatStorage > 200f)//0.15是之前产能公式在200~201的导数
                    {
                        heatStorage += (heatAccumulationRate * ((heatStorage - 200f) * 0.15f + 8.8125f) * produceEnergyPerSec) / parentArea;
                    }
                    else
                    {
                        heatStorage += (heatAccumulationRate * ProduceEnergy * 60f) / parentArea;
                    }
                }

                //}
                //else
                //{
                //    heatStorage = Mathf.Max(0, heatStorage - 1f);
                //}
                //热交换
                if (heatStorage > roomTemperature)
                {
                    //交换的热量=温差*导热系数*散热面积
                    float dltHeat = (heatStorage - roomTemperature) * HeatDissipationCoefficient * thermalConductivity;

                    //自身降低的温度=热量/面积
                    heatStorage -= dltHeat / parentArea;
                    //外部提高的温度(其实也是热量/面积),直接把热量丢到房间里去就行了
                    parent.GetRoomGroup()?.PushHeat(heatStorage);

                    //float dltHeat = GenTemperature.ControlTemperatureTempChange(parent.Position, parent.Map, (heatStorage-parent.AmbientTemperature)*0.5f, 1000f);
                    //RoomGroup rg = parent.GetRoomGroup();
                    //rg.Temperature += dltHeat;

                    //heatStorage -= dltHeat *0.5f *(float)rg.CellCount/9f;//Mathf.Max(0, (heatStorage - parent.AmbientTemperature) * 0.2f);
                    //不低于环境温度
                    heatStorage = Mathf.Max(roomTemperature, heatStorage, 0);
                    //zzLib.Log.Message("环境" + parent.AmbientTemperature + " 热量" + heatStorage + " 环境升温" + dltHeat);
                }
            }


            //过热
            if (heatStorage > 250f && Rand.Chance(0.1f))
            {
                GenExplosion.DoExplosion(parent.Position, parent.Map, 3.9f, DamageDefOf.Bomb, null, 25, -1f, null, null, null, null, null, 0f, 1, false, null, 0f, 1, 0f, false, null, null);

                if (!disableExplosionMessage)
                {
                    Messages.Message("OverHeatAndExplosion".Translate(), new LookTargets(parent), MessageTypeDefOf.ThreatSmall);
                    disableExplosionMessage = true;
                }
            }
            if (heatStorage > 225 && !disableOverHeatMessage)
            {
                Messages.Message("OverHeatAndStop".Translate(), new LookTargets(parent), MessageTypeDefOf.NegativeEvent);
                disableOverHeatMessage = true;
            }
            if (heatStorage < 150)
            {
                disableOverHeatMessage  = false;
                disableExplosionMessage = false;
            }
        }
        protected override bool TryExecuteWorker(IncidentParms parms)
        {
            if (!DropCellFinder.TryFindRaidDropCenterClose(spot: out IntVec3 dropSpot, map: (Map)parms.target))
            {
                return(false);
            }
            if (!FindAlliedWarringFaction(faction: out Faction faction))
            {
                return(false);
            }
            if (faction == null)
            {
                return(false);
            }

            bool   bamboozle           = false;
            string arrivalText         = string.Empty;
            int    factionGoodWillLoss = FactionInteractionDiplomacyTuningsBlatantlyCopiedFromPeaceTalks
                                         .GoodWill_FactionWarPeaceTalks_ImpactSmall.RandomInRange / 2;

            IncidentParms raidParms =
                StorytellerUtility.DefaultParmsNow(incCat: IncidentCategoryDefOf.ThreatBig, target: (Map)parms.target);

            raidParms.forced          = true;
            raidParms.faction         = faction.EnemyInFactionWar();
            raidParms.raidStrategy    = RaidStrategyDefOf.ImmediateAttack;
            raidParms.raidArrivalMode = PawnsArrivalModeDefOf.CenterDrop;
            raidParms.spawnCenter     = dropSpot;

            if (faction.EnemyInFactionWar().def.techLevel >= TechLevel.Industrial &&
                faction.EnemyInFactionWar().RelationKindWith(other: Faction.OfPlayer) == FactionRelationKind.Hostile)
            {
                bamboozle = Rand.Chance(chance: 0.25f);
            }

            if (bamboozle)
            {
                arrivalText = string.Format(format: raidParms.raidArrivalMode.textEnemy, arg0: raidParms.faction.def.pawnsPlural, arg1: raidParms.faction.Name);
            }

            //get combat-pawns to spawn.
            PawnGroupMakerParms defaultPawnGroupMakerParms = IncidentParmsUtility.GetDefaultPawnGroupMakerParms(groupKind: PawnGroupKindDefOf.Combat, parms: raidParms);

            defaultPawnGroupMakerParms.points = IncidentWorker_Raid.AdjustedRaidPoints(points: defaultPawnGroupMakerParms.points, raidArrivalMode: raidParms.raidArrivalMode, raidStrategy: raidParms.raidStrategy, faction: defaultPawnGroupMakerParms.faction, groupKind: PawnGroupKindDefOf.Combat);
            IEnumerable <PawnKindDef> pawnKinds = PawnGroupMakerUtility.GeneratePawnKindsExample(parms: defaultPawnGroupMakerParms).ToList();
            List <Thing> pawnlist = new List <Thing>();

            for (int i = 0; i < this.pawnstoSpawn.RandomInRange; i++)
            {
                PawnGenerationRequest request = new PawnGenerationRequest(kind: pawnKinds.RandomElement(), faction: faction, allowDowned: true, allowDead: true, mustBeCapableOfViolence: true);
                Pawn woundedCombatant         = PawnGenerator.GeneratePawn(request: request);
                woundedCombatant.guest.getRescuedThoughtOnUndownedBecauseOfPlayer = true;
                ThingDef weapon = Rand.Bool ? DefDatabase <ThingDef> .AllDefsListForReading.Where(predicate : x => x.IsWeaponUsingProjectiles).RandomElement() : null;

                ThingDef  usedWeaponDef = weapon;
                DamageDef damageDef     = usedWeaponDef?.Verbs?.First()?.defaultProjectile?.projectile?.damageDef; //null? check? All? THE? THINGS!!!!?
                if (usedWeaponDef != null && damageDef == null)
                {
                    usedWeaponDef = null;
                }
                CustomFaction_HealthUtility.DamageUntilDownedWithSpecialOptions(p: woundedCombatant, allowBleedingWounds: true, damageDef: damageDef, weapon: usedWeaponDef);
                //todo: maybe add some storylogging.
                pawnlist.Add(item: woundedCombatant);
            }

            string  initialMessage = "MFI_WoundedCombatant".Translate(faction.Name);
            DiaNode diaNode        = new DiaNode(text: initialMessage);

            DiaOption diaOptionOk = new DiaOption(text: "OK".Translate())
            {
                resolveTree = true
            };

            DiaOption diaOptionAccept = new DiaOption(text: "RansomDemand_Accept".Translate())
            {
                action = () =>
                {
                    if (bamboozle)
                    {
                        Find.TickManager.slower.SignalForceNormalSpeedShort();
                        IncidentDefOf.RaidEnemy.Worker.TryExecute(parms: raidParms);
                    }
                    else
                    {
                        IntVec3 intVec = IntVec3.Invalid;

                        List <Building> allBuildingsColonist = ((Map)parms.target).listerBuildings.allBuildingsColonist.Where(predicate: x => x.def.thingClass == typeof(Building_Bed)).ToList();
                        for (int i = 0; i < allBuildingsColonist.Count; i++)
                        {
                            if (DropCellFinder.TryFindDropSpotNear(center: allBuildingsColonist[index: i].Position, map: (Map)parms.target, result: out intVec, allowFogged: false, canRoofPunch: false))
                            {
                                break;
                            }
                        }
                        if (intVec == IntVec3.Invalid)
                        {
                            intVec = DropCellFinder.RandomDropSpot(map: (Map)parms.target);
                        }
                        DropPodUtility.DropThingsNear(dropCenter: intVec, map: (Map)parms.target, things: pawnlist, openDelay: 180, leaveSlag: true, canRoofPunch: false);
                        Find.World.GetComponent <WorldComponent_MFI_FactionWar>().NotifyBattleWon(faction: faction);
                    }
                }
            };
            string  bamboozledAndAmbushed = "MFI_WoundedCombatantAmbush".Translate(faction, arrivalText);
            string  commanderGreatful     = "MFI_WoundedCombatantGratitude".Translate();
            DiaNode acceptDiaNode         = new DiaNode(text: bamboozle ? bamboozledAndAmbushed : commanderGreatful);

            diaOptionAccept.link = acceptDiaNode;
            diaNode.options.Add(item: diaOptionAccept);
            acceptDiaNode.options.Add(item: diaOptionOk);

            DiaOption diaOptionRejection = new DiaOption(text: "RansomDemand_Reject".Translate())
            {
                action = () =>
                {
                    if (bamboozle)
                    {
                        Find.World.GetComponent <WorldComponent_MFI_FactionWar>().NotifyBattleWon(faction: faction);
                    }
                    else
                    {
                        faction.TryAffectGoodwillWith(other: Faction.OfPlayer, goodwillChange: factionGoodWillLoss, canSendMessage: false);
                    }
                }
            };
            string  rejectionResponse        = "MFI_WoundedCombatantRejected".Translate(faction.Name, factionGoodWillLoss);
            string  bamboozlingTheBamboozler = "MFI_WoundedCombatantAmbushAvoided".Translate();
            DiaNode rejectionDiaNode         = new DiaNode(text: bamboozle ? bamboozlingTheBamboozler : rejectionResponse);

            diaOptionRejection.link = rejectionDiaNode;
            diaNode.options.Add(item: diaOptionRejection);
            rejectionDiaNode.options.Add(item: diaOptionOk);

            string title = "MFI_WoundedCombatantTitle".Translate(((Map)parms.target).Parent.Label);

            Find.WindowStack.Add(window: new Dialog_NodeTreeWithFactionInfo(nodeRoot: diaNode, faction: faction, delayInteractivity: true, radioMode: true, title: title));
            Find.Archive.Add(archivable: new ArchivedDialog(text: diaNode.text, title: title, relatedFaction: faction));
            return(true);
        }
 private static void Postfix(Bill __instance, Pawn p)
 {
     if (p.HasTrait(VTEDefOf.VTE_Perfectionist) && __instance.recipe.workAmount > 2200 && Find.TickManager.TicksGame % GenDate.TicksPerHour * 3 == 0 && Rand.Chance(0.5f))
     {
         var unfinishedThing = p.CurJob.GetTarget(TargetIndex.B).Thing as UnfinishedThing;
         if (unfinishedThing != null)
         {
             unfinishedThing.Destroy();
             Messages.Message("VTE.HasDestroyedItem".Translate(p.Named("PAWN")), p, MessageTypeDefOf.NeutralEvent, historical: false);
         }
         Log.Message(p + " has Perfectionist trait and randomly decises interrupt current bill job");
         TraitUtils.TraitsManager.perfectionistsWithJobsToStop.Add(p);
     }
 }
        //
        // Static Methods
        //
        public static void GenerateRandomOldAgeInjuries(Pawn pawn, bool tryNotToKillPawn)
        {
            float num    = (!pawn.RaceProps.IsMechanoid) ? pawn.RaceProps.lifeExpectancy : 2500f;
            float num2   = num / 8f;
            float b      = num * 1.5f;
            float chance = (!pawn.RaceProps.Humanlike) ? 0.03f : 0.15f;
            int   num3   = 0;

            for (float num4 = num2; num4 < Mathf.Min((float)pawn.ageTracker.AgeBiologicalYears, b); num4 += num2)
            {
                if (Rand.Chance(chance))
                {
                    num3++;
                }
            }
            for (int i = 0; i < num3; i++)
            {
                IEnumerable <BodyPartRecord> source = from x in pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined, null)
                                                      where x.depth == BodyPartDepth.Outside && (x.def.permanentInjuryChanceFactor != 0f || x.def.pawnGeneratorCanAmputate) && !pawn.health.hediffSet.PartOrAnyAncestorHasDirectlyAddedParts(x)
                                                      select x;
                if (source.Any <BodyPartRecord>())
                {
                    BodyPartRecord bodyPartRecord      = source.RandomElementByWeight((BodyPartRecord x) => x.coverageAbs);
                    DamageDef      dam                 = AgeInjuryUtility.RandomPermanentInjuryDamageType(bodyPartRecord.def.frostbiteVulnerability > 0f && pawn.RaceProps.ToolUser);
                    HediffDef      hediffDefFromDamage = HealthUtility.GetHediffDefFromDamage(dam, pawn, bodyPartRecord);
                    if (bodyPartRecord.def.pawnGeneratorCanAmputate && Rand.Chance(0.3f))
                    {
                        Hediff_MissingPart hediff_MissingPart = (Hediff_MissingPart)HediffMaker.MakeHediff(HediffDefOf.MissingBodyPart, pawn, null);
                        hediff_MissingPart.lastInjury = hediffDefFromDamage;
                        hediff_MissingPart.Part       = bodyPartRecord;
                        hediff_MissingPart.IsFresh    = false;
                        if (!tryNotToKillPawn || !pawn.health.WouldDieAfterAddingHediff(hediff_MissingPart))
                        {
                            pawn.health.AddHediff(hediff_MissingPart, bodyPartRecord, null, null);
                            if (pawn.RaceProps.Humanlike && bodyPartRecord.def == BodyPartDefOf.Leg && Rand.Chance(0.5f))
                            {
                                RecipeDefOf.InstallPegLeg.Worker.ApplyOnPawn(pawn, bodyPartRecord, null, AgeInjuryUtility.emptyIngredientsList, null);
                            }
                        }
                    }
                    else if (bodyPartRecord.def.permanentInjuryChanceFactor > 0f && hediffDefFromDamage.HasComp(typeof(HediffComp_GetsPermanent)))
                    {
                        Hediff_Injury hediff_Injury = (Hediff_Injury)HediffMaker.MakeHediff(hediffDefFromDamage, pawn, null);
                        hediff_Injury.Severity = (float)Rand.RangeInclusive(2, 6);
                        hediff_Injury.TryGetComp <HediffComp_GetsPermanent>().IsPermanent = true;
                        hediff_Injury.Part = bodyPartRecord;
                        if (!tryNotToKillPawn || !pawn.health.WouldDieAfterAddingHediff(hediff_Injury))
                        {
                            pawn.health.AddHediff(hediff_Injury, bodyPartRecord, null, null);
                        }
                    }
                }
            }
            for (int j = 1; j < pawn.ageTracker.AgeBiologicalYears; j++)
            {
                foreach (HediffGiver_Birthday current in AgeInjuryUtility.RandomHediffsToGainOnBirthday(pawn, j))
                {
                    current.TryApplyAndSimulateSeverityChange(pawn, (float)j, tryNotToKillPawn);
                    if (pawn.Dead)
                    {
                        break;
                    }
                }
                if (pawn.Dead)
                {
                    break;
                }
            }
        }
Esempio n. 16
0
        protected override void Impact(Thing hitThing)
        {
            Map map = base.Map;

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

            if (!this.initialized)
            {
                caster = this.launcher as Pawn;
                CompAbilityUserMagic comp = caster.GetComp <CompAbilityUserMagic>();
                MagicPowerSkill      ver  = caster.GetComp <CompAbilityUserMagic>().MagicData.MagicPowerSkill_Resurrection.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_Resurrection_ver");
                verVal     = ver.level;
                this.angle = Rand.Range(-12f, 12f);

                IntVec3 curCell = base.Position;

                this.CheckSpawnSustainer();

                if (curCell.InBounds(map))
                {
                    Corpse       corpse = null;
                    List <Thing> thingList;
                    thingList = curCell.GetThingList(map);
                    int z = 0;
                    while (z < thingList.Count)
                    {
                        corpseThing = thingList[z];
                        if (corpseThing != null)
                        {
                            bool validator = corpseThing is Corpse;
                            if (validator)
                            {
                                corpse = corpseThing as Corpse;
                                CompRottable compRot = corpse.GetComp <CompRottable>();

                                deadPawn         = corpse.InnerPawn;
                                deadPawnPosition = corpse.Position;
                                if (deadPawn.RaceProps.IsFlesh && !TM_Calc.IsUndead(deadPawn) && compRot != null)
                                {
                                    if (!corpse.IsNotFresh())
                                    {
                                        z = thingList.Count;
                                        this.validTarget = true;
                                    }
                                    else
                                    {
                                        Messages.Message("TM_ResurrectionTargetExpired".Translate(), MessageTypeDefOf.RejectInput);
                                    }
                                }
                            }
                        }
                        z++;
                    }
                }
                this.initialized = true;
            }

            if (corpseThing.Position != this.deadPawnPosition || corpseThing.Map == null)
            {
                Log.Message("Corpse was moved or destroyed during resurrection process.");
                this.age = this.timeToRaise;
            }

            if (this.validTarget)
            {
                if (this.sustainer != null)
                {
                    this.sustainer.info.volumeFactor = this.age / this.timeToRaise;
                    this.sustainer.Maintain();
                    if (this.TicksLeft <= 0)
                    {
                        this.sustainer.End();
                        this.sustainer = null;
                    }
                }

                if (this.age + 1 == this.timeToRaise)
                {
                    TM_MoteMaker.MakePowerBeamMoteColor(base.Position, base.Map, this.radius * 3f, 2f, 2f, .1f, 1.5f, colorInt.ToColor);
                    if (this.deadPawn == null)
                    {
                        if (corpseThing != null)
                        {
                            Corpse corpse = corpseThing as Corpse;
                            if (corpse != null)
                            {
                                this.deadPawn = corpse.InnerPawn;
                            }
                        }
                    }
                    if (deadPawn != null)
                    {
                        if (!deadPawn.kindDef.RaceProps.Animal && deadPawn.kindDef.RaceProps.Humanlike)
                        {
                            ResurrectionUtility.ResurrectWithSideEffects(deadPawn);
                            SoundDef.Named("Thunder_OffMap").PlayOneShot(null);
                            SoundDef.Named("Thunder_OffMap").PlayOneShot(null);
                            using (IEnumerator <Hediff> enumerator = deadPawn.health.hediffSet.GetHediffs <Hediff>().GetEnumerator())
                            {
                                while (enumerator.MoveNext())
                                {
                                    Hediff rec = enumerator.Current;
                                    if (rec.def.defName == "ResurrectionPsychosis" || rec.def.defName == "Blindness")
                                    {
                                        if (Rand.Chance(verVal * .33f))
                                        {
                                            deadPawn.health.RemoveHediff(rec);
                                        }
                                    }
                                }
                            }
                            HealthUtility.AdjustSeverity(deadPawn, HediffDef.Named("TM_ResurrectionHD"), 1f);
                        }
                        if (deadPawn.kindDef.RaceProps.Animal)
                        {
                            ResurrectionUtility.Resurrect(deadPawn);
                            HealthUtility.AdjustSeverity(deadPawn, HediffDef.Named("TM_ResurrectionHD"), 1f);
                        }
                    }
                }
            }
            else
            {
                Messages.Message("TM_InvalidResurrection".Translate(
                                     caster.LabelShort
                                     ), MessageTypeDefOf.RejectInput);
                this.age = this.timeToRaise;
            }
            this.age++;
        }
        public override void CompPostPostRemoved()
        {
            Thing   hostThing = Pawn;
            Pawn    hostPawn  = Pawn;
            Map     spawnMap  = !Pawn.Dead ? Pawn.Map : Pawn.MapHeld;
            IntVec3 spawnLoc  = !Pawn.Dead ? Pawn.Position : Pawn.PositionHeld;

            foreach (IntVec3 loc in GenRadial.RadialCellsAround(spawnLoc, 1, false))
            {
                if (loc.Standable(spawnMap))
                {
                    spawnLoc = loc;
                    Rand.Chance(0.5f);
                    break;
                }
            }
            bool spawnLive = this.spawnLive;

            hostPawn.health.AddHediff(XenomorphDefOf.RRY_Hediff_Anesthetic);
            //    if ((hostPawn.health.hediffSet.HasHediff(XenomorphDefOf.RRY_XenomorphImpregnation) && !hasImpregnated))
            if (!hasImpregnated)
            {
                spawnLive = true;
            }
            Pawn pawn;

            if (Instigator != null)
            {
                //    Log.Message("using instigator");
                pawn = instigator;
            }
            else
            {
                if (this.innerContainer.Any(x => x is Pawn))
                {
                    //    Log.Message("using innerContainer");
                    pawn = (Pawn)this.innerContainer.First(x => x is Pawn);
                }
                else
                {
                    //    Log.Message("using PawnGenerator");
                    PawnGenerationRequest pawnGenerationRequest = new PawnGenerationRequest(pawnKindDef, null, PawnGenerationContext.NonPlayer, -1, true, false, true, false, true, true, 0f);
                    pawn = PawnGenerator.GeneratePawn(pawnGenerationRequest);
                }
            }
            if (spawnLive == true)
            {
                //    Log.Message("using spawnLive");
                Comp_Facehugger _Facehugger = pawn.TryGetComp <Comp_Facehugger>();
                if (_Facehugger != null)
                {
                    _Facehugger.Impregnations = previousImpregnations;
                }
                if (!pawn.Spawned)
                {
                    GenSpawn.Spawn(pawn, spawnLoc, spawnMap, 0);
                }
                pawn.jobs.ClearQueuedJobs();
                //    pawn.jobs.curJob = new Verse.AI.Job(JobDefOf.FleeAndCower, hostPawn);
                if (killhugger)
                {
                    pawn.Kill(null);
                }
            }
            else
            {
                //    Log.Message("using spawnDead");
                if (!pawn.Spawned)
                {
                    GenSpawn.Spawn(pawn, spawnLoc, spawnMap, 0);
                }
                Comp_Facehugger _Facehugger = pawn.TryGetComp <Comp_Facehugger>();
                //    pawn.jobs.ClearQueuedJobs();
                //    pawn.jobs.curJob = new Verse.AI.Job(JobDefOf.FleeAndCower, hostPawn);
                _Facehugger.Impregnations = previousImpregnations;
                if (killhugger)
                {
                    pawn.Kill(null);
                }
                // pawn.Kill(null);
            }
            string text = TranslatorFormattedStringExtensions.Translate("Xeno_Facehugger_Detach", base.parent.pawn.LabelShort);

            if (!base.Pawn.Dead)
            {
                MoteMaker.ThrowText(spawnLoc.ToVector3(), spawnMap, text, 5f);
            }
        }
Esempio n. 18
0
        public static bool CreatePOI(PlanetTileInfo tileInfo, string gameName, bool biomeStrict, bool costStrict, bool itemsStrict)
        {
            if (tileInfo.tile >= Find.WorldGrid.TilesCount)
            {
                return(false);
            }

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

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

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

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

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

            BlueprintAnalyzer ba = new BlueprintAnalyzer(bp);

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

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

            var poiType = ba.determinedType;

            Faction faction = null;

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

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

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

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

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

            return(true);
        }
Esempio n. 19
0
 public static bool ImpactSomething(Projectile __instance)
 {
     if (__instance.def.projectile.flyOverhead)
     {
         RoofDef roofDef = __instance.Map.roofGrid.RoofAt(__instance.Position);
         if (roofDef != null)
         {
             if (roofDef.isThickRoof)
             {
                 ThrowDebugText(__instance, "hit-thick-roof", __instance.Position);
                 __instance.def.projectile.soundHitThickRoof.PlayOneShot((SoundInfo) new TargetInfo(__instance.Position, __instance.Map, false));
                 __instance.Destroy(DestroyMode.Vanish);
                 return(false);
             }
             if (__instance.Position.GetEdifice(__instance.Map) == null || __instance.Position.GetEdifice(__instance.Map).def.Fillage != FillCategory.Full)
             {
                 RoofCollapserImmediate.DropRoofInCells(__instance.Position, __instance.Map, (List <Thing>)null);
             }
         }
     }
     if (__instance.usedTarget.HasThing && CanHit(__instance, __instance.usedTarget.Thing))
     {
         if (__instance.usedTarget.Thing is Pawn thing && thing.GetPosture() != PawnPosture.Standing && ((double)(origin(__instance) - destination(__instance)).MagnitudeHorizontalSquared() >= 20.25 && !Rand.Chance(0.2f)))
         {
             ThrowDebugText(__instance, "miss-laying", __instance.Position);
             //Impact.Invoke(__instance, new object[] { (Thing)null });
             Impact(__instance, null);
         }
         else
         {
             Impact(__instance, __instance.usedTarget.Thing);
         }
     }
Esempio n. 20
0
        protected override bool TryCastShot()
        {
            bool result = false;
            Pawn p      = this.CasterPawn;
            CompAbilityUserMagic comp = this.CasterPawn.GetComp <CompAbilityUserMagic>();
            MagicPowerSkill      pwr  = comp.MagicData.MagicPowerSkill_DeathMark.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_DeathMark_pwr");
            MagicPowerSkill      ver  = comp.MagicData.MagicPowerSkill_DeathMark.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_DeathMark_ver");

            verVal         = ver.level;
            pwrVal         = pwr.level;
            this.arcaneDmg = comp.arcaneDmg;
            if (p.story.traits.HasTrait(TorannMagicDefOf.Faceless))
            {
                MightPowerSkill mpwr = p.GetComp <CompAbilityUserMight>().MightData.MightPowerSkill_Mimic.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Mimic_pwr");
                MightPowerSkill mver = p.GetComp <CompAbilityUserMight>().MightData.MightPowerSkill_Mimic.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Mimic_ver");
                pwrVal = mpwr.level;
                verVal = mver.level;
            }

            if (this.currentTarget != null && base.CasterPawn != null)
            {
                Map map = this.CasterPawn.Map;
                this.TargetsAoE.Clear();
                this.UpdateTargets();
                ModOptions.SettingsRef settingsRef = new ModOptions.SettingsRef();
                for (int i = 0; i < this.TargetsAoE.Count; i++)
                {
                    if (this.TargetsAoE[i].Thing is Pawn)
                    {
                        Pawn victim = this.TargetsAoE[i].Thing as Pawn;
                        if (!victim.RaceProps.IsMechanoid)
                        {
                            if (Rand.Chance(TM_Calc.GetSpellSuccessChance(this.CasterPawn, victim, true)))
                            {
                                HealthUtility.AdjustSeverity(victim, HediffDef.Named("TM_DeathMarkCurse"), (Rand.Range(1f + pwrVal, 4 + 2 * pwrVal) * this.arcaneDmg));
                                TM_MoteMaker.ThrowSiphonMote(victim.DrawPos, victim.Map, 1f);
                                if (comp.Pawn.health.hediffSet.HasHediff(HediffDef.Named("TM_LichHD"), false))
                                {
                                    comp.PowerModifier += 1;
                                }

                                if (Rand.Chance(verVal * .2f))
                                {
                                    if (Rand.Chance(verVal * .1f)) //terror
                                    {
                                        HealthUtility.AdjustSeverity(victim, HediffDef.Named("TM_Terror"), Rand.Range(3f * verVal, 5f * verVal) * this.arcaneDmg);
                                        TM_MoteMaker.ThrowDiseaseMote(victim.DrawPos, victim.Map, 1f, .5f, .2f, .4f);
                                        MoteMaker.ThrowText(victim.DrawPos, victim.Map, "Terror", -1);
                                    }
                                    if (Rand.Chance(verVal * .1f)) //berserk
                                    {
                                        if (victim.mindState != null && victim.RaceProps != null && victim.RaceProps.Humanlike)
                                        {
                                            victim.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Berserk, "cursed", true, false, null);
                                            MoteMaker.ThrowMicroSparks(victim.DrawPos, victim.Map);
                                            MoteMaker.ThrowText(victim.DrawPos, victim.Map, "Berserk", -1);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                MoteMaker.ThrowText(victim.DrawPos, victim.Map, "TM_ResistedSpell".Translate(), -1);
                            }
                        }
                    }
                }

                result = true;
            }

            this.burstShotsLeft = 0;
            //this.ability.TicksUntilCasting = (int)base.UseAbilityProps.SecondsToRecharge * 60;
            return(result);
        }
        protected override bool TryExecuteWorker(IncidentParms parms)
        {
            if (!TryGetRandomAvailableTargetMap(out map))
            {
                return(false);
            }

            Settlement Settlement = RandomNearbyTradeableSettlement(map.Tile);

            if (Settlement?.Faction == null)
            {
                return(false);
            }

            int destination = Rand.Chance(directConnectionChance) ? map.Tile : AllyOfNearbySettlement(Settlement)?.Tile ?? map.Tile;

            int maxPriority = Settlement.Faction.def.techLevel >= TechLevel.Medieval ? 30 : 20;

            RoadDef roadToBuild = DefDatabase <RoadDef> .AllDefsListForReading.Where(x => x.priority <= maxPriority).RandomElement();

            WorldPath path = WorldPath.NotFound;

            int    cost2       = 12000;
            int    timeToBuild = 0;
            string letterTitle = "MFI_RoadWorks".Translate();
            List <WorldObject_RoadConstruction> list = new List <WorldObject_RoadConstruction>();

            using (path = Find.WorldPathFinder.FindPath(destination, Settlement.Tile, null))
            {
                if (path == null || path == WorldPath.NotFound)
                {
                    return(true);
                }

                float roadCount = path.NodesReversed.Count(x => !Find.WorldGrid[x].Roads.NullOrEmpty() &&
                                                           Find.WorldGrid[x].Roads.Any(roadLink => roadLink.road.priority >= roadToBuild.priority) ||
                                                           Find.WorldObjects.AnyWorldObjectOfDefAt(MFI_DefOf.MFI_RoadUnderConstruction, x));

                if (roadCount / path.NodesReversed.Count >= maxRoadCoverage)
                {
                    return(false);
                }

                //not 0 and - 1
                for (int i = 1; i < path.NodesReversed.Count - 1; i++)
                {
                    cost2 += Caravan_PathFollower.CostToMove(CaravanTicksPerMoveUtility.DefaultTicksPerMove, path.NodesReversed[i], path.NodesReversed[i + 1]);

                    timeToBuild += (int)(2 * GenDate.TicksPerDay
                                         * WorldPathGrid.CalculatedMovementDifficultyAt(path.NodesReversed[i], true)
                                         * Find.WorldGrid.GetRoadMovementDifficultyMultiplier(i, i + 1));

                    if (!Find.WorldGrid[path.NodesReversed[i]].Roads.NullOrEmpty() &&
                        Find.WorldGrid[path.NodesReversed[i]].Roads.Any(roadLink => roadLink.road.priority >= roadToBuild.priority))
                    {
                        timeToBuild = timeToBuild / 2;
                    }

                    WorldObject_RoadConstruction roadConstruction = (WorldObject_RoadConstruction)WorldObjectMaker.MakeWorldObject(MFI_DefOf.MFI_RoadUnderConstruction);
                    roadConstruction.Tile     = path.NodesReversed[i];
                    roadConstruction.nextTile = path.NodesReversed[i + 1];
                    roadConstruction.road     = roadToBuild;
                    roadConstruction.SetFaction(Settlement.Faction);
                    roadConstruction.projectedTimeOfCompletion = Find.TickManager.TicksGame + timeToBuild;
                    list.Add(roadConstruction);
                }
                cost2 = cost2 / 10;
                DiaNode node = new DiaNode("MFI_RoadWorksDialogue".Translate(Settlement, path.NodesReversed.Count, cost2));
                // {Settlement} wants {cost2 / 10} to build a road of {path.NodesReversed.Count}");
                DiaOption accept = new DiaOption("OK".Translate())
                {
                    resolveTree = true,
                    action      = () =>
                    {
                        TradeUtility.LaunchSilver(TradeUtility.PlayerHomeMapWithMostLaunchableSilver(), cost2);
                        foreach (WorldObject_RoadConstruction worldObjectRoadConstruction in list)
                        {
                            Find.WorldObjects.Add(worldObjectRoadConstruction);
                        }
                        list.Clear();
                    }
                };

                if (!TradeUtility.ColonyHasEnoughSilver(TradeUtility.PlayerHomeMapWithMostLaunchableSilver(), cost2))
                {
                    accept.Disable("NeedSilverLaunchable".Translate(cost2));
                }
                DiaOption reject = new DiaOption("RejectLetter".Translate())
                {
                    resolveTree = true,
                    action      = () =>
                    {
                        for (int i = list.Count - 1; i >= 0; i--)
                        {
                            list[i] = null;
                        }
                        list.Clear();
                    }
                };

                node.options.Add(accept);
                node.options.Add(reject);

                //Log.Message(stringBuilder.ToString());
                Find.WindowStack.Add(new Dialog_NodeTreeWithFactionInfo(node, Settlement.Faction));
                Find.Archive.Add(new ArchivedDialog(node.text, letterTitle, Settlement.Faction));
            }
            return(true);
        }
Esempio n. 22
0
        private void Dig(IntVec3 start, float dir, float width, List <IntVec3> group, Map map, bool closed, HashSet <IntVec3> visited = null)
        {
            Vector3         vector    = start.ToVector3Shifted();
            IntVec3         intVec    = start;
            float           num       = 0f;
            MapGenFloatGrid elevation = MapGenerator.Elevation;
            MapGenFloatGrid caves     = MapGenerator.Caves;
            bool            flag      = false;
            bool            flag2     = false;

            if (visited == null)
            {
                visited = new HashSet <IntVec3>();
            }
            tmpGroupSet.Clear();
            tmpGroupSet.AddRange(group);
            int num2 = 0;

            while (true)
            {
                if (closed)
                {
                    int num3 = GenRadial.NumCellsInRadius(width / 2f + 1.5f);
                    for (int i = 0; i < num3; i++)
                    {
                        IntVec3 intVec2 = intVec + GenRadial.RadialPattern[i];
                        if (!visited.Contains(intVec2) && (!tmpGroupSet.Contains(intVec2) || caves[intVec2] > 0f))
                        {
                            return;
                        }
                    }
                }
                if (num2 >= 15)
                {
                    float      num4 = width;
                    FloatRange branchedTunnelWidthOffset = BranchedTunnelWidthOffset;
                    if (num4 > 1.4f + branchedTunnelWidthOffset.max)
                    {
                        if (!flag && Rand.Chance(0.1f))
                        {
                            DigInBestDirection(intVec, dir, new FloatRange(40f, 90f), width - BranchedTunnelWidthOffset.RandomInRange, group, map, closed, visited);
                            flag = true;
                        }
                        if (!flag2 && Rand.Chance(0.1f))
                        {
                            DigInBestDirection(intVec, dir, new FloatRange(-90f, -40f), width - BranchedTunnelWidthOffset.RandomInRange, group, map, closed, visited);
                            flag2 = true;
                        }
                    }
                }
                SetCaveAround(intVec, width, map, visited, out bool hitAnotherTunnel);
                if (hitAnotherTunnel)
                {
                    break;
                }
                while (vector.ToIntVec3() == intVec)
                {
                    vector += Vector3Utility.FromAngleFlat(dir) * 0.5f;
                    num    += 0.5f;
                }
                if (!tmpGroupSet.Contains(vector.ToIntVec3()))
                {
                    break;
                }
                int     x       = intVec.x;
                IntVec3 intVec3 = vector.ToIntVec3();
                IntVec3 intVec4 = new IntVec3(x, 0, intVec3.z);
                if (IsRock(intVec4, elevation, map))
                {
                    caves[intVec4] = Mathf.Max(caves[intVec4], width);
                    visited.Add(intVec4);
                }
                intVec = vector.ToIntVec3();
                dir   += (float)directionNoise.GetValue((double)(num * 60f), (double)((float)start.x * 200f), (double)((float)start.z * 200f)) * 8f;
                width -= 0.034f;
                if (width < 1.4f)
                {
                    break;
                }
                num2++;
            }
        }
        public static void GenerateRandomOldAgeInjuries(Pawn pawn, bool tryNotToKillPawn)
        {
            int num = 0;

            for (int i = 10; i < Mathf.Min(pawn.ageTracker.AgeBiologicalYears, 120); i += 10)
            {
                if (Rand.Value < 0.15000000596046448)
                {
                    num++;
                }
            }
            for (int j = 0; j < num; j++)
            {
                IEnumerable <BodyPartRecord> source = from x in pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined)
                                                      where x.depth == BodyPartDepth.Outside && !Mathf.Approximately(x.def.oldInjuryBaseChance, 0f) && !pawn.health.hediffSet.PartOrAnyAncestorHasDirectlyAddedParts(x)
                                                      select x;
                if (source.Any())
                {
                    BodyPartRecord bodyPartRecord      = source.RandomElementByWeight((BodyPartRecord x) => x.coverageAbs);
                    DamageDef      dam                 = AgeInjuryUtility.RandomOldInjuryDamageType(bodyPartRecord.def.frostbiteVulnerability > 0.0 && pawn.RaceProps.ToolUser);
                    HediffDef      hediffDefFromDamage = HealthUtility.GetHediffDefFromDamage(dam, pawn, bodyPartRecord);
                    if (bodyPartRecord.def.oldInjuryBaseChance > 0.0 && hediffDefFromDamage.CompPropsFor(typeof(HediffComp_GetsOld)) != null)
                    {
                        if (Rand.Chance(bodyPartRecord.def.amputateIfGeneratedInjuredChance))
                        {
                            Hediff_MissingPart hediff_MissingPart = (Hediff_MissingPart)HediffMaker.MakeHediff(HediffDefOf.MissingBodyPart, pawn, null);
                            hediff_MissingPart.lastInjury = hediffDefFromDamage;
                            hediff_MissingPart.TryGetComp <HediffComp_GetsOld>().IsOld = true;
                            pawn.health.AddHediff(hediff_MissingPart, bodyPartRecord, null);
                            if (pawn.RaceProps.Humanlike && (bodyPartRecord.def == BodyPartDefOf.LeftLeg || bodyPartRecord.def == BodyPartDefOf.RightLeg) && Rand.Chance(0.5f))
                            {
                                RecipeDefOf.InstallPegLeg.Worker.ApplyOnPawn(pawn, bodyPartRecord, null, AgeInjuryUtility.emptyIngredientsList, null);
                            }
                        }
                        else
                        {
                            Hediff_Injury hediff_Injury = (Hediff_Injury)HediffMaker.MakeHediff(hediffDefFromDamage, pawn, null);
                            hediff_Injury.Severity = (float)Rand.RangeInclusive(2, 6);
                            hediff_Injury.TryGetComp <HediffComp_GetsOld>().IsOld = true;
                            pawn.health.AddHediff(hediff_Injury, bodyPartRecord, null);
                        }
                    }
                }
            }
            int num2 = 1;

            while (num2 < pawn.ageTracker.AgeBiologicalYears)
            {
                foreach (HediffGiver_Birthday item in AgeInjuryUtility.RandomHediffsToGainOnBirthday(pawn, num2))
                {
                    item.TryApplyAndSimulateSeverityChange(pawn, (float)num2, tryNotToKillPawn);
                    if (pawn.Dead)
                    {
                        break;
                    }
                }
                if (!pawn.Dead)
                {
                    num2++;
                    continue;
                }
                break;
            }
        }
        public static void AdjustedArmorPenetration_RendingWeapon_Postfix(ref VerbProperties __instance, Tool tool, Pawn attacker, Thing equipment, HediffComp_VerbGiver hediffCompSource, ref float __result)
        {
            if (tool != null)
            {
                if (!tool.capacities.NullOrEmpty())
                {
                    if (tool.capacities.Any(x => x.defName.Contains("OG_RendingWeapon")))
                    {
                        float RendingChance = 0.167f;

                        if (equipment != null)
                        {
                            CompWeapon_MeleeSpecialRules _MeleeSpecialRules = equipment?.TryGetComp <CompWeapon_MeleeSpecialRules>();
                            if (_MeleeSpecialRules != null)
                            {
                                RendingChance = _MeleeSpecialRules.RendingChance;
                            }
                        }
                        else
                        {
                            if (attacker != null)
                            {
                                foreach (Tool item in attacker.Tools.Where(x => x != tool))
                                {
                                    if (item.capacities.Any(x => x.defName.Contains("OG_RendingWeapon")))
                                    {
                                        RendingChance += 0.167f;
                                    }
                                }
                            }
                        }

                        if (Rand.Chance(RendingChance))
                        {
                            MoteMaker.ThrowText(attacker.Position.ToVector3(), attacker.MapHeld, "AMA_Rending_Strike".Translate(), 3f);
                            __result = 2f;
                            return;
                        }
                    }
                }
            }

            /*
             * if (__instance.EquipmentSource != null)
             * {
             *  if (!__instance.EquipmentSource.AllComps.NullOrEmpty())
             *  {
             *      if (__instance.EquipmentSource.GetComp<CompWeapon_MeleeSpecialRules>() != null)
             *      {
             *          if (__instance.EquipmentSource.GetComp<CompWeapon_MeleeSpecialRules>() is CompWeapon_MeleeSpecialRules WeaponRules)
             *          {
             *              if (AMASettings.Instance.AllowRendingMeleeEffect)
             *              {
             *                  bool RendingAttack = __result.Any(x => x.Def.rendingWeapon());
             *                  if (WeaponRules.RendingWeapon && RendingAttack && __instance.CasterPawn is Pawn Caster)
             *                  {
             *
             *                  }
             *              }
             *          }
             *      }
             *  }
             * }
             */
        }
        /// <summary>
        /// Decide pawnkind from mother and father <para/>
        /// Come from RJW
        /// </summary>
        /// <param name="mother"></param>
        /// <param name="father"></param>
        /// <returns></returns>
        public PawnKindDef BabyPawnKindDecider(Pawn mother, Pawn father)
        {
            PawnKindDef spawn_kind_def = mother.kindDef;

            int flag = 0;

            if (xxx.is_human(mother))
            {
                flag += 2;
            }
            if (xxx.is_human(father))
            {
                flag += 1;
            }
            //Mother - Father = Flag
            //Human  - Human  =  3
            //Human  - Animal =  2
            //Animal - Human  =  1
            //Animal - Animal =  0

            switch (flag)
            {
            case 3:
                if (!Rand.Chance(RJWPregnancySettings.humanlike_DNA_from_mother))
                {
                    spawn_kind_def = father.kindDef;
                }
                break;

            case 2:
                if (RJWPregnancySettings.bestiality_DNA_inheritance == 0f)
                {
                    spawn_kind_def = father.kindDef;
                }
                else if (!Rand.Chance(RJWPregnancySettings.bestial_DNA_from_mother))
                {
                    spawn_kind_def = father.kindDef;
                }
                break;

            case 1:
                if (RJWPregnancySettings.bestiality_DNA_inheritance == 1f)
                {
                    spawn_kind_def = father.kindDef;
                }
                else if (!Rand.Chance(RJWPregnancySettings.bestial_DNA_from_mother))
                {
                    spawn_kind_def = father.kindDef;
                }
                break;

            case 0:
                if (!Rand.Chance(RJWPregnancySettings.bestial_DNA_from_mother))
                {
                    spawn_kind_def = father.kindDef;
                }
                break;
            }

            bool IsAndroidmother = AndroidsCompatibility.IsAndroid(mother);
            bool IsAndroidfather = AndroidsCompatibility.IsAndroid(father);

            if (IsAndroidmother && !IsAndroidfather)
            {
                spawn_kind_def = father.kindDef;
            }
            else if (!IsAndroidmother && IsAndroidfather)
            {
                spawn_kind_def = mother.kindDef;
            }

            string MotherRaceName = "";
            string FatherRaceName = "";

            MotherRaceName = mother.kindDef?.race?.defName;
            PawnKindDef tmp = spawn_kind_def;

            if (father != null)
            {
                FatherRaceName = father.kindDef?.race?.defName;
            }


            if (FatherRaceName != "" && Configurations.UseHybridExtention)
            {
                spawn_kind_def = GetHybrid(father, mother);
                //Log.Message("pawnkind: " + spawn_kind_def?.defName);
            }

            if (MotherRaceName != FatherRaceName && FatherRaceName != "")
            {
                if (!Configurations.UseHybridExtention || spawn_kind_def == null)
                {
                    spawn_kind_def = tmp;
                    var groups = DefDatabase <RaceGroupDef> .AllDefs.Where(x => !(x.hybridRaceParents.NullOrEmpty() || x.hybridChildKindDef.NullOrEmpty()));


                    //ModLog.Message(" found custom RaceGroupDefs " + groups.Count());
                    foreach (var t in groups)
                    {
                        if ((t.hybridRaceParents.Contains(MotherRaceName) && t.hybridRaceParents.Contains(FatherRaceName)) ||
                            (t.hybridRaceParents.Contains("Any") && (t.hybridRaceParents.Contains(MotherRaceName) || t.hybridRaceParents.Contains(FatherRaceName))))
                        {
                            //ModLog.Message(" has hybridRaceParents");
                            if (t.hybridChildKindDef.Contains("MotherKindDef"))
                            {
                                spawn_kind_def = mother.kindDef;
                            }
                            else if (t.hybridChildKindDef.Contains("FatherKindDef") && father != null)
                            {
                                spawn_kind_def = father.kindDef;
                            }
                            else
                            {
                                //ModLog.Message(" trying hybridChildKindDef " + t.defName);
                                var child_kind_def_list = new List <PawnKindDef>();
                                child_kind_def_list.AddRange(DefDatabase <PawnKindDef> .AllDefs.Where(x => t.hybridChildKindDef.Contains(x.defName)));

                                //ModLog.Message(" found custom hybridChildKindDefs " + t.hybridChildKindDef.Count);
                                if (!child_kind_def_list.NullOrEmpty())
                                {
                                    spawn_kind_def = child_kind_def_list.RandomElement();
                                }
                            }
                        }
                    }
                }
            }
            else if (!Configurations.UseHybridExtention || spawn_kind_def == null)
            {
                spawn_kind_def = mother.RaceProps?.AnyPawnKind ?? mother.kindDef;
            }

            if (spawn_kind_def.defName.Contains("Nymph"))
            {
                //child is nymph, try to find other PawnKindDef
                var spawn_kind_def_list = new List <PawnKindDef>();
                spawn_kind_def_list.AddRange(DefDatabase <PawnKindDef> .AllDefs.Where(x => x.race == spawn_kind_def.race && !x.defName.Contains("Nymph")));
                //no other PawnKindDef found try mother
                if (spawn_kind_def_list.NullOrEmpty())
                {
                    spawn_kind_def_list.AddRange(DefDatabase <PawnKindDef> .AllDefs.Where(x => x.race == mother.kindDef.race && !x.defName.Contains("Nymph")));
                }
                //no other PawnKindDef found try father
                if (spawn_kind_def_list.NullOrEmpty() && father != null)
                {
                    spawn_kind_def_list.AddRange(DefDatabase <PawnKindDef> .AllDefs.Where(x => x.race == father.kindDef.race && !x.defName.Contains("Nymph")));
                }
                //no other PawnKindDef found fallback to generic colonist
                if (spawn_kind_def_list.NullOrEmpty())
                {
                    spawn_kind_def = PawnKindDefOf.Colonist;
                }

                if (!spawn_kind_def_list.NullOrEmpty())
                {
                    spawn_kind_def = spawn_kind_def_list.RandomElement();
                }
            }



            return(spawn_kind_def);
        }
Esempio n. 26
0
        public static float Ingested(this Thing thing, Pawn ingester, float nutritionWanted, BodyPartRecord targetPart)
        {
            if (thing.Destroyed)
            {
                Log.Error(ingester + " ingested destroyed thing " + thing);
                return(0f);
            }
            if (!thing.IngestibleNow)
            {
                Log.Error(ingester + " ingested IngestibleNow=false thing " + thing);
                return(0f);
            }
            Corpse corpse = thing as Corpse;

            if (corpse == null)
            {
                Log.Error(ingester + " ingested NonCorpse thing " + thing);
                return(0f);
            }
            ingester.mindState.lastIngestTick = Find.TickManager.TicksGame;
            if (ingester.needs.mood != null)
            {
                List <FoodUtility.ThoughtFromIngesting> list = FoodUtility.ThoughtsFromIngesting(ingester, thing, thing.def);
                for (int i = 0; i < list.Count; i++)
                {
                    ingester.needs.mood.thoughts.memories.TryGainMemory(list[i].thought, null);
                }
            }
            if (ingester.needs.drugsDesire != null)
            {
                ingester.needs.drugsDesire.Notify_IngestedDrug(thing);
            }
            if (ingester.IsColonist && FoodUtility.IsHumanlikeCorpseOrHumanlikeMeat(thing, thing.def))
            {
                TaleRecorder.RecordTale(TaleDefOf.AteRawHumanlikeMeat, new object[]
                {
                    ingester
                });
            }
            corpse.IngestedCalculateAmounts(ingester, targetPart, out int num, out float result);

            /*
             *          MethodInfo dynMethod = thing.GetType().GetMethod("IngestedCalculateAmounts",
             *          BindingFlags.NonPublic | BindingFlags.Instance);
             *          object[] parameters = new object[] { ingester, nutritionWanted, null, null };
             *          dynMethod.Invoke(thing, parameters);
             *  //	Log.Message(thing+" eaten by "+ingester+" nutritionWanted: "+ nutritionWanted + " num: " + parameters[2] + " result: " + parameters[3]);
             *          num = (int)parameters[2];
             *          result = (float)parameters[3];
             *          //	thing.IngestedCalculateAmounts(ingester, nutritionWanted, out num, out result);
             */
            if (!ingester.Dead && ingester.needs.joy != null && Mathf.Abs(thing.def.ingestible.joy) > 0.0001f && num > 0)
            {
                JoyKindDef joyKind = (thing.def.ingestible.joyKind != null) ? thing.def.ingestible.joyKind : JoyKindDefOf.Gluttonous;
                ingester.needs.joy.GainJoy((float)num * thing.def.ingestible.joy, joyKind);
            }
            if (ingester.RaceProps.Humanlike && Rand.Chance(thing.GetStatValue(StatDefOf.FoodPoisonChanceFixedHuman, true) * FoodUtility.GetFoodPoisonChanceFactor(ingester)))
            {
                FoodUtility.AddFoodPoisoningHediff(ingester, thing, FoodPoisonCause.DangerousFoodType);
            }
            bool flag = false;

            if (num > 0)
            {
                if (thing.stackCount == 0)
                {
                    Log.Error(thing + " stack count is 0.");
                }
                if (num == thing.stackCount)
                {
                    flag = true;
                }
                else
                {
                    thing.SplitOff(num);
                }
            }
            MethodInfo dynMethod2 = thing.GetType().GetMethod("PrePostIngested",
                                                              BindingFlags.NonPublic | BindingFlags.Instance);

            dynMethod2.Invoke(thing, new object[] { ingester });
            //	thing.PrePostIngested(ingester);
            if (flag)
            {
                ingester.carryTracker.innerContainer.Remove(thing);
            }
            if (thing.def.ingestible.outcomeDoers != null)
            {
                for (int j = 0; j < thing.def.ingestible.outcomeDoers.Count; j++)
                {
                    thing.def.ingestible.outcomeDoers[j].DoIngestionOutcome(ingester, thing);
                }
            }
            if (flag)
            {
                thing.Destroy(DestroyMode.Vanish);
            }
            MethodInfo dynMethod3 = thing.GetType().GetMethod("PostIngested",
                                                              BindingFlags.NonPublic | BindingFlags.Instance);

            dynMethod3.Invoke(thing, new object[] { ingester });
            //	thing.PostIngested(ingester);
            return(result);
        }
        protected override bool TryExecuteWorker(IncidentParms parms)
        {
            Map map = (Map)parms.target;

            if ((from x in DefDatabase <TraderKindDef> .AllDefs
                 where x.orbital
                 select x).TryRandomElement(out TraderKindDef def))
            {
                TradeShip           tradeShip = new TradeShip(def);
                List <Thing>        list      = new List <Thing>();
                ThingSetMakerParams Trader    = default(ThingSetMakerParams);
                Trader.traderDef = tradeShip.def;
                Trader.tile      = map.Tile;
                list             = ThingSetMakerDefOf.TraderStock.root.Generate(Trader);
                List <Thing> tempList = new List <Thing>();
                for (int i = list.Count - 1; i >= 0; i--)
                {
                    bool flag = true;
                    if (list[i] is Pawn pawn)
                    {
                        if (Rand.Chance(0.6f))
                        {
                            list.Remove(list[i]);
                            flag = false;
                        }
                        else
                        {
                            HealthUtility.DamageUntilDowned(pawn);
                        }
                    }
                    else
                    {
                        if (list[i].stackCount == 1)
                        {
                            if (Rand.Chance(0.6f))
                            {
                                list.Remove(list[i]);
                                //list[i].Destroy();
                                flag = false;
                            }
                        }
                        else
                        {
                            list[i].stackCount = Mathf.RoundToInt(list[i].stackCount * 0.3f);
                            if (list[i].stackCount < 1)
                            {
                                list.Remove(list[i]);
                                //list[i].Destroy();
                                flag = false;
                            }
                        }
                    }
                    if (flag)
                    {
                        for (int j = list[i].stackCount; j > list[i].def.stackLimit; j -= list[i].def.stackLimit)
                        {
                            list[i].stackCount -= list[i].def.stackLimit;
                            Thing tempThing = ThingMaker.MakeThing(list[i].def);
                            tempThing.stackCount = list[i].def.stackLimit;
                            if (tempThing is MinifiedThing && (tempThing as MinifiedThing).InnerThing == null)
                            {
                                continue;
                            }
                            tempList.Add(tempThing);
                        }
                    }
                }

                /*foreach (Thing thing in list)
                 * {
                 *  if (thing is Pawn pawn)
                 *      HealthUtility.DamageUntilDowned(pawn);
                 *  for (int i = thing.stackCount; i > thing.def.stackLimit; i -= thing.def.stackLimit)
                 *  {
                 *      thing.stackCount -= thing.def.stackLimit;
                 *      Thing tempThing = ThingMaker.MakeThing(thing.def);
                 *      tempThing.stackCount = thing.def.stackLimit;
                 *      if (tempThing is MinifiedThing && (tempThing as MinifiedThing).InnerThing == null) continue;
                 *      tempList.Add(tempThing);
                 *
                 *  }
                 * }*/
                list.AddRange(tempList);

                IntVec3 intVec = DropCellFinder.RandomDropSpot(map);
                DropPodUtility.DropThingsNear(intVec, map, list, 110, false, true, true);
                Find.LetterStack.ReceiveLetter(tradeShip.def.LabelCap + " " + "PolarisTitleTradeShipPodCrash".Translate(), "PolarisTradeShipPodCrash".Translate(new object[]
                {
                    tradeShip.name,
                    tradeShip.def.label
                }), LetterDefOf.PositiveEvent, new TargetInfo(intVec, map, false), null);
                return(true);
            }
            throw new InvalidOperationException();
        }
        public static void DamageInfosToApply_ForceWeapon_Postfix(ref Verb_MeleeAttackDamage __instance, LocalTargetInfo target, ref IEnumerable <DamageInfo> __result)
        {
            if (__instance.EquipmentSource != null)
            {
                if (!__instance.EquipmentSource.AllComps.NullOrEmpty())
                {
                    if (__instance.EquipmentSource.GetComp <CompWeapon_MeleeSpecialRules>() != null)
                    {
                        if (__instance.EquipmentSource.GetComp <CompWeapon_MeleeSpecialRules>() is CompWeapon_MeleeSpecialRules WeaponRules)
                        {
                            if (AMASettings.Instance.AllowForceWeaponEffect)
                            {
                                bool ForceAttack = __result.Any(x => x.Def.forceWeapon());
                                if (WeaponRules.ForceWeapon && ForceAttack && __instance.CasterPawn is Pawn Caster)
                                {
                                    bool casterPsychiclySensitive = Caster.RaceProps.Humanlike ? Caster.story.traits.HasTrait(TraitDefOf.PsychicSensitivity) : false;
                                    bool Activate = false;
                                    if ((casterPsychiclySensitive || !WeaponRules.ForceEffectRequiresPsyker) && target.Thing.def.category == ThingCategory.Pawn && target.Thing is Pawn Victim)
                                    {
                                        int casterPsychiclySensitiveDegree = casterPsychiclySensitive ? Caster.story.traits.DegreeOfTrait(TraitDefOf.PsychicSensitivity) : 0;
                                        if ((casterPsychiclySensitiveDegree >= 1 || !WeaponRules.ForceEffectRequiresPsyker))
                                        {
                                            float?casterPsychicSensitivity = Caster.GetStatValue(StatDefOf.PsychicSensitivity, true) * 100f;
                                            bool  targetPsychiclySensitive = Victim.RaceProps.Humanlike ? Victim.story.traits.HasTrait(TraitDefOf.PsychicSensitivity) : false;
                                            float?targetPsychicSensitivity = Victim.GetStatValue(StatDefOf.PsychicSensitivity, true) * 100f;
                                            if (targetPsychiclySensitive == true)
                                            {
                                                int targetPsychiclySensitiveDegree = Victim.story.traits.DegreeOfTrait(TraitDefOf.PsychicSensitivity);
                                                if (targetPsychiclySensitiveDegree == -1)
                                                {
                                                    targetPsychicSensitivity = Victim.def.statBases.GetStatValueFromList(StatDefOf.PsychicSensitivity, 1.5f) * 100f;
                                                }
                                                else if (targetPsychiclySensitiveDegree == -2)
                                                {
                                                    targetPsychicSensitivity = Victim.def.statBases.GetStatValueFromList(StatDefOf.PsychicSensitivity, 2f) * 100f;
                                                }
                                            }
                                            else
                                            {
                                                int targetPsychiclySensitiveDegree = 0;
                                            }
                                            if (__result.Any(x => x.Def.forceWeapon()))
                                            {
                                                //        Log.Message(string.Format("1"));
                                                float CasterMood = Caster.needs.mood.CurLevelPercentage;
                                                float VictimMood = Victim?.needs?.mood != null ? Victim.needs.mood.CurLevelPercentage : 1;
                                                foreach (var item in __result.Where(x => x.Def.forceWeapon()))
                                                {
                                                    float?casterRoll = Rand.Range(0, (int)casterPsychicSensitivity) * CasterMood;
                                                    float?targetRoll = Rand.Range(0, (int)targetPsychicSensitivity) * VictimMood;
                                                    casterRoll = (casterRoll - (targetPsychicSensitivity / 2));
                                                    Activate   = (casterRoll > targetRoll);
                                                    //        Log.Message(string.Format("Caster:{0}, Victim:{1}", casterRoll, targetRoll));
                                                    if (Activate)
                                                    {
                                                        DamageDef        damDef           = WeaponRules.ForceWeaponEffect;
                                                        float            damAmount        = __instance.verbProps.AdjustedMeleeDamageAmount(__instance, __instance.CasterPawn);
                                                        float            armorPenetration = __instance.verbProps.AdjustedArmorPenetration(__instance, __instance.CasterPawn);
                                                        BodyPartRecord   bodyPart         = Rand.Chance(0.05f) && Victim.RaceProps.body.AllParts.Any(x => x.def.defName.Contains("Brain")) ? Victim.RaceProps.body.AllParts.Find(x => x.def.defName.Contains("Brain")) : null;
                                                        BodyPartGroupDef bodyPartGroupDef = null;
                                                        HediffDef        hediffDef        = WeaponRules.ForceWeaponHediff;
                                                        damAmount = Rand.Range(damAmount * 0.1f, damAmount * 0.5f);
                                                        ThingDef   source    = __instance.EquipmentSource.def;
                                                        Thing      caster    = __instance.caster;
                                                        Vector3    direction = (target.Thing.Position - __instance.CasterPawn.Position).ToVector3();
                                                        float      num       = damAmount;
                                                        float      num2      = armorPenetration;
                                                        DamageInfo mainDinfo = new DamageInfo(damDef, num, num2, -1f, caster, bodyPart, source, DamageInfo.SourceCategory.ThingOrUnknown, null);
                                                        mainDinfo.SetBodyRegion(BodyPartHeight.Undefined, BodyPartDepth.Outside);
                                                        mainDinfo.SetWeaponBodyPartGroup(bodyPartGroupDef);
                                                        mainDinfo.SetWeaponHediff(hediffDef);
                                                        mainDinfo.SetAngle(direction);
                                                        Victim.TakeDamage(mainDinfo);
                                                        Map      map             = Caster.Map;
                                                        IntVec3  position        = target.Cell;
                                                        Map      map2            = map;
                                                        float    explosionRadius = 0f;
                                                        Thing    launcher        = __instance.EquipmentSource;
                                                        SoundDef soundExplode    = WeaponRules.ForceWeaponTriggerSound;
                                                        Thing    thing           = target.Thing;
                                                        GenExplosion.DoExplosion(position, map2, explosionRadius, damDef, launcher, (int)damAmount, armorPenetration, soundExplode, source, null, thing, null, 0f, 0, false, null, 0, 0, 0, false);
                                                        float KillChance = WeaponRules.ForceWeaponKillChance;
                                                        if (KillChance != 0)
                                                        {
                                                            float KillRoll = Rand.Range(0, 100);
                                                            if (Rand.Chance(WeaponRules.ForceWeaponKillChance))
                                                            {
                                                                string msg = string.Format("{0} was slain by a force strike", target.Thing.LabelCap);
                                                                target.Thing.Kill(mainDinfo);
                                                                if (target.Thing.Faction == Faction.OfPlayer)
                                                                {
                                                                    Messages.Message(msg, MessageTypeDefOf.PawnDeath);
                                                                }
                                                            }
                                                        }

                                                        /*
                                                         */
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Esempio n. 29
0
 public static TerrainDef RandomBasicFloorDef(Faction faction, bool allowCarpet = false)
 {
     if (allowCarpet && (faction == null || !faction.def.techLevel.IsNeolithicOrWorse()) && Rand.Chance(0.1f))
     {
         return((from x in DefDatabase <TerrainDef> .AllDefsListForReading
                 where x.IsCarpet
                 select x).RandomElement <TerrainDef>());
     }
     return(Rand.Element <TerrainDef>(TerrainDefOf.MetalTile, TerrainDefOf.PavedTile, TerrainDefOf.WoodPlankFloor, TerrainDefOf.TileSandstone));
 }
        public List <Thing> Generate(int totalMarketValue, List <Thing> outThings)
        {
            for (int j = 0; j < 10; j++)
            {
                //Medicine
                if (Rand.Chance(MedicineChance) && (totalMarketValue - collectiveMarketValue) > 100)
                {
                    IEnumerable <ThingDef> enumerable = from def in DefDatabase <ThingDef> .AllDefs
                                                        where def.IsMedicine
                                                        select def;
                    int randomInRange = MedicineCountRange.RandomInRange;
                    for (int i = 0; i < randomInRange; i++)
                    {
                        Thing thing = ThingMaker.MakeThing(enumerable.ToList().RandomElement());
                        if (thing.Label.Contains("Glitter"))
                        {
                            thing.stackCount       = Mathf.Clamp(MedicineStackRange.RandomInRange, 1, 2);
                            collectiveMarketValue += thing.stackCount * 100;
                        }
                        else
                        {
                            thing.stackCount = MedicineStackRange.RandomInRange;
                        }
                        if (thing.MarketValue * thing.stackCount > totalMarketValue)
                        {
                            continue;
                        }
                        outThings.Add(thing);
                        collectiveMarketValue += thing.MarketValue * thing.stackCount;
                    }
                }
                //Food
                if (Rand.Chance(FoodChance) && (totalMarketValue - collectiveMarketValue) > 100)
                {
                    IEnumerable <ThingDef> enumerable = DefDatabase <ThingDef> .AllDefs.Where(def => def.IsNutritionGivingIngestible && def.PlayerAcquirable && def.CountAsResource && def.BaseMarketValue < 15 && !def.label.Contains("Human"));

                    int   randomInRange = FoodCountRange.RandomInRange;
                    Thing thing         = ThingMaker.MakeThing(enumerable.RandomElement(), null);
                    thing.stackCount = 0;
                    for (int i = 0; i < randomInRange; i++)
                    {
                        thing.stackCount += FoodStackRange.RandomInRange;
                        if (thing.MarketValue * thing.stackCount > totalMarketValue * 1.5)
                        {
                            continue;
                        }
                    }
                    outThings.Add(thing);
                    collectiveMarketValue += thing.MarketValue * thing.stackCount;
                }
                //Armor
                if (Rand.Chance(ArmorChance) && (totalMarketValue - collectiveMarketValue) > 100)
                {
                    IEnumerable <ThingDef> enumerable = DefDatabase <ThingDef> .AllDefs.Where(def => def.IsApparel && def.BaseMarketValue > 100);

                    int randomInRange = ArmorCountRange.RandomInRange;
                    for (int i = 0; i < randomInRange; i++)
                    {
                        ThingDef thingDef = enumerable.RandomElement();
                        Thing    thing    = ThingMaker.MakeThing(thingDef, GenStuff.RandomStuffByCommonalityFor(thingDef, Find.FactionManager.OfPlayer.def.techLevel));
                        if (thing.MarketValue > totalMarketValue)
                        {
                            continue;
                        }
                        outThings.Add(thing);
                        collectiveMarketValue += thing.MarketValue;
                    }
                }
                //Weapons
                if (Rand.Chance(WeaponsChance) && (totalMarketValue - collectiveMarketValue) > 100)
                {
                    IEnumerable <ThingDef> enumerable = DefDatabase <ThingDef> .AllDefs.Where(def => def.IsWeapon && def.BaseMarketValue > 20 && !def.label.Contains("tornado") && !def.label.Contains("orbital"));

                    int randomInRange = WeaponsCountRange.RandomInRange;
                    for (int i = 0; i < randomInRange; i++)
                    {
                        ThingDef thingDef = enumerable.RandomElement();
                        Thing    thing    = ThingMaker.MakeThing(thingDef, GenStuff.RandomStuffByCommonalityFor(thingDef, Find.FactionManager.OfPlayer.def.techLevel));
                        if (thing.MarketValue > totalMarketValue)
                        {
                            continue;
                        }
                        outThings.Add(thing);
                        collectiveMarketValue += thing.MarketValue;
                    }
                }
                //Misc
                if (Rand.Chance(MiscChance) && (totalMarketValue - collectiveMarketValue) > 100)
                {
                    IEnumerable <ThingDef> enumerable = DefDatabase <ThingDef> .AllDefs.Where(def => def.PlayerAcquirable && def.CountAsResource && !def.IsNutritionGivingIngestible && !def.IsWeapon && !def.IsApparel && !def.IsMedicine && def.stackLimit == 1);

                    int randomInRange = MiscCountRange.RandomInRange;
                    for (int i = 0; i < randomInRange; i++)
                    {
                        Thing thing = ThingMaker.MakeThing(enumerable.RandomElement());
                        thing.stackCount = randomInRange;
                        if (thing.MarketValue * thing.stackCount > totalMarketValue)
                        {
                            continue;
                        }
                        outThings.Add(thing);
                        collectiveMarketValue += thing.MarketValue * thing.stackCount;
                    }
                }
            }
            return(outThings);
        }