public OrderConfig(RecipeDef def) { this.order = null; this.recipe = def; this.ingredientsFilter = new ThingFilter(); this.ingredientsFilter.CopyFrom(def.fixedIngredientFilter); this.scrollPosition = default(Vector2); }
public static void DoThingFilterConfigWindow(Rect rect, ref Vector2 scrollPosition, ThingFilter filter, ThingFilter parentFilter = null, int openMask = 1, string filterText = null) { Widgets.DrawMenuSection(rect, true); Text.Font = GameFont.Tiny; float num = rect.width - 2f; Rect rect2 = new Rect(rect.x + 1f, rect.y + 1f, num / 2f, 24f); if (Widgets.TextButton(rect2, "ClearAll".Translate(), true, false)) { filter.SetDisallowAll(); } Rect rect3 = new Rect(rect2.xMax + 1f, rect2.y, num / 2f, 24f); if (Widgets.TextButton(rect3, "AllowAll".Translate(), true, false)) { filter.SetAllowAll(parentFilter); } Text.Font = GameFont.Small; rect.yMin = rect2.yMax; Rect viewRect = new Rect(0f, 0f, rect.width - 16f, HelperThingFilterUI.viewHeight); Widgets.BeginScrollView(rect, ref scrollPosition, viewRect); float num2 = 0f; num2 += 2f; HelperThingFilterUI.DrawHitPointsFilterConfig(ref num2, viewRect.width, filter); HelperThingFilterUI.DrawQualityFilterConfig(ref num2, viewRect.width, filter); float num3 = num2; Rect rect4 = new Rect(0f, num2, 9999f, 9999f); Listing_TreeThingFilter listing_TreeThingFilter = new Listing_TreeThingFilter(rect4, filter, parentFilter, 210f, true); TreeNode_ThingCategory node = ThingCategoryNodeDatabase.RootNode; if (parentFilter != null) { if (parentFilter.DisplayRootCategory == null) { parentFilter.RecalculateDisplayRootCategory(); } node = parentFilter.DisplayRootCategory; } if (filterText != null && filterText.Length > 2) { var rootNode = new TreeNode_ThingCategory(new ThingCategoryDef()); node.catDef.DescendantThingDefs.Where(td => td.label.ToLower().Contains(filterText.ToLower())); foreach (ThingDef currentThing in node.catDef.DescendantThingDefs.Where(td => td.label.ToLower().Contains(filterText.ToLower()))) { rootNode.catDef.childThingDefs.Add(currentThing); } node = rootNode; } listing_TreeThingFilter.DoCategoryChildren(node, 0, openMask, true); listing_TreeThingFilter.End(); if (Event.current.type == EventType.Layout) { HelperThingFilterUI.viewHeight = num3 + listing_TreeThingFilter.CurHeight + 90f; } Widgets.EndScrollView(); }
public Trigger_Threshold( ManagerJob_Forestry job ) : base(job.manager) { Op = Ops.LowerThan; MaxUpperThreshold = DefaultMaxUpperThreshold; Count = DefaultCount; ThresholdFilter = new ThingFilter(); ThresholdFilter.SetDisallowAll(); ThresholdFilter.SetAllow( Utilities_Forestry.Wood, true ); }
public TriggerThreshold(ManagerJobProduction job) { Op = Ops.LowerThan; MaxUpperThreshold = job.MainProduct.MaxUpperThreshold; Count = MaxUpperThreshold / 5; ThresholdFilter = new ThingFilter(); ThresholdFilter.SetDisallowAll(); if (job.MainProduct.ThingDef != null) ThresholdFilter.SetAllow(job.MainProduct.ThingDef, true); if (job.MainProduct.CategoryDef != null) ThresholdFilter.SetAllow(job.MainProduct.CategoryDef, true); }
public Vehicle_Cart() : base() { wheelRotation = 0; //Inventory Initialize. It should be moved in constructor this.storage = new ThingContainer(this); this.allowances = new ThingFilter(); this.allowances.SetFromPreset(StorageSettingsPreset.DefaultStockpile); this.allowances.SetFromPreset(StorageSettingsPreset.DumpingStockpile); }
private static bool TryGetCached(ThingFilter filter, out int count) { if (Find.TickManager.TicksGame - _lastCache < 250 && _cachedFilter == filter) { count = _cachedCount; return true; } #if DEBUG_COUNTS Log.Message("not cached"); #endif count = 0; return false; }
private static void DrawHitPointsFilterConfig(ref float y, float width, ThingFilter filter) { if (!filter.allowedHitPointsConfigurable) { return; } Rect rect = new Rect(20f, y, width - 20f, 26f); FloatRange allowedHitPointsPercents = filter.AllowedHitPointsPercents; Widgets.FloatRange(rect, 1, ref allowedHitPointsPercents, 0f, 1f, ToStringStyle.PercentZero, "HitPoints"); filter.AllowedHitPointsPercents = allowedHitPointsPercents; y += 26f; y += 5f; Text.Font = GameFont.Small; }
public static void DrawQualityFilterConfig(ref float y, float width, ThingFilter filter) { if (!filter.allowedQualitiesConfigurable) { return; } var rect = new Rect(20f, y, width - 20f, 26f); var allowedQualityLevels = filter.AllowedQualityLevels; Widgets.QualityRange(rect, 2, ref allowedQualityLevels); filter.AllowedQualityLevels = allowedQualityLevels; y += 26f; y += 5f; Text.Font = GameFont.Small; }
public static int CountProducts(ThingFilter filter) { int count = 0; if (filter != null && TryGetCached(filter, out count)) return count; #if DEBUG_COUNTS Log.Message("Obtaining new count"); #endif if (filter != null) { foreach (ThingDef td in filter.AllowedThingDefs) { // if it counts as a resource, use the ingame counter (e.g. only steel in stockpiles.) if (td.CountAsResource) { #if DEBUG_COUNTS Log.Message(td.LabelCap + ", " + Find.ResourceCounter.GetCount(td)); count += Find.ResourceCounter.GetCount(td); #endif } else { foreach (Thing t in Find.ListerThings.ThingsOfDef(td)) { // otherwise, go look for stuff that matches our filters. // TODO: does this catch minified things? QualityCategory quality; if (t.TryGetQuality(out quality)) { if (!filter.AllowedQualityLevels.Includes(quality)) continue; } if (filter.AllowedHitPointsPercents.IncludesEpsilon(t.HitPoints)) continue; #if DEBUG_COUNTS Log.Message(t.LabelCap + ": " + CountProducts(t)); #endif count += CountProducts(t); } } } _cachedFilter = filter; } _lastCache = Find.TickManager.TicksGame; _cachedFilter = filter; _cachedCount = count; return count; }
public Dialog_ManageOutfitsAutoEquip(Outfit selectedOutfit) { this.forcePause = true; this.doCloseX = true; this.closeOnEscapeKey = true; this.doCloseButton = true; this.closeOnClickedOutside = true; this.absorbInputAroundWindow = true; if (Dialog_ManageOutfitsAutoEquip.apparelGlobalFilter == null) { Dialog_ManageOutfitsAutoEquip.apparelGlobalFilter = new ThingFilter(); Dialog_ManageOutfitsAutoEquip.apparelGlobalFilter.SetAllow(ThingCategoryDefOf.Apparel, true); } this.SelectedOutfit = selectedOutfit; }
public static bool Matches( this ThingFilter a, ThingFilter b ) { foreach( var thingDefA in a.AllowedThingDefs ) { if( !b.Allows( thingDefA ) ) { return false; } } foreach( var thingDefB in b.AllowedThingDefs ) { if( !a.Allows( thingDefB ) ) { return false; } } return true; }
public Trigger_Threshold( ManagerJob_Production job ) : base(job.manager) { Op = Ops.LowerThan; MaxUpperThreshold = job.MainProduct.MaxUpperThreshold; // TODO: Better way of setting sensible defaults? Count = MaxUpperThreshold / 20; ThresholdFilter = new ThingFilter(); ThresholdFilter.SetDisallowAll(); if ( job.MainProduct.ThingDef != null ) { ThresholdFilter.SetAllow( job.MainProduct.ThingDef, true ); } if ( job.MainProduct.CategoryDef != null ) { ThresholdFilter.SetAllow( job.MainProduct.CategoryDef, true ); } }
public static void DoThingFilterConfigWindow(Rect rect, ref Vector2 scrollPosition, ThingFilter filter, ThingFilter parentFilter = null, int openMask = 1) { Widgets.DrawMenuSection(rect); Text.Font = GameFont.Tiny; var num = rect.width - 2f; var rect2 = new Rect(rect.x + 1f, rect.y + 1f, num / 2f, 24f); if (Widgets.ButtonText(rect2, "ClearAll".Translate())) { filter.SetDisallowAll(); } var rect3 = new Rect(rect2.xMax + 1f, rect2.y, num / 2f - 1f, 24f); if (Widgets.ButtonText(rect3, "AllowAll".Translate())) { filter.SetAllowAll(parentFilter); } Text.Font = GameFont.Small; rect.yMin = rect2.yMax; var viewRect = new Rect(0f, 0f, rect.width - 16f, viewHeight); Widgets.BeginScrollView(rect, ref scrollPosition, viewRect); var num2 = 0f; num2 += 2f; DrawHitPointsFilterConfig(ref num2, viewRect.width, filter); DrawQualityFilterConfig(ref num2, viewRect.width, filter); var num3 = num2; var rect4 = new Rect(0f, num2, 9999f, 9999f); var listing_TreeThingFilter = new Listing_TreeThingFilter(rect4, filter, parentFilter); var node = ThingCategoryNodeDatabase.RootNode; if (parentFilter != null) { if (parentFilter.DisplayRootCategory == null) { parentFilter.RecalculateDisplayRootCategory(); } node = parentFilter.DisplayRootCategory; } listing_TreeThingFilter.DoCategoryChildren(node, 0, openMask, true); listing_TreeThingFilter.End(); if (Event.current.type == EventType.Layout) { viewHeight = num3 + listing_TreeThingFilter.CurHeight + 90f; } Widgets.EndScrollView(); }
public void DoThingFilterConfigWindow(Rect rect, ref Vector2 scrollPosition, ThingFilter filter, ThingFilter parentFilter = null, int openMask = 1) { Widgets.DrawMenuSection(rect); Text.Font = GameFont.Tiny; float num = rect.width - 2f; Rect rect2 = new Rect(rect.x + 1f, rect.y + 1f, num / 2f, 24f); if (Widgets.TextButton(rect2, "ClearAll".Translate())) { filter.SetDisallowAll(); } Rect rect3 = new Rect(rect2.xMax + 1f, rect2.y, num / 2f, 24f); if (Widgets.TextButton(rect3, "AllowAll".Translate())) { filter.SetAllowAll(parentFilter); } Text.Font = GameFont.Small; rect.yMin = rect2.yMax; Rect viewRect = new Rect(0f, 0f, rect.width - 16f, viewHeight); Widgets.BeginScrollView(rect, ref scrollPosition, viewRect); float num2 = 0f; num2 += 2f; DrawHitPointsFilterConfig(ref num2, viewRect.width, filter); DrawQualityFilterConfig(ref num2, viewRect.width, filter); float num3 = num2; Rect rect4 = new Rect(0f, num2, 9999f, 9999f); Listing_TreeThingFilter listingTreeThingFilter = new Listing_TreeThingFilter(rect4, filter, parentFilter, 210f, true); TreeNode_ThingCategory node = ThingCategoryNodeDatabase.RootNode; if (parentFilter != null) { if (parentFilter.DisplayRootCategory == null) { parentFilter.RecalculateDisplayRootCategory(); } node = parentFilter.DisplayRootCategory; } listingTreeThingFilter.DoCategoryChildren(node, 0, openMask, true); listingTreeThingFilter.End(); viewHeight = num3 + listingTreeThingFilter.CurHeight + 90f; Log.Message(viewHeight.ToString(CultureInfo.InvariantCulture)); Widgets.EndScrollView(); }
protected override Job TryGiveJob(Pawn pawn) { Pawn_WeaponPresetTracker pawn_WeaponPresetTracker = pawn.TryGetComp <Pawn_WeaponPresetTracker>(); if (pawn_WeaponPresetTracker == null) { return(null); } if (pawn.Faction != Faction.OfPlayer) { return(null); } if (!DebugViewSettings.debugApparelOptimize) { if (Find.TickManager.TicksGame < pawn_WeaponPresetTracker.nextWeaponPresetOptimizeTick) { return(null); } } WeaponPreset CurweaponPreset = pawn_WeaponPresetTracker.CurrentWeaponPreset; ThingFilter _equipmentFilter = CurweaponPreset.filter; ThingWithComps thingWithComps = pawn.equipment?.Primary; bool HasWeaponEquipped = true; //true = Has got a weapon equipped bool HasNonePreset = false; //false = Not using "NONE" PRESET bool WeaponNotAllowed = false; //false = The weapon is not allowed by the preset if (thingWithComps is null) { HasWeaponEquipped = false; } if (CurweaponPreset.filter.AllowedDefCount == 0) { HasNonePreset = true; } if (thingWithComps != null && !_equipmentFilter.Allows(thingWithComps.def)) { WeaponNotAllowed = true; } Log.Message(pawn + " HasWeaponEquipped = " + HasWeaponEquipped.ToString(), true); Log.Message(pawn + " HasNonePreset = " + HasNonePreset.ToString(), true); Log.Message(pawn + " WeaponNotAllowed = " + WeaponNotAllowed.ToString(), true); Log.Message(pawn + " Has this equipped " + thingWithComps, true); if ((!HasWeaponEquipped && !HasNonePreset) || (!HasNonePreset && WeaponNotAllowed)) { Log.Warning(pawn + " Will Optimize weapons", true); Thing newWeapon = null; List <Thing> list = pawn.Map.listerThings.ThingsInGroup(ThingRequestGroup.Weapon); if (list.Count == 0) { this.SetNextOptimizeTick(pawn); return(null); } // Top 3 Guns chosen by the pawn first bool found = false; for (int j = 0; j < 3; j++) //it's 3 right now { if (!(CurweaponPreset.SearchPriorityDefnames[j].NullOrEmpty())) { for (int i = 0; i < list.Count; i++) { Thing searchedWeapon = list[i]; if (CurweaponPreset.SearchPriorityDefnames[j] == searchedWeapon.def.defName && searchedWeapon.IsInAnyStorage() && !searchedWeapon.IsForbidden(pawn) && !searchedWeapon.IsBurning() && pawn.CanReserveAndReach(searchedWeapon, PathEndMode.OnCell, pawn.NormalMaxDanger(), 1, -1, null, false)) { newWeapon = searchedWeapon; found = true; break; } } } if (found) { break; } } Log.Warning(pawn + " found weapon = " + found.ToString(), true); //else just keep browsing the other filter stuff if (!found) { Log.Message(pawn + " Looking in the rest of the non priorityized weapons ", true); for (int j = 0; j < list.Count; j++) { Thing searchedWeapon = list[j]; if (_equipmentFilter.Allows(searchedWeapon.def) && searchedWeapon.IsInAnyStorage() && !searchedWeapon.IsForbidden(pawn) && !searchedWeapon.IsBurning() && pawn.CanReserveAndReach(searchedWeapon, PathEndMode.OnCell, pawn.NormalMaxDanger(), 1, -1, null, false)) { newWeapon = searchedWeapon; found = true; break; } } } if (newWeapon == null) { this.SetNextOptimizeTick(pawn); return(null); } return(new Job(JobDefOf.Equip, newWeapon)); } else { Log.Warning("Not doing anything, no need to optimize", true); this.SetNextOptimizeTick(pawn); return(null); } }
public List<Thing> GetAllResources( ThingFilter acceptableResources ) { var things = parent.Position.GetThingList().Where( t => ( ( acceptableResources.Allows( t.def ) ) ) ).ToList(); if( things.NullOrEmpty() ) { return null; } things.Sort( ( Thing x, Thing y ) => ( x.stackCount > y.stackCount ) ? -1 : 1 ); // Return sorted by quantity list of things return things; }
/// <summary> /// Initializes a new instance of the <see cref="ThingSelector"/> class. /// </summary> public ThingSelector() { _thingFilter = new ThingFilter(this.QualityAndHitpointsChangedCallback); }
public void DoThingFilterConfigWindow(Rect canvas, ref Vector2 scrollPosition, ThingFilter filter, ThingFilter parentFilter = null, int openMask = 1, bool buttonsAtBottom = false) { // respect your bounds! GUI.BeginGroup(canvas); canvas = canvas.AtZero(); // set up buttons Text.Font = GameFont.Tiny; float width = canvas.width - 2f; var clearButtonRect = new Rect(canvas.x + 1f, canvas.y + 1f, width / 2f, 24f); var allButtonRect = new Rect(clearButtonRect.xMax + 1f, clearButtonRect.y, width / 2f, 24f); // offset canvas position for buttons. if (buttonsAtBottom) { clearButtonRect.y = canvas.height - clearButtonRect.height; allButtonRect.y = canvas.height - clearButtonRect.height; canvas.yMax -= clearButtonRect.height; } else { canvas.yMin = clearButtonRect.height; } // draw buttons + logic if (Widgets.ButtonTextSubtle(clearButtonRect, "ClearAll".Translate())) { filter.SetDisallowAll(); } if (Widgets.ButtonTextSubtle(allButtonRect, "AllowAll".Translate())) { filter.SetAllowAll(parentFilter); } Text.Font = GameFont.Small; // do list var curY = 2f; var viewRect = new Rect(0f, 0f, canvas.width - ScrollbarWidth, viewHeight); // scrollview Widgets.BeginScrollView(canvas, ref scrollPosition, viewRect); // slider(s) DrawHitPointsFilterConfig(ref curY, viewRect.width, filter); DrawQualityFilterConfig(ref curY, viewRect.width, filter); // main listing var listingRect = new Rect(0f, curY, viewRect.width, 9999f); var listingTreeThingFilter = new Listing_TreeThingFilter(filter, parentFilter, null, null, null); listingTreeThingFilter.Begin(listingRect); TreeNode_ThingCategory node = ThingCategoryNodeDatabase.RootNode; if (parentFilter != null) { if (parentFilter.DisplayRootCategory == null) { parentFilter.RecalculateDisplayRootCategory(); } node = parentFilter.DisplayRootCategory; } // draw the actual thing listingTreeThingFilter.DoCategoryChildren(node, 0, openMask, Find.CurrentMap, true); listingTreeThingFilter.End(); // update height. viewHeight = curY + listingTreeThingFilter.CurHeight; Widgets.EndScrollView(); GUI.EndGroup(); }
public static int CountProducts(this Map map, ThingFilter filter, Zone_Stockpile stockpile = null) { var count = 0; // copout if filter is null if (filter == null) { return(count); } var key = new MapStockpileFilter(map, filter, stockpile); if (TryGetCached(key, out count)) { return(count); } #if DEBUG_COUNTS Log.Message("Obtaining new count"); #endif foreach (ThingDef td in filter.AllowedThingDefs) { // if it counts as a resource and we're not limited to a single stockpile, use the ingame counter (e.g. only steel in stockpiles.) if (td.CountAsResource && stockpile == null) { #if DEBUG_COUNTS Log.Message(td.LabelCap + ", " + Find.ResourceCounter.GetCount(td)); #endif // we don't need to bother with quality / hitpoints as these are non-existant/irrelevant for resources. count += map.resourceCounter.GetCount(td); } else { // otherwise, go look for stuff that matches our filters. List <Thing> thingList = map.listerThings.ThingsOfDef(td); // if filtered by stockpile, filter the thinglist accordingly. if (stockpile != null) { SlotGroup areaSlotGroup = stockpile.slotGroup; thingList = thingList.Where(t => t.Position.GetSlotGroup(map) == areaSlotGroup).ToList(); } foreach (Thing t in thingList) { QualityCategory quality; if (t.TryGetQuality(out quality)) { if (!filter.AllowedQualityLevels.Includes(quality)) { continue; } } if (filter.AllowedHitPointsPercents.IncludesEpsilon(t.HitPoints)) { continue; } #if DEBUG_COUNTS Log.Message(t.LabelCap + ": " + CountProducts(t)); #endif count += t.stackCount; } } // update cache if exists. if (CountCache.ContainsKey(key)) { CountCache[key].Cache = count; CountCache[key].TimeSet = Find.TickManager.TicksGame; } else { CountCache.Add(key, new FilterCountCache(count)); } } return(count); }
static MyStaticConstructor() { IEnumerable <ThingDef> workTables = DefDatabase <ThingDef> .AllDefs.Where(t => t.IsWorkTable); FieldInfo thingDefs = typeof(ThingFilter).GetField("thingDefs", BindingFlags.NonPublic | BindingFlags.Instance); FieldInfo allRecipesCached = typeof(ThingDef).GetField("allRecipesCached", BindingFlags.NonPublic | BindingFlags.Instance); foreach (ThingDef workTable in workTables) { IEnumerable <RecipeDef> tableRecipes = workTable.AllRecipes.Where(r => r.ProducedThingDef?.HasSmeltProducts() ?? false); // If the table has no relevant recipes, no point doing anything else for it. if (!tableRecipes.Any()) { continue; } ThingFilter newFilter = new ThingFilter(); thingDefs.SetValue(newFilter, tableRecipes.Select(r => r.ProducedThingDef).ToList()); IngredientCount newCount = new IngredientCount(); newCount.SetBaseCount(1); newCount.filter = newFilter; RecipeDef generatedRecipe = new RecipeDef { defName = "LuluScrapAnything_DisassembleAt" + workTable.defName, label = "LuluScrapAnything_BillLabel".Translate(), description = "LuluScrapAnything_BillDesc".Translate(), jobString = "LuluScrapAnything_BillJob".Translate(workTable.label), workAmount = 1600, workSpeedStat = MyDefOf.SmeltingSpeed, effectWorking = tableRecipes.GroupBy(r => r.effectWorking).OrderByDescending(g => g.Count()).Select(o => o.Key).First(), soundWorking = tableRecipes.GroupBy(r => r.soundWorking).OrderByDescending(g => g.Count()).Select(o => o.Key).First(), specialProducts = new List <SpecialProductType> { SpecialProductType.Smelted }, recipeUsers = new List <ThingDef> { workTable }, ingredients = new List <IngredientCount> { newCount }, fixedIngredientFilter = newFilter, forceHiddenSpecialFilters = new List <SpecialThingFilterDef> { MyDefOf.AllowBurnableApparel, MyDefOf.AllowBurnableWeapons, MyDefOf.AllowNonBurnableApparel, MyDefOf.AllowNonBurnableWeapons, MyDefOf.AllowNonSmeltableApparel, MyDefOf.AllowNonSmeltableWeapons, MyDefOf.AllowSmeltable, MyDefOf.AllowSmeltableApparel, } }; generatedRecipe.ResolveReferences(); DefDatabase <RecipeDef> .Add(generatedRecipe); // Clear the recipe cache because we've added a new recipe. allRecipesCached.SetValue(workTable, null); } }
public override void DefsLoaded() { //1. Adding Tech Tab to Pawns //ThingDef injection stolen from the work of notfood for Psychology var zombieThinkTree = DefDatabase <ThinkTreeDef> .GetNamedSilentFail("Zombie"); IEnumerable <ThingDef> things = (from def in DefDatabase <ThingDef> .AllDefs where def.race?.intelligence == Intelligence.Humanlike && !def.defName.Contains("Android") && !def.defName.Contains("Robot") && (zombieThinkTree == null || def.race.thinkTreeMain != zombieThinkTree) select def); List <string> registered = new List <string>(); foreach (ThingDef t in things) { if (t.inspectorTabsResolved == null) { t.inspectorTabsResolved = new List <InspectTabBase>(1); } t.inspectorTabsResolved.Add(InspectTabManager.GetSharedInstance(typeof(ITab_PawnKnowledge))); if (t.comps == null) { t.comps = new List <CompProperties>(1); } t.comps.Add(new CompProperties_Knowledge()); registered.Add(t.defName); } //2. Preparing knowledge support infrastructure //a. Things everyone knows UniversalWeapons.AddRange(DefDatabase <ThingDef> .AllDefs.Where(x => x.IsWeapon)); UniversalCrops.AddRange(DefDatabase <ThingDef> .AllDefs.Where(x => x.plant != null && x.plant.Sowable)); //b. Minus things unlocked on research ThingFilter lateFilter = new ThingFilter(); foreach (ResearchProjectDef tech in DefDatabase <ResearchProjectDef> .AllDefs) { tech.InferSkillBias(); tech.CreateStuff(lateFilter, unlocked); foreach (ThingDef weapon in tech.UnlockedWeapons()) { UniversalWeapons.Remove(weapon); } foreach (ThingDef plant in tech.UnlockedPlants()) { UniversalCrops.Remove(plant); } } ; //b. Also removing atipical weapons ThingDef WeaponsNotBasicDef = DefDatabase <ThingDef> .GetNamed("NotBasic"); List <string> ForbiddenWeaponTags = WeaponsNotBasicDef.weaponTags; UniversalWeapons.RemoveAll(x => SplitSimpleWeapons(x, ForbiddenWeaponTags)); AccessTools.Method(typeof(DefDatabase <ThingDef>), "Remove").Invoke(this, new object[] { WeaponsNotBasicDef }); //c. Telling humans what's going on ThingCategoryDef knowledgeCat = TechDefOf.Knowledge; IEnumerable <ThingDef> codifiedTech = DefDatabase <ThingDef> .AllDefs.Where(x => x.IsWithinCategory(knowledgeCat)); if (Prefs.LogVerbose) { Log.Message("[HumanResources] Codified technologies:" + codifiedTech.Select(x => x.label).ToStringSafeEnumerable()); Log.Message("[HumanResources] Basic crops: " + UniversalCrops.ToStringSafeEnumerable()); Log.Message("[HumanResources] Basic weapons: " + UniversalWeapons.ToStringSafeEnumerable()); Log.Message("[HumanResources] Basic weapons that require training: " + SimpleWeapons.ToStringSafeEnumerable()); Log.Warning("[HumanResources] Basic weapons tags: " + SimpleWeapons.Where(x => !x.weaponTags.NullOrEmpty()).SelectMany(x => x.weaponTags).Distinct().ToStringSafeEnumerable()); } else { Log.Message("[HumanResources] This is what we know: " + codifiedTech.EnumerableCount() + " technologies processed, " + UniversalCrops.Count() + " basic crops, " + UniversalWeapons.Count() + " basic weapons + " + SimpleWeapons.Count() + " that require training."); } //3. Filling gaps on the database //a. TechBook dirty trick, but only now this is possible! foreach (ThingDef t in DefDatabase <ThingDef> .AllDefsListForReading.Where(x => x == TechDefOf.TechBook || x == TechDefOf.UnfinishedTechBook)) { t.stuffCategories.Add(TechDefOf.Technic); } //b. Filling main tech category with subcategories foreach (ThingDef t in lateFilter.AllowedThingDefs.Where(t => !t.thingCategories.NullOrEmpty())) { foreach (ThingCategoryDef c in t.thingCategories) { c.childThingDefs.Add(t); if (!knowledgeCat.childCategories.NullOrEmpty() && !knowledgeCat.childCategories.Contains(c)) { knowledgeCat.childCategories.Add(c); } } } //c. Populating knowledge recipes and book shelves foreach (RecipeDef r in DefDatabase <RecipeDef> .AllDefs.Where(x => x.fixedIngredientFilter.AnyAllowedDef == null)) { r.fixedIngredientFilter.ResolveReferences(); } foreach (ThingDef t in DefDatabase <ThingDef> .AllDefs.Where(x => x.thingClass == typeof(Building_BookStore))) { t.building.fixedStorageSettings.filter.ResolveReferences(); t.building.defaultStorageSettings.filter.ResolveReferences(); } //4. Finally, preparing settings UpdateSettings(); }
public _IngredientCount(ThingFilter f, float c) { filter = f; count = c; }
internal SaveDialog(string storageTypeName, ThingFilter thingFilter) : base(storageTypeName) { this.ThingFilter = thingFilter; this.interactButLabel = "OverwriteButton".Translate(); }
public static void DoThingFilterConfigWindow(Rect rect, ref Vector2 scrollPosition, ThingFilter filter, ThingFilter parentFilter = null, int openMask = 1, IEnumerable <ThingDef> forceHiddenDefs = null, IEnumerable <SpecialThingFilterDef> forceHiddenFilters = null, string filterText = null) { Widgets.DrawMenuSection(rect, true); Text.Font = GameFont.Tiny; float num = rect.width - 2f; Rect rect2 = new Rect(rect.x + 1f, rect.y + 1f, num / 2f, 24f); if (Widgets.ButtonText(rect2, "ClearAll".Translate(), true, false, true)) { filter.SetDisallowAll(forceHiddenDefs, forceHiddenFilters); } if (Widgets.ButtonText(new Rect(rect2.xMax + 1f, rect2.y, num / 2f, 24f), "AllowAll".Translate(), true, false, true)) { filter.SetAllowAll(parentFilter); } Text.Font = GameFont.Small; rect.yMin = rect2.yMax; Rect viewRect = new Rect(0f, 0f, rect.width - 16f, HelperThingFilterUI.viewHeight); Widgets.BeginScrollView(rect, ref scrollPosition, viewRect); float num2 = 2f; HelperThingFilterUI.DrawHitPointsFilterConfig(ref num2, viewRect.width, filter); HelperThingFilterUI.DrawQualityFilterConfig(ref num2, viewRect.width, filter); float num3 = num2; Listing_TreeThingFilter listing_TreeThingFilter = new Listing_TreeThingFilter(new Rect(0f, num2, viewRect.width, 9999f), filter, parentFilter, forceHiddenDefs, forceHiddenFilters); TreeNode_ThingCategory treeNode_ThingCategory = ThingCategoryNodeDatabase.RootNode; if (parentFilter != null) { if (parentFilter.DisplayRootCategory == null) { parentFilter.RecalculateDisplayRootCategory(); } treeNode_ThingCategory = parentFilter.DisplayRootCategory; } if (filterText != null && filterText.Length > 0) { TreeNode_ThingCategory treeNode_ThingCategory2 = new TreeNode_ThingCategory(new ThingCategoryDef()); from td in treeNode_ThingCategory.catDef.DescendantThingDefs where td.label.ToLower().Contains(filterText.ToLower()) select td; IEnumerable <ThingDef> arg_1D5_0 = treeNode_ThingCategory.catDef.DescendantThingDefs; Func <ThingDef, bool> < > 9__1; Func <ThingDef, bool> arg_1D5_1; if ((arg_1D5_1 = < > 9__1) == null) { arg_1D5_1 = (< > 9__1 = ((ThingDef td) => td.label.ToLower().Contains(filterText.ToLower()))); } foreach (ThingDef current in arg_1D5_0.Where(arg_1D5_1)) { treeNode_ThingCategory2.catDef.childThingDefs.Add(current); } treeNode_ThingCategory = treeNode_ThingCategory2; } listing_TreeThingFilter.DoCategoryChildren(treeNode_ThingCategory, 0, openMask, true); listing_TreeThingFilter.End(); if (Event.current.type == EventType.Layout) { HelperThingFilterUI.viewHeight = num3 + listing_TreeThingFilter.CurHeight + 90f; } Widgets.EndScrollView(); }
public Trigger_Threshold( ManagerJob_Foraging job ) : base(job.manager) { Op = Ops.LowerThan; MaxUpperThreshold = DefaultMaxUpperThreshold; Count = DefaultCount; ThresholdFilter = new ThingFilter(); ThresholdFilter.SetDisallowAll(); }
static void Postfix(Thing __result, ThingDef def, ThingDef stuff) { if (!Settings.add_meal_ingredients || __result == null || !__result.def.IsIngestible) { return; } CompIngredients ings = __result.TryGetComp <CompIngredients>(); if (ings == null || ings.ingredients.Count > 0) { return; } RecipeDef d = hTable.TryGetValue(def); if (d == null) { List <RecipeDef> l = DefDatabase <RecipeDef> .AllDefsListForReading; if (l == null) { return; } d = l.Where(x => !x.ingredients.NullOrEmpty() && x.products.Any(y => y.thingDef == def)).RandomElement(); if (d == null) { return; } hTable.Add(def, d); } foreach (IngredientCount c in d.ingredients) { ThingFilter ic = c.filter; if (ic == null) { return; } IEnumerable <ThingDef> l = ic.AllowedThingDefs; if (l == null) { return; } ThingDef td = l.Where( x => x.IsIngestible && x.comps != null && !x.comps.Any(y => y.compClass == typeof(CompIngredients)) && !FoodUtility.IsHumanlikeMeat(x) && (x.ingestible.specialThoughtAsIngredient == null || x.ingestible.specialThoughtAsIngredient.stages == null || x.ingestible.specialThoughtAsIngredient.stages[0].baseMoodEffect >= 0) ).RandomElement(); if (td != null) { ings.RegisterIngredient(td); } } }
public static void SetThingDefs(this ThingFilter thingFilter, ThingDef thingDef) { _field_ThingFilter_thingDefs.SetValue(thingFilter, new List <ThingDef> { thingDef }); }
internal int GetWeaponCount(ThingDef expectedDef, QualityRange qualityRange, FloatRange hpRange, ThingFilter ingredientFilter) { int count = 0; foreach (IEnumerable <ThingWithComps> l in this.StoredWeapons.Values) { foreach (ThingWithComps t in l) { if (this.Allows(t, expectedDef, qualityRange, hpRange, ingredientFilter)) { ++count; } } } foreach (IEnumerable <ThingWithComps> l in this.StoredBioEncodedWeapons.Values) { foreach (ThingWithComps t in l) { if (this.Allows(t, expectedDef, qualityRange, hpRange, ingredientFilter)) { ++count; } } } return(count); }
public static void SetThingDefs(this ThingFilter thingFilter, IEnumerable <ThingDef> thingDefs) { _field_ThingFilter_thingDefs.SetValue(thingFilter, thingDefs.ToList()); }
public static string IngredientFilterSummary(ThingFilter thingFilter) { return(thingFilter.Summary); }
public override void DoWindowContents(Rect inRect) // For a specific DSU { // var XXXcontentRect = new Rect(0, 0, inRect.width, inRect.height - (CloseButSize.y + 10f)).ContractedBy(10f); var l = new Listing_Standard(); // l.Begin(new Rect(inRect.x, inRect.y, inRect.width, inRect.height-CloseButSize.y-5f)); var s = new Rect(inRect.x, inRect.y, inRect.width, inRect.height - CloseButSize.y - 5f); var v = new Rect(inRect.x, inRect.y, inRect.width - 20f, inRect.height - CloseButSize.y - 5f); if (useCustomThingFilter) { v.height += 300f; } l.BeginScrollView(s, ref DSUScrollPosition, ref v); // l.BeginScrollView( // l.BeginScrollView(Rect rect, ref Vector2 scrollPosition, ref Rect viewRect) l.Label(def.label); l.GapLine(); // Much TODO, so wow: tmpLabel = l.TextEntryLabeled("LWMDSpDSUlabel".Translate(), tmpLabel); string tmpstring = null; //TODO: redo, include defaults: l.TextFieldNumericLabeled("LWM_DS_maxNumStacks".Translate().CapitalizeFirst() + " " + "LWM_DS_Default".Translate(tmpMaxNumStacks), ref tmpMaxNumStacks, ref tmpstring); // l.TextFieldNumericLabeled("Maximum Number of Stacks per Cell", ref tmpMaxNumStacks, ref tmpstring,0); tmpstring = null; // l.TextFieldNumericLabeled<float>("Maximum Total Mass per Cell", ref tmpMaxTotalMass, ref tmpstring,0f); l.TextFieldNumericLabeled("LWM_DS_maxTotalMass".Translate().CapitalizeFirst() + " " + "LWM_DS_Default".Translate(tmpMaxTotalMass), ref tmpMaxTotalMass, ref tmpstring); tmpstring = null; // l.TextFieldNumericLabeled<float>("Maximum Mass of any Stored Item", ref tmpMaxMassStoredItem, ref tmpstring,0f); l.TextFieldNumericLabeled("LWM_DS_maxMassOfStoredItem".Translate().CapitalizeFirst() + " " + "LWM_DS_Default".Translate(tmpMaxMassStoredItem), ref tmpMaxMassStoredItem, ref tmpstring); l.CheckboxLabeled("LWMDSpDSUshowContents".Translate(), ref tmpShowContents); l.GapLine(); l.EnumRadioButton(ref tmpOverlayType, "LWMDSpDSUoverlay".Translate()); l.GapLine(); l.EnumRadioButton(ref tmpStoragePriority, "LWMDSpDSUstoragePriority".Translate()); l.GapLine(); l.CheckboxLabeled("LWMDSpDSUchangeFilterQ".Translate(), ref useCustomThingFilter, "LWMDSpDSUchangeFilterQDesc".Translate()); if (useCustomThingFilter) { if (customThingFilter == null) { customThingFilter = new ThingFilter(); customThingFilter.CopyAllowancesFrom(def.building.fixedStorageSettings.filter); Utils.Mess(Utils.DBF.Settings, "Created new filter for " + def.defName + ": " + customThingFilter); // Log.Error("Old filter has: "+def.building.fixedStorageSettings.filter.AllowedDefCount); // Log.Warning("New filter has: "+customThingFilter.AllowedDefCount); } var r = l.GetRect(300); r.width *= 2f / 3f; r.x += 10f; ThingFilterUI.DoThingFilterConfigWindow(r, ref thingFilterScrollPosition, customThingFilter); } else { // not using custom thing filter: if (customThingFilter != null || defaultDSUValues.ContainsKey("DSU_" + def.defName + "_filter")) { customThingFilter = null; if (defaultDSUValues.ContainsKey("DSU_" + def.defName + "_filter")) { Utils.Mess(Utils.DBF.Settings, " Removing filter for " + def.defName); def.building.fixedStorageSettings.filter = (ThingFilter)defaultDSUValues["DSU_" + def.defName + "_filter"]; defaultDSUValues.Remove("DSU_" + def.defName + "_filter"); } } } // l.End(); l.EndScrollView(ref v); // Cancel button var closeRect = new Rect(inRect.width - CloseButSize.x, inRect.height - CloseButSize.y, CloseButSize.x, CloseButSize.y); if (Widgets.ButtonText(closeRect, "CancelButton".Translate())) { Utils.Mess(Utils.DBF.Settings, "Cancel button selected - no changes made"); Close(); } // Accept button - with accompanying logic closeRect = new Rect(inRect.width - (2 * CloseButSize.x + 5f), inRect.height - CloseButSize.y, CloseButSize.x, CloseButSize.y); if (Widgets.ButtonText(closeRect, "AcceptButton".Translate())) { GUI.FocusControl(null); // unfocus, so that a focused text field may commit its value Utils.Warn(Utils.DBF.Settings, "\"Accept\" button selected: changing values for " + def.defName); TestAndUpdate("label", tmpLabel, ref def.label); TestAndUpdate("maxNumStacks", tmpMaxNumStacks, ref def.GetCompProperties <Properties>().maxNumberStacks); TestAndUpdate("maxTotalMass", tmpMaxTotalMass, ref def.GetCompProperties <Properties>().maxTotalMass); TestAndUpdate("maxMassStoredItem", tmpMaxMassStoredItem, ref def.GetCompProperties <Properties>().maxMassOfStoredItem); TestAndUpdate("showContents", tmpShowContents, ref def.GetCompProperties <Properties>().showContents); TestAndUpdate("overlayType", tmpOverlayType, ref def.GetCompProperties <Properties>().overlayType); var tmpSP = def.building.defaultStorageSettings.Priority; // hard to access private field directly TestAndUpdate("storagePriority", tmpStoragePriority, ref tmpSP); def.building.defaultStorageSettings.Priority = tmpSP; if (useCustomThingFilter) { if (!defaultDSUValues.ContainsKey("DSU_" + def.defName + "_filter")) { Utils.Mess(Utils.DBF.Settings, "Creating default filter record for item " + def.defName); defaultDSUValues["DSU_" + def.defName + "_filter"] = def.building.fixedStorageSettings.filter; } def.building.fixedStorageSettings.filter = customThingFilter; } else { if (defaultDSUValues.ContainsKey("DSU_" + def.defName + "_filter")) { // we need to remove it Utils.Mess(Utils.DBF.Settings, "Removing default filter record for item " + def.defName); def.building.fixedStorageSettings.filter = (ThingFilter)defaultDSUValues["DSU_" + def.defName + "_filter"]; defaultDSUValues.Remove("DSU_" + def.defName + "_filter"); } } Close(); } // Reset to Defaults closeRect = new Rect(inRect.width - (4 * CloseButSize.x + 10f), inRect.height - CloseButSize.y, 2 * CloseButSize.x, CloseButSize.y); if (!AreTempVarsDefaults() && Widgets.ButtonText(closeRect, "ResetBinding".Translate())) { SetTempVarsToDefaults(); } //ResetDSUToDefaults(def.defName); //SetTempVars(); }
protected override void FillTab() { ConceptDatabase.KnowledgeDemonstrated(ConceptDefOf.StorageTab, KnowledgeAmount.GuiFrame); ConceptDecider.TeachOpportunity(ConceptDefOf.StorageTabCategories, OpportunityType.GuiFrame); ConceptDecider.TeachOpportunity(ConceptDefOf.StoragePriority, OpportunityType.GuiFrame); IStoreSettingsParent selStoreSettingsParent = this.SelStoreSettingsParent; StorageSettings settings = selStoreSettingsParent.GetStoreSettings(); Rect position = new Rect(0f, 0f, ITab_Storage_Enhanced.WinSize.x, ITab_Storage_Enhanced.WinSize.y).ContractedBy(10f); GUI.BeginGroup(position); Text.Font = GameFont.Small; Rect rect = new Rect(0f, 0f, 160f, 29f); if (Widgets.TextButton(rect, "Priority".Translate() + ": " + settings.Priority.Label(), true, false)) { List <FloatMenuOption> list = new List <FloatMenuOption>(); IEnumerator enumerator = Enum.GetValues(typeof(StoragePriority)).GetEnumerator(); try { while (enumerator.MoveNext()) { StoragePriority storagePriority = (StoragePriority)((byte)enumerator.Current); if (storagePriority != StoragePriority.Unstored) { StoragePriority localPr = storagePriority; list.Add(new FloatMenuOption(localPr.Label(), delegate { settings.Priority = localPr; ConceptDatabase.KnowledgeDemonstrated(ConceptDefOf.StoragePriority, KnowledgeAmount.Total); }, MenuOptionPriority.Medium, null, null)); } } } finally { IDisposable disposable = enumerator as IDisposable; if (disposable != null) { disposable.Dispose(); } } Find.WindowStack.Add(new FloatMenu(list, false)); } var clearSearchRect = new Rect(position.width - 33f, (29f - 14f) / 2f, 14f, 14f); var shouldClearSearch = (Widgets.ImageButton(clearSearchRect, Widgets.CheckboxOffTex)); var searchRect = new Rect(165f, 0f, position.width - 160f - 20f, 29f); var watermark = (searchText != string.Empty || isFocused) ? searchText : "Search"; var escPressed = (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape); var clickedOutside = (!Mouse.IsOver(searchRect) && Event.current.type == EventType.MouseDown); if (!isFocused) { GUI.color = new Color(1f, 1f, 1f, 0.6f); } GUI.SetNextControlName("StorageSearchInput"); var searchInput = Widgets.TextField(searchRect, watermark); GUI.color = Color.white; if (isFocused) { searchText = searchInput; } if ((GUI.GetNameOfFocusedControl() == "StorageSearchInput" || isFocused) && (escPressed || clickedOutside)) { GUIUtility.keyboardControl = 0; isFocused = false; } else if (GUI.GetNameOfFocusedControl() == "StorageSearchInput" && !isFocused) { isFocused = true; } if (shouldClearSearch) { searchText = string.Empty; } TutorUIHighlighter.HighlightOpportunity("StoragePriority", rect); ThingFilter parentFilter = null; if (selStoreSettingsParent.GetParentStoreSettings() != null) { parentFilter = selStoreSettingsParent.GetParentStoreSettings().filter; } Rect rect2 = new Rect(0f, 35f, position.width, position.height - 35f); HelperThingFilterUI.DoThingFilterConfigWindow(rect2, ref this.scrollPosition, settings.filter, parentFilter, 8, searchText); GUI.EndGroup(); }
static bool Prefix(ThingFilter __instance, ref string __result) { if (!Settings.gui_extended_recipe) { return(true); } if (!__instance.customSummary.NullOrEmpty()) { __result = __instance.customSummary; } List <ThingDef> thingDefs = Traverse.Create(__instance).Field("thingDefs").GetValue <List <ThingDef> >(); List <string> categories = Traverse.Create(__instance).Field("categories").GetValue <List <string> >(); //List<string> tradeTagsToAllow = Traverse.Create(__instance).Field("tradeTagsToAllow").GetValue<List<string>>(); //List<string> tradeTagsToDisallow = Traverse.Create(__instance).Field("tradeTagsToDisallow").GetValue<List<string>>(); //List<string> thingSetMakerTagsToAllow = Traverse.Create(__instance).Field("thingSetMakerTagsToAllow").GetValue<List<string>>(); //List<string> thingSetMakerTagsToDisallow = Traverse.Create(__instance).Field("thingSetMakerTagsToDisallow").GetValue<List<string>>(); //List<string> disallowedCategories = Traverse.Create(__instance).Field("disallowedCategories").GetValue<List<string>>(); //List<string> specialFiltersToAllow = Traverse.Create(__instance).Field("specialFiltersToAllow").GetValue<List<string>>(); //List<string> specialFiltersToDisallow = Traverse.Create(__instance).Field("specialFiltersToDisallow").GetValue<List<string>>(); //List<StuffCategoryDef> stuffCategoriesToAllow = Traverse.Create(__instance).Field("stuffCategoriesToAllow").GetValue<List<StuffCategoryDef>>(); List <ThingDef> allowAllWhoCanMake = Traverse.Create(__instance).Field("allowAllWhoCanMake").GetValue <List <ThingDef> >(); //FoodPreferability disallowWorsePreferability = Traverse.Create(__instance).Field("disallowWorsePreferability").GetValue<FoodPreferability>(); //bool disallowInedibleByHuman = Traverse.Create(__instance).Field("disallowInedibleByHuman").GetValue<bool>(); //Type allowWithComp = Traverse.Create(__instance).Field("allowWithComp").GetValue<Type>(); //Type disallowWithComp = Traverse.Create(__instance).Field("disallowWithComp").GetValue<Type>(); //float disallowCheaperThan = Traverse.Create(__instance).Field("disallowCheaperThan").GetValue<float>(); //List<ThingDef> disallowedThingDefs = Traverse.Create(__instance).Field("disallowedThingDefs").GetValue<List<ThingDef>>(); HashSet <ThingDef> allowedDefs = Traverse.Create(__instance).Field("allowedDefs").GetValue <HashSet <ThingDef> >(); if (!categories.NullOrEmpty()) { __result = DefDatabase <ThingCategoryDef> .GetNamed(categories[0]).label; for (int i = 1; i < categories.Count; i++) { __result += ", " + DefDatabase <ThingCategoryDef> .GetNamed(categories[i]).label; } } else if (!allowAllWhoCanMake.NullOrEmpty()) { HashSet <StuffCategoryDef> l = new HashSet <StuffCategoryDef>(); foreach (var c in (allowAllWhoCanMake)) { l.AddRange(c.stuffCategories); } __result = ""; foreach (var def in l) { __result += __result == "" ? def.label.CapitalizeFirst() : ", " + def.label.CapitalizeFirst(); } } else if (allowedDefs != null && allowedDefs.Count > 0) { __result = ""; foreach (var thing in allowedDefs) { __result += __result == "" ? thing.label : ", " + thing.label; } } else if (!thingDefs.NullOrEmpty()) { __result = thingDefs[0].label; for (int i = 1; i < thingDefs.Count; i++) { __result += ", " + thingDefs[i].label; } } else { __result = "UsableIngredients".Translate(); } __instance.customSummary = __result; return(false); }
public void DoThingFilterConfigWindow( Rect canvas, ref Vector2 scrollPosition, ThingFilter filter, ThingFilter parentFilter = null, int openMask = 1, bool buttonsAtBottom = false ) { // respect your bounds! GUI.BeginGroup( canvas ); canvas = canvas.AtZero(); // set up buttons Text.Font = GameFont.Tiny; float width = canvas.width - 2f; var clearButtonRect = new Rect( canvas.x + 1f, canvas.y + 1f, width / 2f, 24f ); var allButtonRect = new Rect( clearButtonRect.xMax + 1f, clearButtonRect.y, width / 2f, 24f ); // offset canvas position for buttons. if ( buttonsAtBottom ) { clearButtonRect.y = canvas.height - clearButtonRect.height; allButtonRect.y = canvas.height - clearButtonRect.height; canvas.yMax -= clearButtonRect.height; } else { canvas.yMin = clearButtonRect.height; } // draw buttons + logic if ( Widgets.ButtonTextSubtle( clearButtonRect, "ClearAll".Translate() ) ) { filter.SetDisallowAll(); } if ( Widgets.ButtonTextSubtle( allButtonRect, "AllowAll".Translate() ) ) { filter.SetAllowAll( parentFilter ); } Text.Font = GameFont.Small; // do list var curY = 2f; var viewRect = new Rect( 0f, 0f, canvas.width - 16f, viewHeight ); // scrollview Widgets.BeginScrollView( canvas, ref scrollPosition, viewRect ); // slider(s) DrawHitPointsFilterConfig( ref curY, viewRect.width, filter ); DrawQualityFilterConfig( ref curY, viewRect.width, filter ); // main listing var listingRect = new Rect( 0f, curY, viewRect.width, 9999f ); var listingTreeThingFilter = new Listing_TreeThingFilter( listingRect, filter, parentFilter, null, null ); TreeNode_ThingCategory node = ThingCategoryNodeDatabase.RootNode; if ( parentFilter != null ) { if ( parentFilter.DisplayRootCategory == null ) { parentFilter.RecalculateDisplayRootCategory(); } node = parentFilter.DisplayRootCategory; } // draw the actual thing listingTreeThingFilter.DoCategoryChildren( node, 0, openMask, true ); listingTreeThingFilter.End(); // update height. viewHeight = curY + listingTreeThingFilter.CurHeight; Widgets.EndScrollView(); GUI.EndGroup(); }
public static bool PlayerOrQuestRewardHas(ThingFilter thingFilter) { ThingRequest bestThingRequest = thingFilter.BestThingRequest; List <Map> maps = Find.Maps; for (int i = 0; i < maps.Count; i++) { List <Thing> list = maps[i].listerThings.ThingsMatching(bestThingRequest); for (int j = 0; j < list.Count; j++) { if (thingFilter.Allows(list[j])) { return(true); } } } List <Caravan> caravans = Find.WorldObjects.Caravans; for (int k = 0; k < caravans.Count; k++) { if (!caravans[k].IsPlayerControlled) { continue; } List <Thing> list2 = CaravanInventoryUtility.AllInventoryItems(caravans[k]); for (int l = 0; l < list2.Count; l++) { if (thingFilter.Allows(list2[l])) { return(true); } } } List <Site> sites = Find.WorldObjects.Sites; for (int m = 0; m < sites.Count; m++) { for (int n = 0; n < sites[m].parts.Count; n++) { SitePart sitePart = sites[m].parts[n]; if (sitePart.things == null) { continue; } for (int num = 0; num < sitePart.things.Count; num++) { if (thingFilter.Allows(sitePart.things[num])) { return(true); } } } DefeatAllEnemiesQuestComp component = sites[m].GetComponent <DefeatAllEnemiesQuestComp>(); if (component == null) { continue; } ThingOwner rewards = component.rewards; for (int num2 = 0; num2 < rewards.Count; num2++) { if (thingFilter.Allows(rewards[num2])) { return(true); } } } return(false); }
public Thing GetResource( ThingFilter acceptableResources ) { var things = GetAllResources( acceptableResources ); if( things.NullOrEmpty() ) { return null; } return things.FirstOrDefault(); }
internal int GetApparelCount(ThingDef def, ThingFilter ingredientFilter) { return(this.GetApparelCount(def, ingredientFilter.AllowedQualityLevels, ingredientFilter.AllowedHitPointsPercents, ingredientFilter)); }
public override void DefsLoaded() { //1. Preparing settings UpdateSettings(); //2. Adding Tech Tab to Pawns //ThingDef injection stolen from the work of notfood for Psychology var zombieThinkTree = DefDatabase <ThinkTreeDef> .GetNamedSilentFail("Zombie"); IEnumerable <ThingDef> things = (from def in DefDatabase <ThingDef> .AllDefs where def.race?.intelligence == Intelligence.Humanlike && (zombieThinkTree == null || def.race.thinkTreeMain != zombieThinkTree) select def); List <string> registered = new List <string>(); foreach (ThingDef t in things) { if (t.inspectorTabsResolved == null) { t.inspectorTabsResolved = new List <InspectTabBase>(1); } t.inspectorTabsResolved.Add(InspectTabManager.GetSharedInstance(typeof(ITab_PawnKnowledge))); if (t.comps == null) { t.comps = new List <CompProperties>(1); } t.comps.Add(new CompProperties_Knowledge()); registered.Add(t.defName); } InspectPaneUtility.Reset(); //3. Preparing knowledge support infrastructure //a. Things everyone knows UniversalWeapons.AddRange(DefDatabase <ThingDef> .AllDefs.Where(x => x.IsWeapon)); UniversalCrops.AddRange(DefDatabase <ThingDef> .AllDefs.Where(x => x.plant != null && x.plant.Sowable)); //b. Minus things unlocked on research ThingFilter lateFilter = new ThingFilter(); foreach (ResearchProjectDef tech in DefDatabase <ResearchProjectDef> .AllDefs) { tech.InferSkillBias(); tech.CreateStuff(lateFilter, unlocked); foreach (ThingDef weapon in tech.UnlockedWeapons()) { UniversalWeapons.Remove(weapon); } foreach (ThingDef plant in tech.UnlockedPlants()) { UniversalCrops.Remove(plant); } } ; //b. Also removing atipical weapons List <string> ForbiddenWeaponTags = TechDefOf.WeaponsNotBasic.weaponTags; UniversalWeapons.RemoveAll(x => SplitSimpleWeapons(x, ForbiddenWeaponTags)); List <ThingDef> garbage = new List <ThingDef>(); garbage.Add(TechDefOf.WeaponsNotBasic); //c. Classifying pawn backstories PawnBackgroundUtility.BuildCache(); //d. Telling humans what's going on ThingCategoryDef knowledgeCat = TechDefOf.Knowledge; IEnumerable <ThingDef> codifiedTech = DefDatabase <ThingDef> .AllDefs.Where(x => x.IsWithinCategory(knowledgeCat)); if (Prefs.LogVerbose || FullStartupReport) { Log.Message($"[HumanResources] Codified technologies: {codifiedTech.Select(x => x.label).ToStringSafeEnumerable()}"); Log.Message($"[HumanResources] Basic crops: {UniversalCrops.ToStringSafeEnumerable()}"); Log.Message($"[HumanResources] Basic weapons: {UniversalWeapons.ToStringSafeEnumerable()}"); Log.Message($"[HumanResources] Basic weapons that require training: {SimpleWeapons.ToStringSafeEnumerable()}"); Log.Warning($"[HumanResources] Basic weapons tags: {SimpleWeapons.Where(x => !x.weaponTags.NullOrEmpty()).SelectMany(x => x.weaponTags).Distinct().ToStringSafeEnumerable()}"); if (FullStartupReport) { Log.Warning("[HumanResources] Backstories classified by TechLevel:"); for (int i = 0; i < 8; i++) { TechLevel level = (TechLevel)i; IEnumerable <string> found = PawnBackgroundUtility.TechLevelByBackstory.Where(e => e.Value == level).Select(e => e.Key); if (!found.EnumerableNullOrEmpty()) { Log.Message($"- {level.ToString().CapitalizeFirst()} ({found.EnumerableCount()}): {found.ToStringSafeEnumerable()}"); } } Log.Warning("[HumanResources] Techs classified by associated skill:"); var skills = DefDatabase <SkillDef> .AllDefsListForReading.GetEnumerator(); while (skills.MoveNext()) { SkillDef skill = skills.Current; IEnumerable <string> found = Extension_Research.SkillsByTech.Where(e => e.Value.Contains(skill)).Select(e => e.Key.label); Log.Message($"- {skill.LabelCap} ({found.EnumerableCount()}): {found.ToStringSafeEnumerable()}"); } } } else { Log.Message($"[HumanResources] This is what we know: {codifiedTech.EnumerableCount()} technologies processed, {UniversalCrops.Count()} basic crops, {UniversalWeapons.Count()} basic weapons + {SimpleWeapons.Count()} that require training."); } //4. Filling gaps on the database //a. TechBook dirty trick, but only now this is possible! TechDefOf.TechBook.stuffCategories = TechDefOf.UnfinishedTechBook.stuffCategories = TechDefOf.LowTechCategories.stuffCategories; TechDefOf.TechDrive.stuffCategories = TechDefOf.HiTechCategories.stuffCategories; garbage.Add(TechDefOf.LowTechCategories); garbage.Add(TechDefOf.HiTechCategories); //b. Filling main tech category with subcategories foreach (ThingDef t in lateFilter.AllowedThingDefs.Where(t => !t.thingCategories.NullOrEmpty())) { foreach (ThingCategoryDef c in t.thingCategories) { c.childThingDefs.Add(t); if (!knowledgeCat.childCategories.NullOrEmpty() && !knowledgeCat.childCategories.Contains(c)) { knowledgeCat.childCategories.Add(c); } } } //c. Populating knowledge recipes and book shelves foreach (RecipeDef r in DefDatabase <RecipeDef> .AllDefs.Where(x => x.ingredients.Count == 1 && x.fixedIngredientFilter.AnyAllowedDef == null)) { r.fixedIngredientFilter.ResolveReferences(); r.defaultIngredientFilter.ResolveReferences(); } foreach (ThingDef t in DefDatabase <ThingDef> .AllDefs.Where(x => x.thingClass == typeof(Building_BookStore))) { t.building.fixedStorageSettings.filter.ResolveReferences(); t.building.defaultStorageSettings.filter.ResolveReferences(); } //d. Removing temporary defs from database. foreach (ThingDef def in garbage) { AccessTools.Method(typeof(DefDatabase <ThingDef>), "Remove").Invoke(this, new object[] { def }); } }
internal int GetApparelCount(ThingDef def, QualityRange qualityRange, FloatRange hpRange, ThingFilter ingredientFilter) { return(this.StoredApparel.GetApparelCount(def, qualityRange, hpRange, ingredientFilter)); }
public Trigger_Threshold( ManagerJob_Hunting job ) { Op = Ops.LowerThan; MaxUpperThreshold = DefaultMaxUpperThreshold; Count = DefaultCount; ThresholdFilter = new ThingFilter(); ThresholdFilter.SetDisallowAll(); ThresholdFilter.SetAllow( Utilities_Hunting.RawMeat, true ); }
public bool TryRemoveBestApparel(ThingDef def, ThingFilter filter, out Apparel apparel) { return(this.StoredApparel.TryRemoveBestApparel(def, filter, out apparel)); }
public ThingFilterWidget(string label, ThingFilter tf) : base(true, true) { this.label = label; this.ThingFilter = tf; }
protected override void SaveFields(StreamWriter writer) { foreach (Bill bill in Bills) { if (bill is Bill_Production productionBill) { ThingFilter filter = productionBill.ingredientFilter; ThingFilterReflection reflection = new ThingFilterReflection(filter); string defName = "recipeDefName"; if (bill is Bill_ProductionWithUft) { defName = "recipeDefNameUft"; } WriteField(writer, defName, productionBill.recipe.defName); WriteField(writer, "suspended", productionBill.suspended.ToString()); WriteField(writer, "countEquipped", productionBill.includeEquipped.ToString()); WriteField(writer, "countTainted", productionBill.includeTainted.ToString()); WriteField(writer, "skillRange", productionBill.allowedSkillRange.ToString()); WriteField(writer, "ingSearchRadius", productionBill.ingredientSearchRadius.ToString()); WriteField(writer, "repeatMode", productionBill.repeatMode.defName); WriteField(writer, "repeatCount", productionBill.repeatCount.ToString()); WriteField(writer, "targetCount", productionBill.targetCount.ToString()); WriteField(writer, "pauseWhenSatisfied", productionBill.pauseWhenSatisfied.ToString()); WriteField(writer, "unpauseWhenYouHave", productionBill.unpauseWhenYouHave.ToString()); WriteField(writer, "hpRange", productionBill.hpRange.ToString()); WriteField(writer, "qualityRange", productionBill.qualityRange.ToString()); WriteField(writer, "onlyAllowedIngredients", productionBill.limitToAllowedStuff.ToString()); BillStoreModeDef storeMode = productionBill.GetStoreMode(); WriteField(writer, "storeMode", storeMode.ToString()); if (storeMode == BillStoreModeDefOf.SpecificStockpile) { WriteField(writer, "storeZone", productionBill.GetStoreZone().label); } if (productionBill.includeFromZone != null) { WriteField(writer, "lookIn", productionBill.includeFromZone.label); } StringBuilder builder = new StringBuilder(); foreach (ThingDef thing in filter.AllowedThingDefs) { if (builder.Length > 0) { builder.Append("/"); } builder.Append(thing.defName); } WriteField(writer, "allowedDefs", builder.ToString()); if (filter.allowedHitPointsConfigurable) { builder = new StringBuilder(); builder.Append(Math.Round(filter.AllowedHitPointsPercents.min, 2).ToString()); builder.Append(":"); builder.Append(Math.Round(filter.AllowedHitPointsPercents.max, 2).ToString()); WriteField(writer, "allowedHitPointsPercents", builder.ToString()); } if (filter.allowedQualitiesConfigurable) { builder = new StringBuilder(); builder.Append(filter.AllowedQualityLevels.min.ToString()); builder.Append(":"); builder.Append(filter.AllowedQualityLevels.max.ToString()); WriteField(writer, "allowedQualities", builder.ToString()); } builder = new StringBuilder(); foreach (SpecialThingFilterDef def in reflection.DisallowedSpecialFilters) { if (builder.Length > 0) { builder.Append("/"); } builder.Append(def.defName); } WriteField(writer, "disallowedSpecialFilters", builder.ToString()); writer.WriteLine(BREAK); } } }
private static void Prefix(Pawn pawn, float money, List <ThingStuffPair> apparelCandidates) { // Short-circuit if (pawn == null || pawn.Faction == null || pawn.kindDef.apparelRequired == null) { return; } // [Reflection prep] PawnApparelGenerator.CanUseStuff(pawn, pa); MethodInfo CanUseStuffMethod = AccessTools.Method(typeof(PawnApparelGenerator), "CanUseStuff"); List <ThingStuffPair> allApparelPairs = ThingStuffPair.AllWith(td => td.IsApparel); List <ThingDef> reqApparel = pawn.kindDef.apparelRequired; for (int i = 0; i < reqApparel.Count; i++) { IEnumerable <ThingStuffPair> pairs = allApparelPairs.Where( pa => pa.thing == reqApparel[i] ); // The original method is going to have a bad time, so auto-add an appropriate filter to fix it if (!pairs.Any(pa => (bool)CanUseStuffMethod.Invoke(null, new object[] { pawn, pa }))) { string logMsg = "Found an apparelStuffFilter/stuffCategories conflict for required apparel " + reqApparel[i] + " while generating apparel for " + pawn.kindDef.defName + "; " ; ThingFilter factionFilter = pawn.Faction.def.apparelStuffFilter; string factionName = pawn.Faction.def.defName; if (factionFilter != null) { List <StuffCategoryDef> stuffCategories = reqApparel[i].stuffCategories; ThingStuffPair examplePair = pairs.RandomElementByWeight(pa => pa.Commonality); if (stuffCategories == null && examplePair != null && examplePair.stuff != null) { stuffCategories = examplePair.stuff.stuffProps.categories; } if (stuffCategories != null) { logMsg = logMsg + "adding extra stuffCategories to " + factionName + "'s apparelStuffFilter: " + string.Join(", ", stuffCategories); foreach (StuffCategoryDef sc in stuffCategories) { factionFilter.SetAllow(sc, true); } } else if (examplePair.stuff != null) { logMsg = logMsg + "adding " + examplePair.stuff + " to " + factionName + "'s apparelStuffFilter"; factionFilter.SetAllow(examplePair.stuff, true); } else if (examplePair != null) { logMsg = logMsg + "adding " + examplePair.thing + " to " + factionName + "'s apparelStuffFilter"; factionFilter.SetAllow(examplePair.thing, true); } else // probably pendatic, but ¯\_(ツ)_/¯ { logMsg = logMsg + "adding " + reqApparel[i] + " to " + factionName + "'s apparelStuffFilter"; factionFilter.SetAllow(reqApparel[i], true); } } else { logMsg = logMsg + "cannot fix since there is no apparelStuffFilter for " + factionName; } Base.Instance.ModLogger.Warning(logMsg); } } return; }
public override void SpawnSetup() { base.SpawnSetup(); mountableComp = base.GetComp<CompMountable>(); if (allowances == null) { this.allowances = new ThingFilter(); this.allowances.SetFromPreset(StorageSettingsPreset.DefaultStockpile); this.allowances.SetFromPreset(StorageSettingsPreset.DumpingStockpile); } UpdateGraphics(); }
public MapStockpileFilter(Map map, ThingFilter filter, Zone_Stockpile stockpile) { this.map = map; this.filter = filter; this.stockpile = stockpile; }
private void MergeIngredientIntoFilter( ThingFilter filter, IngredientCount ingredient ) { //Log.Message( string.Format( "{0}.CompHopperUser.MergeIngredientIntoFilter( ThingFilter, IngredientCount )", this.parent.ThingID ) ); if( ingredient.filter != null ) { if( !ingredient.filter.Categories().NullOrEmpty() ) { foreach( var category in ingredient.filter.Categories() ) { var categoryDef = DefDatabase<ThingCategoryDef>.GetNamed( category, true ); filter.SetAllow( categoryDef, true ); } } if( !ingredient.filter.ThingDefs().NullOrEmpty() ) { foreach( var thingDef in ingredient.filter.ThingDefs() ) { filter.SetAllow( thingDef, true ); } } } }
private bool Allows(Thing t, ThingDef expectedDef, QualityRange qualityRange, FloatRange hpRange, ThingFilter filter) { #if DEBUG || DEBUG_DO_UNTIL_X Log.Warning("Building_WeaponStoreage.Allows Begin [" + t.Label + "]"); #endif if (t.def != expectedDef) { #if DEBUG || DEBUG_DO_UNTIL_X Log.Warning(" Building_WeaponStoreage.Allows End Def Does Not Match [False]"); #endif return(false); } if (expectedDef.useHitPoints && hpRange != null && hpRange.min != 0f && hpRange.max != 100f) { float num = (float)t.HitPoints / (float)t.MaxHitPoints; num = GenMath.RoundedHundredth(num); if (!hpRange.IncludesEpsilon(Mathf.Clamp01(num))) { #if DEBUG || DEBUG_DO_UNTIL_X Log.Warning(" Building_WeaponStoreage.Allows End Hit Points [False - HP]"); #endif return(false); } } if (qualityRange != null && qualityRange != QualityRange.All && t.def.FollowQualityThingFilter()) { QualityCategory p; if (!t.TryGetQuality(out p)) { p = QualityCategory.Normal; } if (!qualityRange.Includes(p)) { #if DEBUG || DEBUG_DO_UNTIL_X Log.Warning(" Building_WeaponStoreage.Allows End Quality [False - Quality]"); #endif return(false); } } if (filter != null && !filter.Allows(t.Stuff)) { #if DEBUG || DEBUG_DO_UNTIL_X Log.Warning("StoredApparel.Allows End Quality [False - filters.Allows]"); #endif return(false); } #if DEBUG || DEBUG_DO_UNTIL_X Log.Warning(" Building_WeaponStoreage.Allows End [True]"); #endif return(true); }
static void Postfix(ref Dialog_ManageFoodRestrictions __instance) { ThingFilter f = (ThingFilter)PFoodGlobalFilter.GetValue(__instance); f.SetAllow(AnimalControlsDefOf.Plants, true, null, null); }
protected override void FillTab() { IStoreSettingsParent selStoreSettingsParent = this.SelStoreSettingsParent; StorageSettings settings = selStoreSettingsParent.GetStoreSettings(); Rect position = new Rect(0f, 0f, ITab_Lazy.WinSize.x, ITab_Lazy.WinSize.y).ContractedBy(10f); GUI.BeginGroup(position); if (this.IsPrioritySettingVisible) { Text.Font = GameFont.Small; Rect rect = new Rect(0f, 0f, 160f, this.TopAreaHeight - 6f); if (Widgets.ButtonText(rect, "Priority".Translate() + ": " + settings.Priority.Label(), true, false, true)) { List <FloatMenuOption> list = new List <FloatMenuOption>(); foreach (StoragePriority storagePriority in Enum.GetValues(typeof(StoragePriority))) { if (storagePriority != StoragePriority.Unstored) { StoragePriority localPr = storagePriority; list.Add(new FloatMenuOption(localPr.Label().CapitalizeFirst(), delegate { settings.Priority = localPr; }, MenuOptionPriority.Default, null, null, 0f, null, null)); } } Find.WindowStack.Add(new FloatMenu(list)); } UIHighlighter.HighlightOpportunity(rect, "StoragePriority"); } //Lazy button & Threshold Sliders { Text.Font = GameFont.Small; Rect rect = new Rect(0f, 35f, 160f, this.TopAreaHeight - 6f); LazySettings stockpile = LazySettingsManager.AddOrGetSettings(settings); if (stockpile == null) { Log.Error(string.Format($"Lazy Tab Error: Attempted to load {SelObject} settings as LazySettings, when it was of type {settings.GetType()}")); } else { //Type Button if (Widgets.ButtonText(rect, "Type: " + stockpile.type.ToString(), true, false, true)) { List <FloatMenuOption> list = new List <FloatMenuOption>(); foreach (LazyType type in Enum.GetValues(typeof(LazyType))) { LazyType localTy = type; list.Add(new FloatMenuOption(type.ToString(), delegate { stockpile.type = type; }, MenuOptionPriority.Default, null, null, 0f, null, null)); Find.WindowStack.Add(new FloatMenu(list)); } } //Cache Threshold Slider if (stockpile.type == LazyType.Cache) { Rect sliderRect = new Rect(0f, 66f, WinSize.x - 20f, 70f); Listing_Standard stand = new Listing_Standard(); stand.Begin(sliderRect); stand.Label(string.Format($"Cache Threshold: {stockpile.CacheThreshold * 100:0}%")); stockpile.CacheThreshold = stand.Slider(stockpile.CacheThreshold, 0f, 0.75f); stand.End(); } //Buffer Threshold Slider else if (stockpile.type == LazyType.Buffer) { Rect sliderRect = new Rect(0f, 66f, WinSize.x - 20f, 70f); Listing_Standard stand = new Listing_Standard(); stand.Begin(sliderRect); stand.Label(string.Format($"Buffer Threshold: {stockpile.BufferThreshold * 100:0}%")); stockpile.BufferThreshold = stand.Slider(stockpile.BufferThreshold, 0.25f, 1f); stand.End(); } } } ThingFilter parentFilter = null; if (selStoreSettingsParent.GetParentStoreSettings() != null) { parentFilter = selStoreSettingsParent.GetParentStoreSettings().filter; } Rect rect2 = new Rect(0f, (this.TopAreaHeight * 3) + 5, position.width, position.height - (this.TopAreaHeight * 2)); Bill[] first = (from b in BillUtility.GlobalBills() where b is Bill_Production && b.GetStoreZone() == selStoreSettingsParent && b.recipe.WorkerCounter.CanPossiblyStoreInStockpile((Bill_Production)b, b.GetStoreZone()) select b).ToArray(); ThingFilterUI.DoThingFilterConfigWindow(rect2, ref this.scrollPosition, settings.filter, parentFilter, 8, null, null, false, null, null); Bill[] second = (from b in BillUtility.GlobalBills() where b is Bill_Production && b.GetStoreZone() == selStoreSettingsParent && b.recipe.WorkerCounter.CanPossiblyStoreInStockpile((Bill_Production)b, b.GetStoreZone()) select b).ToArray(); IEnumerable <Bill> enumerable = first.Except(second); foreach (Bill item in enumerable) { Messages.Message("MessageBillValidationStoreZoneInsufficient".Translate(item.LabelCap, item.billStack.billGiver.LabelShort.CapitalizeFirst(), item.GetStoreZone().label), item.billStack.billGiver as Thing, MessageTypeDefOf.RejectInput, false); } PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.StorageTab, KnowledgeAmount.FrameDisplayed); GUI.EndGroup(); }
public void MergeRecipeIntoFilter( ThingFilter filter, RecipeDef recipe ) { //Log.Message( string.Format( "{0}.CompHopperUser.MergeRecipeInfoFilter( ThingFilter, {1} )", this.parent.ThingID, recipe == null ? "null" : recipe.defName ) ); if( recipeFilter.Contains( recipe ) ) { return; } recipeFilter.Add( recipe ); if( !recipe.ingredients.NullOrEmpty() ) { foreach( var ingredient in recipe.ingredients ) { MergeIngredientIntoFilter( filter, ingredient ); } } if( recipe.defaultIngredientFilter != null ) { MergeExceptionsIntoFilter( filter, recipe.defaultIngredientFilter ); } if( recipe.fixedIngredientFilter != null ) { MergeExceptionsIntoFilter( filter, recipe.fixedIngredientFilter ); } }
private bool TryCreateBill(Dictionary <string, string> fields, out Bill_Production bill) { bill = null; RecipeDef def; ThingFilter filter = null; ThingFilterReflection reflection = null; bool changed = false; foreach (var field in fields) { string key = field.Key; string value = field.Value; switch (key) { case BREAK: return(true); case "recipeDefName": case "recipeDefNameUft": def = DefDatabase <RecipeDef> .GetNamed(value); if (def == null) { string msg = "SaveStorageSettings.UnableToLoadRecipeDef".Translate().Replace("%s", value); Messages.Message(msg, MessageTypeDefOf.SilentInput); Log.Warning(msg); return(false); } if (def.researchPrerequisite != null && !def.researchPrerequisite.IsFinished) { string msg = "SaveStorageSettings.ResearchNotDoneForRecipeDef".Translate().Replace("%s", def.label); Messages.Message(msg, MessageTypeDefOf.SilentInput); Log.Warning(msg); return(false); } if (key == "recipeDefName") { bill = new Bill_Production(def); } else { bill = new Bill_ProductionWithUft(def); } filter = bill.ingredientFilter; reflection = new ThingFilterReflection(filter); break; case "suspended": bill.suspended = bool.Parse(value); break; case "countEquipped": bill.includeEquipped = bool.Parse(value); break; case "countTainted": bill.includeTainted = bool.Parse(value); break; case "skillRange": string[] skillRange = value.Split('~'); bill.allowedSkillRange = new IntRange(int.Parse(skillRange[0]), int.Parse(skillRange[1])); break; case "ingSearchRadius": bill.ingredientSearchRadius = float.Parse(value); break; case "repeatMode": bill.repeatMode = null; if (BillRepeatModeDefOf.Forever.defName.Equals(value)) { bill.repeatMode = BillRepeatModeDefOf.Forever; } else if (BillRepeatModeDefOf.RepeatCount.defName.Equals(value)) { bill.repeatMode = BillRepeatModeDefOf.RepeatCount; } else if (BillRepeatModeDefOf.TargetCount.defName.Equals(value)) { bill.repeatMode = BillRepeatModeDefOf.TargetCount; } else if ("TD_ColonistCount".Equals(value)) { EverybodyGetsOneUtil.TryGetRepeatModeDef("TD_ColonistCount", out bill.repeatMode); } else if ("TD_XPerColonist".Equals(value)) { EverybodyGetsOneUtil.TryGetRepeatModeDef("TD_XPerColonist", out bill.repeatMode); } else if ("TD_WithSurplusIng".Equals(value)) { EverybodyGetsOneUtil.TryGetRepeatModeDef("TD_WithSurplusIng", out bill.repeatMode); } if (bill.repeatMode == null) { Log.Warning("Unknown repeatMode of [" + value + "] for bill " + bill.recipe.defName); bill = null; return(false); } break; case "repeatCount": bill.repeatCount = int.Parse(value); break; case "targetCount": bill.targetCount = int.Parse(value); break; case "pauseWhenSatisfied": bill.pauseWhenSatisfied = bool.Parse(value); break; case "unpauseWhenYouHave": bill.unpauseWhenYouHave = int.Parse(value); break; case "hpRange": string[] hpRange = value.Split('~'); bill.hpRange = new FloatRange(float.Parse(hpRange[0]), float.Parse(hpRange[1])); break; case "qualityRange": if (!string.IsNullOrEmpty(value) && value.IndexOf('~') != -1) { string[] qualityRange = value.Split('~'); bill.qualityRange = new QualityRange( (QualityCategory)Enum.Parse(typeof(QualityCategory), qualityRange[0], true), (QualityCategory)Enum.Parse(typeof(QualityCategory), qualityRange[1], true)); } break; case "onlyAllowedIngredients": bill.limitToAllowedStuff = bool.Parse(value); break; case "storeMode": BillStoreModeDef storeMode = DefDatabase <BillStoreModeDef> .GetNamedSilentFail(value); if (storeMode == null || value == BillStoreModeDefOf.SpecificStockpile.ToString()) { storeMode = BillStoreModeDefOf.BestStockpile; } bill.SetStoreMode(storeMode); break; case "storeZone": var destinationZone = (Zone_Stockpile)Current.Game.CurrentMap.zoneManager.AllZones.Find(z => z.label == value); if (destinationZone != null) { bill.SetStoreMode(BillStoreModeDefOf.SpecificStockpile, destinationZone); } else { bill.SetStoreMode(BillStoreModeDefOf.BestStockpile); } break; case "lookIn": var ingredientZone = (Zone_Stockpile)Current.Game.CurrentMap.zoneManager.AllZones.Find(z => z.label == value); bill.includeFromZone = ingredientZone; break; case "allowedDefs": reflection.AllowedDefs.Clear(); if (value != null) { HashSet <string> expected = new HashSet <string>(value.Split('/')); IEnumerable <ThingDef> all = reflection.AllStorableThingDefs; var expectedContained = from thing in all where expected.Contains(thing.defName) select thing; reflection.AllowedDefs.AddRange(expectedContained.ToList()); } changed = true; break; case "allowedHitPointsPercents": if (!string.IsNullOrEmpty(value) && value.IndexOf(':') != -1) { string[] values = value.Split(':'); float min = float.Parse(values[0]); float max = float.Parse(values[1]); filter.AllowedHitPointsPercents = new FloatRange(min, max); changed = true; } break; case "allowedQualities": if (!string.IsNullOrEmpty(value) && value.IndexOf(':') != -1) { string[] values = value.Split(':'); filter.AllowedQualityLevels = new QualityRange( (QualityCategory)Enum.Parse(typeof(QualityCategory), values[0], true), (QualityCategory)Enum.Parse(typeof(QualityCategory), values[1], true)); changed = true; } break; case "disallowedSpecialFilters": reflection.DisallowedSpecialFilters.Clear(); if (!string.IsNullOrEmpty(value)) { HashSet <string> expected = new HashSet <string>(value.Split('/')); List <SpecialThingFilterDef> l = new List <SpecialThingFilterDef>(); foreach (SpecialThingFilterDef specialDef in DefDatabase <SpecialThingFilterDef> .AllDefs) { if (specialDef != null && specialDef.configurable && expected.Contains(specialDef.defName)) { l.Add(specialDef); } } reflection.DisallowedSpecialFilters = l; } changed = true; break; } } if (changed) { reflection.SettingsChangedCallback(); } return(false); }
private void MergeExceptionsIntoHopperSettings( ThingFilter exceptionFilter ) { //Log.Message( string.Format( "{0}.CompHopperUser.MergeExceptionsIntoHopperSettings( ThingFilter )", this.parent.ThingID ) ); if( !exceptionFilter.ExceptedCategories().NullOrEmpty() ) { foreach( var category in exceptionFilter.ExceptedCategories() ) { var categoryDef = DefDatabase<ThingCategoryDef>.GetNamed( category, true ); foreach( var hopperSetting in hopperSettings ) { hopperSetting.settings.filter.SetAllow( categoryDef, false ); } } } if( !exceptionFilter.ExceptedThingDefs().NullOrEmpty() ) { foreach( var thingDef in exceptionFilter.ExceptedThingDefs() ) { foreach( var hopperSetting in hopperSettings ) { hopperSetting.settings.filter.SetAllow( thingDef, false ); } } } }