rimworld-blax-zones/Source/BlaxZones/ZoneStore.cs

280 lines
12 KiB
C#
Raw Permalink Normal View History

using System;
using System.Collections.Generic;
using HarmonyLib;
using RimWorld;
using Verse;
namespace BlaxZones
{
/// <summary>
/// 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.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
public static class ZoneStore
{
private static AccessTools.FieldRef<ZoneManager, List<Zone>> allZonesRef;
private static bool allZonesBindFailed;
/// <summary>
/// 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.
/// </summary>
public static AccessTools.FieldRef<ZoneManager, List<Zone>> AllZonesRef
{
get
{
if (ZonesTestHooks.AllZonesUnbound)
return null;
if (allZonesRef == null && !allZonesBindFailed)
{
try
{
allZonesRef = AccessTools.FieldRefAccess<ZoneManager, List<Zone>>("allZones");
}
catch (Exception e)
{
ZonesLog.Once("Binding ZoneManager.allZones", e);
}
allZonesBindFailed = allZonesRef == null;
}
return allZonesRef;
}
}
/// <summary>
/// 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.
/// </summary>
[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<ZoneManager, Zone, IntVec3> addZoneGridCell;
private static Action<ZoneManager, IntVec3> clearZoneGridCell;
private static Action<ZoneManager, Zone, IntVec3> AddZoneGridCell =>
addZoneGridCell ??= AccessTools.MethodDelegate<Action<ZoneManager, Zone, IntVec3>>(
AccessTools.Method(typeof(ZoneManager), "AddZoneGridCell", new[] { typeof(Zone), typeof(IntVec3) }));
private static Action<ZoneManager, IntVec3> ClearZoneGridCell =>
clearZoneGridCell ??= AccessTools.MethodDelegate<Action<ZoneManager, IntVec3>>(
AccessTools.Method(typeof(ZoneManager), "ClearZoneGridCell", new[] { typeof(IntVec3) }));
/// <summary>
/// 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.
/// </summary>
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;
}
/// <summary>
/// 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).
/// </summary>
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<IntVec3>();
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<ZoneManager, Zone, IntVec3> add = AddZoneGridCell;
List<IntVec3> 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);
}
}
/// <summary>
/// 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.
/// </summary>
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.
}
}
}
/// <summary>What the save prefix changed in one ZoneManager, so the finalizer undoes exactly that.</summary>
public sealed class ZoneSaveState
{
/// <summary>The list object allZones held before the save.</summary>
public List<Zone> list;
/// <summary>The bound field the prefix swapped a filtered copy into; null when it filtered list in place.</summary>
public AccessTools.FieldRef<ZoneManager, List<Zone>> swappedVia;
/// <summary>The list's full contents before an in-place filter; null after a swap.</summary>
public List<Zone> contents;
public void Restore(ZoneManager manager)
{
if (swappedVia != null)
{
swappedVia(manager) = list;
return;
}
list.Clear();
list.AddRange(contents);
}
}
/// <summary>Save: drop Blax zones from ZoneManager's list while it is written, restore it after.</summary>
[HarmonyPatch(typeof(ZoneManager), nameof(ZoneManager.ExposeData))]
public static class Patch_ZoneManager_ExposeData
{
/// <summary>
/// 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.
/// </summary>
public static void Prefix(ZoneManager __instance, out ZoneSaveState __state)
{
__state = null;
try
{
if (Scribe.mode != LoadSaveMode.Saving || __instance == null)
return;
AccessTools.FieldRef<ZoneManager, List<Zone>> field = ZoneStore.AllZonesRef;
List<Zone> all = field != null ? field(__instance) : __instance.AllZones;
if (all == null)
return;
var vanilla = new List<Zone>(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<Zone>(all) };
all.Clear();
all.AddRange(vanilla);
}
}
catch (Exception e)
{
ZonesLog.Once("Zone save filter", e);
}
}
/// <summary>
/// Puts the original list object, or its contents, back, even when saving threw. Returns void, so
/// Harmony rethrows a saving exception with its stack trace intact.
/// </summary>
public static void Finalizer(ZoneManager __instance, ZoneSaveState __state)
{
if (__state != null)
{
try
{
__state.Restore(__instance);
}
catch (Exception e)
{
ZonesLog.Once("Zone save restore", e);
}
}
}
}
/// <summary>
/// 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.
/// </summary>
[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);
}
}
/// <summary>Restores the load flag. Returns void, so Harmony rethrows vanilla's exception with its stack trace intact.</summary>
public static void Finalizer(bool __state)
{
try
{
ZoneStore.Loading = __state;
}
catch (Exception e)
{
ZonesLog.Once("Clearing the zone load flag", e);
}
}
}
}