using System; using System.Collections.Generic; using RimWorld; using Verse; namespace BlaxLaws { /// /// The overlap icon of the lawbook (design: "Lawbook tab", row spec, and "One act, one case"): a row /// that can catch the same act as a row of another category. Outside a break each category files its /// own case, so a dose can open an "Ate" case and a "Recorded acts" case at once; the icon says so. /// /// Only did-it rows outside the breaks take part: inside a break the break case owns the act. Rows that /// are off or whose entry is missing catch nothing and are left out. The pairs come from what one game /// act records in each category, read from the game code: /// /// - Ate and Recorded acts: Thing.Ingested records the eating events (Verse/Thing.cs:2031-2129) and /// CompDrug.PostIngested the drug events (RimWorld/CompDrug.cs:105-113) for the eater as doer. /// - Ate and Records: the ingest toil adds the nutrition eaten (RimWorld/Toils_Ingest.cs:432). /// - Bills and Records: a finished bill counts meals cooked or things crafted /// (RimWorld/RecordsUtility.cs:52-75), a surgery the operations performed (RimWorld/Bill_Medical.cs:138). /// /// Cached per lawbook write (Watch.Version) and catalogue build; the tab reads it every frame. /// public static class ActOverlaps { private static readonly List None = new List(); private static readonly Dictionary> byLaw = new Dictionary>(); private static readonly Dictionary pairCache = new Dictionary(); private static int cachedWatch = -1; private static int cachedCatalogue = -1; private static int cachedCount = -1; // The game the cache belongs to, by identity hash, so the cache never keeps a finished game alive. private static int cachedComp; /// The rows of other categories that can catch the same act as this row. Empty when none. public static IReadOnlyList Of(Law law) { if (law == null) return None; Refresh(); return byLaw.TryGetValue(law, out List list) ? list : None; } /// Whether the row takes part in overlaps at all: on, resolving, did it, outside the breaks. public static bool Counts(Law law) { if (law == null || !law.enabled || law.stage != LawStage.DidIt) return false; ActEntry e = law.Entry; return e != null && !e.IsBreak && e.HasStage(LawStage.DidIt); } /// Whether one game act can be caught by both entries (different categories only). public static bool Overlap(ActEntry a, ActEntry b) { if (a == null || b == null || a.categoryId == b.categoryId) return false; string key = string.CompareOrdinal(a.key, b.key) < 0 ? a.key + "|" + b.key : b.key + "|" + a.key; if (pairCache.TryGetValue(key, out bool known)) return known; bool result = HookGuard.Run("Overlap " + key, () => Compute(a, b), false); pairCache[key] = result; return result; } /// Drops the cache. The next read builds it again. public static void Reset() { byLaw.Clear(); pairCache.Clear(); cachedWatch = -1; } private static void Refresh() { IReadOnlyList laws = Lawbook.Laws; GameComponent_BlaxLaws instance = GameComponent_BlaxLaws.Instance; int comp = instance == null ? 0 : System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(instance); if (cachedWatch == Watch.Version && cachedCatalogue == ActCatalogue.Version && cachedCount == laws.Count && cachedComp == comp) return; cachedWatch = Watch.Version; cachedCount = laws.Count; cachedComp = comp; if (cachedCatalogue != ActCatalogue.Version) { pairCache.Clear(); cachedCatalogue = ActCatalogue.Version; } byLaw.Clear(); for (int i = 0; i < laws.Count; i++) { Law a = laws[i]; if (!Counts(a)) continue; for (int j = i + 1; j < laws.Count; j++) { Law b = laws[j]; if (!Counts(b) || !Overlap(a.Entry, b.Entry)) continue; Add(a, b); Add(b, a); } } } private static void Add(Law of, Law other) { if (!byLaw.TryGetValue(of, out List list)) byLaw[of] = list = new List(); list.Add(other); } private static bool Compute(ActEntry a, ActEntry b) { if (Is(a, b, ActCategories.Ate, ActCategories.RecordedAct, out ActEntry ate, out ActEntry rec)) return Any(ate, rec, (t, e) => t is ThingDef td && e is HistoryEventDef ev && IngestionRecords(td, ev)); if (Is(a, b, ActCategories.Ate, ActCategories.Record, out ate, out rec)) return Any(ate, rec, (t, r) => t is ThingDef td && r is RecordDef rd && rd == RecordDefOf.NutritionEaten && td.IsNutritionGivingIngestible); if (Is(a, b, ActCategories.Bill, ActCategories.Record, out ActEntry bill, out rec)) return Any(bill, rec, (x, r) => x is RecipeDef recipe && r is RecordDef rd && BillCounts(recipe, rd)); return false; } private static bool Is(ActEntry a, ActEntry b, string catA, string catB, out ActEntry first, out ActEntry second) { if (a.categoryId == catA && b.categoryId == catB) { first = a; second = b; return true; } if (b.categoryId == catA && a.categoryId == catB) { first = b; second = a; return true; } first = second = null; return false; } /// True when some member def of a and some member def of b make the pair. private static bool Any(ActEntry a, ActEntry b, Func pair) { List mb = Members(b); if (mb.Count == 0) return false; foreach (Def da in Members(a)) { for (int i = 0; i < mb.Count; i++) { if (pair(da, mb[i])) return true; } } return false; } /// The defs an entry covers: its def, or every def entry of its category the group matches. public static List Members(ActEntry e) { var result = new List(); if (e == null) return result; if (e.def != null) { result.Add(e.def); return result; } ActGroup g = e.group; if (g == null) return result; foreach (ActEntry d in ActCatalogue.EntriesOf(e.categoryId)) { if (d.def == null) continue; bool member; try { member = g.IsAny || g.MatchesDef(d.def); } catch (Exception ex) { HookGuard.Fail("Overlap group " + g.Key, ex); member = false; } if (member) result.Add(d.def); } return result; } /// /// Whether eating a thing of this def can record the event with the eater as doer. Def-level, so it /// says "can": a meal records human meat only when one of its ingredients is. /// public static bool IngestionRecords(ThingDef t, HistoryEventDef ev) { if (t?.ingestible == null || ev == null) return false; if (t.ingestible.ateEvent == ev) return true; bool drug = t.GetCompProperties() != null; bool ingredients = t.HasComp(typeof(CompIngredients)); bool humanMeat = HumanlikeMeatOrCorpse(t); bool rawPlant = t.thingCategories != null && t.thingCategories.Contains(ThingCategoryDefOf.PlantFoodRaw); bool meat = t.IsMeat || t.IsCorpse; switch (ev.defName) { // RimWorld/CompDrug.cs:105-113 case "IngestedDrug": return drug; case "IngestedHardDrug": return drug && t.ingestible.drugCategory == DrugCategory.Hard; case "IngestedRecreationalDrug": return drug && t.IsNonMedicalDrug; // Verse/Thing.cs:2031-2045, 2089-2104 case "AteHumanMeat": return humanMeat || ingredients; case "AteHumanMeatDirect": return humanMeat; case "AteHumanMeatAsIngredient": case "AteInsectMeatAsIngredient": case "AteFungusAsIngredient": case "AteNonFungusMealWithPlants": return ingredients; // Verse/Thing.cs:2046-2049 case "AteNonCannibalFood": return t.IsNutritionGivingIngestible && !humanMeat; // Verse/Thing.cs:2055-2071 case "AteMeat": return meat && !t.IsProcessedFood && !humanMeat; case "AteNonMeat": return !meat && !t.IsProcessedFood && !t.IsDrug && t.IsNutritionGivingIngestible; // Verse/Thing.cs:2072-2086 case "AteVeneratedAnimalMeat": return meat || ingredients; case "AteFungus": case "AteNonFungusPlant": return rawPlant; default: return false; } } private static bool HumanlikeMeatOrCorpse(ThingDef t) { if (t.IsCorpse) return t.ingestible?.sourceDef?.race?.Humanlike ?? false; return FoodUtility.GetMeatSourceCategory(t) == MeatSourceCategory.Humanlike; } /// Whether finishing one iteration of the recipe raises the record for the doer. public static bool BillCounts(RecipeDef recipe, RecordDef record) { if (recipe == null || record == null) return false; if (record == RecordDefOf.OperationsPerformed) return recipe.IsSurgery; if (recipe.products == null) return false; foreach (ThingDefCountClass p in recipe.products) { ThingDef d = p?.thingDef; if (d == null) continue; // RimWorld/RecordsUtility.cs:58-65 and ShouldIncrementThingsCrafted :69-75 bool meal = d.IsNutritionGivingIngestible && (int)d.ingestible.preferability >= 7; if (meal && record == RecordDefOf.MealsCooked) return true; if (!meal && record == RecordDefOf.ThingsCrafted && (d.IsApparel || d.IsWeapon || d.HasComp(typeof(CompArt)) || d.HasComp(typeof(CompQuality)))) return true; } return false; } } }