예제 #1
0
파일: Util.cs 프로젝트: scyde/Hardcore-SK
        //provides a new Compglower
        public static CompGlower newCompGlower(ThingWithComps parent, ColorInt glowColour, float glowRadius)
        {
            CompGlower Comp_NewGlower = new CompGlower();
            Comp_NewGlower.parent = parent;


            CompProperties CompProp_New = new CompProperties();
            CompProp_New.compClass = typeof(CompGlower);
            CompProp_New.glowColor = glowColour;
            CompProp_New.glowRadius = glowRadius;

            Comp_NewGlower.Initialize(CompProp_New);

            return Comp_NewGlower;
        }
예제 #2
0
파일: Util.cs 프로젝트: scyde/Hardcore-SK
        //moved it to util for easier implementation with MAD
        public static void DestroyNCreateGlower(ThingWithComps parent, ColorInt glowColour, float glowRadius)
        {
            CompGlower oldGlower = null;
            CompPowerTrader pwrTrader = null;

            List<ThingComp> list = parent.GetComps();

            foreach (ThingComp comp in list)
            {
                if (typeof(CompGlower) == comp.GetType())
                {
                    if (oldGlower == null)
                    {
                        oldGlower = (CompGlower)comp;
                    }

                }
                if (typeof(CompPowerTrader) == comp.GetType())
                {
                    pwrTrader = (CompPowerTrader)comp;
                }
            }
            if (oldGlower != null)
            {

                Boolean isLitoldGlower = oldGlower.Lit;
                oldGlower.Lit = false;

                CompGlower newGlower = Util.newCompGlower(parent, glowColour, glowRadius);
                list.Remove(oldGlower);
                list.Add(newGlower);

                parent.SetComps(list);

                newGlower.Lit = false;
                updateMap(parent.Position);

                if (pwrTrader != null)
                {
                    if (isLitoldGlower && pwrTrader.PowerOn)
                    {
                        newGlower.Lit = true;
                    }
                }
            }

        }
예제 #3
0
        // swap selected equipment and primary equipment
        public void SwapEquipment(ThingWithComps thing)
        {
            // if pawn has equipped weapon
            if (owner.equipment.Primary != null)
            {
                ThingWithComps resultThing;
                // put weapon in slotter
                owner.equipment.TryTransferEquipmentToContainer(owner.equipment.Primary, slots, out resultThing);
            }
            // equip new weapon
            owner.equipment.AddEquipment(thing);
            // remove that equipment from slotter
            slots.Remove(thing);

            // interrupt current jobs to prevent random errors
            if (owner?.jobs.curJob != null)
                owner.jobs.EndCurrentJob(JobCondition.InterruptForced);
        }
예제 #4
0
        private static float GetMeleeDamage(Pawn pawn, ThingWithComps weapon)
        {
            if (pawn == null)
            {
                return(0f);
            }

            List <Verb> verbsList;

            if (weapon != null)
            {
                verbsList = new List <Verb>();
                verbsList.Add(weapon.GetComp <CompEquippable>().PrimaryVerb);
            }
            else
            {
                verbsList = GetUnarmedVerbs(pawn);
            }

            if (verbsList.Count == 0)
            {
                return(0f);
            }
            float num = 0f;

            for (int i = 0; i < verbsList.Count; i++)
            {
                num += verbsList[i].verbProps.AdjustedSelectionWeight(verbsList[i], pawn, verbsList[i].ownerEquipment);
            }
            float num2 = 0f;

            for (int j = 0; j < verbsList.Count; j++)
            {
                ThingWithComps ownerEquipment  = verbsList[j].ownerEquipment;
                float          selectionWeight = verbsList[j].verbProps.AdjustedSelectionWeight(verbsList[j], pawn, verbsList[j].ownerEquipment);
                num2 += selectionWeight / num * (float)verbsList[j].verbProps.AdjustedMeleeDamageAmount(verbsList[j], pawn, ownerEquipment);
            }
            return(num2);
        }
예제 #5
0
        protected override IEnumerable <Toil> MakeNewToils()
        {
            //this.FailOnDespawnedOrNull(TargetIndex.A);
            this.FailOn(delegate
            {
                Designation designation = this.Map.designationManager.DesignationOn(this.TargetThingA, DesignationDefOf_Reconfigure.Reconfigure);
                return(designation == null);
            });
            yield return(Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.InteractionCell));

            yield return(Toils_General.Wait(100, TargetIndex.None).FailOnDestroyedNullOrForbidden(TargetIndex.A).FailOnCannotTouch(TargetIndex.A, PathEndMode.Touch));

            Toil finalize = new Toil();

            finalize.initAction = delegate
            {
                Pawn           actor = finalize.actor;
                ThingWithComps thing = (ThingWithComps)actor.CurJob.targetA.Thing;

                CompReconfigurable comp = thing.TryGetComp <CompReconfigurable>();
                if (comp != null && comp.NeedToReconfigure)
                {
                    //replace here
                    ThingWithComps replacement = (ThingWithComps)ThingMaker.MakeThing(comp.Props.resultDef, thing.Stuff);
                    replacement.SetFactionDirect(thing.Faction);
                    var spawned = GenSpawn.Spawn(replacement, thing.Position, thing.Map, thing.Rotation);
                    spawned.HitPoints = thing.HitPoints;
                    Find.Selector.Select(spawned, false);
                }

                Designation designation = this.Map.designationManager.DesignationOn(thing, DesignationDefOf_Reconfigure.Reconfigure);
                if (designation != null)
                {
                    designation.Delete();
                }
            };
            finalize.defaultCompleteMode = ToilCompleteMode.Instant;
            yield return(finalize);
        }
예제 #6
0
        private void TryGenerateShieldFor(Pawn pawn, CompInventory inventory, ThingWithComps primary)
        {
            if ((primary != null && !primary.def.weaponTags.Contains(Apparel_Shield.OneHandedTag)) ||
                shieldTags.NullOrEmpty() ||
                pawn.apparel == null ||
                !Rand.Chance(shieldChance))
            {
                return;
            }

            var money = shieldMoney.RandomInRange;

            foreach (ThingStuffPair cur in allShieldPairs)
            {
                if (cur.Price < money &&
                    shieldTags.Any(t => cur.thing.apparel.tags.Contains(t)) &&
                    (cur.thing.generateAllowChance >= 1f || Rand.ValueSeeded(pawn.thingIDNumber ^ 68715844) <= cur.thing.generateAllowChance) &&
                    pawn.apparel.CanWearWithoutDroppingAnything(cur.thing))
                {
                    workingShields.Add(cur);
                }
            }
            if (workingShields.Count == 0)
            {
                return;
            }
            ThingStuffPair pair;

            if (workingShields.TryRandomElementByWeight(p => p.Commonality * p.Price, out pair))
            {
                var shield = (Apparel)ThingMaker.MakeThing(pair.thing, pair.stuff);
                int count;
                if (inventory.CanFitInInventory(shield, out count, false, true))
                {
                    pawn.apparel.Wear(shield);
                }
            }
            workingShields.Clear();
        }
예제 #7
0
        public void removeDroppedEquipment()
        {
            while (DroppedApparel.Any())
            {
                Apparel apparel = DroppedApparel[0];
                UsedApparelList.Remove(DroppedApparel[0]);
                if (apparel != null && apparel.Destroyed == false)
                {
                    apparel.Destroy();
                }
            }

            while (DroppedWeapons.Any())
            {
                ThingWithComps weapon = DroppedWeapons[0];
                UsedWeaponList.Remove(DroppedWeapons[0]);
                if (weapon != null && weapon.Destroyed == false)
                {
                    weapon.Destroy();
                }
            }
        }
예제 #8
0
        public static bool AppendThingHoldersFromThings(List <IThingHolder> outThingsHolders, IList <Thing> container)
        {
            if (container == null)
            {
                return(false);
            }
            int i     = 0;
            int count = container.Count;

            while (i < count)
            {
                IThingHolder thingHolder = container[i] as IThingHolder;
                if (thingHolder != null)
                {
                    lock (outThingsHolders)
                    {
                        outThingsHolders.Add(thingHolder);
                    }
                }
                ThingWithComps thingWithComps = container[i] as ThingWithComps;
                if (thingWithComps != null)
                {
                    List <ThingComp> allComps = thingWithComps.AllComps;
                    for (int j = 0; j < allComps.Count; j++)
                    {
                        IThingHolder thingHolder2 = allComps[j] as IThingHolder;
                        if (thingHolder2 != null)
                        {
                            lock (outThingsHolders)
                            {
                                outThingsHolders.Add(thingHolder2);
                            }
                        }
                    }
                }
                i++;
            }
            return(false);
        }
예제 #9
0
        private void InterfaceDropHaul(Thing t)
        {
            ThingWithComps thingWithComps = t as ThingWithComps;
            Apparel        apparel        = t as Apparel;

            if (apparel != null && this.SelPawnForGear.apparel != null && this.SelPawnForGear.apparel.WornApparel.Contains(apparel))
            {
                this.SelPawnForGear.jobs.TryTakeOrderedJob(new Job(JobDefOf.RemoveApparel, apparel)
                {
                    haulDroppedApparel = true
                });
            }
            else if (thingWithComps != null && this.SelPawnForGear.equipment != null && this.SelPawnForGear.equipment.AllEquipment.Contains(thingWithComps))
            {
                this.SelPawnForGear.jobs.TryTakeOrderedJob(new Job(JobDefOf.DropEquipment, thingWithComps));
            }
            else if (!t.def.destroyOnDrop)
            {
                Thing thing;
                SelPawn.inventory.innerContainer.TryDrop(t, SelPawn.Position, SelPawn.Map, ThingPlaceMode.Near, out thing);
            }
        }
        public static void InitializeComps_PostFix(ThingWithComps __instance)
        {
            if (!(__instance is Pawn p))
            {
                return;
            }
            if (p.RaceProps == null || (!p.RaceProps.Animal))
            {
                return;
            }

            ThingComp thingComp = (ThingComp)Activator.CreateInstance(typeof(CompTransmogrified));

            thingComp.parent = __instance;
            var comps = AccessTools.Field(typeof(ThingWithComps), "comps").GetValue(__instance);

            if (comps != null)
            {
                ((List <ThingComp>)comps).Add(thingComp);
            }
            thingComp.Initialize(null);
        }
        // Token: 0x06000008 RID: 8 RVA: 0x000022A8 File Offset: 0x000004A8
        public override IEnumerable <Gizmo> CompGetGizmosWorn()
        {
            ThingWithComps owner = IsWorn ? GetWearer : parent;
            bool           flag  = Find.Selector.SelectedObjects.Contains(GetWearer);

            if (flag && GetWearer.IsColonist)
            {
                Texture2D CommandTex;
                int       num = 700000101;
                if (Toggled)
                {
                    CommandTex = ContentFinder <Texture2D> .Get("Ui/Commands/CommandButton_TurretModeOn", true);
                }
                else
                {
                    CommandTex = ContentFinder <Texture2D> .Get("Ui/Commands/CommandButton_TurretModeOff", true);
                }
                yield return(new Command_Toggle
                {
                    icon = CommandTex,
                    defaultLabel = Toggled ? "Turret: on." : "Turret: off.",
                    defaultDesc = "Switch mode.",
                    isActive = (() => Toggled),
                    toggleAction = delegate()
                    {
                        Toggled = !Toggled;
                        this.SwitchTurretMode();
                    },
                    activateSound = SoundDef.Named("Click"),
                    groupKey = num + 1,

                    /*
                     * disabled = GetWearer.stances.curStance.StanceBusy,
                     * disabledReason = "Busy"
                     */
                });
            }
            yield break;
        }
예제 #12
0
        /// <summary>
        /// Determines if and how many of an item currently fit into the inventory with regards to weight/bulk constraints.
        /// </summary>
        /// <param name="thing">Thing to check</param>
        /// <param name="count">Maximum amount of that item that can fit into the inventory</param>
        /// <param name="ignoreEquipment">Whether to include currently equipped weapons when calculating current weight/bulk</param>
        /// <param name="useApparelCalculations">Whether to use calculations for worn apparel. This will factor in equipped stat offsets boosting inventory space and use the worn bulk and weight.</param>
        /// <returns>True if one or more items fit into the inventory</returns>
        public bool CanFitInInventory(Thing thing, out int count, bool ignoreEquipment = false, bool useApparelCalculations = false)
        {
            float thingWeight;
            float thingBulk;

            if (useApparelCalculations)
            {
                thingWeight = thing.GetStatValue(StatDef.Named("WornWeight"));
                thingBulk   = thing.GetStatValue(StatDef.Named("WornBulk"));
                if (thingWeight <= 0 && thingBulk <= 0)
                {
                    count = 1;
                    return(true);
                }
                // Subtract the stat offsets we get from wearing this
                thingWeight -= thing.def.equippedStatOffsets.GetStatOffsetFromList(StatDef.Named("CarryWeight"));
                thingBulk   -= thing.def.equippedStatOffsets.GetStatOffsetFromList(StatDef.Named("CarryBulk"));
            }
            else
            {
                thingWeight = thing.GetStatValue(StatDef.Named("Weight"));
                thingBulk   = thing.GetStatValue(StatDef.Named("Bulk"));
            }
            // Subtract weight of currently equipped weapon
            float eqBulk   = 0f;
            float eqWeight = 0f;

            if (ignoreEquipment && this.parentPawn.equipment != null && this.parentPawn.equipment.Primary != null)
            {
                ThingWithComps eq = this.parentPawn.equipment.Primary;
                GetEquipmentStats(eq, out eqWeight, out eqBulk);
            }
            // Calculate how many items we can fit into our inventory
            float amountByWeight = thingWeight <= 0 ? thing.stackCount : (availableWeight + eqWeight) / thingWeight;
            float amountByBulk   = thingBulk <= 0 ? thing.stackCount : (availableBulk + eqBulk) / thingBulk;

            count = Mathf.FloorToInt(Mathf.Min(amountByBulk, amountByWeight, thing.stackCount));
            return(count > 0);
        }
예제 #13
0
        //far as I know, this all now works completely differently again. Yay.

        /*internal static float ReduceForArmorType(StatDef deflectionStat, Pawn target)
         * {
         *  float reduction = 1.0f;
         *  if (target != null)
         *  {
         *      BodyPartGroupDef bodyPartTest = BodyPartGroupDefOf.Torso;   //For statistical purposes, consider torso only
         *
         *      if (target.apparel != null && target.apparel.WornApparel != null)
         *      {
         *          foreach (Apparel apparel in target.apparel.WornApparel.Where(a => a.def.apparel.bodyPartGroups.Contains(bodyPartTest)))
         *          {
         *              reduction *= GetArmorTypeFactor(apparel.GetStatValue(deflectionStat, true));
         *          }
         *      }
         *
         *      reduction *= GetArmorTypeFactor(target.GetStatValue(deflectionStat, true));
         *  }
         *  return reduction;
         * }
         *
         * internal static float GetArmorTypeFactor(float armorRating)
         * {
         *  // Word from Tynan himself, praise be unto he
         *  // https://www.reddit.com/r/RimWorld/comments/2q542f/alpha_eight_armor_changes/
         *
         *   //One armor value.
         *   //Up to 50%, damage resistance increases.
         *   //Past 50%, damage deflection increases.
         *   //Past 100%, damage deflection and resistance both increase at 1/4 rate up to a maximum of 90% and 90%.
         *
         *  float resistance;
         *  float deflectChance;
         *
         *  if (armorRating <= 0.50)
         *  {
         *      resistance = armorRating;
         *      deflectChance = 0;
         *  }
         *  else if (armorRating < 1.0f)
         *  {
         *      resistance = 0.5f;
         *      deflectChance = armorRating - 0.5f;
         *  }
         *  else
         *  {
         *      resistance = 0.5f + (armorRating - 1f) * 0.25f;
         *      deflectChance = 0.5f + (armorRating - 1f) * 0.25f;
         *  }
         *
         *  if (resistance > 0.9f)
         *      resistance = 0.9f;
         *  if (deflectChance > 0.9f)
         *      deflectChance = 0.9f;
         *
         *  // Game code computes deflect or resist, we're looking for just the statistical average:
         *  return (1.0f - resistance) * (1.0f - deflectChance);
         * }*/

        internal static float MeleeDPS(Pawn pawn, ThingWithComps weapon, float speedBias, Pawn target)
        {
            if (pawn == null)
            {
                Log.Warning("attempted to calc meleeDPS for null pawn!");
                return(0);
            }

            float dps;

            if (weapon == null)
            {
                dps = GetUnarmdeMeleeDPS(pawn);
            }
            else
            {
                dps = weapon.GetStatValue(StatDefOf.MeleeWeapon_AverageDPS);
            }
            //float dps = GetMeleeDamage(pawn, weapon, target) * GetMeleeHitChance(pawn) / GetMeleeCooldown(pawn, weapon);

            return(dps);
        }
예제 #14
0
        // Grab slots of the thing if they exists. Returns null if none
        public static List <SlotLoadable> GetSlots(Thing someThing)
        {
            List <SlotLoadable> retval = null;

            ThingWithComps thingWithComps = someThing as ThingWithComps;

            if (thingWithComps != null)
            {
                ThingComp comp = thingWithComps.AllComps.FirstOrDefault((ThingComp x) => x is CompSlotLoadable);
                if (comp != null)
                {
                    CompSlotLoadable compSlotLoadable = comp as CompSlotLoadable;

                    if (compSlotLoadable.Slots != null && compSlotLoadable.Slots.Count > 0)
                    {
                        retval = compSlotLoadable.Slots;
                    }
                }
            }

            return(retval);
        }
        // RimWorld.ITab_Pawn_Gear

        /*
         *  PreFix
         *
         *  Disables the drop button's effect if the user is wearing a straitjacket.
         *  A straitjacket user should not be able to take it off by themselves, right?
         *
         */
        public static bool InterfaceDropPreFix(ITab_Pawn_Gear __instance, Thing t)
        {
            ThingWithComps thingWithComps = t as ThingWithComps;
            Apparel        apparel        = t as Apparel;
            Pawn           __pawn         = (Pawn)AccessTools.Method(typeof(ITab_Pawn_Gear), "get_SelPawnForGear").Invoke(__instance, new object[0]);

            if (__pawn != null)
            {
                if (apparel != null && __pawn.apparel != null && __pawn.apparel.WornApparel.Contains(apparel))
                {
                    if (apparel.def == StraitjacketDefOf.ROM_Straitjacket)
                    {
                        Messages.Message("CannotRemoveByOneself".Translate(new object[]
                        {
                            __pawn.Label
                        }), MessageTypeDefOf.RejectInput);//MessageSound.RejectInput);
                        return(false);
                    }
                }
            }
            return(true);
        }
예제 #16
0
        internal static float RangedDPS(ThingWithComps weapon, float speedBias, float range)
        {
            Verb           atkVerb  = (weapon.GetComp <CompEquippable>()).PrimaryVerb;
            VerbProperties atkProps = atkVerb.verbProps;

            //Log.Message("Range limits: > " + atkProps.minRange * atkProps.minRange + " < " + atkProps.range * atkProps.range + " range is "+range);

            if (atkProps.range * atkProps.range < range || atkProps.minRange * atkProps.minRange > range)
            {
                return(-1);
            }

            float damage            = (atkProps.projectileDef == null) ? 0 : atkProps.projectileDef.projectile.damageAmountBase;
            float warmup            = atkProps.warmupTime;
            float cooldown          = weapon.def.GetStatValueAbstract(StatDefOf.RangedWeapon_Cooldown, null);
            int   burstShot         = atkProps.burstShotCount;
            int   ticksBetweenShots = atkProps.ticksBetweenBurstShots;
            float rawDps            = (damage * burstShot) / (((warmup + cooldown)) + warmup * (speedBias - 1f) + (burstShot - 1) * (ticksBetweenShots / 60f));
            float Dps = rawDps * GetHitChanceFactor(atkProps, weapon, range);

            return(Dps);
        }
예제 #17
0
 public static void InitializeComps_PostFix(ThingWithComps __instance)
 {
     //Log.Message("1");
     if (__instance != null)
     {
         Pawn p = __instance as Pawn;
         if (p != null)
         {
             if (p.RaceProps != null && p.RaceProps.Humanlike)
             {
                 ThingComp thingComp = (ThingComp)Activator.CreateInstance(typeof(CompForceUser));
                 thingComp.parent = __instance;
                 var comps = AccessTools.Field(typeof(ThingWithComps), "comps").GetValue(__instance);
                 if (comps != null)
                 {
                     ((List <ThingComp>)comps).Add(thingComp);
                 }
                 thingComp.Initialize(null);
             }
         }
     }
 }
예제 #18
0
        private static Thing MakeThingSimple(TSP pair)
        {
            ThingWithComps thing       = new ThingWithComps();
            CompQuality    compQuality = new CompQuality
            {
                parent = thing
            };

            Traverse.Create(thing).Field("comps").SetValue(new List <ThingComp>()).Method("Add", compQuality).GetValue();
            Trace.WriteLine(thing.AllComps.Count);
            thing.def = pair.thing;
            thing.SetStuffDirect(pair.stuff);
            if (thing.TryGetComp <CompQuality>() == null)
            {
                Trace.WriteLine(thing.AllComps[0].GetType());
                Trace.WriteLine(thing.AllComps[0] as CompQuality == null ? "null" : "no");
                Trace.WriteLine(typeof(CompQuality));
                Trace.WriteLine("quality is null");
            }
            thing.TryGetComp <CompQuality>().SetQuality(pair.Quality, ArtGenerationContext.Outsider);
            return(thing);
        }
        public static void DrawColorTwoPostFix(Thing __instance, ref Color __result)
        {
            ThingWithComps thingWithComps = __instance as ThingWithComps;

            if (thingWithComps != null)
            {
                //Log.Message("3");
                CompSlotLoadable CompSlotLoadable = thingWithComps.GetComp <CompSlotLoadable>();
                if (CompSlotLoadable != null)
                {
                    SlotLoadable slot = CompSlotLoadable.SecondColorChangingSlot;
                    if (slot != null)
                    {
                        if (!slot.IsEmpty())
                        {
                            __result = slot.SlotOccupant.DrawColor;
                            __instance.Graphic.colorTwo = slot.SlotOccupant.DrawColor;
                        }
                    }
                }
            }
        }
        internal static bool TryDropEquipment(this Pawn_EquipmentTracker _this, ThingWithComps eq, out ThingWithComps resultingEq, IntVec3 pos, bool forbid = true)
        {
            // Fetch private fields
            Pawn pawn = (Pawn)pawnFieldInfo.GetValue(_this);

            if (!_this.AllEquipment.Contains(eq))
            {
                Log.Warning(pawn.LabelCap + " tried to drop equipment they didn't have: " + eq);
                resultingEq = null;
                return(false);
            }
            if (!pos.IsValid)
            {
                Log.Error(string.Concat(new object[]
                {
                    pawn,
                    " tried to drop ",
                    eq,
                    " at invalid cell."
                }));
                resultingEq = null;
                return(false);
            }
            _this.Remove(eq);
            Thing thing  = null;
            bool  result = GenThing.TryDropAndSetForbidden(eq, pos, pawn.MapHeld, ThingPlaceMode.Near, out thing, forbid);

            resultingEq = (thing as ThingWithComps);
            CE_Utility.TryUpdateInventory(pawn);       // Dropped equipment, update inventory

            // Cancel current job (use verb, etc.)
            if (pawn.Spawned)
            {
                pawn.stances.CancelBusyStanceSoft();
            }

            return(result);
        }
예제 #21
0
        public static bool equipBestWeaponFromInventoryByStatModifiers(Pawn pawn, List <StatDef> stats)
        {
            //Log.Message("looking for a stat booster for stats " + String.Join(",", stats.Select(s => s.label))); ;

            if (!pawn.IsValidSidearmsCarrier() || stats.Count == 0 || pawn.Drafted)
            {
                return(false);
            }

            CompSidearmMemory pawnMemory = CompSidearmMemory.GetMemoryCompForPawn(pawn);

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

            ThingWithComps bestBooster = pawn.getCarriedWeapons(includeTools: true).Where(t =>
            {
                _ = t.toThingDefStuffDefPair().getBestStatBoost(stats, out bool found); return(found);
            }).OrderBy(t =>
            {
                return(t.toThingDefStuffDefPair().getBestStatBoost(stats, out _));
            }).FirstOrDefault();

            if (bestBooster == default(ThingWithComps))
            {
                return(false);
            }

            if (bestBooster == pawn.equipment.Primary)
            {
                return(true);
            }

            bool success = equipSpecificWeaponFromInventory(pawn, bestBooster, false, false);

            return(success);
        }
예제 #22
0
 public override void TransformValue(StatRequest req, ref float val)
 {
     try
     {
         if (req.HasThing)
         {
             if (req.Thing.def.weaponTags != null)
             {
                 if (req.Thing.def.weaponTags.Contains("NegativeRecoil"))
                 {
                     ThingWithComps weaponThing = req.Thing as ThingWithComps;
                     if (weaponThing != null)
                     {
                         CompBuffManager buffComp = weaponThing.GetComp <CompBuffManager>();
                         if (buffComp != null)
                         {
                             NegativeRecoilBuff buff = buffComp.FindWithTags(new List <string> {
                                 "NegativeRecoil", "Weapon"
                             }) as NegativeRecoilBuff;
                             if (buff != null)
                             {
                                 float additionalVal = Mathf.Pow(buff.AdditionalAccuracy, buff.CurrentOverlapLevel);
                                 val += (additionalVal - 1);
                             }
                         }
                     }
                 }
             }
         }
     }
     catch (Exception ee)
     {
         if (req.HasThing)
         {
             Log.Error("StatPart_AdditionalWeaponAccuracy.TransformValue() Fail from :" + req.Thing.ToString() + ": " + ee);
         }
     }
 }
예제 #23
0
        protected override void Impact(Thing hitThing)
        {
            Destroy(DestroyMode.Vanish);
            if (intendedTarget.Thing == null)
            {
                return;
            }
            if (((Pawn)launcher).equipment.AllEquipmentListForReading.Find(x => x.def.Equals(RWBYDefOf.RWBY_Anesidora_Camera)).TryGetComp <CompTakePhoto>() == null)
            {
                return;
            }
            string photoOf = "";

            if (intendedTarget.Thing.GetType().Equals(typeof(Pawn))) // took photo of pawn
            {
                Pawn targetPawn = (Pawn)intendedTarget;
                if (targetPawn != null && targetPawn.RaceProps.Humanlike)
                {
                    Thought_Memory thought_Memory = (Thought_Memory)ThoughtMaker.MakeThought(RWBYDefOf.RWBY_PictureTaken);
                    targetPawn.needs.mood.thoughts.memories.TryGainMemory(thought_Memory);
                }
                if (targetPawn != null && (targetPawn.Drafted || targetPawn.IsFighting() || targetPawn.RaceProps.IsMechanoid || ((Pawn)launcher).CurJobDef == RWBYDefOf.RWBY_TakePhotos) && targetPawn.equipment.Primary != null)
                {
                    photoOf = targetPawn.equipment.Primary.def.defName;
                    ((Pawn)launcher).equipment.AllEquipmentListForReading.Find(x => x.def.Equals(RWBYDefOf.RWBY_Anesidora_Camera)).TryGetComp <CompTakePhoto>().ListOfDifferentPhotos.Add(photoOf);
                }
            }

            if (intendedTarget.Thing.GetType().Equals(typeof(ThingWithComps))) // took photo of thing
            {
                ThingWithComps targetThing = (ThingWithComps)intendedTarget;
                if (targetThing.def.equipmentType.Equals(EquipmentType.Primary))
                {
                    photoOf = targetThing.def.defName;
                    ((Pawn)launcher).equipment.AllEquipmentListForReading.Find(x => x.def.Equals(RWBYDefOf.RWBY_Anesidora_Camera)).TryGetComp <CompTakePhoto>().ListOfDifferentPhotos.Add(photoOf);
                }
            }
        }
        private float GetMeleeCooldown(StatRequest req, bool applyPostProcess = true)
        {
            Pawn pawn = req.Thing as Pawn;

            if (pawn != null)
            {
                List <VerbEntry> updatedAvailableVerbsList = pawn.meleeVerbs.GetUpdatedAvailableVerbsList();
                if (updatedAvailableVerbsList.Count == 0)
                {
                    return(1f);
                }
                float num = 0f;
                for (int i = 0; i < updatedAvailableVerbsList.Count; i++)
                {
                    if (updatedAvailableVerbsList[i].IsMeleeAttack)
                    {
                        num += updatedAvailableVerbsList[i].SelectionWeight;
                    }
                }
                float num2 = 0f;
                for (int j = 0; j < updatedAvailableVerbsList.Count; j++)
                {
                    if (updatedAvailableVerbsList[j].IsMeleeAttack)
                    {
                        VerbEntry      verbEntry      = updatedAvailableVerbsList[j];
                        ThingWithComps ownerEquipment = verbEntry.verb.ownerEquipment;
                        float          num3           = num2;
                        float          num4           = updatedAvailableVerbsList[j].SelectionWeight / num;
                        VerbEntry      verbEntry2     = updatedAvailableVerbsList[j];
                        VerbProperties verbProps      = verbEntry2.verb.verbProps;
                        VerbEntry      verbEntry3     = updatedAvailableVerbsList[j];
                        num2 = num3 + num4 * (float)verbProps.AdjustedCooldownTicks(verbEntry3.verb, pawn, ownerEquipment);
                    }
                }
                return((float)(num2 / 60.0));
            }
            return(1f);
        }
        public bool TryGetLastThingUsed(Pawn pawn, out ThingWithComps t)
        {
#if LAST_THING_USED
            Log.Warning("Begin AssignedWeaponContainer.TryGetLastThingUsed " + pawn.Name.ToStringShort);
#endif
            bool result = false;
            if (pawn.Drafted)
            {
                t = this.LastWeaponUsed;
            }
            else
            {
                t = this.LastToolUsed;
            }

            if (t != null)
            {
                if (this.weaponIds.Contains(t.thingIDNumber))
                {
                    result = true;
                }
                else
                {
                    this.SetLastThingUsed(pawn, null, false);
                }
            }
            if (!result)
            {
                t = null;
            }

#if LAST_THING_USED
            Log.Message("    Last Tool Used: " + ((this.LastToolUsed == null) ? "<null>" : this.LastToolUsed.Label));
            Log.Message("    Last Weapon Used: " + ((this.LastWeaponUsed == null) ? "<null>" : this.LastWeaponUsed.Label));
            Log.Warning("End AssignedWeaponContainer.TryGetLastThingUsed -- " + result + " " + ((t == null) ? "<null>" : t.Label));
#endif
            return(result);
        }
 public static bool ShouldReload(Pawn p)
 {
     //For mechanoids replace the check of is p.RaceProps.HumanLike by custom logic
     if (p.RaceProps.IsMechanoid && p.IsHacked())
     {
         //return true when a mechanoid is hacked and does not have much ammo.
         ThingComp      inventory      = TryGetCompByTypeName(p, "CompInventory", "CombatExtended");
         ThingWithComps eq             = p.equipment.Primary;
         bool           shouldTransfer = false;
         if (eq == null)
         {
             eq             = p.inventory.GetDirectlyHeldThings().FirstOrDefault() as ThingWithComps;
             shouldTransfer = eq == null ? false : true;
         }
         if (inventory != null && eq != null)
         {
             //Everything is done using reflection, so we don't need to include a dependency
             ThingComp ammoUser = TryGetCompByTypeName(eq, "CompAmmoUser", "CombatExtended");
             if (ammoUser != null)
             {
                 var currentAmmo  = Traverse.Create(ammoUser).Property("CurrentAmmo").GetValue();
                 int ammoCount    = Traverse.Create(inventory).Method("AmmoCountOfDef", new object[] { currentAmmo }).GetValue <int>();
                 var props        = Traverse.Create(ammoUser).Property("Props").GetValue();
                 int magazineSize = Traverse.Create(props).Field("magazineSize").GetValue <int>();
                 int minAmmo      = magazineSize == 0 ? 10 : magazineSize; //No magic numbers?
                 if (ammoCount < minAmmo)
                 {
                     if (shouldTransfer)
                     {
                         p.equipment.AddEquipment(eq.SplitOff(1) as ThingWithComps);
                     }
                     return(true);
                 }
             }
         }
     }
     return(p.RaceProps.Humanlike);
 }
        public static Graphic ResolveCycledGraphic(ThingWithComps pAnimatee, CompProperties_Animated pProps, int pCurIndex)
        {
            Graphic result           = null;
            bool    haveMovingFrames = !pProps.movingFrames.NullOrEmpty();

            if (!pProps.movingFrames.NullOrEmpty() &&
                AsPawn(pAnimatee, out var pPawn) &&
                pPawn.Drawer?.renderer?.graphics is PawnGraphicSet pawnGraphicSet)
            {
                /*Start Pawn*/
                pawnGraphicSet.ClearCache();

                if (haveMovingFrames && AsPawn(pAnimatee, out var p) && (p?.pather?.MovingNow ?? false))
                {
                    result = pProps.movingFrames[pCurIndex].Graphic;
                    pawnGraphicSet.nakedGraphic = result;
                }
                else if (!pProps.stillFrames.NullOrEmpty())
                {
                    result = pProps.stillFrames[pCurIndex].Graphic;
                    pawnGraphicSet.nakedGraphic = result;
                }
                else if (haveMovingFrames)
                {
                    result = pProps.movingFrames[pCurIndex].Graphic;
                }
            } /*Start Non Pawn*/
            else if (!pProps.stillFrames.NullOrEmpty())
            {
                result = pProps.stillFrames[pCurIndex].Graphic;
            }
            else if (haveMovingFrames)
            {
                result = pProps.movingFrames[pCurIndex].Graphic;
            }

            return(result);
        }
예제 #28
0
        protected override IEnumerable <Toil> MakeNewToils()
        {
            this.FailOnDespawnedOrNull(TargetIndex.A);
            this.FailOn(delegate()
            {
                Designation designation = this.Map.designationManager.DesignationOn(this.TargetThingA, DesignationDefOf.Flick);
                return(designation == null);
            });
            yield return(Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch));

            yield return(Toils_General.Wait(15, TargetIndex.None).FailOnCannotTouch(TargetIndex.A, PathEndMode.Touch));

            Toil finalize = new Toil();

            finalize.initAction = delegate()
            {
                Pawn           actor          = finalize.actor;
                ThingWithComps thingWithComps = (ThingWithComps)actor.CurJob.targetA.Thing;
                for (int i = 0; i < thingWithComps.AllComps.Count; i++)
                {
                    CompFlickable compFlickable = thingWithComps.AllComps[i] as CompFlickable;
                    if (compFlickable != null && compFlickable.WantsFlick())
                    {
                        compFlickable.DoFlick();
                    }
                }
                actor.records.Increment(RecordDefOf.SwitchesFlicked);
                Designation designation = this.Map.designationManager.DesignationOn(thingWithComps, DesignationDefOf.Flick);
                if (designation != null)
                {
                    designation.Delete();
                }
            };
            finalize.defaultCompleteMode = ToilCompleteMode.Instant;
            yield return(finalize);

            yield break;
        }
예제 #29
0
        protected override IEnumerable <Toil> MakeNewToils()
        {
            this.FailOnDespawnedNullOrForbidden(TargetIndex.A);
            this.FailOn(delegate
            {
                ThingWithComps thingWithComps = this.$this.job.GetTarget(TargetIndex.A).Thing as ThingWithComps;
                if (thingWithComps != null)
                {
                    CompFlickable comp = thingWithComps.GetComp <CompFlickable>();
                    if (comp != null && !comp.SwitchIsOn)
                    {
                        return(true);
                    }
                }
                return(false);
            });
            base.AddEndCondition(() => (!this.$this.RefuelableComp.IsFull) ? JobCondition.Ongoing : JobCondition.Succeeded);
            yield return(Toils_General.DoAtomic(delegate
            {
                this.$this.job.count = this.$this.RefuelableComp.GetFuelCountToFullyRefuel();
            }));

            Toil reserveFuel = Toils_Reserve.Reserve(TargetIndex.B, 1, -1, null);

            yield return(reserveFuel);

            yield return(Toils_Goto.GotoThing(TargetIndex.B, PathEndMode.ClosestTouch).FailOnDespawnedNullOrForbidden(TargetIndex.B).FailOnSomeonePhysicallyInteracting(TargetIndex.B));

            yield return(Toils_Haul.StartCarryThing(TargetIndex.B, false, true, false).FailOnDestroyedNullOrForbidden(TargetIndex.B));

            yield return(Toils_Haul.CheckForGetOpportunityDuplicate(reserveFuel, TargetIndex.B, TargetIndex.None, true, null));

            yield return(Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch));

            yield return(Toils_General.Wait(240).FailOnDestroyedNullOrForbidden(TargetIndex.B).FailOnDestroyedNullOrForbidden(TargetIndex.A).FailOnCannotTouch(TargetIndex.A, PathEndMode.Touch).WithProgressBarToilDelay(TargetIndex.A, false, -0.5f));

            yield return(Toils_Refuel.FinalizeRefueling(TargetIndex.A, TargetIndex.B));
        }
예제 #30
0
        public override IEnumerable <StatDrawEntry> SpecialDisplayStatsForThing(ThingWithComps parentThing, string preLabel)
        {
            // Add additional Equipped Stat Offsets modifiers
            var statDrawEntry = new StatDrawEntry(
                category:    StatCategoryDefOf.EquippedStatOffsets,
                label:       affectedStat.LabelCap,
                valueString: ModifierChangeString,  // much more flexible than value
                reportText:  affectedStat.description,
                displayPriorityWithinCategory: 10
                );

            StatRequest req = StatRequest.For(parentThing);

            // Extra properties, since we're overriding the typical stat value display
            statDrawEntry.stat           = affectedStat;
            statDrawEntry.hasOptionalReq = true;
            statDrawEntry.optionalReq    = req;

            // Calculate an example value
            StatWorker worker       = affectedStat.Worker;
            float      exampleValue =
                parentThing.ParentHolder != null && parentThing.ParentHolder is Pawn pawn?
                worker.GetValueUnfinalized(StatRequest.For(pawn)) :
                    affectedStat.defaultBaseValue
            ;

            // Use the Thing-tied StatRequest to hit our StatPart
            worker.FinalizeValue(req, ref exampleValue, true);

            // And finally, another private we need to dodge around to install both kinds of StatDrawEntry fields.

            // [Reflection] statDrawEntry.value = exampleValue;
            FieldInfo valueField = AccessTools.Field(typeof(StatDrawEntry), "value");

            valueField.SetValue(statDrawEntry, exampleValue);

            yield return(statDrawEntry);
        }
예제 #31
0
        static private int CalculateTotalLootAffixPoints(ThingWithComps thing)
        {
            float ptsF = 0f;

            // Up to 6 points based on total wealth (1M max)
            float wealth = 0f;

            if (Current.ProgramState == ProgramState.Playing)    // don't bother while initializing
            {
                if (thing.Map != null && thing.Map.wealthWatcher != null)
                {
                    wealth = thing.Map.wealthWatcher.WealthTotal;
                }
                else if (Find.CurrentMap != null && Find.CurrentMap.wealthWatcher != null)
                {
                    wealth = Find.CurrentMap.wealthWatcher.WealthTotal;
                }
                else if (Find.World != null)
                {
                    wealth = Find.World.PlayerWealthForStoryteller;
                }
            }

            ptsF += Mathf.Min(wealth / 166_666, 6);

            // Up to 8 points based on item quality
            QualityCategory qc;

            thing.TryGetQuality(out qc);

            // Normal = 1, Good = 2, Excellent = 4, Masterwork = 6, Legendary = 8
            ptsF += Mathf.Pow((int)qc, 2f) / 4.5f;

            // Capped at 12
            ptsF = Mathf.Clamp(ptsF, 0, 12);

            return(Mathf.RoundToInt(ptsF));
        }
예제 #32
0
        public override string CompInspectStringExtra()
        {
            bool flag;

            if (this.Active)
            {
                ThingWithComps parent = this.parent;
                flag = (parent != null && parent.Faction.IsPlayer);
            }
            else
            {
                flag = false;
            }
            string result;

            if (flag)
            {
                if (this.MilkProps.firstResourceName)
                {
                    result = this.MilkProps.milkProgessKeyString.Translate(new object[]
                    {
                        this.MilkProgressPercent.ToStringPercent()
                    });
                }
                else
                {
                    result = this.MilkProps.widowMilkProgessKeyString.Translate(new object[]
                    {
                        this.MilkProgressPercent.ToStringPercent()
                    });
                }
            }
            else
            {
                result = null;
            }
            return(result);
        }
        public static void AddVerbs(this VerbManager man, ThingWithComps eq)
        {
            if (man == null)
            {
                return;
            }
            if (Base.IsIgnoredMod(eq?.def?.modContentPack?.Name))
            {
                return;
            }
            if (Compat.ShouldIgnore(eq))
            {
                return;
            }
            var comp = eq.TryGetComp <CompEquippable>();

            if (comp?.VerbTracker?.AllVerbs == null)
            {
                return;
            }
            if (!Base.Features.ExtraEquipmentVerbs && !Base.IgnoredFeatures.ExtraEquipmentVerbs &&
                comp.VerbTracker.AllVerbs.Count(v => !v.IsMeleeAttack) > 1)
            {
                Log.ErrorOnce(
                    "[MVCF] Found equipment with more than one ranged attack while that feature is not enabled. Enabling now. This is not recommend. Contact the author of " +
                    eq?.def?.modContentPack?.Name + " and ask them to add a MVCF.ModDef.",
                    eq?.def?.modContentPack?.Name?.GetHashCode() ?? -1);
                Base.Features.ExtraEquipmentVerbs = true;
                Base.ApplyPatches();
            }

            foreach (var verb in comp.VerbTracker.AllVerbs)
            {
                man.AddVerb(verb, VerbSource.Equipment, comp.props is CompProperties_VerbProps props
                    ? props.PropsFor(verb)
                    : eq.TryGetComp <Comp_VerbProps>()?.Props?.PropsFor(verb));
            }
        }
예제 #34
0
파일: GasNet.cs 프로젝트: isistoy/DevLib
 private void RegisterAllComponentsOf(ThingWithComps parentThing)
 {
     CompGasTrader comp = parentThing.GetComp<CompGasTrader>();
     if (comp != null)
     {
         if (this.traders.Contains(comp))
         {
             Log.Error("GasNet Adding GasComp " + comp + " which it already has.");
         }
         else
         {
             this.traders.Add(comp);
         }
     }
 }
예제 #35
0
파일: GasNet.cs 프로젝트: isistoy/DevLib
 private void DeregisterAllComponentsOf(ThingWithComps parentThing)
 {
     CompGasTrader comp = parentThing.GetComp<CompGasTrader>();
     if (comp != null)
     {
         this.traders.Remove(comp);
     }
 }
예제 #36
0
        public void Draw(Rect rect, ThingWithComps ownerPawn)
        {
            Text.Font = GameFont.Small;
            string value = "-";

            switch (oType)
            {
                case objectType.Stat:
                    Text.Anchor = TextAnchor.MiddleCenter;
                    StatDef stat = (StatDef)displayObject;
                    string statValue = (stat.ValueToString(ownerPawn.GetStatValue((StatDef)displayObject, true)));
                    Widgets.Label(rect, statValue);
                    if (Mouse.IsOver(rect))
                    {
                        GUI.DrawTexture(rect, TexUI.HighlightTex);
                    }

                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.AppendLine(stat.LabelCap);
                    stringBuilder.AppendLine();
                    stringBuilder.AppendLine(stat.description);                
                    TooltipHandler.TipRegion(rect, new TipSignal(stringBuilder.ToString(), rect.GetHashCode()));
                    break;    

                case objectType.Skill:
                    if ((ownerPawn is Pawn) && (ownerPawn as Pawn).RaceProps.Humanlike) DrawSkill(rect, ownerPawn as Pawn);
                    break;

                case objectType.Need:
                    if (ownerPawn is Pawn) DrawNeed(rect, ownerPawn as Pawn);
                    break;

                case objectType.Age:
                    Text.Anchor = TextAnchor.MiddleCenter;
                    string ageValue = ((ownerPawn as Pawn).ageTracker.AgeBiologicalYears.ToString());
                    Widgets.Label(rect, ageValue);
                    if (Mouse.IsOver(rect))
                    {
                        GUI.DrawTexture(rect, TexUI.HighlightTex);
                    }
                    break;

                case objectType.Gear:
                    DrawGear(rect, ownerPawn);
                    break;

                case objectType.ControlPrisonerGetsFood:
                    if (ownerPawn is Pawn)
                    {
                        if (Mouse.IsOver(rect))
                        {
                            GUI.DrawTexture(rect, TexUI.HighlightTex);
                        }
                        bool getsFood = (ownerPawn as Pawn).guest.GetsFood;
                        Widgets.CheckboxLabeled(new Rect(rect.x + 8f, rect.y + 3f, 27f, 27f), "", ref getsFood, false);
                        (ownerPawn as Pawn).guest.GetsFood = getsFood;
                    }
                    break;

                case objectType.ControlPrisonerInteraction:
                    if (ownerPawn is Pawn)
                    {
                        if (Mouse.IsOver(rect))
                        {
                            GUI.DrawTexture(rect, TexUI.HighlightTex);
                        }
                        float x = 8f;

                        GUI.BeginGroup(rect);
                        IEnumerator enumerator = Enum.GetValues(typeof(PrisonerInteractionMode)).GetEnumerator();
                        try
                        {
                            while (enumerator.MoveNext())
                            {
                                PrisonerInteractionMode prisonerInteractionMode = (PrisonerInteractionMode)((byte)enumerator.Current);
                                if (Widgets.RadioButton(new Vector2(x, 3f), (ownerPawn as Pawn).guest.interactionMode == prisonerInteractionMode))
                                {
                                    (ownerPawn as Pawn).guest.interactionMode = prisonerInteractionMode;
                                }
                                TooltipHandler.TipRegion(new Rect(x, 0f, 30f, 30f), new TipSignal(prisonerInteractionMode.GetLabel()));
                                x += 30f;
                            }
                        }
                        finally
                        {
                            IDisposable disposable = enumerator as IDisposable;
                            if (disposable != null)
                            {
                                disposable.Dispose();
                            }
                        }
                        GUI.EndGroup();
                    }
                    break;

                case objectType.ControlMedicalCare:
                    if (ownerPawn is Pawn) MedicalCareSetter(rect, ref (ownerPawn as Pawn).playerSettings.medCare);
                    break;

                case objectType.AnimalMilkFullness:
                    Text.Anchor = TextAnchor.MiddleCenter;
                    if (ownerPawn is Pawn && ((Pawn)ownerPawn).ageTracker.CurLifeStage.milkable)
                    {
                        var comp = ((Pawn)ownerPawn).AllComps.Where<ThingComp>(x => x is CompMilkable).FirstOrDefault();
                        if(comp != null)
                        value = ((CompMilkable)comp).Fullness.ToStringPercent();
                    }

                    Widgets.Label(rect, value);
                    break;

                case objectType.AnimalWoolGrowth:
                    Text.Anchor = TextAnchor.MiddleCenter;
                    if (ownerPawn is Pawn && ((Pawn)ownerPawn).ageTracker.CurLifeStage.shearable)
                    {
                        var comp = ((Pawn)ownerPawn).AllComps.Where<ThingComp>(x => x is CompShearable).FirstOrDefault();
                        if (comp != null)
                            value = ((CompShearable)comp).Fullness.ToStringPercent();
                    }

                    Widgets.Label(rect, value);
                    break;

                case objectType.CurrentJob:
                    if(ownerPawn is Pawn)
                    {
                        string text = ((Pawn)ownerPawn).jobs.curDriver.GetReport();
                        Text.Anchor = TextAnchor.MiddleLeft;
                        Rect tRect = new Rect(rect.xMin + 2, rect.yMin + 3, rect.width - 2, rect.height);
                        GenText.SetTextSizeToFit(text, tRect);

                        if (Text.Font == GameFont.Tiny)
                            Widgets.Label(tRect, text);
                        else
                        {
                            Rect sRect = new Rect(rect.xMin + 2, rect.yMin, rect.width - 2, rect.height);
                            Widgets.Label(sRect, text);
                        }

                        if (Mouse.IsOver(rect))
                        {
                            GUI.DrawTexture(rect, TexUI.HighlightTex);
                        }
                    }
                    break;
            }


        }
예제 #37
0
        private void DrawGear(Rect rect, ThingWithComps ownerPawn)
        {
            GUI.BeginGroup(rect);
            float x = 0;
            float gWidth = 28f;
            float gHeight = 28f;
            Pawn p1 = (ownerPawn is Pawn) ? (ownerPawn as Pawn) : (ownerPawn as Corpse).innerPawn;
            if (p1.RaceProps.Animal) return;
            if (p1.equipment != null)
            foreach(ThingWithComps thing in p1.equipment.AllEquipment)
                {
                    Rect rect2 = new Rect(x, 0, gWidth, gHeight);
                    DrawThing(rect2, thing, p1);
                    x += gWidth;
                }

            if (p1.apparel != null)
            foreach (Apparel thing in from ap in p1.apparel.WornApparel
                                            orderby ap.def.apparel.bodyPartGroups[0].listOrder descending
                                            select ap)
                {
                    Rect rect2 = new Rect(x, 0, gWidth, gHeight);
                    DrawThing(rect2, thing, p1);
                    x += gWidth;
                }
            GUI.EndGroup();
        }
예제 #38
0
        private void PostDrawPawnRow(Rect rect, ThingWithComps p)
		{
            if (p is Pawn)
            {
                if ((p as Pawn).Downed)
                {
                    GUI.color = new Color(1f, 0f, 0f, 0.5f);
                    Widgets.DrawLineHorizontal(rect.x, rect.center.y, rect.width);
                    GUI.color = Color.white;
                }
            }
		}
예제 #39
0
 protected abstract void DrawPawnRow(Rect r, ThingWithComps p);
예제 #40
0
        protected override void DrawPawnRow(Rect r, ThingWithComps p)
        {
            float x = 175f;
            float y = r.yMin;

            Text.Anchor = TextAnchor.MiddleCenter;

            //TODO: better interface - auto width calculation, make sure columns won't overlap
            for (int i = 0; i < kList.Count; i++)
            {
                float colWidth = kList[i].minWidthDesired;
                if (colWidth + x + cFreeSpaceAtTheEnd > maxWindowWidth)
                {
                    //soft break
                    break;
                }
                Rect capCell = new Rect(x, y, colWidth, PawnRowHeight);
                kList[i].Draw(capCell, p);
                x += colWidth;
            }

            /*
            if (p.health.Downed) {
                Widgets.DrawLine(new Vector2(5f, y + PawnRowHeight / 2), new Vector2(r.xMax - 5f, y + PawnRowHeight / 2), Color.red, 1);
            }*/

        }
예제 #41
0
		private void PreDrawPawnRow(Rect rect, ThingWithComps p)
		{
			Rect rect2 = new Rect(0f, rect.y, rect.width, PawnRowHeight);
			if (Mouse.IsOver(rect2))
			{
				GUI.DrawTexture(rect2, TexUI.HighlightTex);
			}
			Rect rect3 = new Rect(0f, rect.y, 175f, PawnRowHeight);
			Rect position = rect3.ContractedBy(3f);
            if (p is Pawn)
            {
			    if ((p as Pawn).health.summaryHealth.SummaryHealthPercent < 0.999f)
			    {
				    Rect rect4 = new Rect(rect3);
				    rect4.xMin -= 4f;
				    rect4.yMin += 4f;
				    rect4.yMax -= 6f;
				    Widgets.FillableBar(rect4, (p as Pawn).health.summaryHealth.SummaryHealthPercent, GenWorldUI.OverlayHealthTex, BaseContent.ClearTex, false);
			    }
            }
			if (Mouse.IsOver(rect3))
			{
				GUI.DrawTexture(position, TexUI.HighlightTex);
			}
			string label;
            Pawn p1 = (p is Corpse) ? (p as Corpse).innerPawn : p as Pawn;
			if (!p1.RaceProps.Humanlike && p1.Name != null && !p1.Name.Numerical)
			{
				label = p1.Name.ToStringShort.CapitalizeFirst() + ", " + p1.KindLabel;
			}
			else
			{
				label = p1.LabelCap;
			}
			Text.Font = GameFont.Small;
			Text.Anchor = TextAnchor.MiddleLeft;
			Text.WordWrap = false;
			Rect rect5 = new Rect(rect3);
			rect5.xMin += 15f;
			Widgets.Label(rect5, label);
			Text.WordWrap = true;
			if (Widgets.ButtonInvisible(rect3))
			{
				Find.MainTabsRoot.EscapeCurrentTab(true);
                Find.CameraDriver.JumpTo(p.PositionHeld);
				Find.Selector.ClearSelection();
				if (p.Spawned)
				{
					Find.Selector.Select(p, true, true);
				}
				return;
			}
			TipSignal tooltip = p.GetTooltip();
			tooltip.text = "ClickToJumpTo".Translate() + "\n\n" + tooltip.text;
			TooltipHandler.TipRegion(rect3, tooltip);
		}
        public Job TryEquipFreeTool(Pawn pawn)
        {
            // find proper tools of the specific work type
            IEnumerable<Thing> availableTools =
                Find.ListerThings.AllThings.FindAll(
                    tool =>
                        IsProperTool(tool) && !tool.IsForbidden(pawn.Faction) &&
                        pawn.CanReserveAndReach(tool, PathEndMode.ClosestTouch, pawn.NormalMaxDanger()));

            if (availableTools.Any())
            {
                // find closest reachable tool of the specific work type
                closestAvailableTool = GenClosest.ClosestThing_Global(pawn.Position, availableTools) as ThingWithComps;

                if (closestAvailableTool != null)
                {
                    // if pawn has equipped weapon, put it in inventory
                    if (pawn.equipment.Primary != null)
                    {
                        previousPawnWeapons.Add(pawn.equipment.Primary, pawn);
                        ThingWithComps leftover;
                        pawn.equipment.TryTransferEquipmentToContainer(pawn.equipment.Primary, pawn.inventory.container,
                            out leftover);
                    }

                    // reserve and set as auto equipped
                    pawn.Reserve(closestAvailableTool);
                    closestAvailableTool.TryGetComp<CompTool>().wasAutoEquipped = true;

                    return new Job(JobDefOf.Equip, closestAvailableTool);
                }
            }

            return null;
        }
예제 #43
0
 public DurabilityPair( ThingWithComps thing, float durability = 1f )
 {
     this.thing = thing;
     this.durability = durability;
 }