public void ShouldBindCorrectValues()
        {
            var thing = new Thing
            {
                Id = 4,
                Name = "Henry",
                Date = new DateTime(2008, 09, 04),
                Price = 10.42M,
                IsValid = false, 
                Age = 1
            };

            var form = new FormCollection
            {
                { "Id", "4" },
                { "Name", "Joe" },
                { "Date", "2007-01-01" },
                { "Price", "2.45" },
                { "IsValid", "True,False" },
                { "Age", "34" }
            };

            validatingBinder.UpdateFrom(thing, form);

            Assert.That(thing.Id, Is.EqualTo(4));
            Assert.That(thing.Name, Is.EqualTo("Joe"));
            Assert.That(thing.Date, Is.EqualTo(new DateTime(2007, 01, 01)));
            Assert.That(thing.Price, Is.EqualTo(2.45M));
            Assert.That(thing.IsValid, Is.True);
            Assert.That(thing.Age, Is.EqualTo(34));
        }
        public override AcceptanceReport CanDesignateThing(Thing thing)
        {
            // fast check if already added to "designations"
            if (slotsComp.designatedThings.Contains(thing))
            {
                return true;
            }

            // corpse has no icon\texture to render in the slot
            if (thing is Corpse)
            {
                return false;
            }

            if (!slotsComp.owner.CanReserveAndReach(thing, PathEndMode.ClosestTouch, slotsComp.owner.NormalMaxDanger()))
            {
                return false;
            }

            // if there are free slots
            if (slotsComp.designatedThings.Count + slotsComp.slots.Count >= slotsComp.Properties.maxSlots)
            {
                return false;
            }

            // if any of the thing's categories is allowed and not forbidden
            if (thing.def.thingCategories.Exists(category => slotsComp.Properties.allowedThingCategoryDefs.Exists(subCategory => subCategory.ThisAndChildCategoryDefs.Contains(category)) && !slotsComp.Properties.forbiddenSubThingCategoryDefs.Exists(subCategory => subCategory.ThisAndChildCategoryDefs.Contains(category))))
            {
                slotsComp.designatedThings.Add(thing);
                return true;
            }

            return false;
        }
Ejemplo n.º 3
0
        public ReplyViewModel(IBaconProvider baconProvider, Thing replyTargetThing, RelayCommand cancel, Action<Thing> convertIntoUIReply, bool isEdit = false)
        {
            _convertIntoUIReply = convertIntoUIReply;
            _cancel = cancel;
            _baconProvider = baconProvider;
            _redditService = _baconProvider.GetService<IRedditService>();
            _userService = _baconProvider.GetService<IUserService>();
            _markdownProcessor = _baconProvider.GetService<IMarkdownProcessor>();
            _replyTargetThing = replyTargetThing;

            if (isEdit)
            {
                Editing = true;
                EditingId = ((Comment)_replyTargetThing.Data).Name;
                ReplyBody = ((Comment)_replyTargetThing.Data).Body.Replace("&gt;", ">").Replace("&lt;", "<");
            }

			RefreshUserImpl();

            _addBold = new RelayCommand(AddBoldImpl);
            _addItalic = new RelayCommand(AddItalicImpl);
            _addStrike = new RelayCommand(AddStrikeImpl);
            _addSuper = new RelayCommand(AddSuperImpl);
            _addLink = new RelayCommand(AddLinkImpl);
            _addQuote = new RelayCommand(AddQuoteImpl);
            _addCode = new RelayCommand(AddCodeImpl);
            _addBullets = new RelayCommand(AddBulletsImpl);
            _addNumbers = new RelayCommand(AddNumbersImpl);
            _submit = new RelayCommand(SubmitImpl);
			_refreshUser = new RelayCommand(RefreshUserImpl);
        }
 public override AcceptanceReport CanDesignateThing( Thing t )
 {
     var building = t.GetInnerIfMinified() as Building;
     if (building?.def.category != ThingCategory.Building)
     {
         return false;
     }
     if (!Game.GodMode)
     {
         if (!building.def.building.IsDeconstructible)
         {
             return false;
         }
         if (building.Faction != Faction.OfColony)
         {
             if (building.Faction != null)
             {
                 return false;
             }
             if (!building.ClaimableBy( Faction.OfColony ))
             {
                 return false;
             }
         }
     }
     if (Find.DesignationManager.DesignationOn( t, DesignationDefOf.Deconstruct ) != null)
     {
         return false;
     }
     return Find.DesignationManager.DesignationOn( t, DesignationDefOf.Uninstall ) == null;
 }
Ejemplo n.º 5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="WieldUnwieldEvent"/> class.
 /// </summary>
 /// <param name="wieldedItem">The thing being affected by this event.</param>
 /// <param name="isBeingWielded">Whether the thing is being wielded (true) or unwielded (false).</param>
 /// <param name="activeThing">The actor causing the event (if applicable).</param>
 /// <param name="sensoryMessage">The message to display to those who can perceive the change.</param>
 public WieldUnwieldEvent(Thing wieldedItem, bool isBeingWielded, Thing activeThing, SensoryMessage sensoryMessage)
     : base(activeThing, sensoryMessage)
 {
     this.WieldedItem = wieldedItem;
     this.IsBeingWielded = isBeingWielded;
     sensoryMessage.Context.Add("WieldedItem", this.WieldedItem);
 }
Ejemplo n.º 6
0
 public Comment Init(Reddit reddit, JToken json, IWebAgent webAgent, Thing sender)
 {
     var data = CommonInit(reddit, json, webAgent, sender);
     ParseComments(reddit, json, webAgent, sender);
     JsonConvert.PopulateObject(data.ToString(), this, reddit.JsonSerializerSettings);
     return this;
 }
Ejemplo n.º 7
0
 public async Task<Comment> InitAsync(Reddit reddit, JToken json, IWebAgent webAgent, Thing sender)
 {
     var data = CommonInit(reddit, json, webAgent, sender);
     await ParseCommentsAsync(reddit, json, webAgent, sender);
     await Task.Factory.StartNew(() => JsonConvert.PopulateObject(data.ToString(), this, reddit.JsonSerializerSettings));
     return this;
 }
        public override Job JobOnThing( Pawn pawn, Thing t )
        {
            if( !pawn.CanReserveAndReach( ( TargetInfo )t.Position, PathEndMode.Touch, DangerUtility.NormalMaxDanger( pawn ), 1 ) )
            {
                return (Job) null;
            }

            var hopperSgp = t as ISlotGroupParent;
            if( hopperSgp == null )
            {
                return (Job) null;
            }

            var resource = HopperGetCurrentResource( t.Position, hopperSgp );
            if(
                ( resource == null )||
                ( resource.stackCount <= ( resource.def.stackLimit / 2 ) )
            )
            {
                return WorkGiver_FillHopper.HopperFillJob( pawn, hopperSgp, resource );
            }

            JobFailReason.Is( "AlreadyFilledLower".Translate() );
            return (Job) null;
        }
Ejemplo n.º 9
0
    public override void UpdateContributor(Thing contributor)
    {
        base.UpdateContributor (contributor);

        //On(contributor, SensorType.OnSensorEnter, OnSensorEnter);
        //On(contributor, SensorType.OnSensorExit, OnSensorExit);
    }
Ejemplo n.º 10
0
        public static void load(ref List<Thing> thingsToLoad, string fileLocation, Thing currentSource)
        {
            Log.Message("ScribeINIT, loding from:" + fileLocation);
            Scribe.InitLoading(fileLocation);

            //Scribe.EnterNode("Stargate");

            Log.Message("DeepProfiler.Start()");
            DeepProfiler.Start("Load non-compressed things");

            List<Thing> list2 = (List<Thing>)null;
            Log.Message("Scribe_Collections.LookList");
            Scribe_Collections.LookList<Thing>(ref thingsToLoad, "things", LookMode.Deep);
            Log.Message("List1Count:" + thingsToLoad.Count);

            Log.Message("DeepProfiler.End()");
            DeepProfiler.End();

            //Scribe.ExitNode();
            Scribe.mode = LoadSaveMode.Inactive;

            //Log.Message("list: " + thingsToLoad.Count.ToString());

            Log.Message("Exit Node");
            //Scribe.ExitNode();

            Log.Message("ResolveAllCrossReferences");
            CrossRefResolver.ResolveAllCrossReferences();

            Log.Message("DoAllPostLoadInits");
            PostLoadInitter.DoAllPostLoadInits();

            Log.Message("Return");
        }
Ejemplo n.º 11
0
        public static void save(List<Thing> thingsToSave, string fileLocation, Thing source)
        {
            Scribe.InitWriting(fileLocation,"Stargate");

            //Log.Message("Starting Save");
            //Save Pawn

            //Scribe_Collections.LookList<Thing>(ref thingsToSave, "things", LookMode.Deep, (object)null);

            //Scribe.EnterNode("map");
            //Scribe.EnterNode("things");
            //source.ExposeData();
            Scribe_Collections.LookList<Thing>(ref thingsToSave, "things", LookMode.Deep, (object)null);
            //Scribe.ExitNode();

            //Scribe.ExitNode();

            /*
            for (int i = 0; i < thingsToSave.Count; i++)
            {
                Scribe_Deep.LookDeep<Thing>(ref thingsToSave[i], thingsToSave[i].ThingID);
            }*/

            Scribe.FinalizeWriting();
            Scribe.mode = LoadSaveMode.Inactive;
            //Log.Message("End Save");
        }
Ejemplo n.º 12
0
        public override bool HasJobOnThing( Pawn pawn, Thing thing )
        {
            if ( thing.Faction != pawn.Faction )
                return false;

            if ( pawn.Faction == Faction.OfColony && !Find.AreaHome[thing.Position] )
                return false;

            if ( thing.IsBurning() )
                return false;

            if ( Find.DesignationManager.DesignationOn( thing, DesignationDefOf.Deconstruct ) != null )
                return false;

            ThingWithComps twc = thing as ThingWithComps;
            if ( twc == null )
                return false;

            var comp = twc.TryGetComp<CompBreakdownable>();
            if ( comp == null )
                return false;

            if ( !MapComponent_Durability.RequiresMaintenance( comp ) )
                return false;

            if ( !pawn.CanReserveAndReach( thing, PathEndMode.Touch, pawn.NormalMaxDanger() ) )
                return false;

            return true;
        }
 public override bool HasJobOnThing(Pawn pawn, Thing t)
 {
     Fire fire = t as Fire;
     if (fire == null)
     {
         return false;
     }
     Area outpostArea = OG_Util.FindOutpostArea();
     Pawn pawn2 = fire.parent as Pawn;
     if (pawn2 != null)
     {
         if (pawn2 == pawn)
         {
             return false;
         }
         if ((pawn2.Faction == pawn.Faction || pawn2.HostFaction == pawn.Faction || pawn2.HostFaction == pawn.HostFaction)
             && ((outpostArea == null) || (outpostArea.ActiveCells.Contains(t.Position) == false))
             && IntVec3Utility.ManhattanDistanceFlat(pawn.Position, pawn2.Position) > 15)
         {
             return false;
         }
     }
     else if ((outpostArea == null)
         || (outpostArea.ActiveCells.Contains(t.Position) == false))
     {
         return false;
     }
     return ((pawn.Position - fire.Position).LengthHorizontalSquared <= 225f || pawn.CanReserve(fire, 1)) && !WorkGiver_FightFiresOutpost.FireIsBeingHandled(fire, pawn);
 }
 public override AcceptanceReport AllowsPlacing(BuildableDef checkingDef, IntVec3 loc, Rot4 rot, Thing thingToIgnore = null)
 {
     IEnumerable<IntVec3> cells = GenAdj.CellsAdjacent8Way(loc, rot, checkingDef.Size).Union<IntVec3>(GenAdj.CellsOccupiedBy(loc, rot, checkingDef.Size));
     foreach (IntVec3 cell in cells)
     {
         List<Thing> things = Map.thingGrid.ThingsListAt(cell);
         foreach (Thing thing in things)
         {
             if (thing.TryGetComp<CompRTQuantumStockpile>() != null
                 || thing.TryGetComp<CompRTQuantumChunkSilo>() != null)
             {
                 return "PlaceWorker_RTNoQSOverlap".Translate();
             }
             else if (thing.def.entityDefToBuild != null)
             {
                 ThingDef thingDef = thing.def.entityDefToBuild as ThingDef;
                 if (null != thingDef &&
                     null != thingDef.comps &&
                     null != thingDef.comps.Find(x => typeof(CompRTQuantumStockpile) == x.compClass))
                 {
                     return "PlaceWorker_RTNoQSOverlap".Translate();
                 }
             }
         }
     }
     return true;
 }
Ejemplo n.º 15
0
        public CommentViewModel(IBaconProvider baconProvider, Thing comment, string linkId, bool oddNesting, int depth = 0)
        {
            _isMinimized = false;
            _comment = new TypedThing<Comment>(comment);
            _baconProvider = baconProvider;
            _redditService = _baconProvider.GetService<IRedditService>();
            _navigationService = _baconProvider.GetService<INavigationService>();
            _userService = _baconProvider.GetService<IUserService>();
            _dynamicViewLocator = _baconProvider.GetService<IDynamicViewLocator>();
            _markdownProcessor = _baconProvider.GetService<IMarkdownProcessor>();
            _linkId = linkId;
            OddNesting = oddNesting;
			Depth = depth;
            AuthorFlair = _redditService.GetUsernameModifiers(_comment.Data.Author, _linkId, _comment.Data.Subreddit);
            AuthorFlairText = _comment.Data.AuthorFlairText;
            _showExtendedView = new RelayCommand(ShowExtendedViewImpl);
            _gotoReply = new RelayCommand(GotoReplyImpl);
            _save = new RelayCommand(SaveImpl);
            _report = new RelayCommand(ReportImpl);
            _gotoFullLink = new RelayCommand(GotoFullLinkImpl);
            _gotoContext = new RelayCommand(GotoContextImpl);
            _gotoUserDetails = new RelayCommand(GotoUserDetailsImpl);
            _gotoEdit = new RelayCommand(GotoEditImpl);
            _minimizeCommand = new RelayCommand(() => IsMinimized = !IsMinimized);
            Body = _comment.Data.Body;
        }
 public override Job JobOnThing( Pawn pawn, Thing t )
 {
     var warden = pawn;
     var slave = t as Pawn;
     if(
         ( slave == null )||
         ( slave.guest == null )||
         ( slave.guest.interactionMode != Data.PIM.FreeSlave )||
         ( slave.Downed )||
         ( !slave.Awake() )||
         ( !warden.CanReserveAndReach(
             slave,
             PathEndMode.ClosestTouch,
             warden.NormalMaxDanger(),
             1 )
         )
     )
     {
         return null;
     }
     var collar = slave.WornCollar();
     if( collar == null )
     {   // Slave isn't wearing a collar, wut?
         return null;
     }
     IntVec3 result;
     if( !RCellFinder.TryFindPrisonerReleaseCell( slave, warden, out result ) )
     {
         return null;
     }
     var job = new Job( Data.JobDefOf.FreeSlave, slave, collar, result );
     job.maxNumToCarry = 1;
     return job;
 }
 private Toil Ignite(Thing target)
 {
     Toil toil = new Toil();
     toil.initAction = delegate
     {
         Pawn feenix = this.pawn;
         if (target.FlammableNow && !target.IsBurning())
         {
             if (target.CanEverAttachFire())
             {
                 target.TryAttachFire(1f);
             }
             else
             {
                 FireUtility.TryStartFireIn(target.Position, 1f);
             }
             PawnUtility.ForceWait(feenix, 250, target);
         }
         else
         {
             return;
         }
     };
     toil.defaultCompleteMode = ToilCompleteMode.Delay;
     toil.defaultDuration = 250;
     return toil;
 }
Ejemplo n.º 18
0
        public void Init()
        {
            var testBehavior = new TalentsBehavior(null);
            var warriorAttribute = new WarriorAttribute();
            var rogueAttribute = new RogueAttribute();
            var mageAttribute = new MageAttribute();
            var damageStat = new DamageStat();
            var attackStat = new AttackStat();

            this.playerThing = new Thing() { Name = "PlayerThing", ID = TestThingID.Generate("testthing") };

            playerThing.Behaviors.Add(testBehavior);

            warriorAttribute.Parent = this.playerThing;
            playerThing.AddAttribute(warriorAttribute);

            mageAttribute.Parent = this.playerThing;
            playerThing.AddAttribute(rogueAttribute);

            rogueAttribute.Parent = this.playerThing;
            playerThing.AddAttribute(mageAttribute);

            warriorAttribute.SetValue(10, playerThing);
            rogueAttribute.SetValue(10, playerThing);
            mageAttribute.SetValue(10, playerThing);

            playerThing.Stats.Add(damageStat.Name, damageStat);
            playerThing.Stats.Add(attackStat.Name, attackStat);
        }
Ejemplo n.º 19
0
 public void ReplacePowerCell(Thing newCell)
 {
     if (newCell == null)
     {
         Log.Error("Tried to add a new power cell to " + parent.ThingID + " but it was null");
         return;
     }
     bool hasStat = false;
     StatDef sDef = StatDef.Named("MD2PowerCellMaxStorage");
     if (newCell.def.statBases != null)
     {
         for (int i = 0; i < parent.def.statBases.Count; i++)
         {
             if (newCell.def.statBases[i].stat == sDef)
             {
                 hasStat = true;
                 break;
             }
         }
     }
     if (!hasStat)
     {
         Log.Error(newCell.ThingID + " has no power cell stat");
         return;
     }
     if (PowerCell != null)
         GenSpawn.Spawn(PowerCell, parent.Position);
     PowerCell = newCell;
     parent.TotalCharge = newCell.GetStatValue(sDef) * 0.1f;
     if (newCell.SpawnedInWorld)
         newCell.DeSpawn();
 }
Ejemplo n.º 20
0
 static void Plucky(out Thing t)
 {
     Thing r = new Thing();
     r.whatever = 8;
     // Can't do this: Console.Write("t was " + t);
     t = r;
 }
Ejemplo n.º 21
0
 static void Splunge(ref Thing t)
 {
     Thing r = new Thing();
     r.whatever = 17;
     Console.WriteLine("t was " + t);
     t = r;
 }
 public override Job JobOnThing(Pawn pawn, Thing t)
 {
     Building_RepairStation rps = ListerDroids.ClosestRepairStationFor(pawn,t);
     Job job = new Job(ReactivateDroidJobDef, t, rps);
     job.maxNumToCarry = 1;
     return job;
 }
		public override bool HasJobOnThing(Pawn pawn, Thing t)
		{
            if ((t is Building_AquacultureBasin) == false)
            {
                return false;
            }
            Building_AquacultureBasin aquacultureBasin = t as Building_AquacultureBasin;

            if (pawn.Dead
                || pawn.Downed
                || pawn.IsBurning())
            {
                return false;
            }
            if (pawn.CanReserveAndReach(aquacultureBasin, this.PathEndMode, Danger.Some) == false)
            {
                return false;
            }

            if (aquacultureBasin.breedingIsFinished)
            {
                return true;
            }
            return false;
		}
Ejemplo n.º 24
0
 public override Job JobOnThing(Pawn pawn, Thing t)
 {
     Vehicle_Cart cart = t as Vehicle_Cart;
     if (cart == null)
         return (Job)null;
     if (cart.IsForbidden(pawn.Faction) || !ReservationUtility.CanReserveAndReach(pawn, cart, PathEndMode.ClosestTouch, DangerUtility.NormalMaxDanger(pawn)))
         return (Job)null;
     if (FireUtility.IsBurning(cart))
     {
         JobFailReason.Is(ToolsForHaulUtility.BurningLowerTrans);
         return (Job)null;
     }
     if (ListerHaulables.ThingsPotentiallyNeedingHauling().Count == 0 && cart.storage.Count == 0)
     {
         JobFailReason.Is(ToolsForHaulUtility.NoHaulable);
         return (Job)null;
     }
     if (Find.SlotGroupManager.AllGroupsListInPriorityOrder.Count == 0)
     {
         JobFailReason.Is(ToolsForHaulUtility.NoEmptyPlaceLowerTrans);
         return (Job)null;
     }
     if (ToolsForHaulUtility.AvailableAnimalCart(cart) || ToolsForHaulUtility.AvailableCart(cart, pawn))
         return ToolsForHaulUtility.HaulWithTools(pawn, cart);
     JobFailReason.Is(ToolsForHaulUtility.NoAvailableCart);
     return (Job)null;
 }
Ejemplo n.º 25
0
        /// <summary>
        /// Better version of base AnimalAwareOf that works for Things with passability XML
        /// set to Impassable. 
        /// </summary>
        public static bool AnimalAwareOfEx(this Pawn p, Thing t)
        {
            if (p.RaceProps.ToolUser || p.Faction != null)
            {
                return true;
            }

            var pRoom = p.GetRoom();
            List<Room> thingRooms = new List<Room>();
            if (t.def.passability != Traversability.Impassable)
            {
                thingRooms.Add(t.GetRoom());
            }
            else
            {
                // Find the rooms that are adjacent to the impassable Thing.
                foreach (IntVec3 pos in GenAdj.CellsAdjacent8Way(t))
                {
                    var room = pos.GetRoom();
                    if (room == null) continue;
                    thingRooms.Add(room);
                }
            }

            return ((p.Position - t.Position).LengthHorizontalSquared <= 900f &&
                thingRooms.Any(tRoom => tRoom == pRoom) &&
                GenSight.LineOfSight(p.Position, t.Position, false));
        }
 public FloatMenuOption_Group(string label, Action action, Designator designator,
     MenuOptionPriority priority = MenuOptionPriority.Medium, Action mouseoverGuiAction = null,
     Thing revalidateClickTarget = null)
     : base(label, action, priority, mouseoverGuiAction, revalidateClickTarget)
 {
     this.designator = designator;
 }
Ejemplo n.º 27
0
        public override void SpawnSetup()
        {
            base.SpawnSetup();

            // Initialize take-off tick.
            takeOffTick = Find.TickManager.TicksGame + ressuplyDuration;

            // Spawn cryptosleep bays.
            if (this.cryptosleepBay1 == null)
            {
                cryptosleepBay1 = ThingMaker.MakeThing(OG_Util.SupplyShipCryptosleepBayLeftDef);
                cryptosleepBay1.SetFactionDirect(this.Faction);
                GenSpawn.Spawn(cryptosleepBay1, this.Position + new IntVec3(-4, 0, -2).RotatedBy(this.Rotation), this.Rotation);
            }
            if (this.cryptosleepBay2 == null)
            {
                cryptosleepBay2 = ThingMaker.MakeThing(OG_Util.SupplyShipCryptosleepBayRightDef);
                cryptosleepBay2.SetFactionDirect(this.Faction);
                GenSpawn.Spawn(cryptosleepBay2, this.Position + new IntVec3(3, 0, -2).RotatedBy(this.Rotation), this.Rotation);
            }
            // Spawn cargo bays.
            if (this.cargoBay1 == null)
            {
                cargoBay1 = ThingMaker.MakeThing(OG_Util.SupplyShipCargoBayLeftDef);
                cargoBay1.SetFactionDirect(this.Faction);
                GenSpawn.Spawn(cargoBay1, this.Position + new IntVec3(-4, 0, 1).RotatedBy(this.Rotation), this.Rotation);
            }
            if (this.cargoBay2 == null)
            {
                cargoBay2 = ThingMaker.MakeThing(OG_Util.SupplyShipCargoBayRightDef);
                cargoBay2.SetFactionDirect(this.Faction);
                GenSpawn.Spawn(cargoBay2, this.Position + new IntVec3(4, 0, 1).RotatedBy(this.Rotation), this.Rotation);
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Loads this instance.
        /// </summary>
        public void Load()
        {
            var areaRepository = new AreaRepository();

            // @@@ TODO: Fix hack: http://www.wheelmud.net/tabid/59/aft/1622/Default.aspx
            string areaNumber = this.Parent.ID.Replace("area/", string.Empty);
            long persistedAreaID = long.Parse(areaNumber);
            ICollection<RoomRecord> rooms = areaRepository.GetRoomsForArea(persistedAreaID);

            foreach (var roomRecord in rooms)
            {
                // @@@ TODO: Fix hack: http://www.wheelmud.net/tabid/59/aft/1622/Default.aspx
                var roomBehavior = new RoomBehavior()
                {
                    ID = roomRecord.ID,
                };
                var currRoom = new Thing(roomBehavior)
                {
                    Name = roomRecord.Name,
                    Description = roomRecord.Description,
                    ID = "room/" + roomRecord.ID,
                };

                // Load this room and it's children.
                roomBehavior.Load();
                this.Parent.Add(currRoom);
            }
        }
Ejemplo n.º 29
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EnterEvent"/> class.
 /// </summary>
 /// <param name="thingEntered">The thing entered.</param>
 /// <param name="activeThing">The active thing.</param>
 /// <param name="sensoryMessage">The sensory message.</param>
 /// <param name="startLocation">The start location.</param>
 /// <param name="endLocation">The end location.</param>
 public EnterEvent(Thing thingEntered, Thing activeThing, SensoryMessage sensoryMessage, Thing startLocation, Thing endLocation)
     : base(activeThing, sensoryMessage)
 {
     this.ThingEntered = thingEntered;
     this.StartLocation = startLocation;
     this.EndLocation = endLocation;
 }
        // Look for a receiver and lock it.
        public override IntVec3 GetDestinationForThing( Thing thing )
        {
            // Already targetted
            if( ( Receiver != null )&&
                ( Receiver.CanAcceptSomething() ) )
                return Receiver.parent.Position;

            // Find a new target
            var pos = parent.Position.ToVector3();

            // Get only only receivers on my channel and return them in order of
            // closest to furthest.
            var recv = Manager.GetReceivers( Channel )
                              .Where( r => r.CanAcceptFrom( this ) )
                              .OrderBy( r => ( r.parent.Position.ToVector3() - pos ).sqrMagnitude );

            try{
                // This will be the closest unlocked receiver, try to lock it
                var target = recv.First();
                if( LockTarget( target ) ){
                    return target.parent.Position;
                } else{
                    return IntVec3.Invalid;
                }

            } catch( InvalidOperationException ){
                // If nothing was acceptable, return IntVec3.Invalid
                return IntVec3.Invalid;
            }
        }
Ejemplo n.º 31
0
 public MaterialRedHot(Thing t)
 {
     this._effect      = Content.Load <MTEffect>("Shaders/redhot");
     this._goldTexture = Content.Load <Tex2D>("redHot");
     this._thing       = t;
 }
        //get next, goto, take, check for more. Branches off to "all over the place"
        protected override IEnumerable <Toil> MakeNewToils()
        {
            CompHauledToInventory takenToInventory = pawn.TryGetComp <CompHauledToInventory>();

            Toil wait = Toils_General.Wait(2);

            Toil nextTarget = Toils_JobTransforms.ExtractNextTargetFromQueue(TargetIndex.A); //also does count

            yield return(nextTarget);

            //honestly the workgiver checks for encumbered, so until CE checks are in this is unnecessary
            //yield return CheckForOverencumbered();//Probably redundant without CE checks

            var gotoThing = new Toil
            {
                initAction          = () => pawn.pather.StartPath(TargetThingA, PathEndMode.ClosestTouch),
                defaultCompleteMode = ToilCompleteMode.PatherArrival
            };

            gotoThing.FailOnDespawnedNullOrForbidden(TargetIndex.A);
            yield return(gotoThing);

            var takeThing = new Toil
            {
                initAction = () =>
                {
                    Pawn  actor = pawn;
                    Thing thing = actor.CurJob.GetTarget(TargetIndex.A).Thing;
                    Toils_Haul.ErrorCheckForCarry(actor, thing);

                    //get max we can pick up
                    var countToPickUp = Mathf.Min(job.count, MassUtility.CountToPickUpUntilOverEncumbered(actor, thing));
                    Log.Message($"{actor} is hauling to inventory {thing}:{countToPickUp}");

                    // yo dawg, I heard you like delegates so I put delegates in your delegate, so you can delegate your delegates.
                    // because compilers don't respect IF statements in delegates and toils are fully iterated over as soon as the job starts.
                    try
                    {
                        ((Action)(() =>
                        {
                            if (ModCompatibilityCheck.CombatExtendedIsActive)
                            {
                                //CombatExtended.CompInventory ceCompInventory = actor.GetComp<CombatExtended.CompInventory>();
                                //ceCompInventory.CanFitInInventory(thing, out countToPickUp);
                            }
                        }))();
                    }
                    catch (TypeLoadException) { }

                    if (countToPickUp > 0)
                    {
                        Thing splitThing  = thing.SplitOff(countToPickUp);
                        var   shouldMerge = takenToInventory.GetHashSet().Any(x => x.def == thing.def);
                        actor.inventory.GetDirectlyHeldThings().TryAdd(splitThing, shouldMerge);
                        takenToInventory.RegisterHauledItem(splitThing);

                        try
                        {
                            ((Action)(() =>
                            {
                                if (ModCompatibilityCheck.CombatExtendedIsActive)
                                {
                                    //CombatExtended.CompInventory ceCompInventory = actor.GetComp<CombatExtended.CompInventory>();
                                    //ceCompInventory.UpdateInventory();
                                }
                            }))();
                        }
                        catch (TypeLoadException)
                        {
                        }
                    }

                    //thing still remains, so queue up hauling if we can + end the current job (smooth/instant transition)
                    //This will technically release the reservations in the queue, but what can you do
                    if (thing.Spawned)
                    {
                        Job haul = HaulAIUtility.HaulToStorageJob(actor, thing);
                        if (haul?.TryMakePreToilReservations(actor, false) ?? false)
                        {
                            actor.jobs.jobQueue.EnqueueFirst(haul, JobTag.Misc);
                        }
                        actor.jobs.curDriver.JumpToToil(wait);
                    }
                }
            };

            yield return(takeThing);

            yield return(Toils_Jump.JumpIf(nextTarget, () => !job.targetQueueA.NullOrEmpty()));

            //Find more to haul, in case things spawned while this was in progess
            yield return(new Toil
            {
                initAction = () =>
                {
                    List <Thing> haulables = pawn.Map.listerHaulables.ThingsPotentiallyNeedingHauling();
                    var haulMoreWork = DefDatabase <WorkGiverDef> .AllDefsListForReading.First(wg => wg.Worker is WorkGiver_HaulToInventory).Worker as WorkGiver_HaulToInventory;

                    Thing haulMoreThing = GenClosest.ClosestThing_Global(pawn.Position, haulables, 12, t => haulMoreWork.HasJobOnThing(pawn, t));

                    //WorkGiver_HaulToInventory found more work nearby
                    if (haulMoreThing != null)
                    {
                        Log.Message($"{pawn} hauling again : {haulMoreThing}");
                        Job haulMoreJob = haulMoreWork.JobOnThing(pawn, haulMoreThing);

                        if (haulMoreJob.TryMakePreToilReservations(pawn, false))
                        {
                            pawn.jobs.jobQueue.EnqueueFirst(haulMoreJob, JobTag.Misc);
                            EndJobWith(JobCondition.Succeeded);
                        }
                    }
                }
            });

            //maintain cell reservations on the trip back
            //TODO: do that when we carry things
            //I guess that means TODO: implement carrying the rest of the items in this job instead of falling back on HaulToStorageJob
            yield return(Toils_Goto.GotoCell(TargetIndex.B, PathEndMode.ClosestTouch));

            yield return(new Toil //Queue next job
            {
                initAction = () =>
                {
                    Pawn actor = pawn;
                    Job curJob = actor.jobs.curJob;
                    LocalTargetInfo storeCell = curJob.targetB;

                    Job unloadJob = JobMaker.MakeJob(PickUpAndHaulJobDefOf.UnloadYourHauledInventory, storeCell);
                    if (unloadJob.TryMakePreToilReservations(actor, false))
                    {
                        actor.jobs.jobQueue.EnqueueFirst(unloadJob, JobTag.Misc);
                        EndJobWith(JobCondition.Succeeded);
                        //This will technically release the cell reservations in the queue, but what can you do
                    }
                }
            });

            yield return(wait);
        }
Ejemplo n.º 33
0
 internal static bool CanAutoDesignateThingForUrgentHauling(Thing t)
 {
     return(!t.def.designateHaulable);
 }
Ejemplo n.º 34
0
        public override AcceptanceReport AllowsPlacing(BuildableDef checkingDef, IntVec3 loc, Rot4 rot, Map map, Thing thingToIgnore = null)
        {
            // God Mode allows placing the quarry without the grid restriction
            if (!DebugSettings.godMode)
            {
                int occCells  = 0;
                int rockCells = 0;
                foreach (IntVec3 c in GenAdj.CellsOccupiedBy(loc, rot, checkingDef.Size))
                {
                    occCells++;

                    // Make sure the quarry is placeable here
                    if (map.GetComponent <QuarryGrid>().GetCellBool(c))
                    {
                        rockCells++;
                    }
                }

                // Require at least 60% rocky terrain
                if ((float)(occCells - rockCells) / occCells > 0.4f)
                {
                    return(Static.ReportNotEnoughStone);
                }
            }

            return(true);
        }
Ejemplo n.º 35
0
 public static bool TryDropAndSetForbidden(Thing th, IntVec3 pos, Map map, ThingPlaceMode mode, out Thing resultingThing, bool forbidden)
 {
     if (GenDrop.TryDropSpawn_NewTmp(th, pos, map, ThingPlaceMode.Near, out resultingThing))
     {
         if (resultingThing != null)
         {
             resultingThing.SetForbidden(forbidden, warnOnFail: false);
         }
         return(true);
     }
     resultingThing = null;
     return(false);
 }
Ejemplo n.º 36
0
 public static bool CloserThingBetween(ThingDef thingDef, IntVec3 a, IntVec3 b, Map map, Thing thingToIgnore = null)
 {
     foreach (IntVec3 item in CellRect.FromLimits(a, b))
     {
         if (item == a || item == b || !item.InBounds(map))
         {
             continue;
         }
         foreach (Thing thing in item.GetThingList(map))
         {
             if ((thingToIgnore == null || thingToIgnore != thing) && (thing.def == thingDef || thing.def.entityDefToBuild == thingDef))
             {
                 return(true);
             }
         }
     }
     return(false);
 }
Ejemplo n.º 37
0
 public static Vector3 TrueCenter(this Thing t)
 {
     return((t as Pawn)?.Drawer.DrawPos ?? TrueCenter(t.Position, t.Rotation, t.def.size, t.def.Altitude));
 }
Ejemplo n.º 38
0
        public static bool ShouldEquipByOutfit(this JobGiver_PickUpOpportunisticWeapon jobGiver, Thing thing, Pawn pawn)
        {
            var currentOutfit = pawn.outfits.CurrentOutfit;

            if (currentOutfit.filter.Allows(thing))
            {
                return(true);
            }

            Trace("Not Allowed To Thing : " + thing);
            return(false);
        }
 public static bool IsAmmo(Thing ammo)
 {
     return
         (HasCombatExtended &&
          ammo?.GetType().GetProperty("AmmoDef", BindingFlags.NonPublic | BindingFlags.Instance) != null);
 }
Ejemplo n.º 40
0
        private static bool compareGuns(Thing oldGun, Thing newGun,
                                        Pawn pawn)
        {
            var hunter  = pawn.workSettings.WorkIsActive(WorkTypeDefOf.Hunting);
            var brawler = pawn.story.traits.HasTrait(TraitDefOf.Brawler);

            if (brawler && newGun.def.IsRangedWeapon)
            {
                Trace(newGun.def + " is ranged and pawn " + pawn.NameShortColored.RawText + " is brawler, ignoring.",
                      true);
                return(false);
            }

            if (hunter && newGun.def.IsMeleeWeapon)
            {
                Trace(newGun.def + " is melee and pawn " + pawn.NameShortColored.RawText + " is hunter, ignoring.",
                      true);
                return(false);
            }

            if (oldGun == null)
            {
                Trace(pawn.NameShortColored.RawText + " has no weapon, anything is better.", true);
                return(true);
            }

            var newEquippable  = newGun.TryGetComp <CompEquippable>();
            var newPrimaryVerb = newEquippable.PrimaryVerb;
            var oldEquippable  = oldGun.TryGetComp <CompEquippable>();
            var oldPrimaryVerb = oldEquippable.PrimaryVerb;

            var newHarmsHealth = newPrimaryVerb.HarmsHealth();
            var newDamageDef   = newPrimaryVerb.GetDamageDef();
            var newIsExplosive = newPrimaryVerb.UsesExplosiveProjectiles();

            var oldHarmsHealth = oldPrimaryVerb.HarmsHealth();
            var oldDamageDef   = oldPrimaryVerb.GetDamageDef();

            if (hunter && newIsExplosive)
            {
                Trace(newGun.def + " is explosive and pawn " + pawn.NameShortColored.RawText + " is hunter, ignoring.",
                      true);
                return(false);
            }

            if (oldHarmsHealth && !newHarmsHealth)
            {
                Trace(oldGun.def + " does actual damage and " + newGun.def + " does not, ignoring.", true);
                return(false);
            }

            if (hunter && (newDamageDef.hediffSkin != null && oldDamageDef.hediffSkin == null ||
                           newDamageDef.hediffSolid != null && oldDamageDef.hediffSolid == null))
            {
                Trace(
                    newGun.def + " is some kind of flamethrower/pay and spray weapon and pawn " +
                    pawn.NameShortColored.RawText + " is hunter, ignoring.", true);
                return(false);
            }

            var preferMelee = pawn.skills.GetSkill(SkillDefOf.Melee).Level >
                              pawn.skills.GetSkill(SkillDefOf.Shooting).Level;

            if (newGun.def.IsRangedWeapon && !oldGun.def.IsRangedWeapon)
            {
                if (hunter)
                {
                    return(true);
                }

                if (preferMelee)
                {
                    Trace(
                        newGun.def + " is ranged and pawn " + pawn.NameShortColored.RawText +
                        " is better with melee weapons, ignoring.", true);
                    return(false);
                }
            }

            if (newGun.def.IsMeleeWeapon && !oldGun.def.IsMeleeWeapon)
            {
                if (brawler)
                {
                    return(true);
                }

                if (!preferMelee)
                {
                    Trace(
                        newGun.def + " is melee and pawn " + pawn.NameShortColored.RawText +
                        " is better with ranged weapons, ignoring.", true);
                    return(false);
                }
            }

            if (newGun.MarketValue <= oldGun.MarketValue)
            {
                Trace(newGun.def + " is worth less than " + oldGun.def + ", ignoring.", true);
                return(false);
            }

            if (FindAGunDamnItMod.instance.Settings.StayInRange && !hasTheSameTypeOfAccuracy(oldGun, newGun))
            {
                Trace(newGun.def + " does not have the same type of accuracy as " + oldGun.def + ", ignoring.", true);
                return(false);
            }


            return(true);
        }
Ejemplo n.º 41
0
        private static bool TryFindBestBillIngredients(Bill bill, Pawn pawn, Thing billGiver, List <ThingCount> chosen)
        {
            chosen.Clear();
            newRelevantThings.Clear();
            if (bill.recipe.ingredients.Count == 0)
            {
                return(true);
            }
            IntVec3 rootCell = GetBillGiverRootCell(billGiver, pawn);
            Region  rootReg  = rootCell.GetRegion(pawn.Map);

            if (rootReg == null)
            {
                return(false);
            }
            MakeIngredientsListInProcessingOrder(ingredientsOrdered, bill);
            relevantThings.Clear();
            processedThings.Clear();
            bool foundAll = false;
            Predicate <Thing> baseValidator = (Thing t) => t.Spawned && !t.IsForbidden(pawn) && (float)(t.Position - billGiver.Position).LengthHorizontalSquared < bill.ingredientSearchRadius * bill.ingredientSearchRadius && bill.IsFixedOrAllowedIngredient(t) && bill.recipe.ingredients.Any((IngredientCount ingNeed) => ingNeed.filter.Allows(t)) && pawn.CanReserve(t);
            bool billGiverIsPawn            = billGiver is Pawn;

            if (billGiverIsPawn)
            {
                AddEveryMedicineToRelevantThings(pawn, billGiver, relevantThings, baseValidator, pawn.Map);
                if (TryFindBestBillIngredientsInSet(relevantThings, bill, chosen))
                {
                    relevantThings.Clear();
                    ingredientsOrdered.Clear();
                    return(true);
                }
            }
            TraverseParms        traverseParams = TraverseParms.For(pawn);
            RegionEntryPredicate entryCondition = (Region from, Region r) => r.Allows(traverseParams, isDestination: false);
            int adjacentRegionsAvailable        = rootReg.Neighbors.Count((Region region) => entryCondition(rootReg, region));
            int regionsProcessed = 0;

            processedThings.AddRange(relevantThings);
            RegionProcessor regionProcessor = delegate(Region r)
            {
                List <Thing> list = r.ListerThings.ThingsMatching(ThingRequest.ForGroup(ThingRequestGroup.HaulableEver));
                for (int i = 0; i < list.Count; i++)
                {
                    Thing thing = list[i];
                    if (!processedThings.Contains(thing) && ReachabilityWithinRegion.ThingFromRegionListerReachable(thing, r, PathEndMode.ClosestTouch, pawn) && baseValidator(thing) && (!thing.def.IsMedicine || !billGiverIsPawn))
                    {
                        newRelevantThings.Add(thing);
                        processedThings.Add(thing);
                    }
                }
                regionsProcessed++;
                if (newRelevantThings.Count > 0 && regionsProcessed > adjacentRegionsAvailable)
                {
                    Comparison <Thing> comparison = delegate(Thing t1, Thing t2)
                    {
                        float num   = (float)(t1.Position - rootCell).LengthHorizontalSquared;
                        float value = (float)(t2.Position - rootCell).LengthHorizontalSquared;
                        return(num.CompareTo(value));
                    };
                    newRelevantThings.Sort(comparison);
                    relevantThings.AddRange(newRelevantThings);
                    newRelevantThings.Clear();
                    if (TryFindBestBillIngredientsInSet(relevantThings, bill, chosen))
                    {
                        foundAll = true;
                        return(true);
                    }
                }
                return(false);
            };

            RegionTraverser.BreadthFirstTraverse(rootReg, entryCondition, regionProcessor, 99999);
            relevantThings.Clear();
            newRelevantThings.Clear();
            processedThings.Clear();
            ingredientsOrdered.Clear();
            return(foundAll);
        }
 public static int GetAmmoCount(Thing ammo)
 {
     return(GetAmmoCount(ammo.def));
 }
Ejemplo n.º 43
0
        protected override IEnumerable <Toil> MakeNewToils()
        {
            if (TargetA.Thing != null)
            {
                targetThing = TargetA.Thing;
            }
            Toil gotoThing = new Toil()
            {
                initAction = () =>
                {
                    pawn.pather.StartPath(TargetA, PathEndMode.Touch);
                },
                defaultCompleteMode = ToilCompleteMode.PatherArrival
            };

            yield return(gotoThing);

            Toil doSpell = new Toil();

            doSpell.initAction = delegate
            {
                if (ability != null)
                {
                    this.duration = (int)(ability.Def.MainVerb.warmupTime * 60 * this.pawn.GetStatValue(StatDefOf.AimingDelayFactor, false));
                }
                if (age > duration)
                {
                    this.EndJobWith(JobCondition.Succeeded);
                }
                if (targetThing != null && (targetThing.DestroyedOrNull() || targetThing.Map == null))
                {
                    this.EndJobWith(JobCondition.Incompletable);
                }

                if (targetThing != null)
                {
                    this.pawn.rotationTracker.FaceTarget(targetThing);
                }
            };
            doSpell.tickAction = delegate
            {
                if (targetThing != null && (targetThing.DestroyedOrNull() || targetThing.Map == null))
                {
                    this.EndJobWith(JobCondition.Incompletable);
                }
                age++;
                ticksLeftThisToil = duration - age;
                if (Find.TickManager.TicksGame % 12 == 0)
                {
                    TM_MoteMaker.ThrowCastingMote(pawn.DrawPos, pawn.Map, Rand.Range(1.2f, 2f));
                }

                if (age > duration)
                {
                    this.EndJobWith(JobCondition.Succeeded);
                }
            };
            doSpell.defaultCompleteMode = ToilCompleteMode.Never;
            doSpell.defaultDuration     = this.duration;
            doSpell.AddFinishAction(delegate
            {
                if (ability != null)
                {
                    if (ability.Def == TorannMagicDefOf.TM_Transmutate && targetThing != null)
                    {
                        bool flagRawResource = false;
                        bool flagStuffItem   = false;
                        bool flagNoStuffItem = false;
                        bool flagNutrition   = false;
                        bool flagCorpse      = false;

                        TM_Calc.GetTransmutableThingFromCell(targetThing.Position, pawn, out flagRawResource, out flagStuffItem, out flagNoStuffItem, out flagNutrition, out flagCorpse);
                        TM_Action.DoTransmutate(pawn, targetThing, flagNoStuffItem, flagRawResource, flagStuffItem, flagNutrition, flagCorpse);
                    }
                    else if (ability.Def == TorannMagicDefOf.TM_RegrowLimb)
                    {
                        AbilityUser.SpawnThings tempThing = new SpawnThings();
                        tempThing.def = ThingDef.Named("SeedofRegrowth");
                        Verb_RegrowLimb.SingleSpawnLoop(tempThing, TargetA.Cell, pawn.Map);
                    }
                    ability.PostAbilityAttempt();
                }
                //AssignXP();
            });
            yield return(doSpell);
        }
        public static bool TryDropAmmo(ThingDef def, int count, IntVec3 position, Map map, out Thing droppedAmmo)
        {
            //Log.Warning("Util Drop: " + def.defName + " x" + count);
            if (count > 0 &&
                def != null &&
                Ammo.TryGetValue(def, out int i) &&
                i > 0)
            {
                if (i < count)
                {
                    count = i;
                }

                i -= count;

                //Log.Message("    Dropping Count: " + count);
                droppedAmmo = MakeAmmo(def, count);
                if (BuildingUtil.DropThing(droppedAmmo, position, map))
                {
                    //Log.Message("    Remaining Count: " + i);
                    Ammo[def] = i;
                    return(true);
                }
                else
                {
                    Log.Error("Failed to drop " + def.defName + " x" + count);
                }
            }
            droppedAmmo = null;
            return(false);
        }
        ///// <summary>
        ///// Prevents the user from having damage with the verb.
        ///// </summary>
        ///// <param name="__instance"></param>
        ///// <param name="__result"></param>
        ///// <param name="pawn"></param>
        //public static void GetDamageFactorForPostFix(Verb __instance, ref float __result, Pawn pawn)
        //{
        //    Pawn_EquipmentTracker pawn_EquipmentTracker = pawn.equipment;
        //    if (pawn_EquipmentTracker != null)
        //    {
        //        //Log.Message("2");
        //        ThingWithComps thingWithComps = (ThingWithComps)AccessTools.Field(typeof(Pawn_EquipmentTracker), "primaryInt").GetValue(pawn_EquipmentTracker);

        //        if (thingWithComps != null)
        //        {
        //            //Log.Message("3");
        //            CompActivatableEffect compActivatableEffect = thingWithComps.GetComp<CompActivatableEffect>();
        //            if (compActivatableEffect != null)
        //            {
        //                if (compActivatableEffect.CurrentState != CompActivatableEffect.State.Activated)
        //                {
        //                    //Messages.Message("DeactivatedWarning".Translate(), MessageSound.RejectInput);
        //                    __result = 0f;
        //                }
        //            }
        //        }
        //    }
        //}


        /// <summary>
        /// Adds another "layer" to the equipment aiming if they have a
        /// weapon with a CompActivatableEffect.
        /// </summary>
        /// <param name="__instance"></param>
        /// <param name="eq"></param>
        /// <param name="drawLoc"></param>
        /// <param name="aimAngle"></param>
        public static void DrawEquipmentAimingPostFix(PawnRenderer __instance, Thing eq, Vector3 drawLoc, float aimAngle)
        {
            Pawn pawn = (Pawn)AccessTools.Field(typeof(PawnRenderer), "pawn").GetValue(__instance);

            Pawn_EquipmentTracker pawn_EquipmentTracker = pawn.equipment;

            if (pawn_EquipmentTracker != null)
            {
                //Log.Message("2");
                //ThingWithComps thingWithComps = (ThingWithComps)AccessTools.Field(typeof(Pawn_EquipmentTracker), "primaryInt").GetValue(pawn_EquipmentTracker);
                ThingWithComps thingWithComps = pawn_EquipmentTracker.Primary; //(ThingWithComps)AccessTools.Field(typeof(Pawn_EquipmentTracker), "primaryInt").GetValue(pawn_EquipmentTracker);

                if (thingWithComps != null)
                {
                    //Log.Message("3");
                    CompActivatableEffect compActivatableEffect = thingWithComps.GetComp <CompActivatableEffect>();
                    if (compActivatableEffect != null)
                    {
                        //Log.Message("4");
                        if (compActivatableEffect.Graphic != null)
                        {
                            if (compActivatableEffect.CurrentState == CompActivatableEffect.State.Activated)
                            {
                                float num  = aimAngle - 90f;
                                bool  flip = false;

                                if (aimAngle > 20f && aimAngle < 160f)
                                {
                                    //mesh = MeshPool.GridPlaneFlip(thingWithComps.def.graphicData.drawSize);
                                    num += eq.def.equippedAngleOffset;
                                }
                                else if (aimAngle > 200f && aimAngle < 340f)
                                {
                                    //mesh = MeshPool.GridPlane(thingWithComps.def.graphicData.drawSize);
                                    flip = true;
                                    num -= 180f;
                                    num -= eq.def.equippedAngleOffset;
                                }
                                else
                                {
                                    //mesh = MeshPool.GridPlaneFlip(thingWithComps.def.graphicData.drawSize);
                                    num += eq.def.equippedAngleOffset;
                                }

                                if (eq is ThingWithComps eqComps)
                                {
                                    ThingComp deflector = eqComps.AllComps.FirstOrDefault <ThingComp>((ThingComp y) => y.GetType().ToString().Contains("Deflect"));
                                    if (deflector != null)
                                    {
                                        bool isActive = (bool)AccessTools.Property(deflector.GetType(), "IsAnimatingNow").GetValue(deflector, null);
                                        if (isActive)
                                        {
                                            float numMod = (int)AccessTools.Property(deflector.GetType(), "AnimationDeflectionTicks").GetValue(deflector, null);
                                            //float numMod2 = new float();
                                            //numMod2 = numMod;
                                            if (numMod > 0)
                                            {
                                                if (!flip)
                                                {
                                                    num += ((numMod + 1) / 2);
                                                }
                                                else
                                                {
                                                    num -= ((numMod + 1) / 2);
                                                }
                                            }
                                        }
                                    }
                                }
                                num %= 360f;

                                //ThingWithComps eqComps = eq as ThingWithComps;
                                //if (eqComps != null)
                                //{
                                //    ThingComp deflector = eqComps.AllComps.FirstOrDefault<ThingComp>((ThingComp y) => y.GetType().ToString() == "CompDeflector.CompDeflector");
                                //    if (deflector != null)
                                //    {
                                //        float numMod = (float)((int)AccessTools.Property(deflector.GetType(), "AnimationDeflectionTicks").GetValue(deflector, null));
                                //        //Log.ErrorOnce("NumMod " + numMod.ToString(), 1239);
                                //numMod = (numMod + 1) / 2;
                                //if (subtract) num -= numMod;
                                //else num += numMod;
                                //    }
                                //}

                                Material matSingle = compActivatableEffect.Graphic.MatSingle;
                                //if (mesh == null) mesh = MeshPool.GridPlane(thingWithComps.def.graphicData.drawSize);

                                Vector3   s      = new Vector3(eq.def.graphicData.drawSize.x, 1f, eq.def.graphicData.drawSize.y);
                                Matrix4x4 matrix = default(Matrix4x4);
                                matrix.SetTRS(drawLoc, Quaternion.AngleAxis(num, Vector3.up), s);
                                if (!flip)
                                {
                                    Graphics.DrawMesh(MeshPool.plane10, matrix, matSingle, 0);
                                }
                                else
                                {
                                    Graphics.DrawMesh(MeshPool.plane10Flip, matrix, matSingle, 0);
                                }
                                //Graphics.DrawMesh(mesh, drawLoc, Quaternion.AngleAxis(num, Vector3.up), matSingle, 0);
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 46
0
        public void Explosion(int pwr, IntVec3 center, Map map, float radius, DamageDef damType, Thing instigator, SoundDef explosionSound = null, ThingDef projectile = null, ThingDef source = null, ThingDef postExplosionSpawnThingDef = null, float postExplosionSpawnChance = 0f, int postExplosionSpawnThingCount = 1, bool applyDamageToExplosionCellsNeighbors = false, ThingDef preExplosionSpawnThingDef = null, float preExplosionSpawnChance = 0f, int preExplosionSpawnThingCount = 1)
        {
            System.Random rnd = new System.Random();
            int           modDamAmountRand = GenMath.RoundRandom(rnd.Next(4 + (pwr * 1), projectile.projectile.damageAmountBase + (pwr * 2)));

            modDamAmountRand *= Mathf.RoundToInt(this.arcaneDmg);
            if (pwr >= 1)
            {
                radius = (float)(rnd.Next(pwr, pwr * 2) / 1.8);
            }
            if (map == null)
            {
                Log.Warning("Tried to do explosion in a null map.");
                return;
            }
            Explosion explosion = (Explosion)GenSpawn.Spawn(ThingDefOf.Explosion, center, map);

            explosion.dealMoreDamageAtCenter = true;
            explosion.chanceToStartFire      = 0.0f;
            explosion.Position   = center;
            explosion.radius     = radius;
            explosion.damType    = damType;
            explosion.instigator = instigator;
            explosion.damAmount  = ((projectile == null) ? GenMath.RoundRandom((float)damType.explosionDamage) : modDamAmountRand);
            explosion.weapon     = source;
            explosion.preExplosionSpawnThingDef            = preExplosionSpawnThingDef;
            explosion.preExplosionSpawnChance              = preExplosionSpawnChance;
            explosion.preExplosionSpawnThingCount          = preExplosionSpawnThingCount;
            explosion.postExplosionSpawnThingDef           = postExplosionSpawnThingDef;
            explosion.postExplosionSpawnChance             = postExplosionSpawnChance;
            explosion.postExplosionSpawnThingCount         = postExplosionSpawnThingCount;
            explosion.applyDamageToExplosionCellsNeighbors = applyDamageToExplosionCellsNeighbors;
            explosion.StartExplosion(explosionSound);
        }
 public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false)
 => JobMaker.MakeJob(JobDefOf.ToggleLock, t);
Ejemplo n.º 48
0
 public static bool CanEatForNutritionNow(Thing food, Pawn pawn)
 {
     return(food.IngestibleNow && CaravanPawnsNeedsUtility.CanEatForNutritionNow(food.def, pawn));
 }
Ejemplo n.º 49
0
 public bool DoesThingOnMapMatchFilter(ThingFilter ingredientFilter, Thing thing)
 {
     return(IsThingInAppropriateStockpile(thing) && DoesThingMatchFilter(ingredientFilter, thing));
 }
Ejemplo n.º 50
0
        public override void MapComponentTick()
        {
            base.MapComponentTick();

            switch (this.stage)
            {
            case ExecutingStage.ClearParameters:
                this.competitorTable = null;
                this.style           = null;
                this.roundNumbers    = null;
                this.sandBagChance   = null;
                this.wallChance      = null;
                this.raidScales.Clear();
                this.stage = ExecutingStage.PickingParameters;
                break;

            case ExecutingStage.PickingParameters:
                break;

            case ExecutingStage.CalculatingFights:
                this.fights.Clear();
                switch (this.competitorTable.Value)
                {
                case ChallengeType.AnotherFaction:
                    this.CalculateFights(this.toRaid[0], this.toRaid[1]);
                    break;

                case ChallengeType.AllOtherFactions:
                    foreach (Faction faction in Find.FactionManager.AllFactions.Where(i => i.HostileTo(Faction.OfColony)))
                    {
                        this.CalculateFights(this.toRaid[0], faction);
                    }
                    break;

                case ChallengeType.AllCoreFactions:
                    foreach (Faction faction in Find.FactionManager.AllFactions.Where(i => i.HostileTo(Faction.OfColony)))
                    {
                        if ((faction.def.defName == "Colony") ||
                            (faction.def.defName == "Spacer") ||
                            (faction.def.defName == "SpacerHostile") ||
                            (faction.def.defName == "Outlander") ||
                            (faction.def.defName == "Pirate") ||
                            (faction.def.defName == "Tribe") ||
                            (faction.def.defName == "Mechanoid"))
                        {
                            this.CalculateFights(this.toRaid[0], faction);
                        }
                    }
                    break;
                }
                this.stage = ExecutingStage.CreatingArena;
                break;

            case ExecutingStage.CreatingArena:

                if (this.fights.Where(i => i.winners.Count < this.roundNumbers.Value).Any())
                {
                    this.currentFight = this.fights.Where(i => i.winners.Count < this.roundNumbers.Value).First();
                }
                else
                {
                    this.stage = ExecutingStage.DisplaingResults;
                    return;
                }

                CellRect rect = CellRect.FromLimits(5, 5, 100, 60);

                rect.ClipInsideMap();

                foreach (IntVec3 current in rect)
                {
                    Find.RoofGrid.SetRoof(current, null);
                }

                foreach (IntVec3 current in rect)
                {
                    List <Thing> thingList = current.GetThingList();
                    for (int i = thingList.Count - 1; i >= 0; i--)
                    {
                        if (!Thing.allowDestroyNonDestroyable && !thingList[i].def.destroyable)
                        {
                            thingList[i].DeSpawn();
                        }
                        else
                        {
                            thingList[i].Destroy(DestroyMode.Vanish);
                        }
                    }

                    if (Rand.Range(0, 100) < this.sandBagChance.Value)
                    {
                        GenSpawn.Spawn(ThingDefOf.Sandbags, current);
                    }
                    else
                    if (Rand.Range(0, 100) < this.wallChance.Value)
                    {
                        ThingDef wall     = ThingDefOf.Wall;
                        Thing    newThing = ThingMaker.MakeThing(wall, ThingDefOf.Plasteel);
                        GenSpawn.Spawn(newThing, current);
                    }
                }

                foreach (IntVec3 current in rect)
                {
                    Find.TerrainGrid.SetTerrain(current, TerrainDefOf.Concrete);
                }

                foreach (IntVec3 current in rect.EdgeCells)
                {
                    ThingDef wall     = ThingDefOf.Wall;
                    Thing    newThing = ThingMaker.MakeThing(wall, ThingDefOf.Plasteel);
                    GenSpawn.Spawn(newThing, current);
                }

                AbilityRequeriment_ColonyBiggerThan.forcedValue = this.currentFight.points;

                this.currentFight.factionOne.SetHostileTo(this.currentFight.factionTwo, true);
                this.currentFight.factionOne.SetHostileTo(Faction.OfColony, true);
                this.currentFight.factionTwo.SetHostileTo(this.currentFight.factionOne, true);
                this.currentFight.factionTwo.SetHostileTo(Faction.OfColony, true);

                List <Brain> oldBrains = new List <Brain>(Find.SquadBrainManager.allSquadBrains);

                IncidentDef   incidentDef   = IncidentDef.Named("RaidEnemy");
                IncidentParms incidentParms = Find.Storyteller.def.IncidentMaker.ParmsNow(incidentDef.category);
                incidentParms.faction         = this.currentFight.factionOne;
                incidentParms.spawnCenter     = new IntVec3(30, 0, 35);
                incidentParms.raidStrategy    = RaidStrategyDefOf.ImmediateAttack;
                incidentParms.points          = this.currentFight.points;
                incidentParms.raidArrivalMode = PawnsArriveMode.EdgeWalkIn;
                incidentDef.Worker.TryExecute(incidentParms);

                incidentDef                   = IncidentDef.Named("RaidEnemy");
                incidentParms                 = Find.Storyteller.def.IncidentMaker.ParmsNow(incidentDef.category);
                incidentParms.faction         = this.currentFight.factionTwo;
                incidentParms.spawnCenter     = new IntVec3(80, 0, 35);
                incidentParms.raidStrategy    = RaidStrategyDefOf.ImmediateAttack;
                incidentParms.points          = this.currentFight.points;
                incidentParms.raidArrivalMode = PawnsArriveMode.EdgeWalkIn;
                incidentDef.Worker.TryExecute(incidentParms);

                List <Brain> newBrains = new List <Brain>(Find.SquadBrainManager.allSquadBrains);
                foreach (Brain b in oldBrains)
                {
                    newBrains.Remove(b);
                }

                this.currentBrain1  = this.GetBrain(this.currentFight.factionOne, newBrains);
                this.currentBrain2  = this.GetBrain(this.currentFight.factionTwo, newBrains);
                this.currentPoints1 = this.BrainPoints(this.currentBrain1);
                this.currentPoints2 = this.BrainPoints(this.currentBrain2);

                this.remainingTicks = MapComponentFactionGauntlet.roundLenght;
                this.stage          = ExecutingStage.Fighting;
                break;

            case ExecutingStage.Fighting:

                this.currentPoints1 = this.BrainPoints(this.currentBrain1);
                this.currentPoints2 = this.BrainPoints(this.currentBrain2);

                if ((this.currentPoints1 == 0.0f) ||
                    (this.currentPoints2 == 0.0f))
                {
                    this.EndFight();
                    return;
                }

                if (this.style.Value == FightStyle.TimedRounds)
                {
                    if (this.remainingTicks > 0)
                    {
                        this.remainingTicks--;
                    }
                    else
                    {
                        this.EndFight();
                        return;
                    }
                }

                break;

            case ExecutingStage.CleaningArena:
                this.remainingTicks--;
                if (this.remainingTicks <= 0)
                {
                    this.stage = ExecutingStage.CreatingArena;
                }
                break;
            }
        }
Ejemplo n.º 51
0
        private static void DoRow(Rect rect, Thing thing, CompVehicle vehicle, ref Pawn specificNeedsTabForPawn,
                                  bool doNeeds)
        {
            GUI.BeginGroup(rect);
            var rect2 = rect.AtZero();
            var pawn  = thing as Pawn;

            //if (listingUsesAbandonSpecificCountButtons)
            //{
            //    if (thing.stackCount != 1)
            //    {
            //        CaravanPeopleAndItemsTabUtility.DoAbandonSpecificCountButton(rect2, thing, caravan);
            //    }
            //    rect2.width -= 24f;
            //}
            //CaravanPeopleAndItemsTabUtility.DoAbandonButton(rect2, thing, caravan);
            rect2.width -= 24f;
            Widgets.InfoCardButton(rect2.width - 24f, (rect.height - 24f) / 2f, thing);
            rect2.width -= 24f;
            if (pawn != null && !pawn.Dead)
            {
                CaravanPeopleAndItemsTabUtility.DoOpenSpecificTabButton(rect2, pawn, ref specificNeedsTabForPawn);
                rect2.width -= 24f;
            }
            if (pawn == null)
            {
                var rect3 = rect2;
                rect3.xMin = rect3.xMax - 60f;
                CaravanPeopleAndItemsTabUtility.TryDrawMass(thing, rect3);
                rect2.width -= 60f;
            }
            if (Mouse.IsOver(rect2))
            {
                Widgets.DrawHighlight(rect2);
            }
            var rect4 = new Rect(4f, (rect.height - 27f) / 2f, 27f, 27f);

            Widgets.ThingIcon(rect4, thing, 1f);
            if (pawn != null)
            {
                var bgRect = new Rect(rect4.xMax + 4f, 16f, 100f, 18f);
                GenMapUI.DrawPawnLabel(pawn, bgRect, 1f, 100f, null, GameFont.Small, false, false);
                if (doNeeds)
                {
                    GetNeedsToDisplay(pawn, tmpNeeds);
                    var xMax = bgRect.xMax;
                    for (var i = 0; i < tmpNeeds.Count; i++)
                    {
                        var need = tmpNeeds[i];
                        var maxThresholdMarkers = 0;
                        var doTooltip           = true;
                        var rect5 = new Rect(xMax, 0f, 100f, 50f);
#pragma warning disable IDE0019 // Use pattern matching
                        var mood = need as Need_Mood;
#pragma warning restore IDE0019 // Use pattern matching
                        if (mood != null)
                        {
                            maxThresholdMarkers = 1;
                            doTooltip           = false;
                            //TooltipHandler.TipRegion(rect5, new TipSignal(() => CaravanPeopleAndItemsTabUtility.CustomMoodNeedTooltip(mood), rect5.GetHashCode()));
                        }
                        need.DrawOnGUI(rect5, maxThresholdMarkers, 10f, false, doTooltip);
                        xMax = rect5.xMax;
                    }
                }
                if (pawn.Downed)
                {
                    GUI.color = new Color(1f, 0f, 0f, 0.5f);
                    Widgets.DrawLineHorizontal(0f, rect.height / 2f, rect.width);
                    GUI.color = Color.white;
                }
            }
            else
            {
                var rect6 = new Rect(rect4.xMax + 4f, 0f, 300f, 30f);
                Text.Anchor   = TextAnchor.MiddleLeft;
                Text.WordWrap = false;
                Widgets.Label(rect6, thing.LabelCap);
                Text.Anchor   = TextAnchor.UpperLeft;
                Text.WordWrap = true;
            }
            GUI.EndGroup();
        }
Ejemplo n.º 52
0
 /// <summary>Initializes a new instance of the SensoryEvent class.</summary>
 /// <param name="activeThing">The active thing.</param>
 /// <param name="senseMessage">The sensory message.</param>
 public SensoryEvent(Thing activeThing, SensoryMessage senseMessage)
     : base(activeThing, senseMessage)
 {
 }
Ejemplo n.º 53
0
        static void Postfix(ref float __result, Pawn eater, Thing foodSource, ThingDef foodDef, float dist, bool takingToInventory = false)
        {
            float modifier = 0f;

            if (eater.needs != null && eater.needs.mood != null)
            {
                return;
            }
            //
            if (Settings.allow_feeding_with_plants)
            {
                if (eater.RaceProps.Eats(FoodTypeFlags.Plant))
                {
                    if (foodDef.ingestible.foodType == FoodTypeFlags.Plant)
                    {
                        modifier += 5f;
                    }
                    if (foodSource is Plant)
                    {
                        modifier += 25f;
                    }
                }
            }
            //
            FoodPreferability pref = foodDef.ingestible.preferability;

            switch (pref)
            {
            case FoodPreferability.DesperateOnlyForHumanlikes:
                modifier += 5f;
                break;

            case FoodPreferability.RawBad:
                break;

            case FoodPreferability.RawTasty:
                modifier -= 5f;
                break;

            case FoodPreferability.MealAwful:
                modifier += 5f;
                break;

            case FoodPreferability.MealFine:
                modifier -= 10f;
                break;

            case FoodPreferability.MealLavish:
                modifier -= 15f;
                break;

            default:
                modifier -= 5f;
                break;
            }
            //
            if (foodDef.ingestible?.specialThoughtAsIngredient?.stages?.Count > 0)
            {
                modifier -= foodDef.ingestible.specialThoughtAsIngredient.stages[0].baseMoodEffect;
            }
            //
            if (foodSource != null)
            {
                CompIngredients ings = foodSource.TryGetComp <CompIngredients>();

                if (ings != null)
                {
                    foreach (var ing in ings.ingredients)
                    {
                        if (ing.ingestible?.specialThoughtAsIngredient?.stages?.Count > 0)
                        {
                            modifier -= ing.ingestible.specialThoughtAsIngredient.stages[0].baseMoodEffect * 3;
                        }
                    }
                }
            }
            //
            __result += modifier;
        }
Ejemplo n.º 54
0
 public void SetThing(Thing thing)
 {
     _things.Add(thing);
 }
Ejemplo n.º 55
0
 internal static bool TryDrop(this ThingContainer _this, Thing thing, IntVec3 dropLoc, Map map, ThingPlaceMode mode, int count, out Thing resultingThing, Action <Thing, int> placedAction = null)
 {
     if (thing.stackCount < count)
     {
         Log.Error(string.Concat(new object[]
         {
             "Tried to drop ",
             count,
             " of ",
             thing,
             " while only having ",
             thing.stackCount
         }));
         count = thing.stackCount;
     }
     if (count == thing.stackCount)
     {
         if (GenDrop.TryDropSpawn(thing, dropLoc, map, mode, out resultingThing, placedAction))
         {
             _this.Remove(thing);
             CE_Utility.TryUpdateInventory(_this.owner as Pawn_InventoryTracker);   // Thing dropped, update inventory
             return(true);
         }
         return(false);
     }
     else
     {
         Thing thing2 = thing.SplitOff(count);
         if (GenDrop.TryDropSpawn(thing2, dropLoc, map, mode, out resultingThing, placedAction))
         {
             CE_Utility.TryUpdateInventory(_this.owner as Pawn_InventoryTracker);   // Thing dropped, update inventory
             return(true);
         }
         thing.stackCount += thing2.stackCount;
         return(false);
     }
 }
Ejemplo n.º 56
0
        static bool belowNutrition(Thing thing)
        {
            float statValue = thing.GetStatValue(StatDefOf.Nutrition, true);

            return(statValue <= AnimalControls.BestFoodSourceOnMap_maxNutrition);
        }
Ejemplo n.º 57
0
 protected override void Impact(Thing hitThing)
 {
     //    base.Impact(hitThing);
     Ignite();
 }
Ejemplo n.º 58
0
        public bool shouldCancelJob(ExtendedPawnData riderData)
        {
            if (interrupted)
            {
                //Log.Message("cancel job, shouldEnd called");
                return(true);
            }

            if (riderData == null || riderData.mount == null)
            {
                //Log.Message("riderData is null or riderData.mount is null");
                return(true);
            }

            Thing thing = pawn as Thing;

            if (Rider.Downed || Rider.Dead || pawn.Downed || pawn.Dead || pawn.IsBurning() || Rider.IsBurning() || Rider.GetPosture() != PawnPosture.Standing)
            {
                //Log.Message("cancel job, rider downed or dead");
                return(true);
            }
            if (pawn.InMentalState || (Rider.InMentalState && Rider.MentalState.def != MentalStateDefOf.PanicFlee))
            {
                //Log.Message("cancel job, rider or mount in mental state");
                return(true);
            }
            if (!Rider.Spawned)
            {
                if (!Rider.IsColonist && !Rider.Dead)
                {
                    //Log.Message("rider not spawned, despawn");
                    pawn.ExitMap(false, CellRect.WholeMap(base.Map).GetClosestEdge(this.pawn.Position));
                    return(true);
                }
                else if (Rider.IsColonist && Rider.GetCaravan() != null)
                {
                    //Log.Message("rider moved to map, despawn");
                    pawn.ExitMap(true, CellRect.WholeMap(base.Map).GetClosestEdge(this.pawn.Position));
                    return(true);
                }
                else
                {
                    //Log.Message("rider died, dismount");
                    return(true);
                }
            }

            if (!Rider.Drafted && Rider.IsColonist) //TODO refactor this as a postfix in Giddy-up Caravan.
            {
                if ((Rider.mindState != null && Rider.mindState.duty != null && (Rider.mindState.duty.def == DutyDefOf.TravelOrWait || Rider.mindState.duty.def == DutyDefOf.TravelOrLeave || Rider.mindState.duty.def == DutyDefOf.PrepareCaravan_GatherAnimals || Rider.mindState.duty.def == DutyDefOf.PrepareCaravan_GatherDownedPawns)))
                {
                    if (riderData.caravanMount == pawn)
                    {
                        return(false);
                    }
                    return(true);
                    //if forming caravan, stay mounted.
                }
                else if (riderData.owning == pawn)
                {
                    //Log.Message("cancel job, rider not drafted while being colonist");
                    //Log.Message("riderData.owning: " + riderData.owning);
                    return(false);
                }
                else
                {
                    return(true);
                }
            }



            if (riderData.mount == null)
            {
                //Log.Message("cancel job, rider has no mount");
                return(true);
            }
            return(false);
        }
Ejemplo n.º 59
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ScaleReferenceQuantityValueDialogViewModel"/> class.
 /// </summary>
 /// <param name="scaleReferenceQuantityValue">
 /// The <see cref="ScaleReferenceQuantityValue"/> that is the subject of the current view-model. This is the object
 /// that will be either created, or edited.
 /// </param>
 /// <param name="transaction">
 /// The <see cref="ThingTransaction"/> that contains the log of recorded changes.
 /// </param>
 /// <param name="session">
 /// The <see cref="ISession"/> in which the current <see cref="Thing"/> is to be added or updated
 /// </param>
 /// <param name="isRoot">
 /// Assert if this <see cref="ScaleReferenceQuantityValueDialogViewModel"/> is the root of all <see cref="IThingDialogViewModel"/>
 /// </param>
 /// <param name="dialogKind">
 /// The kind of operation this <see cref="ScaleReferenceQuantityValueDialogViewModel"/> performs
 /// </param>
 /// <param name="thingDialogNavigationService">
 /// The <see cref="IThingDialogNavigationService"/> that is used to navigate to a dialog of a specific <see cref="Thing"/>.
 /// </param>
 /// <param name="container">
 /// The <see cref="Thing"/> that contains the created <see cref="Thing"/> in this Dialog
 /// </param>
 /// <param name="chainOfContainers">
 /// The optional chain of containers that contains the <paramref name="container"/> argument
 /// </param>
 public ScaleReferenceQuantityValueDialogViewModel(ScaleReferenceQuantityValue scaleReferenceQuantityValue, IThingTransaction transaction, ISession session, bool isRoot, ThingDialogKind dialogKind, IThingDialogNavigationService thingDialogNavigationService, Thing container = null, IEnumerable <Thing> chainOfContainers = null)
     : base(scaleReferenceQuantityValue, transaction, session, isRoot, dialogKind, thingDialogNavigationService, container, chainOfContainers)
 {
 }
Ejemplo n.º 60
0
        internal static bool TryAdd(this ThingContainer _this, Thing item, bool canMergeWithExistingStacks = true)
        {
            if (item == null)
            {
                Log.Warning("Tried to add null item to ThingContainer.");
                return(false);
            }
            if (_this.Contains(item))
            {
                Log.Warning("Tried to add " + item + " to ThingContainer but this item is already here.");
                return(false);
            }

            if (item.stackCount > _this.AvailableStackSpace)
            {
                return(_this.TryAdd(item, _this.AvailableStackSpace) > 0);
            }

            List <Thing> innerList = (List <Thing>)innerListFieldInfo.GetValue(_this);    // Fetch innerList through reflection

            SlotGroupUtility.Notify_TakingThing(item);
            if (canMergeWithExistingStacks && item.def.stackLimit > 1)
            {
                for (int i = 0; i < innerList.Count; i++)
                {
                    if (innerList[i].def == item.def)
                    {
                        int num = item.stackCount;
                        if (num > _this.AvailableStackSpace)
                        {
                            num = _this.AvailableStackSpace;
                        }
                        Thing other = item.SplitOff(num);
                        if (!innerList[i].TryAbsorbStack(other, false))
                        {
                            Log.Error("ThingContainer did TryAbsorbStack " + item + " but could not absorb stack.");
                        }
                    }
                    if (item.Destroyed)
                    {
                        //CE PART!!!
                        CE_Utility.TryUpdateInventory(_this.owner as Pawn_InventoryTracker);   // Item has been added, notify CompInventory
                        return(true);
                    }
                }
            }

            int maxStacks = (int)maxStacksFieldInfo.GetValue(_this);    // Fetch maxStacks through reflection

            if (innerList.Count >= maxStacks)
            {
                return(false);
            }
            if (item.Spawned)
            {
                item.DeSpawn();
            }
            if (item.HasAttachment(ThingDefOf.Fire))
            {
                item.GetAttachment(ThingDefOf.Fire).Destroy(DestroyMode.Vanish);
            }
            item.holdingContainer = _this;
            innerList.Add(item);

            CE_Utility.TryUpdateInventory(_this.owner as Pawn_InventoryTracker);   // Item has been added, notify CompInventory

            return(true);
        }