Esempio n. 1
0
        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 (base.EquipmentSource != null)
            {
                CompChangeableProjectile comp = base.EquipmentSource.GetComp <CompChangeableProjectile>();
                if (comp != null)
                {
                    comp.Notify_ProjectileLaunched();
                }
            }
            Thing        launcher     = this.caster;
            Thing        equipment    = base.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) ? null : randomCoverToMissInto.def;

            if (!Rand.Chance(shotReport.AimOnTargetChance_IgnoringPosture))
            {
                shootLine.ChangeDestToMissWild(shotReport.AimOnTargetChance_StandardTarget);
                this.ThrowDebugText("ToWild" + ((!this.canHitNonTargetPawnsNow) ? string.Empty : "\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) ? string.Empty : "\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) ? string.Empty : "\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. 2
0
 public static IntVec3 RandomAdjacentCellCardinal(this IntVec3 root)
 {
     return(root + GenAdj.CardinalDirections[Rand.RangeInclusive(0, 3)]);
 }
 public void CheckForStateChange(DamageInfo?dinfo, Hediff hediff)
 {
     if (Dead)
     {
         return;
     }
     if (ShouldBeDead())
     {
         if (!pawn.Destroyed)
         {
             pawn.Kill(dinfo, hediff);
         }
     }
     else if (!Downed)
     {
         if (ShouldBeDowned())
         {
             if (!forceIncap && dinfo.HasValue && dinfo.Value.Def.ExternalViolenceFor(pawn) && !pawn.IsWildMan() && (pawn.Faction == null || !pawn.Faction.IsPlayer) && (pawn.HostFaction == null || !pawn.HostFaction.IsPlayer))
             {
                 float num = (pawn.RaceProps.Animal ? 0.5f : ((!pawn.RaceProps.IsMechanoid) ? (HealthTuning.DeathOnDownedChance_NonColonyHumanlikeFromPopulationIntentCurve.Evaluate(StorytellerUtilityPopulation.PopulationIntent) * Find.Storyteller.difficultyValues.enemyDeathOnDownedChanceFactor) : 1f));
                 if (Rand.Chance(num))
                 {
                     if (DebugViewSettings.logCauseOfDeath)
                     {
                         Log.Message("CauseOfDeath: chance on downed " + num.ToStringPercent());
                     }
                     pawn.Kill(dinfo);
                     return;
                 }
             }
             forceIncap = false;
             MakeDowned(dinfo, hediff);
         }
         else
         {
             if (capacities.CapableOf(PawnCapacityDefOf.Manipulation))
             {
                 return;
             }
             if (pawn.carryTracker != null && pawn.carryTracker.CarriedThing != null && pawn.jobs != null && pawn.CurJob != null)
             {
                 pawn.jobs.EndCurrentJob(JobCondition.InterruptForced);
             }
             if (pawn.equipment == null || pawn.equipment.Primary == null)
             {
                 return;
             }
             if (pawn.kindDef.destroyGearOnDrop)
             {
                 pawn.equipment.DestroyEquipment(pawn.equipment.Primary);
             }
             else if (pawn.InContainerEnclosed)
             {
                 pawn.equipment.TryTransferEquipmentToContainer(pawn.equipment.Primary, pawn.holdingOwner);
             }
             else if (pawn.SpawnedOrAnyParentSpawned)
             {
                 pawn.equipment.TryDropEquipment(pawn.equipment.Primary, out var _, pawn.PositionHeld);
             }
             else if (pawn.IsCaravanMember())
             {
                 ThingWithComps primary = pawn.equipment.Primary;
                 pawn.equipment.Remove(primary);
                 if (!pawn.inventory.innerContainer.TryAdd(primary))
                 {
                     primary.Destroy();
                 }
             }
             else
             {
                 pawn.equipment.DestroyEquipment(pawn.equipment.Primary);
             }
         }
     }
     else if (!ShouldBeDowned())
     {
         MakeUndowned();
     }
 }
Esempio n. 4
0
 public float RandomInRangeSeeded(int seed)
 {
     return(Rand.RangeSeeded(min, max, seed));
 }
Esempio n. 5
0
        private bool CheckForFreeIntercept(IntVec3 c)
        {
            if (destination.ToIntVec3() == c)
            {
                return(false);
            }
            float num = VerbUtility.InterceptChanceFactorFromDistance(origin, c);

            if (num <= 0f)
            {
                return(false);
            }
            bool         flag      = false;
            List <Thing> thingList = c.GetThingList(base.Map);

            for (int i = 0; i < thingList.Count; i++)
            {
                Thing thing = thingList[i];
                if (!CanHit(thing))
                {
                    continue;
                }
                bool flag2 = false;
                if (thing.def.Fillage == FillCategory.Full)
                {
                    Building_Door building_Door = thing as Building_Door;
                    if (building_Door == null || !building_Door.Open)
                    {
                        ThrowDebugText("int-wall", c);
                        Impact(thing);
                        return(true);
                    }
                    flag2 = true;
                }
                float num2 = 0f;
                Pawn  pawn = thing as Pawn;
                if (pawn != null)
                {
                    num2 = 0.4f * Mathf.Clamp(pawn.BodySize, 0.1f, 2f);
                    if (pawn.GetPosture() != 0)
                    {
                        num2 *= 0.1f;
                    }
                    if (launcher != null && pawn.Faction != null && launcher.Faction != null && !pawn.Faction.HostileTo(launcher.Faction))
                    {
                        num2 *= 0.4f;
                    }
                }
                else if (thing.def.fillPercent > 0.2f)
                {
                    num2 = (flag2 ? 0.05f : ((!DestinationCell.AdjacentTo8Way(c)) ? (thing.def.fillPercent * 0.15f) : (thing.def.fillPercent * 1f)));
                }
                num2 *= num;
                if (num2 > 1E-05f)
                {
                    if (Rand.Chance(num2))
                    {
                        ThrowDebugText("int-" + num2.ToStringPercent(), c);
                        Impact(thing);
                        return(true);
                    }
                    flag = true;
                    ThrowDebugText(num2.ToStringPercent(), c);
                }
            }
            if (!flag)
            {
                ThrowDebugText("o", c);
            }
            return(false);
        }
Esempio n. 6
0
        private bool CheckForFreeIntercept(IntVec3 c)
        {
            bool result;

            if (this.destination.ToIntVec3() == c)
            {
                result = false;
            }
            else
            {
                float num = VerbUtility.DistanceInterceptChance(this.origin, c, this.intendedTarget.Cell);
                if (num <= 0f)
                {
                    result = false;
                }
                else
                {
                    bool         flag      = false;
                    List <Thing> thingList = c.GetThingList(base.Map);
                    for (int i = 0; i < thingList.Count; i++)
                    {
                        Thing thing = thingList[i];
                        if (this.CanHit(thing))
                        {
                            bool flag2 = false;
                            if (thing.def.Fillage == FillCategory.Full)
                            {
                                Building_Door building_Door = thing as Building_Door;
                                if (building_Door == null || !building_Door.Open)
                                {
                                    this.ThrowDebugText("int-wall", c);
                                    this.Impact(thing);
                                    return(true);
                                }
                                flag2 = true;
                            }
                            float num2 = 0f;
                            Pawn  pawn = thing as Pawn;
                            if (pawn != null)
                            {
                                num2  = 0.4f;
                                num2 *= Mathf.Clamp(pawn.BodySize, 0.1f, 2f);
                                if (pawn.GetPosture() != PawnPosture.Standing)
                                {
                                    num2 *= 0.1f;
                                }
                                if (this.launcher != null && pawn.Faction != null && this.launcher.Faction != null && !pawn.Faction.HostileTo(this.launcher.Faction))
                                {
                                    num2 *= 0.4f;
                                }
                            }
                            else if (thing.def.fillPercent > 0.2f)
                            {
                                if (flag2)
                                {
                                    num2 = 0.05f;
                                }
                                else if (this.DestinationCell.AdjacentTo8Way(c))
                                {
                                    num2 = thing.def.fillPercent * 1f;
                                }
                                else
                                {
                                    num2 = thing.def.fillPercent * 0.15f;
                                }
                            }
                            num2 *= num;
                            if (num2 > 1E-05f)
                            {
                                if (Rand.Chance(num2))
                                {
                                    this.ThrowDebugText("int-" + num2.ToStringPercent(), c);
                                    this.Impact(thing);
                                    return(true);
                                }
                                flag = true;
                                this.ThrowDebugText(num2.ToStringPercent(), c);
                            }
                        }
                    }
                    if (!flag)
                    {
                        this.ThrowDebugText("o", c);
                    }
                    result = false;
                }
            }
            return(result);
        }
 private static float GestationDaysEach(ThingDef d)
 {
     if (d.HasComp(typeof(CompEggLayer)))
     {
         CompProperties_EggLayer compProperties = d.GetCompProperties <CompProperties_EggLayer>();
         return(compProperties.eggLayIntervalDays / compProperties.eggCountRange.Average);
     }
     return(d.race.gestationPeriodDays / ((d.race.litterSizeCurve == null) ? 1f : Rand.ByCurveAverage(d.race.litterSizeCurve)));
 }
        protected override void ApplySpecialEffectsToPart(Pawn pawn, float totalDamage, DamageInfo dinfo, DamageWorker.DamageResult result)
        {
            bool       flag     = Rand.Chance(this.def.bluntInnerHitChance);
            float      num      = (!flag) ? 0f : this.def.bluntInnerHitDamageFractionToConvert.RandomInRange;
            float      num2     = totalDamage * (1f - num);
            DamageInfo lastInfo = dinfo;

            while (true)
            {
                num2 -= base.FinalizeAndAddInjury(pawn, num2, lastInfo, result);
                if (!pawn.health.hediffSet.PartIsMissing(lastInfo.HitPart))
                {
                    break;
                }
                if (num2 <= 1f)
                {
                    break;
                }
                BodyPartRecord parent = lastInfo.HitPart.parent;
                if (parent == null)
                {
                    break;
                }
                lastInfo.SetHitPart(parent);
            }
            if (flag && !lastInfo.HitPart.def.IsSolid(lastInfo.HitPart, pawn.health.hediffSet.hediffs) && lastInfo.HitPart.depth == BodyPartDepth.Outside)
            {
                IEnumerable <BodyPartRecord> source = from x in pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined, null, null)
                                                      where x.parent == lastInfo.HitPart && x.def.IsSolid(x, pawn.health.hediffSet.hediffs) && x.depth == BodyPartDepth.Inside
                                                      select x;
                BodyPartRecord hitPart;
                if (source.TryRandomElementByWeight((BodyPartRecord x) => x.coverageAbs, out hitPart))
                {
                    DamageInfo lastInfo2 = lastInfo;
                    lastInfo2.SetHitPart(hitPart);
                    float totalDamage2 = totalDamage * num + totalDamage * this.def.bluntInnerHitDamageFractionToAdd.RandomInRange;
                    base.FinalizeAndAddInjury(pawn, totalDamage2, lastInfo2, result);
                }
            }
            if (!pawn.Dead)
            {
                SimpleCurve simpleCurve = null;
                if (lastInfo.HitPart.parent == null)
                {
                    simpleCurve = this.def.bluntStunChancePerDamagePctOfCorePartToBodyCurve;
                }
                else
                {
                    foreach (BodyPartRecord current in pawn.RaceProps.body.GetPartsWithTag(BodyPartTagDefOf.ConsciousnessSource))
                    {
                        if (this.InSameBranch(current, lastInfo.HitPart))
                        {
                            simpleCurve = this.def.bluntStunChancePerDamagePctOfCorePartToHeadCurve;
                            break;
                        }
                    }
                }
                if (simpleCurve != null)
                {
                    float x2 = totalDamage / pawn.def.race.body.corePart.def.GetMaxHealth(pawn);
                    if (Rand.Chance(simpleCurve.Evaluate(x2)))
                    {
                        DamageInfo dinfo2 = dinfo;
                        dinfo2.Def = DamageDefOf.Stun;
                        dinfo2.SetAmount((float)this.def.bluntStunDuration.SecondsToTicks() / 30f);
                        pawn.TakeDamage(dinfo2);
                    }
                }
            }
        }
Esempio n. 9
0
        public override void DrawWorker(Vector3 loc, Rot4 rot, ThingDef thingDef, Thing thing, float extraRotation)
        {
            Rand.PushState();
            Rand.Seed = thing.thingIDNumber.GetHashCode();
            Gas       gas    = thing as Gas;
            float     angle  = (float)Rand.Range(0, 360) + ((gas != null) ? gas.graphicRotation : 0f);
            Vector3   pos    = thing.TrueCenter() + new Vector3(Rand.Range(-0.45f, 0.45f), 0f, Rand.Range(-0.45f, 0.45f));
            Vector3   s      = new Vector3(Rand.Range(0.8f, 1.2f) * this.drawSize.x, 0f, Rand.Range(0.8f, 1.2f) * this.drawSize.y);
            Matrix4x4 matrix = default(Matrix4x4);

            matrix.SetTRS(pos, Quaternion.AngleAxis(angle, Vector3.up), s);
            Graphics.DrawMesh(MeshPool.plane10, matrix, this.MatSingle, 0);
            Rand.PopState();
        }
        public static void AnimalBreeding()
        {
            IEnumerable <ThingDef> arg_14B_0 = (from d in DefDatabase <ThingDef> .AllDefs
                                                where d.category == ThingCategory.Pawn && d.race.IsFlesh
                                                select d).OrderByDescending(new Func <ThingDef, float>(DebugOutputsEconomy.GestationDaysEach));

            TableDataGetter <ThingDef>[] expr_4F = new TableDataGetter <ThingDef> [6];
            expr_4F[0] = new TableDataGetter <ThingDef>(string.Empty, (ThingDef d) => d.defName);
            expr_4F[1] = new TableDataGetter <ThingDef>("gestDaysEach", (ThingDef d) => DebugOutputsEconomy.GestationDaysEach(d).ToString("F2"));
            expr_4F[2] = new TableDataGetter <ThingDef>("avgOffspring", (ThingDef d) => (!d.HasComp(typeof(CompEggLayer))) ? ((d.race.litterSizeCurve == null) ? 1f : Rand.ByCurveAverage(d.race.litterSizeCurve)).ToString("F2") : d.GetCompProperties <CompProperties_EggLayer>().eggCountRange.Average.ToString("F2"));
            expr_4F[3] = new TableDataGetter <ThingDef>("gestDaysRaw", (ThingDef d) => (!d.HasComp(typeof(CompEggLayer))) ? d.race.gestationPeriodDays.ToString("F1") : d.GetCompProperties <CompProperties_EggLayer>().eggLayIntervalDays.ToString("F1"));
            expr_4F[4] = new TableDataGetter <ThingDef>("growth per 30d", delegate(ThingDef d)
            {
                float f    = 1f + ((!d.HasComp(typeof(CompEggLayer))) ? ((d.race.litterSizeCurve == null) ? 1f : Rand.ByCurveAverage(d.race.litterSizeCurve)) : d.GetCompProperties <CompProperties_EggLayer>().eggCountRange.Average);
                float num  = d.race.lifeStageAges[d.race.lifeStageAges.Count - 1].minAge * 60f;
                float num2 = num + ((!d.HasComp(typeof(CompEggLayer))) ? d.race.gestationPeriodDays : d.GetCompProperties <CompProperties_EggLayer>().eggLayIntervalDays);
                float p    = 30f / num2;
                return(Mathf.Pow(f, p).ToString("F2"));
            });
            expr_4F[5] = new TableDataGetter <ThingDef>("growth per 60d", delegate(ThingDef d)
            {
                float f    = 1f + ((!d.HasComp(typeof(CompEggLayer))) ? ((d.race.litterSizeCurve == null) ? 1f : Rand.ByCurveAverage(d.race.litterSizeCurve)) : d.GetCompProperties <CompProperties_EggLayer>().eggCountRange.Average);
                float num  = d.race.lifeStageAges[d.race.lifeStageAges.Count - 1].minAge * 60f;
                float num2 = num + ((!d.HasComp(typeof(CompEggLayer))) ? d.race.gestationPeriodDays : d.GetCompProperties <CompProperties_EggLayer>().eggLayIntervalDays);
                float p    = 60f / num2;
                return(Mathf.Pow(f, p).ToString("F2"));
            });
            DebugTables.MakeTablesDialog <ThingDef>(arg_14B_0, expr_4F);
        }
Esempio n. 11
0
 public static Vector3 RandomHorizontalVector(float max)
 {
     return(new Vector3(Rand.Range(0f - max, max), 0f, Rand.Range(0f - max, max)));
 }
Esempio n. 12
0
 public static T RandomEnumValue <T>(bool disallowFirstValue)
 {
     return((T)(object)Rand.Range(disallowFirstValue ? 1 : 0, Enum.GetValues(typeof(T)).Length));
 }
Esempio n. 13
0
 public static void AnimalBreeding()
 {
     DebugTables.MakeTablesDialog(from d in DefDatabase <ThingDef> .AllDefs
                                  where d.category == ThingCategory.Pawn && d.race.IsFlesh
                                  orderby GestationDaysEach(d) descending
                                  select d, new TableDataGetter <ThingDef>("", (ThingDef d) => d.defName), new TableDataGetter <ThingDef>("gestDaysEach", (ThingDef d) => GestationDaysEach(d).ToString("F2")), new TableDataGetter <ThingDef>("avgOffspring", (ThingDef d) => (!d.HasComp(typeof(CompEggLayer))) ? ((d.race.litterSizeCurve != null) ? Rand.ByCurveAverage(d.race.litterSizeCurve) : 1f).ToString("F2") : d.GetCompProperties <CompProperties_EggLayer>().eggCountRange.Average.ToString("F2")), new TableDataGetter <ThingDef>("gestDaysRaw", (ThingDef d) => (!d.HasComp(typeof(CompEggLayer))) ? d.race.gestationPeriodDays.ToString("F1") : d.GetCompProperties <CompProperties_EggLayer>().eggLayIntervalDays.ToString("F1")), new TableDataGetter <ThingDef>("growth per 30d", delegate(ThingDef d)
     {
         float f2   = 1f + (d.HasComp(typeof(CompEggLayer)) ? d.GetCompProperties <CompProperties_EggLayer>().eggCountRange.Average : ((d.race.litterSizeCurve != null) ? Rand.ByCurveAverage(d.race.litterSizeCurve) : 1f));
         float num2 = d.race.lifeStageAges[d.race.lifeStageAges.Count - 1].minAge * 60f + (d.HasComp(typeof(CompEggLayer)) ? d.GetCompProperties <CompProperties_EggLayer>().eggLayIntervalDays : d.race.gestationPeriodDays);
         float p2   = 30f / num2;
         return(Mathf.Pow(f2, p2).ToString("F2"));
     }), new TableDataGetter <ThingDef>("growth per 60d", delegate(ThingDef d)
     {
         float f   = 1f + (d.HasComp(typeof(CompEggLayer)) ? d.GetCompProperties <CompProperties_EggLayer>().eggCountRange.Average : ((d.race.litterSizeCurve != null) ? Rand.ByCurveAverage(d.race.litterSizeCurve) : 1f));
         float num = d.race.lifeStageAges[d.race.lifeStageAges.Count - 1].minAge * 60f + (d.HasComp(typeof(CompEggLayer)) ? d.GetCompProperties <CompProperties_EggLayer>().eggLayIntervalDays : d.race.gestationPeriodDays);
         float p   = 60f / num;
         return(Mathf.Pow(f, p).ToString("F2"));
     }));
 }
        private static int FinalLevelOfSkill(Pawn pawn, SkillDef sk)
        {
            float num = (!sk.usuallyDefinedInBackstories) ? Rand.ByCurve(PawnGenerator.LevelRandomCurve, 100) : ((float)Rand.RangeInclusive(0, 4));

            foreach (Backstory item in from bs in pawn.story.AllBackstories
                     where bs != null
                     select bs)
            {
                foreach (KeyValuePair <SkillDef, int> item2 in item.skillGainsResolved)
                {
                    if (item2.Key == sk)
                    {
                        num += (float)item2.Value * Rand.Range(1f, 1.4f);
                    }
                }
            }
            for (int i = 0; i < pawn.story.traits.allTraits.Count; i++)
            {
                int num2 = 0;
                if (pawn.story.traits.allTraits[i].CurrentData.skillGains.TryGetValue(sk, out num2))
                {
                    num += (float)num2;
                }
            }
            float num3 = Rand.Range(1f, PawnGenerator.AgeSkillMaxFactorCurve.Evaluate((float)pawn.ageTracker.AgeBiologicalYears));

            num *= num3;
            num  = PawnGenerator.LevelFinalAdjustmentCurve.Evaluate(num);
            return(Mathf.Clamp(Mathf.RoundToInt(num), 0, 20));
        }
Esempio n. 15
0
        private static Pawn GenerateOrRedressPawnInternal(PawnGenerationRequest request)
        {
            Pawn result = null;

            if (!request.Newborn && !request.ForceGenerateNewPawn)
            {
                if (request.ForceRedressWorldPawnIfFormerColonist)
                {
                    IEnumerable <Pawn> validCandidatesToRedress = GetValidCandidatesToRedress(request);
                    if (validCandidatesToRedress.Where(PawnUtility.EverBeenColonistOrTameAnimal).TryRandomElementByWeight(WorldPawnSelectionWeight, out result))
                    {
                        RedressPawn(result, request);
                        Find.WorldPawns.RemovePawn(result);
                    }
                }
                if (result == null && request.Inhabitant && request.Tile != -1)
                {
                    SettlementBase settlement = Find.WorldObjects.WorldObjectAt <SettlementBase>(request.Tile);
                    if (settlement != null && settlement.previouslyGeneratedInhabitants.Any())
                    {
                        IEnumerable <Pawn> validCandidatesToRedress2 = GetValidCandidatesToRedress(request);
                        if ((from x in validCandidatesToRedress2
                             where settlement.previouslyGeneratedInhabitants.Contains(x)
                             select x).TryRandomElementByWeight(WorldPawnSelectionWeight, out result))
                        {
                            RedressPawn(result, request);
                            Find.WorldPawns.RemovePawn(result);
                        }
                    }
                }
                if (result == null && Rand.Chance(ChanceToRedressAnyWorldPawn(request)))
                {
                    IEnumerable <Pawn> validCandidatesToRedress3 = GetValidCandidatesToRedress(request);
                    if (validCandidatesToRedress3.TryRandomElementByWeight(WorldPawnSelectionWeight, out result))
                    {
                        RedressPawn(result, request);
                        Find.WorldPawns.RemovePawn(result);
                    }
                }
            }
            bool redressed;

            if (result == null)
            {
                redressed = false;
                result    = GenerateNewPawnInternal(ref request);
                if (result == null)
                {
                    return(null);
                }
                if (request.Inhabitant && request.Tile != -1)
                {
                    Find.WorldObjects.WorldObjectAt <SettlementBase>(request.Tile)?.previouslyGeneratedInhabitants.Add(result);
                }
            }
            else
            {
                redressed = true;
            }
            if (Find.Scenario != null)
            {
                Find.Scenario.Notify_PawnGenerated(result, request.Context, redressed);
            }
            return(result);
        }
Esempio n. 16
0
        protected override bool TryCastShot()
        {
            if (this.currentTarget.HasThing && this.currentTarget.Thing.Map != this.caster.Map)
            {
                return(false);
            }
            //  ThingDef projectile = this.Projectile;
            ThingDef projectile = this.Projectile;

            //   projectile.projectileWhenLoaded.
            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);


            //---------------
            int pellets = this.PelletsPerShot(projectile);

            if (pellets < 1)
            {
                pellets = 1;
            }

            Projectile[] projectiles = new Projectile[pellets];
            ShootLine[]  shootLines  = new ShootLine[pellets];
            for (int i = 0; i < pellets; i++)
            {
                base.TryFindShootLineFromTo(this.caster.Position, this.currentTarget, out shootLines[i]);
                projectiles[i] = (Projectile)GenSpawn.Spawn(projectile, shootLines[i].Source, this.caster.Map);
                //projectiles[i].FreeIntercept = (this.canFreeInterceptNow && !projectiles[i].def.projectile.flyOverhead);
            }

            //projectile2.FreeIntercept = (this.canFreeInterceptNow && !projectile2.def.projectile.flyOverhead);
            //projectile3.FreeIntercept = (this.canFreeInterceptNow && !projectile2.def.projectile.flyOverhead);
            //projectile4.FreeIntercept = (this.canFreeInterceptNow && !projectile2.def.projectile.flyOverhead);
            float distance   = (float)(this.currentTarget.Cell - this.caster.Position).LengthHorizontal;
            float scatter    = ScatterRadiusAt10tilesAway(projectile) * distance / 10.0f;
            float missRadius = this.verbProps.forcedMissRadius + ForsedScatterRadius(projectile) + scatter;

            for (int i = 0; i < pellets; i++)
            {
                if (missRadius > 0.5f)
                {
                    float num = (float)(this.currentTarget.Cell - this.caster.Position).LengthHorizontalSquared;
                    float num2;
                    if (num < 9f)
                    {
                        num2 = 0f;
                    }
                    else if (num < 25f)
                    {
                        num2 = missRadius * 0.5f;
                    }
                    else if (num < 49f)
                    {
                        num2 = missRadius * 0.8f;
                    }
                    else
                    {
                        num2 = missRadius * 1f;
                    }
                    if (num2 > 0.5f)
                    {
                        int max = GenRadial.NumCellsInRadius(missRadius);
                        //int num3 = Rand.Range(0, max);
                        int num3 = Rand.Range(0, max);
                        if (num3 > 0)
                        {
                            if (DebugViewSettings.drawShooting)
                            {
                                MoteMaker.ThrowText(this.caster.DrawPos, this.caster.Map, "ToForRad", -1f);
                            }
                            //if (this.currentTarget.HasThing)
                            //{
                            //    // projectile2.ThingToNeverIntercept = this.currentTarget.Thing;

                            //   projectiles[i].ThingToNeverIntercept = this.currentTarget.Thing;
                            //}

                            //if (!projectiles[i].def.projectile.flyOverhead)
                            //{
                            //        projectiles[i].InterceptWalls = true;
                            //}
                            IntVec3 c = this.currentTarget.Cell + GenRadial.RadialPattern[num3];
                            projectiles[i].Launch(launcher, origin: drawPos, usedTarget: new LocalTargetInfo(c), intendedTarget: currentTarget, hitFlags: projectiles[i].HitFlags, equipment: equipment);
                            //projectile2.Launch(launcher, drawPos, c, equipment, this.currentTarget.Thing);
                            //projectile3.Launch(launcher, drawPos, c, equipment, this.currentTarget.Thing);
                            //projectile4.Launch(launcher, drawPos, c, equipment, this.currentTarget.Thing);
                            continue;// return true;
                        }
                        else
                        {
                            projectiles[i].Launch(launcher, origin: drawPos, usedTarget: new LocalTargetInfo(this.currentTarget.Cell), intendedTarget: currentTarget, hitFlags: projectiles[i].HitFlags, equipment: equipment);
                            //projectiles[i].Launch(launcher, drawPos, this.currentTarget.Cell, equipment, this.currentTarget.Thing);
                            continue;
                        }
                    }
                }
                ShotReport shotReport = ShotReport.HitReportFor(this.caster, this, this.currentTarget);
                if (Rand.Value > shotReport.AimOnTargetChance_IgnoringPosture)
                {
                    if (DebugViewSettings.drawShooting)
                    {
                        MoteMaker.ThrowText(this.caster.DrawPos, this.caster.Map, "ToWild", -1f);
                    }

                    shootLines[i].ChangeDestToMissWild(shotReport.AimOnTargetChance);
                    // shootLine2.ChangeDestToMissWild();

                    if (this.currentTarget.HasThing)
                    {
                        projectiles[i].HitFlags = ProjectileHitFlags.All;
                        // projectile2.ThingToNeverIntercept = this.currentTarget.Thing;
                    }
                    if (!projectiles[i].def.projectile.flyOverhead)
                    {
                        projectiles[i].HitFlags = ProjectileHitFlags.IntendedTarget;
                    }
                    projectiles[i].Launch(launcher, origin: drawPos, usedTarget: new LocalTargetInfo(shootLines[i].Dest), intendedTarget: currentTarget, hitFlags: projectiles[i].HitFlags, equipment: equipment);
                    //projectiles[i].Launch(launcher, drawPos, shootLines[i].Dest, equipment, this.currentTarget.Thing);
                    //projectile2.Launch(launcher, drawPos, shootLine2.Dest, equipment, this.currentTarget.Thing);
                    continue;//return true;
                }
                if (Rand.Value > shotReport.PassCoverChance)
                {
                    if (DebugViewSettings.drawShooting)
                    {
                        MoteMaker.ThrowText(this.caster.DrawPos, this.caster.Map, "ToCover", -1f);
                    }
                    if (this.currentTarget.Thing != null && this.currentTarget.Thing.def.category == ThingCategory.Pawn)
                    {
                        Thing randomCoverToMissInto = shotReport.GetRandomCoverToMissInto();
                        if (!projectiles[i].def.projectile.flyOverhead)
                        {
                            projectiles[i].HitFlags = ProjectileHitFlags.IntendedTarget;
                        }
                        projectiles[i].Launch(launcher, origin: drawPos, usedTarget: new LocalTargetInfo(randomCoverToMissInto), intendedTarget: currentTarget, hitFlags: projectiles[i].HitFlags, equipment: equipment);
                        //projectiles[i].Launch(launcher, drawPos, randomCoverToMissInto, equipment, this.currentTarget.Thing);
                        //projectile2.Launch(launcher, drawPos, randomCoverToMissInto, equipment, this.currentTarget.Thing);
                        continue;//return true;
                    }
                }
                if (DebugViewSettings.drawShooting)
                {
                    MoteMaker.ThrowText(this.caster.DrawPos, this.caster.Map, "ToHit", -1f);
                }

                if (!projectiles[i].def.projectile.flyOverhead && (!this.currentTarget.HasThing || this.currentTarget.Thing.def.Fillage == FillCategory.Full))
                {
                    projectiles[i].HitFlags = ProjectileHitFlags.IntendedTarget;
                }

                if (this.currentTarget.Thing != null)
                {
                    projectiles[i].Launch(launcher, origin: drawPos, usedTarget: currentTarget, intendedTarget: currentTarget, hitFlags: projectiles[i].HitFlags, equipment: equipment);
                    //projectiles[i].Launch(launcher, drawPos, this.currentTarget, equipment, this.currentTarget.Thing);
                }
                else
                {
                    projectiles[i].Launch(launcher, origin: drawPos, usedTarget: new LocalTargetInfo(shootLines[i].Dest), intendedTarget: currentTarget, hitFlags: projectiles[i].HitFlags, equipment: equipment);
                    //projectiles[i].Launch(launcher, drawPos, shootLines[i].Dest, equipment, this.currentTarget.Thing);
                }
            }

            return(true);
        }
Esempio n. 17
0
 private static Pair <Pawn, PawnRelationDef>[] GenerateSamples(Pawn[] pawns, PawnRelationDef[] relations, int count)
 {
     Pair <Pawn, PawnRelationDef>[] array = new Pair <Pawn, PawnRelationDef> [count];
     for (int i = 0; i < count; i++)
     {
         array[i] = new Pair <Pawn, PawnRelationDef>(pawns[Rand.Range(0, pawns.Length)], relations[Rand.Range(0, relations.Length)]);
     }
     return(array);
 }
        public static IEnumerable <Thing> MakeRecipeProducts(RecipeDef recipeDef, Pawn worker, List <Thing> ingredients, Thing dominantIngredient, IBillGiver billGiver)
        {
            float efficiency;

            if (recipeDef.efficiencyStat == null)
            {
                efficiency = 1f;
            }
            else
            {
                efficiency = worker.GetStatValue(recipeDef.efficiencyStat, true);
            }
            if (recipeDef.workTableEfficiencyStat != null)
            {
                Building_WorkTable building_WorkTable = billGiver as Building_WorkTable;
                if (building_WorkTable != null)
                {
                    efficiency *= building_WorkTable.GetStatValue(recipeDef.workTableEfficiencyStat, true);
                }
            }
            if (recipeDef.products != null)
            {
                for (int i = 0; i < recipeDef.products.Count; i++)
                {
                    ThingDefCountClass prod = recipeDef.products[i];
                    ThingDef           stuffDef;
                    if (prod.thingDef.MadeFromStuff)
                    {
                        stuffDef = dominantIngredient.def;
                    }
                    else
                    {
                        stuffDef = null;
                    }
                    Thing product = ThingMaker.MakeThing(prod.thingDef, stuffDef);
                    product.stackCount = Mathf.CeilToInt((float)prod.count * efficiency);
                    if (dominantIngredient != null)
                    {
                        product.SetColor(dominantIngredient.DrawColor, false);
                    }
                    CompIngredients ingredientsComp = product.TryGetComp <CompIngredients>();
                    if (ingredientsComp != null)
                    {
                        for (int l = 0; l < ingredients.Count; l++)
                        {
                            ingredientsComp.RegisterIngredient(ingredients[l].def);
                        }
                    }
                    CompFoodPoisonable foodPoisonable = product.TryGetComp <CompFoodPoisonable>();
                    if (foodPoisonable != null)
                    {
                        Room  room   = worker.GetRoom(RegionType.Set_Passable);
                        float chance = (room == null) ? RoomStatDefOf.FoodPoisonChance.roomlessScore : room.GetStat(RoomStatDefOf.FoodPoisonChance);
                        if (Rand.Chance(chance))
                        {
                            foodPoisonable.SetPoisoned(FoodPoisonCause.FilthyKitchen);
                        }
                        else
                        {
                            float statValue = worker.GetStatValue(StatDefOf.FoodPoisonChance, true);
                            if (Rand.Chance(statValue))
                            {
                                foodPoisonable.SetPoisoned(FoodPoisonCause.IncompetentCook);
                            }
                        }
                    }
                    yield return(GenRecipe.PostProcessProduct(product, recipeDef, worker));
                }
            }
            if (recipeDef.specialProducts != null)
            {
                for (int j = 0; j < recipeDef.specialProducts.Count; j++)
                {
                    for (int k = 0; k < ingredients.Count; k++)
                    {
                        Thing ing = ingredients[k];
                        SpecialProductType specialProductType = recipeDef.specialProducts[j];
                        if (specialProductType != SpecialProductType.Butchery)
                        {
                            if (specialProductType == SpecialProductType.Smelted)
                            {
                                foreach (Thing product2 in ing.SmeltProducts(efficiency))
                                {
                                    yield return(GenRecipe.PostProcessProduct(product2, recipeDef, worker));
                                }
                            }
                        }
                        else
                        {
                            foreach (Thing product3 in ing.ButcherProducts(worker, efficiency))
                            {
                                yield return(GenRecipe.PostProcessProduct(product3, recipeDef, worker));
                            }
                        }
                    }
                }
            }
            yield break;
        }
Esempio n. 19
0
 public override void CompPostTick(ref float severityAdjustment)
 {
     if (!base.Pawn.IsHashIntervalTick(60))
     {
         return;
     }
     if (base.Pawn.RaceProps.Humanlike)
     {
         if (base.Pawn.mindState.mentalStateHandler.CurStateDef != Props.humanMentalState && Rand.MTBEventOccurs(Props.mtbDaysToCauseMentalState, 60000f, 60f) && base.Pawn.Awake() && base.Pawn.mindState.mentalStateHandler.TryStartMentalState(Props.humanMentalState, parent.def.LabelCap, forceWake: false, causedByMood: false, null, transitionSilently: true) && base.Pawn.Spawned)
         {
             SendLetter(Props.humanMentalState);
         }
     }
     else if (base.Pawn.RaceProps.Animal && base.Pawn.mindState.mentalStateHandler.CurStateDef != Props.animalMentalState && (Props.animalMentalStateAlias == null || base.Pawn.mindState.mentalStateHandler.CurStateDef != Props.animalMentalStateAlias) && Rand.MTBEventOccurs(Props.mtbDaysToCauseMentalState, 60000f, 60f) && base.Pawn.Awake() && base.Pawn.mindState.mentalStateHandler.TryStartMentalState(Props.animalMentalState, parent.def.LabelCap, forceWake: false, causedByMood: false, null, transitionSilently: true) && base.Pawn.Spawned)
     {
         SendLetter(Props.animalMentalState);
     }
 }
Esempio n. 20
0
        private void ImpactSomething()
        {
            if (def.projectile.flyOverhead)
            {
                RoofDef roofDef = base.Map.roofGrid.RoofAt(base.Position);
                if (roofDef != null)
                {
                    if (roofDef.isThickRoof)
                    {
                        ThrowDebugText("hit-thick-roof", base.Position);
                        def.projectile.soundHitThickRoof.PlayOneShot(new TargetInfo(base.Position, base.Map));
                        Destroy();
                        return;
                    }
                    if (base.Position.GetEdifice(base.Map) == null || base.Position.GetEdifice(base.Map).def.Fillage != FillCategory.Full)
                    {
                        RoofCollapserImmediate.DropRoofInCells(base.Position, base.Map);
                    }
                }
            }
            if (usedTarget.HasThing && CanHit(usedTarget.Thing))
            {
                Pawn pawn = usedTarget.Thing as Pawn;
                if (pawn != null && pawn.GetPosture() != 0 && (origin - destination).MagnitudeHorizontalSquared() >= 20.25f && !Rand.Chance(0.2f))
                {
                    ThrowDebugText("miss-laying", base.Position);
                    Impact(null);
                }
                else
                {
                    Impact(usedTarget.Thing);
                }
                return;
            }
            cellThingsFiltered.Clear();
            List <Thing> thingList = base.Position.GetThingList(base.Map);

            for (int i = 0; i < thingList.Count; i++)
            {
                Thing thing = thingList[i];
                if ((thing.def.category == ThingCategory.Building || thing.def.category == ThingCategory.Pawn || thing.def.category == ThingCategory.Item || thing.def.category == ThingCategory.Plant) && CanHit(thing))
                {
                    cellThingsFiltered.Add(thing);
                }
            }
            cellThingsFiltered.Shuffle();
            for (int j = 0; j < cellThingsFiltered.Count; j++)
            {
                Thing thing2 = cellThingsFiltered[j];
                Pawn  pawn2  = thing2 as Pawn;
                float num;
                if (pawn2 != null)
                {
                    num = 0.5f * Mathf.Clamp(pawn2.BodySize, 0.1f, 2f);
                    if (pawn2.GetPosture() != 0 && (origin - destination).MagnitudeHorizontalSquared() >= 20.25f)
                    {
                        num *= 0.2f;
                    }
                    if (launcher != null && pawn2.Faction != null && launcher.Faction != null && !pawn2.Faction.HostileTo(launcher.Faction))
                    {
                        num *= VerbUtility.InterceptChanceFactorFromDistance(origin, base.Position);
                    }
                }
                else
                {
                    num = 1.5f * thing2.def.fillPercent;
                }
                if (Rand.Chance(num))
                {
                    ThrowDebugText("hit-" + num.ToStringPercent(), base.Position);
                    Impact(cellThingsFiltered.RandomElement());
                    return;
                }
                ThrowDebugText("miss-" + num.ToStringPercent(), base.Position);
            }
            Impact(null);
        }
 private void ResetTicksToHeal()
 {
     this.ticksToHeal = Rand.Range(15, 30) * 60000;
 }
Esempio n. 22
0
 private void ImpactSomething()
 {
     if (this.def.projectile.flyOverhead)
     {
         RoofDef roofDef = base.Map.roofGrid.RoofAt(base.Position);
         if (roofDef != null)
         {
             if (roofDef.isThickRoof)
             {
                 this.ThrowDebugText("hit-thick-roof", base.Position);
                 this.def.projectile.soundHitThickRoof.PlayOneShot(new TargetInfo(base.Position, base.Map, false));
                 this.Destroy(DestroyMode.Vanish);
                 return;
             }
             if (base.Position.GetEdifice(base.Map) == null || base.Position.GetEdifice(base.Map).def.Fillage != FillCategory.Full)
             {
                 RoofCollapserImmediate.DropRoofInCells(base.Position, base.Map, null);
             }
         }
     }
     if (this.usedTarget.HasThing && this.CanHit(this.usedTarget.Thing))
     {
         Pawn pawn = this.usedTarget.Thing as Pawn;
         if (pawn != null && pawn.GetPosture() != PawnPosture.Standing && (this.origin - this.destination).MagnitudeHorizontalSquared() >= 20.25f)
         {
             if (!Rand.Chance(0.2f))
             {
                 this.ThrowDebugText("miss-laying", base.Position);
                 this.Impact(null);
                 return;
             }
         }
         this.Impact(this.usedTarget.Thing);
     }
     else
     {
         Projectile.cellThingsFiltered.Clear();
         List <Thing> thingList = base.Position.GetThingList(base.Map);
         for (int i = 0; i < thingList.Count; i++)
         {
             Thing thing = thingList[i];
             if (thing.def.category == ThingCategory.Building || thing.def.category == ThingCategory.Pawn || thing.def.category == ThingCategory.Item || thing.def.category == ThingCategory.Plant)
             {
                 if (this.CanHit(thing))
                 {
                     Projectile.cellThingsFiltered.Add(thing);
                 }
             }
         }
         Projectile.cellThingsFiltered.Shuffle <Thing>();
         for (int j = 0; j < Projectile.cellThingsFiltered.Count; j++)
         {
             Thing thing2 = Projectile.cellThingsFiltered[j];
             Pawn  pawn2  = thing2 as Pawn;
             float num;
             if (pawn2 != null)
             {
                 num = 0.5f * Mathf.Clamp(pawn2.BodySize, 0.1f, 2f);
             }
             else
             {
                 num = 1.5f * thing2.def.fillPercent;
             }
             if (Rand.Chance(num))
             {
                 this.ThrowDebugText("hit-" + num.ToStringPercent(), base.Position);
                 this.Impact(Projectile.cellThingsFiltered.RandomElement <Thing>());
                 return;
             }
             this.ThrowDebugText("miss-" + num.ToStringPercent(), base.Position);
         }
         this.Impact(null);
     }
 }
        private static Pawn GeneratePawnInternal(PawnGenerationRequest request)
        {
            request.EnsureNonNullFaction();
            Pawn pawn = null;

            if (!request.Newborn && !request.ForceGenerateNewPawn)
            {
                if (request.ForceRedressWorldPawnIfFormerColonist)
                {
                    IEnumerable <Pawn> validCandidatesToRedress = PawnGenerator.GetValidCandidatesToRedress(request);
                    if (validCandidatesToRedress.Where(PawnUtility.EverBeenColonistOrTameAnimal).TryRandomElementByWeight <Pawn>((Func <Pawn, float>)PawnGenerator.WorldPawnSelectionWeight, out pawn))
                    {
                        PawnGenerator.RedressPawn(pawn, request);
                        Find.WorldPawns.RemovePawn(pawn);
                    }
                }
                if (pawn == null && request.Inhabitant && request.Tile != -1)
                {
                    Settlement settlement = Find.WorldObjects.WorldObjectAt <Settlement>(request.Tile);
                    if (settlement != null && settlement.previouslyGeneratedInhabitants.Any())
                    {
                        IEnumerable <Pawn> validCandidatesToRedress2 = PawnGenerator.GetValidCandidatesToRedress(request);
                        if ((from x in validCandidatesToRedress2
                             where settlement.previouslyGeneratedInhabitants.Contains(x)
                             select x).TryRandomElementByWeight <Pawn>((Func <Pawn, float>)PawnGenerator.WorldPawnSelectionWeight, out pawn))
                        {
                            PawnGenerator.RedressPawn(pawn, request);
                            Find.WorldPawns.RemovePawn(pawn);
                        }
                    }
                }
                if (pawn == null && Rand.Chance(PawnGenerator.ChanceToRedressAnyWorldPawn(request)))
                {
                    IEnumerable <Pawn> validCandidatesToRedress3 = PawnGenerator.GetValidCandidatesToRedress(request);
                    if (validCandidatesToRedress3.TryRandomElementByWeight <Pawn>((Func <Pawn, float>)PawnGenerator.WorldPawnSelectionWeight, out pawn))
                    {
                        PawnGenerator.RedressPawn(pawn, request);
                        Find.WorldPawns.RemovePawn(pawn);
                    }
                }
            }
            if (pawn == null)
            {
                pawn = PawnGenerator.GenerateNewNakedPawn(ref request);
                if (pawn == null)
                {
                    return(null);
                }
                if (!request.Newborn)
                {
                    PawnGenerator.GenerateGearFor(pawn, request);
                }
                if (request.Inhabitant && request.Tile != -1)
                {
                    Settlement settlement2 = Find.WorldObjects.WorldObjectAt <Settlement>(request.Tile);
                    if (settlement2 != null)
                    {
                        settlement2.previouslyGeneratedInhabitants.Add(pawn);
                    }
                }
            }
            if (Find.Scenario != null)
            {
                Find.Scenario.Notify_PawnGenerated(pawn, request.Context);
            }
            return(pawn);
        }
        public void HealthTick()
        {
            if (Dead)
            {
                return;
            }
            for (int num = hediffSet.hediffs.Count - 1; num >= 0; num--)
            {
                Hediff hediff = hediffSet.hediffs[num];
                try
                {
                    hediff.Tick();
                    hediff.PostTick();
                }
                catch (Exception ex)
                {
                    Log.Error("Exception ticking hediff " + hediff.ToStringSafe() + " for pawn " + pawn.ToStringSafe() + ". Removing hediff... Exception: " + ex);
                    try
                    {
                        RemoveHediff(hediff);
                    }
                    catch (Exception arg)
                    {
                        Log.Error("Error while removing hediff: " + arg);
                    }
                }
                if (Dead)
                {
                    return;
                }
            }
            bool flag = false;

            for (int num2 = hediffSet.hediffs.Count - 1; num2 >= 0; num2--)
            {
                Hediff hediff2 = hediffSet.hediffs[num2];
                if (hediff2.ShouldRemove)
                {
                    hediffSet.hediffs.RemoveAt(num2);
                    hediff2.PostRemoved();
                    flag = true;
                }
            }
            if (flag)
            {
                Notify_HediffChanged(null);
            }
            if (Dead)
            {
                return;
            }
            immunity.ImmunityHandlerTick();
            if (pawn.RaceProps.IsFlesh && pawn.IsHashIntervalTick(600) && (pawn.needs.food == null || !pawn.needs.food.Starving))
            {
                bool flag2 = false;
                if (hediffSet.HasNaturallyHealingInjury())
                {
                    float num3 = 8f;
                    if (pawn.GetPosture() != 0)
                    {
                        num3 += 4f;
                        Building_Bed building_Bed = pawn.CurrentBed();
                        if (building_Bed != null)
                        {
                            num3 += building_Bed.def.building.bed_healPerDay;
                        }
                    }
                    foreach (Hediff hediff3 in hediffSet.hediffs)
                    {
                        HediffStage curStage = hediff3.CurStage;
                        if (curStage != null && curStage.naturalHealingFactor != -1f)
                        {
                            num3 *= curStage.naturalHealingFactor;
                        }
                    }
                    (from x in hediffSet.GetHediffs <Hediff_Injury>()
                     where x.CanHealNaturally()
                     select x).RandomElement().Heal(num3 * pawn.HealthScale * 0.01f);
                    flag2 = true;
                }
                if (hediffSet.HasTendedAndHealingInjury() && (pawn.needs.food == null || !pawn.needs.food.Starving))
                {
                    Hediff_Injury hediff_Injury = (from x in hediffSet.GetHediffs <Hediff_Injury>()
                                                   where x.CanHealFromTending()
                                                   select x).RandomElement();
                    float tendQuality = hediff_Injury.TryGetComp <HediffComp_TendDuration>().tendQuality;
                    float num4        = GenMath.LerpDouble(0f, 1f, 0.5f, 1.5f, Mathf.Clamp01(tendQuality));
                    hediff_Injury.Heal(8f * num4 * pawn.HealthScale * 0.01f);
                    flag2 = true;
                }
                if (flag2 && !HasHediffsNeedingTendByPlayer() && !HealthAIUtility.ShouldSeekMedicalRest(pawn) && !hediffSet.HasTendedAndHealingInjury() && PawnUtility.ShouldSendNotificationAbout(pawn))
                {
                    Messages.Message("MessageFullyHealed".Translate(pawn.LabelCap, pawn), pawn, MessageTypeDefOf.PositiveEvent);
                }
            }
            if (pawn.RaceProps.IsFlesh && hediffSet.BleedRateTotal >= 0.1f)
            {
                float num5 = hediffSet.BleedRateTotal * pawn.BodySize;
                num5 = ((pawn.GetPosture() != 0) ? (num5 * 0.0004f) : (num5 * 0.004f));
                if (Rand.Value < num5)
                {
                    DropBloodFilth();
                }
            }
            if (!pawn.IsHashIntervalTick(60))
            {
                return;
            }
            List <HediffGiverSetDef> hediffGiverSets = pawn.RaceProps.hediffGiverSets;

            if (hediffGiverSets != null)
            {
                for (int i = 0; i < hediffGiverSets.Count; i++)
                {
                    List <HediffGiver> hediffGivers = hediffGiverSets[i].hediffGivers;
                    for (int j = 0; j < hediffGivers.Count; j++)
                    {
                        hediffGivers[j].OnIntervalPassed(pawn, null);
                        if (pawn.Dead)
                        {
                            return;
                        }
                    }
                }
            }
            if (pawn.story == null)
            {
                return;
            }
            List <Trait> allTraits = pawn.story.traits.allTraits;

            for (int k = 0; k < allTraits.Count; k++)
            {
                TraitDegreeData currentData = allTraits[k].CurrentData;
                if (!(currentData.randomDiseaseMtbDays > 0f) || !Rand.MTBEventOccurs(currentData.randomDiseaseMtbDays, 60000f, 60f))
                {
                    continue;
                }
                BiomeDef biome;
                if (pawn.Tile != -1)
                {
                    biome = Find.WorldGrid[pawn.Tile].biome;
                }
                else
                {
                    biome = DefDatabase <BiomeDef> .GetRandom();
                }
                IncidentDef incidentDef = DefDatabase <IncidentDef> .AllDefs.Where((IncidentDef d) => d.category == IncidentCategoryDefOf.DiseaseHuman).RandomElementByWeightWithFallback((IncidentDef d) => biome.CommonalityOfDisease(d));

                if (incidentDef == null)
                {
                    continue;
                }
                string      blockedInfo;
                List <Pawn> list = ((IncidentWorker_Disease)incidentDef.Worker).ApplyToPawns(Gen.YieldSingle(pawn), out blockedInfo);
                if (PawnUtility.ShouldSendNotificationAbout(pawn))
                {
                    if (list.Contains(pawn))
                    {
                        Find.LetterStack.ReceiveLetter("LetterLabelTraitDisease".Translate(incidentDef.diseaseIncident.label), "LetterTraitDisease".Translate(pawn.LabelCap, incidentDef.diseaseIncident.label, pawn.Named("PAWN")).AdjustedFor(pawn), LetterDefOf.NegativeEvent, pawn);
                    }
                    else if (!blockedInfo.NullOrEmpty())
                    {
                        Messages.Message(blockedInfo, pawn, MessageTypeDefOf.NeutralEvent);
                    }
                }
            }
        }
 private static void GenerateRandomAge(Pawn pawn, PawnGenerationRequest request)
 {
     if (request.FixedBiologicalAge.HasValue && request.FixedChronologicalAge.HasValue)
     {
         float?fixedBiologicalAge    = request.FixedBiologicalAge;
         bool  hasValue              = fixedBiologicalAge.HasValue;
         float?fixedChronologicalAge = request.FixedChronologicalAge;
         if ((hasValue & fixedChronologicalAge.HasValue) && fixedBiologicalAge.GetValueOrDefault() > fixedChronologicalAge.GetValueOrDefault())
         {
             Log.Warning("Tried to generate age for pawn " + pawn + ", but pawn generation request demands biological age (" + request.FixedBiologicalAge + ") to be greater than chronological age (" + request.FixedChronologicalAge + ").");
         }
     }
     if (request.Newborn)
     {
         pawn.ageTracker.AgeBiologicalTicks = 0L;
     }
     else if (request.FixedBiologicalAge.HasValue)
     {
         pawn.ageTracker.AgeBiologicalTicks = (long)(request.FixedBiologicalAge.Value * 3600000.0);
     }
     else
     {
         float num  = 0f;
         int   num2 = 0;
         while (true)
         {
             num = ((pawn.RaceProps.ageGenerationCurve == null) ? ((!pawn.RaceProps.IsMechanoid) ? (Rand.ByCurve(PawnGenerator.DefaultAgeGenerationCurve, 200) * pawn.RaceProps.lifeExpectancy) : ((float)Rand.Range(0, 2500))) : ((float)Mathf.RoundToInt(Rand.ByCurve(pawn.RaceProps.ageGenerationCurve, 200))));
             num2++;
             if (num2 > 300)
             {
                 Log.Error("Tried 300 times to generate age for " + pawn);
                 break;
             }
             if (!(num > (float)pawn.kindDef.maxGenerationAge) && !(num < (float)pawn.kindDef.minGenerationAge))
             {
                 break;
             }
         }
         pawn.ageTracker.AgeBiologicalTicks = (long)(num * 3600000.0) + Rand.Range(0, 3600000);
     }
     if (request.Newborn)
     {
         pawn.ageTracker.AgeChronologicalTicks = 0L;
     }
     else if (request.FixedChronologicalAge.HasValue)
     {
         pawn.ageTracker.AgeChronologicalTicks = (long)(request.FixedChronologicalAge.Value * 3600000.0);
     }
     else
     {
         int num3;
         if (request.CertainlyBeenInCryptosleep || Rand.Value < pawn.kindDef.backstoryCryptosleepCommonality)
         {
             float value = Rand.Value;
             if (value < 0.699999988079071)
             {
                 num3 = Rand.Range(0, 100);
             }
             else if (value < 0.949999988079071)
             {
                 num3 = Rand.Range(100, 1000);
             }
             else
             {
                 int max = GenDate.Year(GenTicks.TicksAbs, 0f) - 2026 - pawn.ageTracker.AgeBiologicalYears;
                 num3 = Rand.Range(1000, max);
             }
         }
         else
         {
             num3 = 0;
         }
         int  ticksAbs = GenTicks.TicksAbs;
         long num4     = ticksAbs - pawn.ageTracker.AgeBiologicalTicks;
         num4 -= (long)num3 * 3600000L;
         pawn.ageTracker.BirthAbsTicks = num4;
     }
     if (pawn.ageTracker.AgeBiologicalTicks > pawn.ageTracker.AgeChronologicalTicks)
     {
         pawn.ageTracker.AgeChronologicalTicks = pawn.ageTracker.AgeBiologicalTicks;
     }
 }
Esempio n. 26
0
        public static void FlavorfulCombatTest()
        {
            List <DebugMenuOption>    list      = new List <DebugMenuOption>();
            IEnumerable <ManeuverDef> maneuvers = DefDatabase <ManeuverDef> .AllDefsListForReading;

            Func <ManeuverDef, RulePackDef>[] results = new Func <ManeuverDef, RulePackDef>[5]
            {
                (ManeuverDef m) => new RulePackDef[4]
                {
                    m.combatLogRulesHit,
                    m.combatLogRulesDeflect,
                    m.combatLogRulesMiss,
                    m.combatLogRulesDodge
                }.RandomElement(),
                (ManeuverDef m) => m.combatLogRulesHit,
                (ManeuverDef m) => m.combatLogRulesDeflect,
                (ManeuverDef m) => m.combatLogRulesMiss,
                (ManeuverDef m) => m.combatLogRulesDodge
            };
            string[] array = new string[5]
            {
                "(random)",
                "Hit",
                "Deflect",
                "Miss",
                "Dodge"
            };
            foreach (Pair <ManeuverDef, int> item2 in maneuvers.Concat(null).Cross(Enumerable.Range(0, array.Length)))
            {
                DebugMenuOption item = new DebugMenuOption(string.Format("{0}/{1}", (item2.First != null) ? item2.First.defName : "(random)", array[item2.Second]), DebugMenuOptionMode.Action, delegate
                {
                    CreateDamagedDestroyedMenu(delegate(Action <List <BodyPartRecord>, List <bool> > bodyPartCreator)
                    {
                        StringBuilder stringBuilder7 = new StringBuilder();
                        for (int num2 = 0; num2 < 100; num2++)
                        {
                            ManeuverDef maneuver = item2.First;
                            if (maneuver == null)
                            {
                                maneuver = maneuvers.RandomElement();
                            }
                            RulePackDef rulePackDef     = results[item2.Second](maneuver);
                            List <BodyPartRecord> list8 = null;
                            List <bool> list9           = null;
                            if (rulePackDef == maneuver.combatLogRulesHit)
                            {
                                list8 = new List <BodyPartRecord>();
                                list9 = new List <bool>();
                                bodyPartCreator(list8, list9);
                            }
                            Pair <ThingDef, Tool> pair = (from ttp in (from td in DefDatabase <ThingDef> .AllDefsListForReading
                                                                       where td.IsMeleeWeapon && !td.tools.NullOrEmpty()
                                                                       select td).SelectMany((ThingDef td) => from tool in td.tools
                                                                                             select new Pair <ThingDef, Tool>(td, tool))
                                                          where ttp.Second.capacities.Contains(maneuver.requiredCapacity)
                                                          select ttp).RandomElement();
                            BattleLogEntry_MeleeCombat battleLogEntry_MeleeCombat = new BattleLogEntry_MeleeCombat(rulePackDef, alwaysShowInCompact: false, CombatLogTester.GenerateRandom(), CombatLogTester.GenerateRandom(), (pair.Second == null) ? ImplementOwnerTypeDefOf.Bodypart : ImplementOwnerTypeDefOf.Weapon, (pair.Second == null) ? "body part" : pair.Second.label, pair.First);
                            battleLogEntry_MeleeCombat.FillTargets(list8, list9, battleLogEntry_MeleeCombat.RuleDef.defName.Contains("Deflect"));
                            battleLogEntry_MeleeCombat.Debug_OverrideTicks(Rand.Int);
                            stringBuilder7.AppendLine(battleLogEntry_MeleeCombat.ToGameStringFromPOV(null));
                        }
                        Log.Message(stringBuilder7.ToString());
                    });
                });
                list.Add(item);
            }
            int rf;

            for (rf = 0; rf < 2; rf++)
            {
                list.Add(new DebugMenuOption((rf != 0) ? "Ranged fire burst" : "Ranged fire singleshot", DebugMenuOptionMode.Action, delegate
                {
                    StringBuilder stringBuilder6 = new StringBuilder();
                    for (int num = 0; num < 100; num++)
                    {
                        ThingDef thingDef = (from td in DefDatabase <ThingDef> .AllDefsListForReading
                                             where td.IsRangedWeapon
                                             select td).RandomElement();
                        bool flag  = Rand.Value < 0.2f;
                        bool flag2 = !flag && Rand.Value < 0.95f;
                        BattleLogEntry_RangedFire battleLogEntry_RangedFire = new BattleLogEntry_RangedFire(CombatLogTester.GenerateRandom(), (!flag) ? CombatLogTester.GenerateRandom() : null, (!flag2) ? thingDef : null, null, rf != 0);
                        battleLogEntry_RangedFire.Debug_OverrideTicks(Rand.Int);
                        stringBuilder6.AppendLine(battleLogEntry_RangedFire.ToGameStringFromPOV(null));
                    }
                    Log.Message(stringBuilder6.ToString());
                }));
            }
            list.Add(new DebugMenuOption("Ranged impact hit", DebugMenuOptionMode.Action, delegate
            {
                CreateDamagedDestroyedMenu(delegate(Action <List <BodyPartRecord>, List <bool> > bodyPartCreator)
                {
                    StringBuilder stringBuilder5 = new StringBuilder();
                    for (int n = 0; n < 100; n++)
                    {
                        ThingDef weaponDef3 = (from td in DefDatabase <ThingDef> .AllDefsListForReading
                                               where td.IsRangedWeapon
                                               select td).RandomElement();
                        List <BodyPartRecord> list6 = new List <BodyPartRecord>();
                        List <bool> list7           = new List <bool>();
                        bodyPartCreator(list6, list7);
                        Pawn pawn2 = CombatLogTester.GenerateRandom();
                        BattleLogEntry_RangedImpact battleLogEntry_RangedImpact3 = new BattleLogEntry_RangedImpact(CombatLogTester.GenerateRandom(), pawn2, pawn2, weaponDef3, null, ThingDefOf.Wall);
                        battleLogEntry_RangedImpact3.FillTargets(list6, list7, Rand.Chance(0.5f));
                        battleLogEntry_RangedImpact3.Debug_OverrideTicks(Rand.Int);
                        stringBuilder5.AppendLine(battleLogEntry_RangedImpact3.ToGameStringFromPOV(null));
                    }
                    Log.Message(stringBuilder5.ToString());
                });
            }));
            list.Add(new DebugMenuOption("Ranged impact miss", DebugMenuOptionMode.Action, delegate
            {
                StringBuilder stringBuilder4 = new StringBuilder();
                for (int l = 0; l < 100; l++)
                {
                    ThingDef weaponDef2 = (from td in DefDatabase <ThingDef> .AllDefsListForReading
                                           where td.IsRangedWeapon
                                           select td).RandomElement();
                    BattleLogEntry_RangedImpact battleLogEntry_RangedImpact2 = new BattleLogEntry_RangedImpact(CombatLogTester.GenerateRandom(), null, CombatLogTester.GenerateRandom(), weaponDef2, null, ThingDefOf.Wall);
                    battleLogEntry_RangedImpact2.Debug_OverrideTicks(Rand.Int);
                    stringBuilder4.AppendLine(battleLogEntry_RangedImpact2.ToGameStringFromPOV(null));
                }
                Log.Message(stringBuilder4.ToString());
            }));
            list.Add(new DebugMenuOption("Ranged impact hit incorrect", DebugMenuOptionMode.Action, delegate
            {
                CreateDamagedDestroyedMenu(delegate(Action <List <BodyPartRecord>, List <bool> > bodyPartCreator)
                {
                    StringBuilder stringBuilder3 = new StringBuilder();
                    for (int k = 0; k < 100; k++)
                    {
                        ThingDef weaponDef = (from td in DefDatabase <ThingDef> .AllDefsListForReading
                                              where td.IsRangedWeapon
                                              select td).RandomElement();
                        List <BodyPartRecord> list4 = new List <BodyPartRecord>();
                        List <bool> list5           = new List <bool>();
                        bodyPartCreator(list4, list5);
                        BattleLogEntry_RangedImpact battleLogEntry_RangedImpact = new BattleLogEntry_RangedImpact(CombatLogTester.GenerateRandom(), CombatLogTester.GenerateRandom(), CombatLogTester.GenerateRandom(), weaponDef, null, ThingDefOf.Wall);
                        battleLogEntry_RangedImpact.FillTargets(list4, list5, Rand.Chance(0.5f));
                        battleLogEntry_RangedImpact.Debug_OverrideTicks(Rand.Int);
                        stringBuilder3.AppendLine(battleLogEntry_RangedImpact.ToGameStringFromPOV(null));
                    }
                    Log.Message(stringBuilder3.ToString());
                });
            }));
            foreach (RulePackDef item3 in from def in DefDatabase <RulePackDef> .AllDefsListForReading
                     where def.defName.Contains("Transition") && !def.defName.Contains("Include")
                     select def)
            {
                list.Add(new DebugMenuOption(item3.defName, DebugMenuOptionMode.Action, delegate
                {
                    StringBuilder stringBuilder2 = new StringBuilder();
                    for (int j = 0; j < 100; j++)
                    {
                        Pawn pawn                 = CombatLogTester.GenerateRandom();
                        Pawn initiator            = CombatLogTester.GenerateRandom();
                        BodyPartRecord partRecord = pawn.health.hediffSet.GetNotMissingParts().RandomElement();
                        BattleLogEntry_StateTransition battleLogEntry_StateTransition = new BattleLogEntry_StateTransition(pawn, item3, initiator, HediffMaker.MakeHediff(DefDatabase <HediffDef> .AllDefsListForReading.RandomElement(), pawn, partRecord), pawn.RaceProps.body.AllParts.RandomElement());
                        battleLogEntry_StateTransition.Debug_OverrideTicks(Rand.Int);
                        stringBuilder2.AppendLine(battleLogEntry_StateTransition.ToGameStringFromPOV(null));
                    }
                    Log.Message(stringBuilder2.ToString());
                }));
            }
            foreach (RulePackDef item4 in from def in DefDatabase <RulePackDef> .AllDefsListForReading
                     where def.defName.Contains("DamageEvent") && !def.defName.Contains("Include")
                     select def)
            {
                list.Add(new DebugMenuOption(item4.defName, DebugMenuOptionMode.Action, delegate
                {
                    CreateDamagedDestroyedMenu(delegate(Action <List <BodyPartRecord>, List <bool> > bodyPartCreator)
                    {
                        StringBuilder stringBuilder = new StringBuilder();
                        for (int i = 0; i < 100; i++)
                        {
                            List <BodyPartRecord> list2 = new List <BodyPartRecord>();
                            List <bool> list3           = new List <bool>();
                            bodyPartCreator(list2, list3);
                            Pawn recipient = CombatLogTester.GenerateRandom();
                            BattleLogEntry_DamageTaken battleLogEntry_DamageTaken = new BattleLogEntry_DamageTaken(recipient, item4);
                            battleLogEntry_DamageTaken.FillTargets(list2, list3, deflected: false);
                            battleLogEntry_DamageTaken.Debug_OverrideTicks(Rand.Int);
                            stringBuilder.AppendLine(battleLogEntry_DamageTaken.ToGameStringFromPOV(null));
                        }
                        Log.Message(stringBuilder.ToString());
                    });
                }));
            }
            Find.WindowStack.Add(new Dialog_DebugOptionListLister(list));
        }
        private static void GenerateTraits(Pawn pawn, PawnGenerationRequest request)
        {
            if (pawn.story != null)
            {
                if (pawn.story.childhood.forcedTraits != null)
                {
                    List <TraitEntry> forcedTraits = pawn.story.childhood.forcedTraits;
                    for (int i = 0; i < forcedTraits.Count; i++)
                    {
                        TraitEntry traitEntry = forcedTraits[i];
                        if (traitEntry.def == null)
                        {
                            Log.Error("Null forced trait def on " + pawn.story.childhood);
                        }
                        else if (!pawn.story.traits.HasTrait(traitEntry.def))
                        {
                            pawn.story.traits.GainTrait(new Trait(traitEntry.def, traitEntry.degree, false));
                        }
                    }
                }
                if (pawn.story.adulthood != null && pawn.story.adulthood.forcedTraits != null)
                {
                    List <TraitEntry> forcedTraits2 = pawn.story.adulthood.forcedTraits;
                    for (int j = 0; j < forcedTraits2.Count; j++)
                    {
                        TraitEntry traitEntry2 = forcedTraits2[j];
                        if (traitEntry2.def == null)
                        {
                            Log.Error("Null forced trait def on " + pawn.story.adulthood);
                        }
                        else if (!pawn.story.traits.HasTrait(traitEntry2.def))
                        {
                            pawn.story.traits.GainTrait(new Trait(traitEntry2.def, traitEntry2.degree, false));
                        }
                    }
                }
                int num = Rand.RangeInclusive(2, 3);
                if (request.AllowGay && (LovePartnerRelationUtility.HasAnyLovePartnerOfTheSameGender(pawn) || LovePartnerRelationUtility.HasAnyExLovePartnerOfTheSameGender(pawn)))
                {
                    Trait trait = new Trait(TraitDefOf.Gay, PawnGenerator.RandomTraitDegree(TraitDefOf.Gay), false);
                    pawn.story.traits.GainTrait(trait);
                }
                while (pawn.story.traits.allTraits.Count < num)
                {
                    TraitDef newTraitDef = DefDatabase <TraitDef> .AllDefsListForReading.RandomElementByWeight((TraitDef tr) => tr.GetGenderSpecificCommonality(pawn));

                    Trait trait2;
                    if (!pawn.story.traits.HasTrait(newTraitDef) && (newTraitDef != TraitDefOf.Gay || (request.AllowGay && !LovePartnerRelationUtility.HasAnyLovePartnerOfTheOppositeGender(pawn) && !LovePartnerRelationUtility.HasAnyExLovePartnerOfTheOppositeGender(pawn))) && (request.Faction == null || Faction.OfPlayerSilentFail == null || !request.Faction.HostileTo(Faction.OfPlayer) || newTraitDef.allowOnHostileSpawn) && !pawn.story.traits.allTraits.Any((Trait tr) => newTraitDef.ConflictsWith(tr)) && (newTraitDef.conflictingTraits == null || !newTraitDef.conflictingTraits.Any((TraitDef tr) => pawn.story.traits.HasTrait(tr))) && (newTraitDef.requiredWorkTypes == null || !pawn.story.OneOfWorkTypesIsDisabled(newTraitDef.requiredWorkTypes)) && !pawn.story.WorkTagIsDisabled(newTraitDef.requiredWorkTags))
                    {
                        int degree = PawnGenerator.RandomTraitDegree(newTraitDef);
                        if (!pawn.story.childhood.DisallowsTrait(newTraitDef, degree) && (pawn.story.adulthood == null || !pawn.story.adulthood.DisallowsTrait(newTraitDef, degree)))
                        {
                            trait2 = new Trait(newTraitDef, degree, false);
                            if (pawn.mindState != null && pawn.mindState.mentalBreaker != null)
                            {
                                float breakThresholdExtreme = pawn.mindState.mentalBreaker.BreakThresholdExtreme;
                                breakThresholdExtreme += trait2.OffsetOfStat(StatDefOf.MentalBreakThreshold);
                                breakThresholdExtreme *= trait2.MultiplierOfStat(StatDefOf.MentalBreakThreshold);
                                if (!(breakThresholdExtreme > 0.40000000596046448))
                                {
                                    goto IL_04be;
                                }
                                continue;
                            }
                            goto IL_04be;
                        }
                    }
                    continue;
IL_04be:
                    pawn.story.traits.GainTrait(trait2);
                }
            }
        }
 public override bool ShowInCompactView()
 {
     return(Rand.ChanceSeeded(BattleLogEntry_RangedFire.DisplayChance, this.logID));
 }
Esempio n. 29
0
 public static IntVec3 RandomAdjacentCell8Way(this IntVec3 root)
 {
     return(root + GenAdj.AdjacentCells[Rand.RangeInclusive(0, 7)]);
 }