private static void SetAllowInCategory(Listing_TreeThingFilter instance, TreeNode_ThingCategory node, bool allow, List <ThingDef> exceptedDefs, List <SpecialThingFilterDef> exceptedFilters) { ThingFilter filter = fieldFilter.GetValue(instance) as ThingFilter; ThingCategoryDef categoryDef = node.catDef; if (!ThingCategoryNodeDatabase.initialized) { Log.Error("SetAllow categories won't work before ThingCategoryDatabase is initialized.", false); } foreach (ThingDef thingDef in categoryDef.DescendantThingDefs) { if ((exceptedDefs == null || !exceptedDefs.Contains(thingDef)) && SearchUtility.CheckVisible(thingDef)) { if (SearchUtility.CheckVisible(thingDef)) { filter.SetAllow(thingDef, allow); } } } foreach (SpecialThingFilterDef specialThingFilterDef in categoryDef.DescendantSpecialThingFilterDefs) { if (exceptedFilters == null || !exceptedFilters.Contains(specialThingFilterDef)) { filter.SetAllow(specialThingFilterDef, allow); } } (fieldSettingsChangedCallback.GetValue(filter) as Action)?.Invoke(); }
public void FindAllValidApparel() { var headgearCategoryDef = ThingCategoryDef.Named(defName: "Headgear"); var fullHead = Defs_Rimworld.Head; var eyes = Defs_Rimworld.Eyes; var allEyeCoveringHeadgearDefs = new HashSet <ThingDef>( collection: DefDatabase <ThingDef> .AllDefsListForReading.FindAll( match: def => def.IsApparel && ((def.thingCategories?.Contains(item: headgearCategoryDef) ?? false) || def.apparel.bodyPartGroups.Any(predicate: bpg => bpg == eyes || bpg == fullHead) || def.HasComp(compType: typeof(Comp_NightVisionApparel))) ) ); var nvApparel = Settings.Store.NVApparel ?? new Dictionary <ThingDef, ApparelVisionSetting>(); //Add defs that have NV comp foreach (ThingDef apparel in allEyeCoveringHeadgearDefs) { if (apparel.comps.Find(match: comp => comp is CompProperties_NightVisionApparel) is CompProperties_NightVisionApparel) { if (!nvApparel.TryGetValue(key: apparel, value: out ApparelVisionSetting setting)) { nvApparel[key : apparel] = new ApparelVisionSetting(apparel : apparel); } else { setting.InitExistingSetting(apparel: apparel); } }
private void CalculateTabs() { tabs.Clear(); List <ThingCategoryDef> allDefsListForReading = DefDatabase <ThingCategoryDef> .AllDefsListForReading; for (int i = 0; i < allDefsListForReading.Count; i++) { ThingCategoryDef category = allDefsListForReading[i]; if (category.parent == ThingCategoryDefOf.Root && AnyTraderWillEverTrade(category)) { if (currentCategory == null) { currentCategory = category; } tabs.Add(new TabRecord(category.LabelCap, delegate { currentCategory = category; pawnsTabOpen = false; }, () => currentCategory == category)); } } tabs.Add(new TabRecord("PawnsTabShort".Translate(), delegate { currentCategory = null; pawnsTabOpen = true; }, () => pawnsTabOpen)); }
public override bool CanEverMatch(ThingDef def) { bool result; if (!def.IsWeapon) { result = false; } else { if (!def.thingCategories.NullOrEmpty <ThingCategoryDef>()) { for (int i = 0; i < def.thingCategories.Count; i++) { for (ThingCategoryDef thingCategoryDef = def.thingCategories[i]; thingCategoryDef != null; thingCategoryDef = thingCategoryDef.parent) { if (thingCategoryDef == ThingCategoryDefOf.Weapons) { return(true); } } } } result = false; } return(result); }
private List <ThingDef> GetSellableItemsInCategory(ThingCategoryDef category, bool pawns) { if (pawns) { if (this.cachedSellablePawns == null) { this.cachedSellablePawns = new List <ThingDef>(); for (int i = 0; i < this.sellableItems.Count; i++) { if (this.sellableItems[i].category == ThingCategory.Pawn) { this.cachedSellablePawns.Add(this.sellableItems[i]); } } } return(this.cachedSellablePawns); } List <ThingDef> list; if (this.cachedSellableItemsByCategory.TryGetValue(category, out list)) { return(list); } list = new List <ThingDef>(); for (int j = 0; j < this.sellableItems.Count; j++) { if (this.sellableItems[j].IsWithinCategory(category)) { list.Add(this.sellableItems[j]); } } this.cachedSellableItemsByCategory.Add(category, list); return(list); }
// create a category def and plop it into the defDB private ThingCategoryDef CreateChildCategory( ThingCategoryDef thisRoot, string bodypart, string label, string type) { // create cat def ThingCategoryDef cat = new ThingCategoryDef { parent = thisRoot, label = label, defName = GetChildCatName(bodypart, label, type) }; DefDatabase <ThingCategoryDef> .Add(cat); // don't forget to call the PostLoad() function, or you'll get swarmed in red... (ugh) cat.PostLoad(); // update parent cat.parent.childCategories.Add(cat); // done! return(cat); }
public static void Postfix(ref ThingFilter __instance, StorageSettingsPreset preset) { if (preset == StorageSettingsPreset.DefaultStockpile) { __instance.SetAllow(ThingCategoryDef.Named("RoadEquipment"), allow: true); } }
private static string DetermineLetterToSend(ThingCategoryDef thingCategoryDef) { if (thingCategoryDef == ThingCategoryDefOf.PlantFoodRaw) { return("MFI_ReverseTradeRequest_Blight"); } switch (Rand.RangeInclusive(min: 0, max: 4)) { case 0: return("MFI_ReverseTradeRequest_Pyro"); case 1: return("MFI_ReverseTradeRequest_Mechs"); case 2: return("MFI_ReverseTradeRequest_Caravan"); case 3: return("MFI_ReverseTradeRequest_Pirates"); case 4: return("MFI_ReverseTradeRequest_Hardship"); default: return("MFI_ReverseTradeRequest_Pyro"); } }
public void BuildEquipmentLists() { thingCategorySweetMeals = DefDatabase <ThingCategoryDef> .GetNamedSilentFail("SweetMeals"); thingCategoryMeatRaw = DefDatabase <ThingCategoryDef> .GetNamedSilentFail("MeatRaw"); thingCategoryBodyPartsArtificial = DefDatabase <ThingCategoryDef> .GetNamedSilentFail("BodyPartsArtificial"); foreach (var def in DefDatabase <ThingDef> .AllDefs) { try { if (def != null) { EquipmentType type = ClassifyThingDef(def); if (type != null && type != TypeDiscard) { AddThingDef(def, type); } } } catch (Exception e) { Log.Warning("Prepare Carefully failed to classify thing definition while building equipment lists: " + def.defName); Log.Message(" Exception: " + e.Message); } } }
private static void AddFilter(ThingCategoryDef rootCategory, string defName, string description, string label, string saveKey, Type type) { SpecialThingFilterDef existing = DefDatabase <SpecialThingFilterDef> .GetNamedSilentFail(defName); if (existing != null) { Log.Error($"Clashed with an existing filter named '{defName}' from '{existing.fileName}' with description '{existing.description}'"); return; } SpecialThingFilterDef freezeFilter = new SpecialThingFilterDef { allowedByDefault = true, configurable = true, defName = defName, description = description, label = label, generated = true, /// ??? parentCategory = rootCategory, saveKey = saveKey, /// ??? workerClass = type, }; DefDatabase <SpecialThingFilterDef> .Add(freezeFilter); }
private ThingDatabase() { //Log.Message("Initializing ThingDatabase..."); thingCategorySweetMeals = DefDatabase <ThingCategoryDef> .GetNamedSilentFail("SweetMeals"); thingCategoryMeatRaw = DefDatabase <ThingCategoryDef> .GetNamedSilentFail("MeatRaw"); }
private static void UnforbidItemsToLoadInCargoBay() { // Unforbid any weapon, apparel, raw food or corpse in the outpost area so it can be carried to a cargo bay. if (OG_Util.FindOutpostArea() != null) { foreach (IntVec3 cell in OG_Util.FindOutpostArea().ActiveCells) { foreach (Thing thing in cell.GetThingList()) { if (thing.def.thingCategories == null) { continue; } if (thing.def.thingCategories.Contains(ThingCategoryDefOf.Apparel) || thing.def.thingCategories.Contains(ThingCategoryDef.Named("Headgear")) || thing.def.thingCategories.Contains(ThingCategoryDef.Named("WeaponsMelee")) || thing.def.thingCategories.Contains(ThingCategoryDef.Named("WeaponsRanged")) || thing.def.thingCategories.Contains(ThingCategoryDef.Named("CorpsesHumanlike")) || thing.def.thingCategories.Contains(ThingCategoryDef.Named("Textiles")) || (thing.def == ThingDef.Named("RawHops")) || (thing.def.thingCategories.Contains(ThingCategoryDef.Named("PlantFoodRaw")) && (thing.def != ThingDef.Named("Hay")))) { thing.SetForbidden(false); } } } } }
private Thing FindIngredient(Pawn pawn, string thirdItem, Building_ItemProcessor building_processor) { if (building_processor.compItemProcessor.Props.isCategoryBuilding) { Predicate <Thing> predicate = (Thing x) => !x.IsForbidden(pawn) && pawn.CanReserve(x, 1, 1, null, false); IntVec3 position = pawn.Position; Map map = pawn.Map; List <Thing> searchSet = new List <Thing>(); foreach (ThingDef thingDef in ThingCategoryDef.Named(thirdItem).childThingDefs) { if (!(DefDatabase <CombinationDef> .GetNamed(building_processor.thisRecipe).disallowedThingDefs != null && DefDatabase <CombinationDef> .GetNamed(building_processor.thisRecipe).disallowedThingDefs.Contains(thingDef.defName))) { searchSet.AddRange(pawn.Map.listerThings.ThingsOfDef(thingDef)); } } TraverseParms traverseParams = TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false); Predicate <Thing> validator = predicate; PathEndMode peMode = PathEndMode.ClosestTouch; return(GenClosest.ClosestThing_Global_Reachable(pawn.Position, pawn.Map, searchSet, peMode, traverseParams, 9999f, validator, null)); } else { Predicate <Thing> predicate = (Thing x) => !x.IsForbidden(pawn) && pawn.CanReserve(x, 1, 1, null, false); IntVec3 position = pawn.Position; Map map = pawn.Map; ThingRequest thingReq = ThingRequest.ForDef(ThingDef.Named(thirdItem)); PathEndMode peMode = PathEndMode.ClosestTouch; TraverseParms traverseParams = TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false); Predicate <Thing> validator = predicate; return(GenClosest.ClosestThingReachable(position, map, thingReq, peMode, traverseParams, 9999f, validator, null, 0, -1, false, RegionType.Set_Passable, false)); } }
private List <ThingDef> GetSellableItemsInCategory(ThingCategoryDef category, bool pawns) { if (pawns) { if (cachedSellablePawns == null) { cachedSellablePawns = new List <ThingDef>(); for (int i = 0; i < sellableItems.Count; i++) { if (sellableItems[i].category == ThingCategory.Pawn) { cachedSellablePawns.Add(sellableItems[i]); } } } return(cachedSellablePawns); } if (cachedSellableItemsByCategory.TryGetValue(category, out List <ThingDef> value)) { return(value); } value = new List <ThingDef>(); for (int j = 0; j < sellableItems.Count; j++) { if (sellableItems[j].IsWithinCategory(category)) { value.Add(sellableItems[j]); } } cachedSellableItemsByCategory.Add(category, value); return(value); }
public static void GenerateSmallRoomWeaponRoom(IntVec3 areaSouthWestOrigin, int zoneAbs, int zoneOrd, Rot4 rotation, ref OG_OutpostData outpostData) { IntVec3 origin = Zone.GetZoneOrigin(areaSouthWestOrigin, zoneAbs, zoneOrd); IntVec3 rotatedOrigin = Zone.GetZoneRotatedOrigin(areaSouthWestOrigin, zoneAbs, zoneOrd, rotation); OG_Common.GenerateEmptyRoomAt(rotatedOrigin + new IntVec3(smallRoomWallOffset, 0, smallRoomWallOffset).RotatedBy(rotation), Genstep_GenerateOutpost.zoneSideSize - 2 * smallRoomWallOffset, Genstep_GenerateOutpost.zoneSideSize - 2 * smallRoomWallOffset, rotation, TerrainDefOf.Concrete, TerrainDef.Named("MetalTile"), ref outpostData); // Spawn weapon racks, weapons and lamps. Building_Storage rack = OG_Common.TrySpawnThingAt(ThingDefOf.EquipmentRack, ThingDefOf.Steel, rotatedOrigin + new IntVec3(smallRoomWallOffset + 1, 0, smallRoomWallOffset + 1).RotatedBy(rotation), true, new Rot4(Rot4.North.AsInt + rotation.AsInt), ref outpostData) as Building_Storage; TrySpawnWeaponOnRack(rack); rack.GetStoreSettings().filter.SetAllow(ThingCategoryDef.Named("WeaponsMelee"), false); rack.GetStoreSettings().Priority = StoragePriority.Critical; rack = OG_Common.TrySpawnThingAt(ThingDefOf.EquipmentRack, ThingDefOf.Steel, rotatedOrigin + new IntVec3(smallRoomWallOffset + 4, 0, smallRoomWallOffset + 1).RotatedBy(rotation), true, new Rot4(Rot4.North.AsInt + rotation.AsInt), ref outpostData) as Building_Storage; TrySpawnWeaponOnRack(rack); rack.GetStoreSettings().filter.SetAllow(ThingCategoryDef.Named("WeaponsMelee"), false); rack.GetStoreSettings().Priority = StoragePriority.Critical; rack = OG_Common.TrySpawnThingAt(ThingDefOf.EquipmentRack, ThingDefOf.Steel, rotatedOrigin + new IntVec3(smallRoomWallOffset + 2, 0, smallRoomWallOffset + 5).RotatedBy(rotation), true, new Rot4(Rot4.South.AsInt + rotation.AsInt), ref outpostData) as Building_Storage; TrySpawnWeaponOnRack(rack); rack.GetStoreSettings().filter.SetAllow(ThingCategoryDef.Named("WeaponsMelee"), false); rack.GetStoreSettings().Priority = StoragePriority.Critical; rack = OG_Common.TrySpawnThingAt(ThingDefOf.EquipmentRack, ThingDefOf.Steel, rotatedOrigin + new IntVec3(smallRoomWallOffset + 5, 0, smallRoomWallOffset + 5).RotatedBy(rotation), true, new Rot4(Rot4.South.AsInt + rotation.AsInt), ref outpostData) as Building_Storage; TrySpawnWeaponOnRack(rack); rack.GetStoreSettings().filter.SetAllow(ThingCategoryDef.Named("WeaponsMelee"), false); rack.GetStoreSettings().Priority = StoragePriority.Critical; OG_Common.TrySpawnLampAt(rotatedOrigin + new IntVec3(smallRoomWallOffset + 1, 0, smallRoomWallOffset + 3).RotatedBy(rotation), Color.white, ref outpostData); OG_Common.TrySpawnLampAt(rotatedOrigin + new IntVec3(smallRoomWallOffset + 5, 0, smallRoomWallOffset + 3).RotatedBy(rotation), Color.white, ref outpostData); // Spawn vertical alley and door. for (int zOffset = smallRoomWallOffset; zOffset <= Genstep_GenerateOutpost.zoneSideSize - smallRoomWallOffset; zOffset++) { Find.TerrainGrid.SetTerrain(rotatedOrigin + new IntVec3(Genstep_GenerateOutpost.zoneSideCenterOffset, 0, zOffset).RotatedBy(rotation), TerrainDef.Named("PavedTile")); } OG_Common.SpawnDoorAt(rotatedOrigin + new IntVec3(Genstep_GenerateOutpost.zoneSideCenterOffset, 0, Genstep_GenerateOutpost.zoneSideSize - smallRoomWallOffset - 1).RotatedBy(rotation), ref outpostData); }
private void TryInsertFirstThing(string item = "") { if (item != "") { building.firstCategory = ThingCategoryDef.Named(item).defName; building.firstItem = building.firstCategory; } else { building.firstItem = things.RandomElement().def.defName; } if (building.compItemProcessor.Props.isSemiAutomaticMachine) { if (building.compPowerTrader != null && !building.compPowerTrader.PowerOn && building.compItemProcessor.Props.noPowerDestroysProgress) { Messages.Message("IP_NoPowerDestroysWarning".Translate(building.def.LabelCap), building, MessageTypeDefOf.NegativeEvent, true); } else if (building.compFuelable != null && !building.compFuelable.HasFuel && building.compItemProcessor.Props.noPowerDestroysProgress) { Messages.Message("IP_NoFuelDestroysWarning".Translate(building.def.LabelCap), building, MessageTypeDefOf.NegativeEvent, true); } else { building.IngredientsChosenBringThemIn(); } } else { building.processorStage = ProcessorStage.IngredientsChosen; } }
public ItemEditor() { resizeable = false; category = DefDatabase <ThingCategoryDef> .GetRandom(); UpdateItemsList(); }
public void Clear() { Type = Types.Unknown; _thingDef = null; _categoryDef = null; _label = null; Count = 1; }
public bool ShowSpoilTime(ThingCategoryDef catDef) { if (!cacheShowSpoilTime.ContainsKey(catDef)) { cacheShowSpoilTime[catDef] = CalculateShowSpoilTime(catDef); } return(cacheShowSpoilTime[catDef]); }
static bool ThingFilter_SetAllow(ThingCategoryDef categoryDef, bool allow) { if (SyncMarkers.DrawnThingFilter == null) { return(true); } return(!AllowCategory.DoSync(SyncMarkers.DrawnThingFilter, categoryDef, allow)); }
public void GenerateStrangeMeatRecipe() { if (LoadedModManager.RunningMods.Any(x => x.Name.Contains("Cosmic Horrors")) && !AreRecipesReady) { //Not really, but hey, let's get started. AreRecipesReady = true; //We want to use strange meat to make wax. RecipeDef recipeMakeWax = DefDatabase <RecipeDef> .AllDefs.FirstOrDefault((RecipeDef d) => d.defName == "Jecrell_MakeWax"); if (recipeMakeWax != null) { ThingFilter newFilter = new ThingFilter(); newFilter.CopyAllowancesFrom(recipeMakeWax.fixedIngredientFilter); newFilter.SetAllow(ThingCategoryDef.Named("ROM_StrangeMeatRaw"), true); recipeMakeWax.fixedIngredientFilter = newFilter; ThingFilter newFilter2 = new ThingFilter(); newFilter2.CopyAllowancesFrom(recipeMakeWax.defaultIngredientFilter); newFilter2.SetAllow(ThingCategoryDef.Named("ROM_StrangeMeatRaw"), true); recipeMakeWax.defaultIngredientFilter = newFilter; foreach (IngredientCount temp in recipeMakeWax.ingredients) { if (temp.filter != null) { ThingFilter newFilter3 = new ThingFilter(); newFilter3.CopyAllowancesFrom(temp.filter); newFilter3.SetAllow(ThingCategoryDef.Named("ROM_StrangeMeatRaw"), true); temp.filter = newFilter3; Log.Message("Added new filter"); } } Log.Message("Strange meat added to wax recipes."); } //I want stoves to be able to cook strange meals too. ThingDef stoveDef = DefDatabase <ThingDef> .AllDefs.FirstOrDefault((ThingDef def) => def.defName == "WoodStoveFurnace"); if (stoveDef != null) { if (stoveDef.recipes.FirstOrDefault((RecipeDef def) => def.defName == "ROM_CookStrangeMealSimple") == null) { stoveDef.recipes.Add(DefDatabase <RecipeDef> .GetNamed("ROM_CookStrangeMealSimple")); } if (stoveDef.recipes.FirstOrDefault((RecipeDef def) => def.defName == "ROM_CookStrangeMealFine") == null) { stoveDef.recipes.Add(DefDatabase <RecipeDef> .GetNamed("ROM_CookStrangeMealFine")); } if (stoveDef.recipes.FirstOrDefault((RecipeDef def) => def.defName == "ROM_CookStrangeMealLavish") == null) { stoveDef.recipes.Add(DefDatabase <RecipeDef> .GetNamed("ROM_CookStrangeMealLavish")); } Log.Message("Strange meal recipes added to WoodStoveFurnace defs"); } } return; }
public static List <ThingCategoryDef> GetValidChildCategories(ThingCategoryDef categoryDef, List <ThingCategoryDef> validCategories) { if (categoryDef.childCategories == null) { return(new List <ThingCategoryDef>()); } return(categoryDef.childCategories.Where(category => validCategories.Contains(category)).ToList()); }
static BlackFuelUtil() { carbonThingCategory = DefDatabase <ThingCategoryDef> .GetNamed("Carbon", false); if (carbonThingCategory == null) { Log.Error("No thingCategory 'Carbon' was found! BlackFuel mod will NOT function correctly."); } }
static Base() { using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Program Files (x86)\Steam\steamapps\common\RimWorld\Mods\researchprojects.csv")) { ThingCategoryDef bp = DefDatabase <ThingCategoryDef> .GetNamed("BuildingsProduction"); foreach (ResearchProjectDef rpd in DefDatabase <ResearchProjectDef> .AllDefsListForReading) { if (rpd.UnlockedDefs.Any(delegate(Def d) { ThingDef td = d as ThingDef; if (td != null) { return(td.IsWeapon || td.IsApparel || (td.building != null && (td.building.buildingTags != null && td.building.buildingTags.Contains("Production") || td.thingCategories != null && td.thingCategories.Contains(bp)))); } return(false); })) { file.WriteLine(rpd.defName + "," + rpd.label + "," + rpd.modContentPack); } } } foreach (RecipeDef recipe in DefDatabase <RecipeDef> .AllDefsListForReading) { ResearchProjectDef rpd = DArcaneTechnology.Base.GetBestRPDForRecipe(recipe); if (rpd != null && recipe.ProducedThingDef != null) { ThingDef producedThing = recipe.ProducedThingDef; thingDic.SetOrAdd(producedThing, rpd); List <ThingDef> things; if (researchDic.TryGetValue(rpd, out things)) { things.Add(producedThing); } else { researchDic.Add(rpd, new List <ThingDef> { producedThing }); } } } GearAssigner.HardAssign(ref thingDic, ref researchDic); using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Program Files (x86)\Steam\steamapps\common\RimWorld\Mods\unassignedgear.csv")) { var thingList = DefDatabase <ThingDef> .AllDefsListForReading; foreach (ThingDef thing in thingList) { ResearchProjectDef rpd = thingDic.TryGetValue(thing); if ((thing.IsWeapon || thing.IsApparel) && rpd == null) { file.WriteLine(thing.defName + "," + thing.label + "," + thing.modContentPack); } } } }
private bool BelongsToCategory(ThingDef def, ThingCategoryDef categoryDef) { if (categoryDef == null || def.thingCategories == null) { return(false); } return(def.thingCategories.FirstOrDefault(d => categoryDef == d) != null); }
public static IEnumerable <ThingCategoryDef> ThisAndParents(this ThingCategoryDef cat) { yield return(cat); foreach (ThingCategoryDef def in cat.Parents) { yield return(def); } }
public static void HijackDef(ThingDef def, ThingCategoryDef tc, ThingCategoryDef newCat = null) { def.thingCategories.Remove(tc); tc.childThingDefs.Remove(def); if (newCat != null) { def.thingCategories.Add(newCat); newCat.childThingDefs.Add(def); } }
public static List <Thing> GetAllStoredFood() { return(Find.Maps.SelectMany(map => map.spawnedThings) .Where(thing => thing.Spawned && thing.IsInValidStorage() && thing.def.IsIngestible && thing.def.thingCategories.Contains(ThingCategoryDef.Named("FoodMeals"))) .OrderBy(thing => thing.thingIDNumber) .ToList()); }
/// <summary> /// Calculate the total number of ingredients needed to fully repair an item. /// </summary> /// <param name="itemDamaged">The item to be repaired.</param> /// <returns></returns> internal static List <ThingDefCount> CalculateTotalIngredients(Thing itemDamaged) { List <ThingDefCount> totalCost; switch (Settings.ResourceMode) { case ResourceModes.REPAIR_KIT: totalCost = new List <ThingDefCount>(1); int hpPerPack; if (Settings.HpPercentage) { hpPerPack = (int)Math.Floor(itemDamaged.MaxHitPoints * (Settings.HpPerPack / 100.0f)); if (hpPerPack == 0) { hpPerPack = 100; Log.Error($"RepairBench Error: Thing={itemDamaged}, MaxHitPoints={itemDamaged.MaxHitPoints}, Settings.HpPerPack={Settings.HpPerPack}, hpPercentage=true, hpPerPack=0%, did you put bad values in the config?"); } } else { hpPerPack = Settings.HpPerPack; } var kitsToFetch = (itemDamaged.MaxHitPoints - itemDamaged.HitPoints) / hpPerPack; totalCost.Add(new ThingDefCount(ThingDef.Named(Settings.THINGDEF_REPKIT), kitsToFetch)); break; case ResourceModes.INGREDIENTS: //tmpTotalCost is cached, DO NOT MODIFY IT var tmpFullCost = itemDamaged.CostListAdjusted(); totalCost = new List <ThingDefCount>(tmpFullCost.Count); foreach (var thingCount in tmpFullCost) { var origCount = thingCount.count; var damPercent = (itemDamaged.MaxHitPoints - itemDamaged.HitPoints) / (float)itemDamaged.MaxHitPoints; var amountPct = thingCount.thingDef.IsWithinCategory(ThingCategoryDef.Named("ResourcesRaw"))? 0.75f: 0.33f; var newCount = (int)Math.Floor(origCount * damPercent * amountPct * Settings.INGRED_REPAIR_PERCENT); Debug.PrintLine($"Thing={itemDamaged.LabelNoCount}, mat={thingCount.thingDef}, origCount: {origCount} | damPer:{damPercent} | newCount:{newCount}"); if (newCount > 0) { totalCost.Add(new ThingDefCount(thingCount.thingDef, newCount)); } } break; default: return(new List <ThingDefCount>(0)); } return(totalCost); }
public static bool ThingHasThingCategoryDef( Thing t, ThingCategoryDef c ) { if( t == null ) return false; if( t.def.thingCategories == null ) return false; foreach( ThingCategoryDef curCategory in t.def.thingCategories ) { if( curCategory == c ) return true; } return false; }
private static bool CalculateShowSpoilTime(ThingCategoryDef catDef) { foreach (ThingDef descendantThingDef in catDef.DescendantThingDefs) { if (descendantThingDef.HasComp(typeof(CompRottable))) { return(true); } } return(false); }
// create a category def and plop it into the defDB private ThingCategoryDef CreateCategory( string label, string type ) { // create cat def ThingCategoryDef cat = new ThingCategoryDef(); cat.parent = apparelRoot; cat.label = label; cat.defName = GetCatName( label, type ); DefDatabase<ThingCategoryDef>.Add( cat ); // don't forget to call the PostLoad() function, or you'll get swarmed in red... (ugh) cat.PostLoad(); // update parent cat.parent.childCategories.Add( cat ); // done! return cat; }
public HopperSettingsAmount( ThingCategoryDef categoryDef, float count ) { this.fixedCategoryDef = categoryDef; this.fixedThingDef = null; this.fixedCount = Mathf.CeilToInt( count ); }
public static void AddToList( List<HopperSettingsAmount> list, ThingCategoryDef categoryDef, float baseCount, RecipeDef recipe ) { int countNeeded = CountForCategoryDef( categoryDef, baseCount, recipe ); for( int index = 0; index < list.Count; ++index ) { if( list[ index ].fixedCategoryDef == categoryDef ) { if( countNeeded > list[ index ].fixedCount ) { list[ index ] = new HopperSettingsAmount( list[ index ].fixedCategoryDef, countNeeded ); } return; } } list.Add( new HopperSettingsAmount( categoryDef, countNeeded ) ); }
public static int CountForCategoryDef( ThingCategoryDef categoryDef, float baseCount, RecipeDef recipe ) { int largest = 0; foreach( var thingDef in categoryDef.DescendantThingDefs ) { int thisThingCount = CountForThingDef( thingDef, baseCount, recipe ); if( thisThingCount > largest ) { largest = thisThingCount; } } foreach( var childCategoryDef in categoryDef.childCategories ) { int thisCategoryCount = CountForCategoryDef( childCategoryDef, baseCount, recipe ); if( thisCategoryCount > largest ) { largest = thisCategoryCount; } } return largest; }
public void Set() { try { // get the (main) product if ( _recipe.products != null && _recipe.products.Count > 0 && _recipe.products.First().thingDef.BaseMarketValue > 0 ) { Clear(); _thingDef = _recipe.products.First().thingDef; Type = Types.Thing; Count = _recipe.products.First().count; return; } // no main, is there a special? if ( _recipe.specialProducts == null ) { Clear(); Type = Types.None; Count = 0; } if ( _recipe.specialProducts != null && _recipe.specialProducts.Count > 0 ) { // get the first special product of the first thingdef allowed by the fixedFilter. if ( _recipe.defaultIngredientFilter.AllowedThingDefs == null ) { throw new Exception( "AllowedThingDefs NULL" ); } ThingDef allowedThingDef = _recipe.fixedIngredientFilter.AllowedThingDefs.DefaultIfEmpty( null ).FirstOrDefault(); if ( allowedThingDef == null ) { throw new Exception( "AllowedThingDef NULL" ); } if ( _recipe.specialProducts[0] == SpecialProductType.Butchery ) { if ( allowedThingDef.butcherProducts != null && allowedThingDef.butcherProducts.Count > 0 ) { // butcherproducts are defined, no problem. List<ThingCount> butcherProducts = allowedThingDef.butcherProducts; if ( butcherProducts.Count == 0 ) { throw new Exception( "No butcherproducts defined: " + allowedThingDef.defName ); } Clear(); _thingDef = butcherProducts.First().thingDef; Type = Types.Thing; Count = butcherProducts.First().count; return; } // still not defined, see if we can catch corpses. if ( allowedThingDef.defName.Contains( "Corpse" ) && !allowedThingDef.defName.Contains( "Mechanoid" ) ) { // meat for non-mech corpses Clear(); _categoryDef = ThingCategoryDef.Named( "MeatRaw" ); Type = Types.Category; Count = 50; } else if ( allowedThingDef.defName.Contains( "Corpse" ) && allowedThingDef.defName.Contains( "Mechanoid" ) ) { // plasteel for mech corpses Clear(); _thingDef = ThingDef.Named( "Plasteel" ); Type = Types.Thing; Count = 20; } else { Clear(); return; } } if ( _recipe.specialProducts[0] == SpecialProductType.Smelted ) { if ( allowedThingDef.smeltProducts == null ) { Clear(); return; } List<ThingCount> smeltingProducts = allowedThingDef.smeltProducts; if ( smeltingProducts.Count == 0 ) { Clear(); return; } Clear(); _thingDef = smeltingProducts.First().thingDef; Type = Types.Thing; Count = smeltingProducts.First().count; if ( _thingDef == null ) { Clear(); } } } } // ReSharper disable once UnusedVariable catch ( Exception e ) { #if DEBUG Log.Warning( e.Message ); #endif Clear(); } }