using System; using System.Collections.Generic; using RimWorld; using RimWorld.Planet; using UnityEngine; using Verse; using Verse.AI; namespace BlaxZones { /// /// Package Rules: the reach cache per district, the unusable cells per delivery zone, the red /// overlay while a zone is selected and the inspect line "N cells drop pods can't use". /// /// Reach entries are keyed by the District object and stamped with the tick and the district's /// lastChangeTick. Vanilla reuses a District when walls go up next to it and stamps it then /// (RegionAndRoomUpdater.cs:307-314, District.cs:245), so a changed district is never trusted, and /// any entry is dropped once it is DeliveryRules.ReachMaxAgeTicks old (colonists walled off /// elsewhere change no district of the zone). /// /// Unusable cells are cached only for the selected delivery zone, the one the overlay and the /// inspect pane read every frame. It is recomputed, reach included, when it gets selected and every /// DeliveryRules.SelectedRecheckTicks while it stays selected. Any other zone is computed on demand. /// public partial class MapComponent_BlaxZones { /// The overlay color: red, like vanilla's invalid-cell outlines. private static readonly Color UnusableCellColor = Color.red; private readonly struct ReachKey : IEquatable { public readonly District district; public readonly PathEndMode mode; public ReachKey(District district, PathEndMode mode) { this.district = district; this.mode = mode; } // District doesn't override Equals, so this is reference equality: a rebuilt district is a new key. public bool Equals(ReachKey other) => ReferenceEquals(district, other.district) && mode == other.mode; public override bool Equals(object obj) => obj is ReachKey other && Equals(other); public override int GetHashCode() => (district.GetHashCode() * 397) ^ (int)mode; } private struct ReachEntry { public bool canReach; public int stamp; public int districtChangeTick; } private sealed class UnusableEntry { public readonly List cells = new List(); public int stamp; } private readonly Dictionary reachCache = new Dictionary(); private readonly Dictionary unusableCache = new Dictionary(); private readonly HashSet refreshedDistricts = new HashSet(); private readonly List expiredReach = new List(); private Zone_Delivery lastSelectedZone; private static int Now => Find.TickManager?.TicksGame ?? 0; /// /// The cached reach rule result for a district and path end mode, if fresh (younger than /// DeliveryRules.ReachMaxAgeTicks). False when there is no fresh entry. /// public bool TryGetCachedReach(District district, PathEndMode mode, out bool canReach) { canReach = false; if (district == null) return false; var key = new ReachKey(district, mode); if (!reachCache.TryGetValue(key, out ReachEntry entry)) return false; if (Now - entry.stamp >= DeliveryRules.ReachMaxAgeTicks || entry.districtChangeTick != district.lastChangeTick) { reachCache.Remove(key); return false; } canReach = entry.canReach; return true; } /// Stores a reach rule result for a district and path end mode, stamped with the current tick. public void StoreReach(District district, PathEndMode mode, bool canReach) { if (district == null) return; reachCache[new ReachKey(district, mode)] = new ReachEntry { canReach = canReach, stamp = Now, districtChangeTick = district.lastChangeTick, }; } /// /// The zone's cells drop pods can't use (failing DeliveryRules.PodCellOk), cached per zone, /// recomputed every DeliveryRules.SelectedRecheckTicks while the zone is selected. The list /// of the selected zone is the cache itself: read it, never change it. /// public List UnusableCells(Zone_Delivery zone) { if (zone == null || zone.MapOrNull != map) return new List(); if (zone != SelectedDeliveryZone()) return ComputeUnusable(zone, refreshReach: false, new List()); if (!unusableCache.TryGetValue(zone, out UnusableEntry entry) || Now - entry.stamp >= DeliveryRules.ReachMaxAgeTicks) entry = RefreshUnusable(zone); return entry.cells; } /// Count of UnusableCells(zone). public int UnusableCellCount(Zone_Delivery zone) => UnusableCells(zone).Count; /// /// The Rules line for Zone_Delivery.GetInspectString: "N cells drop pods can't use" /// (key BlaxZones_UnusableCells in BlaxZones_Rules.xml), or null when every cell is usable. /// public string InspectLineFor(Zone_Delivery zone) { int count = UnusableCellCount(zone); if (count <= 0) return null; if (count == 1) return "BlaxZones_UnusableCell".Translate().Resolve(); return "BlaxZones_UnusableCells".Translate(count).Resolve(); } /// Every tick: recompute the selected delivery zone's unusable cells every SelectedRecheckTicks. private void TickRules() { int now = Now; if (now % DeliveryRules.ReachMaxAgeTicks == 0) DropExpiredReach(now); Zone_Delivery zone = SelectedDeliveryZone(); if (zone == null) { lastSelectedZone = null; return; } if (zone != lastSelectedZone || !unusableCache.TryGetValue(zone, out UnusableEntry entry) || now - entry.stamp >= DeliveryRules.SelectedRecheckTicks) { RefreshUnusable(zone); } lastSelectedZone = zone; } /// Every frame: GenDraw.DrawFieldEdges over the selected delivery zone's unusable cells, in red. private void UpdateOverlay() { // MapComponentUpdate runs for every map, also while the world is shown (Map.cs:1154-1202). if (!WorldRendererUtility.DrawingMap) return; Zone_Delivery zone = SelectedDeliveryZone(); if (zone == null) { lastSelectedZone = null; return; } // Selected while paused: no tick comes, so the overlay recomputes on the first frame. if (zone != lastSelectedZone || !unusableCache.TryGetValue(zone, out UnusableEntry entry)) entry = RefreshUnusable(zone); lastSelectedZone = zone; if (entry.cells.Count > 0) GenDraw.DrawFieldEdges(entry.cells, UnusableCellColor); } /// Drops the zone's unusable-cell cache (its cells changed or it was deregistered). private void DropRuleCaches(Zone_Delivery zone) { if (zone == null) return; unusableCache.Remove(zone); if (lastSelectedZone == zone) lastSelectedZone = null; } /// Drops every Rules cache (FinalizeInit, MapRemoved). private void ClearRuleCaches() { reachCache.Clear(); unusableCache.Clear(); refreshedDistricts.Clear(); expiredReach.Clear(); lastSelectedZone = null; } /// The selected delivery zone if it lies on this map and this map is shown, else null. private Zone_Delivery SelectedDeliveryZone() { if (Current.ProgramState != ProgramState.Playing || !(Find.UIRoot is UIRoot_Play) || Find.CurrentMap != map) return null; Zone_Delivery zone = Find.Selector.SelectedZone as Zone_Delivery; return zone != null && zone.MapOrNull == map ? zone : null; } /// Recomputes and caches the zone's unusable cells, rechecking the reach of each of its districts once. private UnusableEntry RefreshUnusable(Zone_Delivery zone) { if (!unusableCache.TryGetValue(zone, out UnusableEntry entry)) { entry = new UnusableEntry(); unusableCache[zone] = entry; } ComputeUnusable(zone, refreshReach: true, entry.cells); entry.stamp = Now; return entry; } /// /// Fills the list with the zone's cells failing the pod rule. With refreshReach, the first cell /// of each district drops that district's reach entry, so the reach rule runs once per district. /// private List ComputeUnusable(Zone_Delivery zone, bool refreshReach, List into) { into.Clear(); refreshedDistricts.Clear(); try { List cells = zone.Cells; for (int i = 0; i < cells.Count; i++) { IntVec3 c = cells[i]; if (refreshReach && c.InBounds(map)) { District district = c.GetDistrict(map); if (district != null && refreshedDistricts.Add(district)) reachCache.Remove(new ReachKey(district, PathEndMode.OnCell)); } if (!DeliveryRules.PodCellOk(map, c)) into.Add(c); } } finally { refreshedDistricts.Clear(); } return into; } private void DropExpiredReach(int now) { if (reachCache.Count == 0) return; expiredReach.Clear(); foreach (KeyValuePair kv in reachCache) { if (now - kv.Value.stamp >= DeliveryRules.ReachMaxAgeTicks) expiredReach.Add(kv.Key); } for (int i = 0; i < expiredReach.Count; i++) reachCache.Remove(expiredReach[i]); expiredReach.Clear(); } } }