using System;
using System.Collections.Generic;
using HarmonyLib;
using RimWorld;
using Verse;
namespace BlaxZones
{
///
/// Package Store. Design: "Zone store, safe to remove from a save" and 1.0 "Save-safe zone storage".
/// Blax zones never enter ZoneManager's save list: the save prefix swaps allZones for a filtered
/// copy and the finalizer puts the original list object back, even if saving throws. On load the
/// Map.FinalizeLoading prefix re-registers the zones the component loaded.
///
///
/// No static field here has an initializer, so the class has no type initializer: a reflection bind
/// that fails can never make ZoneStore.Loading throw TypeInitializationException in the load hook.
/// Every bind happens on first use, inside the callers' try/catch.
///
public static class ZoneStore
{
private static AccessTools.FieldRef> allZonesRef;
private static bool allZonesBindFailed;
///
/// ZoneManager's private allZones (ZoneManager.cs:9), bound on first use. Null when the field can't
/// be bound (logged once); the save filter then filters the public AllZones list in place.
///
public static AccessTools.FieldRef> AllZonesRef
{
get
{
if (ZonesTestHooks.AllZonesUnbound)
return null;
if (allZonesRef == null && !allZonesBindFailed)
{
try
{
allZonesRef = AccessTools.FieldRefAccess>("allZones");
}
catch (Exception e)
{
ZonesLog.Once("Binding ZoneManager.allZones", e);
}
allZonesBindFailed = allZonesRef == null;
}
return allZonesRef;
}
}
///
/// True while the Map.FinalizeLoading prefix registers loaded zones, set in the prefix and cleared
/// in its finalizer. RemoveCell must not unclaim or destroy beds (1.2) while it is set.
///
[ThreadStatic] public static bool Loading;
// The internal grid setters (ZoneManager.cs:68, 73). Bound on first use, so a renamed method
// breaks loading only, never the save filter.
private static Action addZoneGridCell;
private static Action clearZoneGridCell;
private static Action AddZoneGridCell =>
addZoneGridCell ??= AccessTools.MethodDelegate>(
AccessTools.Method(typeof(ZoneManager), "AddZoneGridCell", new[] { typeof(Zone), typeof(IntVec3) }));
private static Action ClearZoneGridCell =>
clearZoneGridCell ??= AccessTools.MethodDelegate>(
AccessTools.Method(typeof(ZoneManager), "ClearZoneGridCell", new[] { typeof(IntVec3) }));
///
/// Is this one of ours: a zone whose class, or a base class below Zone, comes from this assembly.
/// A subclass another mod derives from a Blax zone needs Blax Zones to load just the same, so it
/// is saved with ours.
///
public static bool IsBlaxZone(Zone zone)
{
if (zone == null)
return false;
for (Type t = zone.GetType(); t != null && t != typeof(Zone); t = t.BaseType)
{
if (t.Assembly == typeof(ZoneStore).Assembly)
return true;
}
return false;
}
///
/// Registers one loaded zone with the map: sets zone.zoneManager, calls the public
/// ZoneManager.RegisterZone (ZoneManager.cs:52), then the internal AddZoneGridCell
/// (ZoneManager.cs:68) per cell through an AccessTools delegate, and marks the zone mesh dirty.
/// Cells outside the map or already held by another zone are dropped first, so the grid keeps
/// one zone per cell; a zone left with no cells is not registered and is never saved again.
/// Things are not checked here: the thingGrid is still empty, and vanilla's spawn loop trims
/// our zones as it trims stockpiles (ZoneManager.cs:97-112).
///
public static void RegisterLoaded(Map map, Zone zone)
{
if (map == null || zone == null)
return;
ZoneManager manager = map.zoneManager;
if (manager == null)
throw new InvalidOperationException("map " + map + " has no zoneManager");
if (manager.AllZones.Contains(zone))
return;
zone.cells ??= new List();
zone.cells.RemoveAll(c => !c.InBounds(map) || (manager.ZoneAt(c) != null && manager.ZoneAt(c) != zone));
if (zone.cells.Count == 0)
return;
zone.zoneManager = manager;
manager.RegisterZone(zone);
Action add = AddZoneGridCell;
List cells = zone.cells;
for (int i = 0; i < cells.Count; i++)
add(manager, zone, cells[i]);
// A no-op while loading (MapDrawer.cs:68); Map.FinalizeInit regenerates every mesh anyway (Map.cs:834-837).
if (map.mapDrawer != null)
{
for (int i = 0; i < cells.Count; i++)
map.mapDrawer.MapMeshDirty(cells[i], MapMeshFlagDefOf.Zone);
}
}
///
/// Takes a zone whose registration threw back out of the manager and the grid, so a half-registered
/// zone is never saved or drawn. Never throws.
///
internal static void UndoRegister(Map map, Zone zone)
{
if (map?.zoneManager == null || zone == null)
return;
try
{
ZoneManager manager = map.zoneManager;
// AllZones is allZones itself (ZoneManager.cs:13); DeregisterZone would run PostDeregister.
manager.AllZones?.Remove(zone);
if (zone.cells != null)
{
foreach (IntVec3 c in zone.cells)
{
if (c.InBounds(map) && manager.ZoneAt(c) == zone)
ClearZoneGridCell(manager, c);
}
}
}
catch
{
// Best effort inside a catch that already logged.
}
}
}
/// What the save prefix changed in one ZoneManager, so the finalizer undoes exactly that.
public sealed class ZoneSaveState
{
/// The list object allZones held before the save.
public List list;
/// The bound field the prefix swapped a filtered copy into; null when it filtered list in place.
public AccessTools.FieldRef> swappedVia;
/// The list's full contents before an in-place filter; null after a swap.
public List contents;
public void Restore(ZoneManager manager)
{
if (swappedVia != null)
{
swappedVia(manager) = list;
return;
}
list.Clear();
list.AddRange(contents);
}
}
/// Save: drop Blax zones from ZoneManager's list while it is written, restore it after.
[HarmonyPatch(typeof(ZoneManager), nameof(ZoneManager.ExposeData))]
public static class Patch_ZoneManager_ExposeData
{
///
/// Only when Scribe.mode == Saving: swap allZones for a copy without Blax zones; __state keeps the
/// original. When allZones can't be bound, the public AllZones list (the same object) is filtered
/// in place instead, so a failed bind never writes Blax zones into the vanilla list.
///
public static void Prefix(ZoneManager __instance, out ZoneSaveState __state)
{
__state = null;
try
{
if (Scribe.mode != LoadSaveMode.Saving || __instance == null)
return;
AccessTools.FieldRef> field = ZoneStore.AllZonesRef;
List all = field != null ? field(__instance) : __instance.AllZones;
if (all == null)
return;
var vanilla = new List(all.Count);
for (int i = 0; i < all.Count; i++)
{
if (!ZoneStore.IsBlaxZone(all[i]))
vanilla.Add(all[i]);
}
if (field != null)
{
__state = new ZoneSaveState { list = all, swappedVia = field };
field(__instance) = vanilla;
}
else if (vanilla.Count != all.Count)
{
__state = new ZoneSaveState { list = all, contents = new List(all) };
all.Clear();
all.AddRange(vanilla);
}
}
catch (Exception e)
{
ZonesLog.Once("Zone save filter", e);
}
}
/// Puts the original list object, or its contents, back, even when saving threw.
public static Exception Finalizer(ZoneManager __instance, ZoneSaveState __state, Exception __exception)
{
if (__state != null)
{
try
{
__state.Restore(__instance);
}
catch (Exception e)
{
ZonesLog.Once("Zone save restore", e);
}
}
return __exception;
}
}
///
/// Load: Map.FinalizeLoading (Map.cs:750) runs while zoneGrid exists and nothing has spawned. The
/// prefix registers the component's loaded zones so vanilla's spawn loop trims them like stockpiles.
/// Its whole body sits in try/catch: vanilla catches an exception there and skips the rest of the
/// map's load (Game.cs:619-623). The finalizer never throws either.
///
[HarmonyPatch(typeof(Map), nameof(Map.FinalizeLoading))]
public static class Patch_Map_FinalizeLoading
{
public static void Prefix(Map __instance, out bool __state)
{
__state = false;
try
{
__state = ZoneStore.Loading;
ZoneStore.Loading = true;
MapComponent_BlaxZones.Of(__instance)?.RegisterLoadedZones();
}
catch (Exception e)
{
ZonesLog.Once("Registering loaded zones", e);
}
}
public static Exception Finalizer(bool __state, Exception __exception)
{
try
{
ZoneStore.Loading = __state;
}
catch (Exception e)
{
ZonesLog.Once("Clearing the zone load flag", e);
}
return __exception;
}
}
}