diff --git a/1.7/Assemblies/BlaxLaws.dll b/1.7/Assemblies/BlaxLaws.dll index 5c4e3ca..76b2b95 100644 Binary files a/1.7/Assemblies/BlaxLaws.dll and b/1.7/Assemblies/BlaxLaws.dll differ diff --git a/1.7/Assemblies/BlaxLaws.pdb b/1.7/Assemblies/BlaxLaws.pdb index dd30576..cefcda2 100644 Binary files a/1.7/Assemblies/BlaxLaws.pdb and b/1.7/Assemblies/BlaxLaws.pdb differ diff --git a/About/About.xml b/About/About.xml index 5ed05c1..35cb276 100644 --- a/About/About.xml +++ b/About/About.xml @@ -3,7 +3,7 @@ Blax Laws Blax Gaming blax.laws - 1.0.0 + 1.1.0
  • 1.7
  • @@ -29,6 +29,7 @@ - A law's action comes from a searchable list built from the game's own defs: every mental break, everything that can be eaten or used, every social interaction, every act the game records and every bill, plus setting a fire, displaying a corpse and starting a social fight. DLC and modded content show up with their mod's name. - "Starter lawbook" adds seven suggested laws in one click. - The Cases tab lists who did what and when, the punishment and its status. +- A court place: switch it on for a table, party spot, campfire, throne, lectern or ritual spot you own, one per map. Court sessions and public punishments of later releases will use it. <color=#19C63C>Punishments</color> - Warn, guilty for N days, subdue (a short fistfight that ends a break: bruises on torso and limbs, never the head), jail for N days, and subdue then jail. diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f7c0e1..9faa76c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## 1.1.0 + +- Court place: select a table, party spot, campfire, throne (Royalty), lectern or ritual spot (Ideology) or other furniture you own and switch on "Court place", or use "Pick court place" below the lawbook in the Laws tab. One place per map; switching it on elsewhere on the map moves it. The switch shows while the lawbook has at least one law. +- Its room is the court room: with the mouse over the switch the room is outlined, and the Laws tab shows the place with its room and the room's impressiveness as the room stats show it, or "Not a proper room". "Show" moves the view to it, "Clear" removes it, also with an empty lawbook. +- Uninstalling the place into a crate and installing it again, on this map or another, keeps it as the court place, unless a newer place was set on that map in the meantime. Deconstructed, destroyed or claimed by another faction, it reads "No court place" at once. +- The place is set now; court sessions and public punishments of later releases will use it. Nothing is stored on the building: after Blax Laws is removed it is just a table, and a save still loads with the same two errors. + ## 1.0.0 - First release. "Laws" in the bottom bar opens the lawbook and the case log. The book starts empty, and until you add a law Blax Laws watches nothing. diff --git a/Languages/English/Keyed/BlaxLaws_UI.xml b/Languages/English/Keyed/BlaxLaws_UI.xml index 4ff14fa..9d16467 100644 --- a/Languages/English/Keyed/BlaxLaws_UI.xml +++ b/Languages/English/Keyed/BlaxLaws_UI.xml @@ -67,4 +67,18 @@ Arrest now Laws doesn't make this arrest on its own: {0}. Press to arrest now. + + Court place + Make this the court place of this map. Switching it on here moves it from anywhere else on this map. Its room is the court room. Court sessions and public punishments of later releases will use it.\n\nCourt room: {0} + Court place: + {0}: {1} + {0}, {1} ({2}) + Not a proper room + No court place + The court place's room is the court room, with its impressiveness as the room stats show it. Court sessions and public punishments of later releases will use the place. Select a table, party spot, campfire, throne, lectern, ritual spot or other furniture you own and switch on "Court place", or pick it here. + Pick court place + Click a table, party spot, campfire, throne, lectern, ritual spot or other furniture you own on this map. + Clear + This map has no court place afterwards. + diff --git a/README.md b/README.md index b2d3b2c..33f1d00 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ [![RimWorld 1.7](https://img.shields.io/badge/RimWorld-1.7-19C63C)](https://rimworldgame.com) [![Needs Harmony](https://img.shields.io/badge/needs-Harmony-050805)](https://steamcommunity.com/sharedfiles/filedetails/?id=2009463077) [![Any DLC combination](https://img.shields.io/badge/DLCs-any_combination-5a6b5d)](#dlc-support) -[![Status: 1.0](https://img.shields.io/badge/status-1.0-CDCDCD)](CHANGELOG.md) +[![Status: 1.1](https://img.shields.io/badge/status-1.1-CDCDCD)](CHANGELOG.md) RimWorld mod (1.7) by Blax Gaming. Lawbook, crimes and punishments. Write your colony's laws from every act the game knows, picked the way you pick what to tailor, and your wardens enforce them. Add "Drug binge, planning: subdue" and when a colonist starts a wake-up binge, a warden goes for it at once and beats it down; if it reaches a drug first, that dose counts as "did it". Add "Drug binge, did it: jail 5 days" and the one who already took some sits out five days in your prison and walks back to work. Needs Harmony. Works with any DLC combination, core only included. @@ -21,6 +21,7 @@ RimWorld mod (1.7) by Blax Gaming. Lawbook, crimes and punishments. Write your c - ⚖️ **Severity and days.** Minor, Moderate, Serious or Grave set the default days (1, 3, 5, 10) and order the case log. Days go from 1 to 50. Changing the severity moves the days along only while you haven't typed your own. - 📋 **Case log.** Who, what, stage, when, punishment and status, newest first, with a jump to the pawn and "Arrest now" for cases that wait. Deleting a law with open cases asks first, names the count and closes them as "law repealed". - 🧩 **Missing entries wait.** A row whose DLC or mod is gone stays in the book with its saved name, shows "Needs " or "Missing: ", isn't enforced and works again when the content comes back. +- 🏛️ **Court place.** Select a table, party spot, campfire, throne (Royalty), lectern or ritual spot (Ideology) or other furniture you own and switch on "Court place", or pick it below the lawbook. One per map. Hovering the switch outlines its room, and the Laws tab shows the room's impressiveness or "Not a proper room". The place follows its crate when you move it; court sessions and public punishments of later releases will use it. `Source/BlaxLaws/Court/CourtPlace.cs` ### Crimes @@ -88,6 +89,7 @@ Blax Laws works with any combination of DLCs, core only included, and lists none - **Ideology** adds slaves, who get warn, guilty and subdue, and records most of the game's acts (cut a tree, butchered a human); without it the recorded acts category rarely fires. An arrest would take a role holder's role, so its case waits for "Arrest now". - **Biotech** adds children, who are never beaten, and mechanitors, whose mechs would shut down in jail, so their case waits for "Arrest now". +- **Royalty** adds thrones as court places; with **Ideology** the lectern and the ritual spot can be one too. Tables, party spots, campfires and furniture work on the core game. - **Royalty**, **Anomaly** and **Odyssey**: their acts appear in the list when active; Laws needs none of them. - **A save made with a DLC** loads without it. A law naming a DLC entry stays and shows "Needs "; a case whose offender was a slave keeps its name. diff --git a/Source/BlaxLaws/Court/CourtPlace.cs b/Source/BlaxLaws/Court/CourtPlace.cs new file mode 100644 index 0000000..fa8f37d --- /dev/null +++ b/Source/BlaxLaws/Court/CourtPlace.cs @@ -0,0 +1,149 @@ +using System.Collections.Generic; +using RimWorld; +using Verse; + +namespace BlaxLaws +{ + /// + /// One stored court place (design: "Court place"). Only the building reference and the tick it was set + /// are saved, never a map: the map is read from the building, so a place that is uninstalled into a crate + /// and installed on another map follows it (RimWorld/MinifyUtility.cs:15-23 keeps the same instance and + /// ThingID; RimWorld/Blueprint_Install.cs:99-112). A destroyed building saves as "null" + /// (Verse/Scribe_References.cs:60-78) and the entry is dropped after the load. + /// + public sealed class CourtPlaceEntry : IExposable + { + public Building building; + + /// When the player set this place. The newest place on a map wins. + public int setTick; + + public CourtPlaceEntry() + { + } + + public CourtPlaceEntry(Building building, int setTick) + { + this.building = building; + this.setTick = setTick; + } + + public void ExposeData() + { + Scribe_References.Look(ref building, "building"); + Scribe_Values.Look(ref setTick, "setTick"); + } + } + + /// + /// The court place of each map: the public API that the switch on a building, the Laws tab and the later + /// court features (sessions, "Court on its own", public punishments) read and write. The state lives in + /// GameComponent_BlaxLaws; every read goes through Valid, so a deconstructed, destroyed, claimed or + /// crated place reads as no place at once, with no Destroy or DeSpawn hook. + /// + public static class CourtPlace + { + // Per-def cache of the kind rule. Defs, not game state. + private static readonly Dictionary eligibleDefs = new Dictionary(); + private static DesignationCategoryDef furnitureCategory; + private static bool furnitureLooked; + + /// + /// The building can be a court place right now: spawned, not destroyed and the player's + /// (Verse/Thing.cs:180-209, 390). A failed check reads as no place. + /// + public static bool Valid(Building b) => + b != null && !b.Destroyed && b.Spawned && b.Faction != null && b.Faction == Faction.OfPlayer; + + /// Valid and of a kind that can hold court. The switch, the picker and Set all use this. + public static bool CanBe(Building b) => Valid(b) && EligibleDef(b.def); + + /// + /// The kind rule, per def: tables (Verse/ThingDef.cs:1008, or any eating surface), every gathering spot + /// (CompGatherSpot: the gather tables, the campfire, Royalty's instruments, Ideology's autobong), the + /// party spot (it has no CompGatherSpot, Core Buildings_Misc.xml:1188-1215), Royalty's thrones + /// (Building_Throne), Ideology's lectern and ritual spot (RimWorld/ThingDefOf.cs:687, 813, null without + /// Ideology), and other minifiable furniture (designation category Furniture). Impassable defs are refused + /// except thrones, so walls never qualify; no vanilla throne is impassable (Verse/BuildableDef.cs:13). + /// + public static bool EligibleDef(ThingDef d) + { + if (d == null) + return false; + if (eligibleDefs.TryGetValue(d, out bool known)) + return known; + bool result = ComputeEligible(d); + eligibleDefs[d] = result; + return result; + } + + private static bool ComputeEligible(ThingDef d) + { + if (d.category != ThingCategory.Building || d.building == null) + return false; + bool throne = d.thingClass != null && typeof(Building_Throne).IsAssignableFrom(d.thingClass); + if (d.passability == Traversability.Impassable && !throne) + return false; + if (throne) + return true; + if (d.IsTable || d.surfaceType == SurfaceType.Eat || d.HasComp(typeof(CompGatherSpot))) + return true; + if (d == ThingDefOf.PartySpot || d == ThingDefOf.RitualSpot || d == ThingDefOf.Lectern) + return true; + if (!furnitureLooked) + { + furnitureCategory = DefDatabase.GetNamedSilentFail("Furniture"); + furnitureLooked = true; + } + return d.Minifiable && furnitureCategory != null && d.designationCategory == furnitureCategory; + } + + /// The map's court place, or null when it has none or the place fails Valid. + public static Building For(Map map) => GameComponent_BlaxLaws.Instance?.CourtPlaceOn(map); + + /// The building is its map's court place. + public static bool IsPlace(Building b) => b != null && b.Spawned && For(b.Map) == b; + + /// + /// Makes the building its map's court place and drops the map's former one, crated ones included. + /// False when CanBe refuses it. + /// + public static bool Set(Building b) + { + GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance; + if (comp == null || !CanBe(b)) + return false; + comp.SetCourtPlace(b); + return true; + } + + /// The map has no court place afterwards. Works with an empty lawbook. + public static void Clear(Map map) => GameComponent_BlaxLaws.Instance?.ClearCourtPlace(map); + + /// + /// The court room, read when used and never stored (Room.ID changes on every region rebuild, + /// Verse/Room.cs:43, 597-600): vanilla's room stats rule, Gizmo_RoomStats.GetRoomToShowStatsFor + /// (Verse/Gizmo_RoomStats.cs:89-132), which handles passable and impassable buildings and returns null + /// for an unspawned or fogged building, a fogged room and a room without a role (outdoors, huge). + /// + public static Room RoomOf(Building b) => b != null && b.Spawned ? Gizmo_RoomStats.GetRoomToShowStatsFor(b) : null; + + /// The room is a court room: not null and a proper room (Verse/Room.cs:536). + public static bool IsProperRoom(Room room) => room != null && room.ProperRoom; + + /// + /// The picker's parameters: buildings only, the court place kind rule as validator, and + /// mapObjectTargetsMustBeAutoAttackable off, since it refuses buildings that aren't targetable + /// (RimWorld/TargetingParameters.cs:55, 277-281). + /// + public static TargetingParameters TargetParams() => new TargetingParameters + { + canTargetPawns = false, + canTargetBuildings = true, + canTargetItems = false, + canTargetLocations = false, + mapObjectTargetsMustBeAutoAttackable = false, + validator = t => t.Thing is Building b && CanBe(b), + }; + } +} diff --git a/Source/BlaxLaws/Court/Hook_P_CourtPlaceGizmo.cs b/Source/BlaxLaws/Court/Hook_P_CourtPlaceGizmo.cs new file mode 100644 index 0000000..8196a9b --- /dev/null +++ b/Source/BlaxLaws/Court/Hook_P_CourtPlaceGizmo.cs @@ -0,0 +1,167 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using HarmonyLib; +using RimWorld; +using Verse; + +namespace BlaxLaws +{ + /// + /// Hook P: the "Court place" switch on a building (design: "Court place"). A postfix on Building.GetGizmos + /// (Verse/Building.cs:401), an iterator that yields base first; the overrides of ThingWithComps and + /// Building_Throne call base too (Verse/ThingWithComps.cs:536; RimWorld/Building_Throne.cs:79-89). Gizmos + /// are rebuilt every frame for every selected object (Verse/GizmoGridDrawer.cs:62-100), so the postfix + /// returns after one static field read while the lawbook is empty, and otherwise wraps the result only + /// for a single selected building (Find.Selector.SingleSelectedObject, RimWorld/Selector.cs:74, the gate of + /// vanilla's room stats button, Verse/Building.cs:407) of a kind that can hold court. A box-select of 200 + /// walls leaves the result untouched. + /// + [HarmonyPatch(typeof(Building), nameof(Building.GetGizmos))] + public static class Patch_Building_GetGizmos + { + public const string Where = "hook P, Building.GetGizmos"; + + public static void Postfix(Building __instance, ref IEnumerable __result) + { + if (!Watch.AnyLaw) + return; + Work(__instance, ref __result); + } + + // Off the hot path: a method with a try block is never inlined, so the check above stays small. + [MethodImpl(MethodImplOptions.NoInlining)] + private static void Work(Building building, ref IEnumerable result) + { + try + { + if (LawsTestHooks.CourtGizmoThrows) + throw new InvalidOperationException("test: the court place gizmo hook throws"); + if (result == null || Find.Selector?.SingleSelectedObject != building || !CourtPlace.CanBe(building)) + return; + result = Append(result, building); + } + catch (Exception e) + { + HookGuard.Fail(Where, e); + } + } + + // C# allows no yield inside a try with a catch, so the switch is built in Make, which catches its own + // throw and gives null: a Laws error never breaks the gizmo bar. Vanilla's own gizmos pass unchanged. + private static IEnumerable Append(IEnumerable original, Building building) + { + foreach (Gizmo g in original) + yield return g; + Gizmo own = Make(building); + if (own != null) + yield return own; + } + + private static Gizmo Make(Building building) + { + try + { + return new Command_CourtPlace(building); + } + catch (Exception e) + { + HookGuard.Fail(Where + ", the switch", e); + return null; + } + } + } + + /// + /// Hook P's second half: a postfix on Building.SpawnSetup (Verse/Building.cs:113), which every building + /// runs when it spawns, a reinstall from its crate included (RimWorld/Blueprint_Install.cs:99-112 hands + /// the same instance to GenSpawn). When the building is a stored court place, the older place spawned on + /// the same map is dropped at once (GameComponent_BlaxLaws.CourtPlaceSpawned), so a crate that arrives on + /// a map with a place resolves "the place set last wins" now and not at the next save. One field read + /// and one count while no place is stored; spawns after a load are skipped, FinalizeInit cleans those. + /// + [HarmonyPatch(typeof(Building), nameof(Building.SpawnSetup))] + public static class Patch_Building_SpawnSetup + { + public const string Where = "hook P, Building.SpawnSetup"; + + public static void Postfix(Building __instance, bool respawningAfterLoad) + { + if (respawningAfterLoad) + return; + Work(__instance); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void Work(Building building) + { + try + { + GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance; + if (comp == null || !comp.AnyCourtPlace) + return; + comp.CourtPlaceSpawned(building); + } + catch (Exception e) + { + HookGuard.Fail(Where, e); + } + } + } + + /// + /// The "Court place" switch. A Command_Toggle (Verse/Command_Toggle.cs:7-60) has no hover hook, so this + /// subclass overrides Gizmo.GizmoUpdateOnMouseover (Verse/Gizmo.cs:49) to outline the court room, as + /// Gizmo_RoomStats does (Verse/Gizmo_RoomStats.cs:83-87). Built per frame and never saved, so the + /// tooltip with its room text is built only when read, on hover (Verse/Command.cs:71, 203-205). + /// + public class Command_CourtPlace : Command_Toggle + { + private readonly Building building; + + public Command_CourtPlace(Building building) + { + if (LawsTestHooks.CourtSwitchThrows) + throw new InvalidOperationException("test: the court place switch throws"); + this.building = building; + defaultLabel = "BlaxLaws_CourtPlace".Translate(); + icon = TexButton.ShowRoomStats; + isActive = () => CourtPlace.IsPlace(building); + toggleAction = () => HookGuard.Run("Court place switch", () => CourtPlaceUi.Toggle(building)); + } + + public Building Building => building; + + public override string Desc + { + get + { + try + { + return "BlaxLaws_CourtPlaceDesc".Translate(CourtPlaceUi.RoomText(building)); + } + catch (Exception e) + { + HookGuard.Fail("Court place tooltip", e); + return "BlaxLaws_CourtPlace".Translate(); + } + } + } + + public override void GizmoUpdateOnMouseover() + { + base.GizmoUpdateOnMouseover(); + try + { + // Null for an outdoor or huge room, so the outline never walks thousands of cells a frame. + Room room = CourtPlace.RoomOf(building); + if (CourtPlace.IsProperRoom(room)) + room.DrawFieldEdges(); + } + catch (Exception e) + { + HookGuard.Fail("Court place outline", e); + } + } + } +} diff --git a/Source/BlaxLaws/GameComponent_BlaxLaws.cs b/Source/BlaxLaws/GameComponent_BlaxLaws.cs index 8f0e5a3..17e5b37 100644 --- a/Source/BlaxLaws/GameComponent_BlaxLaws.cs +++ b/Source/BlaxLaws/GameComponent_BlaxLaws.cs @@ -22,6 +22,9 @@ namespace BlaxLaws private List cases = new List(); private int nextCaseId = 1; + // The court places, at most about one per map plus crated ones; no map key (design: "Court place"). + private List courtPlaces = new List(); + /// A random number per save, for ids Laws hands to other mods later. Never 0 after the first tick. private int saveToken; @@ -66,7 +69,8 @@ namespace BlaxLaws } } - private static void Remember(GameComponent_BlaxLaws comp, Game game) + // Internal for the old-save test, which loads a second component and then gives the game's back. + internal static void Remember(GameComponent_BlaxLaws comp, Game game) { cached.SetTarget(comp); cachedGame.SetTarget(game); @@ -271,6 +275,112 @@ namespace BlaxLaws Index(c); } + // ---- court place, for CourtPlace ------------------------------------------------------------ + + /// The stored entries, newest set last. Do not change the list; use CourtPlace. + public IReadOnlyList CourtPlaceEntries => courtPlaces; + + /// A place is stored, crated ones included. The spawn hook's gate. + internal bool AnyCourtPlace => courtPlaces.Count > 0; + + /// + /// The map's court place: of the entries spawned on the map, the one set last; null when it fails + /// CourtPlace.Valid (claimed by another faction). A map never holds two spawned entries for long: Set + /// drops the map's others and a stored place that spawns drops the older ones at once + /// (CourtPlaceSpawned), so a place lost later never falls back to an older one. + /// One count check while no place exists. + /// + internal Building CourtPlaceOn(Map map) + { + if (map == null || courtPlaces.Count == 0) + return null; + CourtPlaceEntry best = null; + for (int i = 0; i < courtPlaces.Count; i++) + { + CourtPlaceEntry e = courtPlaces[i]; + Building b = e?.building; + if (b == null || b.Destroyed || !b.Spawned || b.Map != map) + continue; + if (best == null || e.setTick >= best.setTick) + best = e; + } + return best != null && CourtPlace.Valid(best.building) ? best.building : null; + } + + internal void SetCourtPlace(Building b) + { + Map map = b.Map; + courtPlaces.RemoveAll(e => e?.building == null || e.building == b || e.building.MapHeld == map); + courtPlaces.Add(new CourtPlaceEntry(b, Find.TickManager?.TicksGame ?? 0)); + } + + /// + /// A building spawned on a map (hook P, Building.SpawnSetup). When it is a stored place, installed from + /// its crate, only the entry set last among those spawned on that map stays, as CleanCourtPlaces keeps + /// it: a crate that arrives on a map with a newer place loses to it, and a newer crate replaces the + /// older place. Resolved now, not at the next save, so the result never depends on save timing. + /// + internal void CourtPlaceSpawned(Building b) + { + Map map = b.Map; + if (map == null) + return; + bool stored = false; + CourtPlaceEntry best = null; + for (int i = 0; i < courtPlaces.Count; i++) + { + CourtPlaceEntry e = courtPlaces[i]; + Building other = e?.building; + if (other == b) + stored = true; + if (other == null || other.Destroyed || !other.Spawned || other.Map != map) + continue; + if (best == null || e.setTick >= best.setTick) + best = e; + } + if (!stored || best == null) + return; + courtPlaces.RemoveAll(e => e != best && e?.building != null && !e.building.Destroyed && e.building.Spawned && e.building.Map == map); + } + + internal void ClearCourtPlace(Map map) + { + if (map == null) + return; + courtPlaces.RemoveAll(e => e?.building == null || e.building.MapHeld == map); + } + + /// + /// Drops entries whose building is gone: null, destroyed (deconstructed, burnt, a destroyed crate, a + /// removed map, Verse/Thing.cs:1123-1143) or unspawned outside any container, which nothing would save. + /// Keeps a crated or carried place, so it follows its crate. Of the entries spawned on one map, only the + /// one set last stays: a crate installed on a map that already has a place loses to the place set later. + /// Only after the maps have spawned their things (FinalizeInit, saving, a write). + /// + internal void CleanCourtPlaces() + { + if (courtPlaces.Count == 0) + return; + courtPlaces.RemoveAll(e => e?.building == null || e.building.Destroyed || (!e.building.Spawned && e.building.holdingOwner == null)); + for (int i = courtPlaces.Count - 1; i >= 0; i--) + { + CourtPlaceEntry e = courtPlaces[i]; + if (!e.building.Spawned) + continue; + for (int j = 0; j < courtPlaces.Count; j++) + { + CourtPlaceEntry o = courtPlaces[j]; + if (j == i || !o.building.Spawned || o.building.Map != e.building.Map) + continue; + if (o.setTick > e.setTick || (o.setTick == e.setTick && j > i)) + { + courtPlaces.RemoveAt(i); + break; + } + } + } + } + // ---- game hooks ---------------------------------------------------------------------- public override void GameComponentTick() @@ -306,6 +416,8 @@ namespace BlaxLaws { HookGuard.Fail("Game start", e); } + // Maps have spawned their things by now (Verse/Game.cs:614-636), so unspawned entries are real. + HookGuard.Run("Cleaning court places", CleanCourtPlaces); } // ---- save ---------------------------------------------------------------------------- @@ -322,6 +434,7 @@ namespace BlaxLaws { HookGuard.Fail("Pruning closed cases", e); } + HookGuard.Run("Saving court places", CleanCourtPlaces); } Scribe_Values.Look(ref saveToken, "saveToken"); @@ -329,6 +442,10 @@ namespace BlaxLaws Scribe_Collections.Look(ref laws, "laws", LookMode.Deep); Scribe_Values.Look(ref nextCaseId, "nextCaseId", 1); Scribe_Collections.Look(ref cases, "cases", LookMode.Deep); + // Deep, not a bare reference list: a 1.0.0 save without this node loads it as null and registers + // no ids (Verse/Scribe_Collections.cs:372-379), where a missing reference list would warn on every + // load (Verse/LoadIDsWantedBank.cs:33-55). + Scribe_Collections.Look(ref courtPlaces, "courtPlaces", LookMode.Deep); if (Scribe.mode == LoadSaveMode.LoadingVars) Remember(this, Current.Game); @@ -343,6 +460,9 @@ namespace BlaxLaws laws.RemoveAll(l => l == null || l.actKey.NullOrEmpty()); cases ??= new List(); cases.RemoveAll(c => c == null); + // Things on maps spawn after this (Verse/Game.cs:611-619): drop only what is gone for sure here. + courtPlaces ??= new List(); + courtPlaces.RemoveAll(e => e?.building == null || e.building.Destroyed); if (saveToken == 0) saveToken = NewToken(); foreach (Law l in laws) diff --git a/Source/BlaxLaws/LawsLog.cs b/Source/BlaxLaws/LawsLog.cs index a2eb865..d2697b5 100644 --- a/Source/BlaxLaws/LawsLog.cs +++ b/Source/BlaxLaws/LawsLog.cs @@ -80,6 +80,12 @@ namespace BlaxLaws /// CaseFiler.Report throws, to test that a hook's HookGuard keeps vanilla running. public static bool ReportThrows; + /// Hook P's gizmo postfix throws inside its guard, to test that the gizmo bar keeps vanilla's gizmos. + public static bool CourtGizmoThrows; + + /// The court place switch throws while it is built, to test the guard around it in hook P. + public static bool CourtSwitchThrows; + /// GameComponent_BlaxLaws skips its tick, as if the mod were absent (the performance test's baseline). public static bool TickSuspended; @@ -109,6 +115,8 @@ namespace BlaxLaws public static void Reset() { ReportThrows = false; + CourtGizmoThrows = false; + CourtSwitchThrows = false; TickSuspended = false; RestorePatches(); } diff --git a/Source/BlaxLaws/UI/CourtPlaceUi.cs b/Source/BlaxLaws/UI/CourtPlaceUi.cs new file mode 100644 index 0000000..0a58935 --- /dev/null +++ b/Source/BlaxLaws/UI/CourtPlaceUi.cs @@ -0,0 +1,95 @@ +using RimWorld; +using RimWorld.Planet; +using Verse; + +namespace BlaxLaws +{ + /// + /// The court place section of the Laws tab and the switch's texts (design: "Court place"). Logic only, so + /// the tests can read the strings without drawing a window. This release shows the room's impressiveness + /// as vanilla's room stats button does (Verse/Gizmo_RoomStats.cs:40-42), with no courtroom setting yet. + /// + public static class CourtPlaceUi + { + /// The room state of a building as a court place: role, impressiveness label and number, or "Not a proper room". + public static string RoomText(Building b) + { + Room room = CourtPlace.RoomOf(b); + if (!CourtPlace.IsProperRoom(room)) + return "BlaxLaws_NotProperRoom".Translate(); + float stat = room.GetStat(RoomStatDefOf.Impressiveness); + RoomStatScoreStage stage = RoomStatDefOf.Impressiveness.GetScoreStage(stat); + string role = room.Role != null ? room.Role.PostProcessedLabelCap(room) : ""; + return "BlaxLaws_CourtRoomStats".Translate(role, stage?.label ?? "", RoomStatDefOf.Impressiveness.ScoreToString(stat)); + } + + /// The tab's line for the map: the place and its room, or "No court place". + public static string Line(Map map) + { + Building b = CourtPlace.For(map); + if (b == null) + return "BlaxLaws_NoCourtPlace".Translate(); + return "BlaxLaws_CourtPlaceLine".Translate(b.LabelCap, RoomText(b)); + } + + /// The switch: on makes the building the map's place, off clears the map's place. + public static void Toggle(Building b) + { + if (b == null) + return; + if (CourtPlace.IsPlace(b)) + CourtPlace.Clear(b.Map); + else + CourtPlace.Set(b); + } + + public static bool CanJump(Map map) + { + Building b = CourtPlace.For(map); + return b != null && CameraJumper.CanJump(new GlobalTargetInfo(b)); + } + + public static void JumpTo(Map map) + { + Building b = CourtPlace.For(map); + if (b != null) + CameraJumper.TryJumpAndSelect(new GlobalTargetInfo(b)); + } + + /// Something on this map is stored as its place, valid or not (a claimed or crated one included). + public static bool CanClear(Map map) + { + GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance; + if (comp == null || map == null) + return false; + foreach (CourtPlaceEntry e in comp.CourtPlaceEntries) + { + if (e?.building != null && !e.building.Destroyed && e.building.MapHeld == map) + return true; + } + return false; + } + + /// + /// "Pick court place": closes the Laws tab, as vanilla does before map picking + /// (RimWorld/MainTabsRoot.cs:32), and starts the targeter (RimWorld/Targeter.cs:93) with the same + /// kind rule as the switch. A pick reopens the tab. + /// + public static void BeginPick() + { + if (Find.CurrentMap == null) + return; + Find.MainTabsRoot?.EscapeCurrentTab(false); + Find.Targeter.BeginTargeting(CourtPlace.TargetParams(), Pick); + } + + public static void Pick(LocalTargetInfo target) + { + HookGuard.Run("Pick court place", () => + { + if (target.Thing is Building b && CourtPlace.Set(b)) + Find.MainTabsRoot?.SetCurrentTab(BlaxLawsDefOf.BlaxLaws_Laws, false); + }); + } + } +} diff --git a/Source/BlaxLaws/UI/MainTabWindow_Laws.cs b/Source/BlaxLaws/UI/MainTabWindow_Laws.cs index 29dbefa..e6528ab 100644 --- a/Source/BlaxLaws/UI/MainTabWindow_Laws.cs +++ b/Source/BlaxLaws/UI/MainTabWindow_Laws.cs @@ -14,6 +14,7 @@ namespace BlaxLaws /// "Starter lawbook" adds the suggested rows. An empty book shows one line. /// - Cases: newest first, who, what, stage, when, punishment and status, a button to jump to the pawn /// and, for a held case, "Arrest now". + /// Below the Lawbook: the current map's court place (CourtPlaceUi), with "Pick court place" and "Clear". /// The logic lives in LawbookUi and CaseLog; every write goes through Lawbook. Only the lines in view /// are drawn. /// @@ -107,6 +108,24 @@ namespace BlaxLaws private void DoLawbook(Rect rect) { + // The court place strip sits at the bottom, drawn before the empty-book return so "Clear" works + // with an empty book. + if (Find.CurrentMap != null) + { + Rect court = new Rect(rect.x, rect.yMax - ButtonHeight, rect.width, ButtonHeight); + try + { + DrawCourtPlace(court, Find.CurrentMap); + } + catch (Exception e) + { + LawsLog.Once("Laws tab, court place", e); + } + rect.yMax = court.y - Gap; + Widgets.DrawLineHorizontal(rect.x, rect.yMax, rect.width); + rect.yMax -= Gap; + } + Rect buttons = new Rect(rect.x, rect.y, rect.width, ButtonHeight); Rect add = new Rect(buttons.x, buttons.y, 160f, ButtonHeight); if (Widgets.ButtonText(add, "BlaxLaws_AddLaw".Translate())) @@ -161,6 +180,46 @@ namespace BlaxLaws } } + private const float CourtHeaderWidth = 110f; + private const float PickWidth = 170f; + private const float ClearWidth = 80f; + private const float ShowWidth = 70f; + + /// "Court place:", the place and its room, Show, Pick court place and Clear. + private static void DrawCourtPlace(Rect r, Map map) + { + float right = r.xMax; + if (CourtPlaceUi.CanClear(map)) + { + Rect clear = new Rect(right - ClearWidth, r.y, ClearWidth, r.height); + if (Widgets.ButtonText(clear, "BlaxLaws_ClearCourtPlace".Translate())) + HookGuard.Run("Clear court place", () => CourtPlace.Clear(map)); + TooltipHandler.TipRegion(clear, "BlaxLaws_ClearCourtPlaceTip".Translate()); + right = clear.x - Gap; + } + Rect pick = new Rect(right - PickWidth, r.y, PickWidth, r.height); + if (Widgets.ButtonText(pick, "BlaxLaws_PickCourtPlace".Translate())) + HookGuard.Run("Pick court place", CourtPlaceUi.BeginPick); + TooltipHandler.TipRegion(pick, "BlaxLaws_PickCourtPlaceTip".Translate()); + right = pick.x - Gap; + if (CourtPlaceUi.CanJump(map)) + { + Rect show = new Rect(right - ShowWidth, r.y, ShowWidth, r.height); + if (Widgets.ButtonText(show, "BlaxLaws_JumpTo".Translate())) + HookGuard.Run("Jump to court place", () => CourtPlaceUi.JumpTo(map)); + right = show.x - Gap; + } + + Rect header = new Rect(r.x, r.y, CourtHeaderWidth, r.height); + using (new TextBlock(GameFont.Small, TextAnchor.MiddleLeft, ColoredText.SubtleGrayColor)) + Widgets.Label(header, "BlaxLaws_CourtPlaceHeader".Translate()); + Rect line = new Rect(header.xMax + Gap, r.y, right - header.xMax - Gap * 2, r.height); + string text = CourtPlaceUi.Line(map); + using (new TextBlock(GameFont.Small, TextAnchor.MiddleLeft, Color.white)) + Widgets.Label(line, text.Truncate(line.width)); + TooltipHandler.TipRegion(new Rect(r.x, r.y, line.xMax - r.x, r.height), () => text + "\n\n" + "BlaxLaws_CourtPlaceTip".Translate().ToString(), 7351); + } + private void ScrollToFocus(IReadOnlyList laws, float height) { if (!LawbookUi.ScrollPending) diff --git a/Source/BlaxLaws/Watch.cs b/Source/BlaxLaws/Watch.cs index d155ef7..0f2531e 100644 --- a/Source/BlaxLaws/Watch.cs +++ b/Source/BlaxLaws/Watch.cs @@ -24,6 +24,12 @@ namespace BlaxLaws /// Any category or special act is watched. False for an empty book. public static bool Any; + /// + /// The lawbook has at least one row, disabled rows and rows whose entry is missing included. Hook P + /// (the "Court place" switch) reads it first, so while the book is empty the hook costs one field read. + /// + public static bool AnyLaw; + // One flag per category: some enabled row (or a break row's link) uses it. public static bool Break; public static bool Ate; @@ -97,6 +103,7 @@ namespace BlaxLaws /// Everything off: an empty book. public static void Clear() { + AnyLaw = false; byCategory.Clear(); specials.Clear(); SetFlags(); @@ -114,6 +121,7 @@ namespace BlaxLaws byCategory.Clear(); specials.Clear(); GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance; + AnyLaw = comp != null && comp.Laws.Count > 0; if (comp != null) { foreach (Law law in comp.Laws) diff --git a/Tests/BlaxLawsTests/Source/CourtPlaceTests.cs b/Tests/BlaxLawsTests/Source/CourtPlaceTests.cs new file mode 100644 index 0000000..fe8d043 --- /dev/null +++ b/Tests/BlaxLawsTests/Source/CourtPlaceTests.cs @@ -0,0 +1,713 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using BlaxLaws; +using RimWorld; +using Verse; + +namespace BlaxLawsTests +{ + /// + /// The court place (design: "Court place", Tests): the switch on a building (hook P), the place per map, its + /// way through a crate, deconstruction, the save and the removal, the Laws tab's texts and the picker. Rows + /// use an act key no catalogue knows, so a row only makes "a law exists" true and files nothing. Every test + /// clears the map's place afterwards; the save test in phase 1 runs last and keeps its table and place. + /// + public static class CourtPlaceTests + { + private const string Key = "Ate/BlaxLawsTest_CourtPlace"; + private const string CarryPlace = "court.place"; + + // ---- helpers ----------------------------------------------------------------------------- + + private static Map Map => Fixtures.Map; + + private static Law AnyLaw() => DetectionKit.Row(Key, LawStage.DidIt); + + /// The map has no place before the test and none after it; crates a test left off the map are destroyed. + private static void CleanPlace(params Func[] crates) + { + CourtPlace.Clear(Map); + T.Check(CourtPlace.For(Map) == null, "fixture: the map still has a court place: " + CourtPlace.For(Map)); + Fixtures.OnCleanup(() => + { + foreach (Func get in crates) + { + MinifiedThing crate = get(); + if (crate != null && !crate.Destroyed && !crate.Spawned && crate.holdingOwner == null) + crate.Destroy(DestroyMode.Vanish); + } + CourtPlace.Clear(Map); + Fixtures.Comp.CleanCourtPlaces(); + }); + } + + private static Building Make(ThingDef def, Faction faction = null, ThingDef stuff = null, IntVec3? near = null) + { + var b = (Building)ThingMaker.MakeThing(def, def.MadeFromStuff ? stuff ?? GenStuff.DefaultStuffFor(def) : null); + if (faction != null) + b.SetFaction(faction); + return DetectionKit.Place(b, DetectionKit.FreeCell(near ?? Fixtures.PawnCell(), def.size)); + } + + private static Building Table(Faction faction = null, IntVec3? near = null) => + Make(ThingDefOf.Table1x2c, faction ?? Faction.OfPlayer, ThingDefOf.WoodLog, near); + + private static void Select(params Thing[] things) + { + Find.Selector.ClearSelection(); + foreach (Thing t in things) + Find.Selector.Select(t, playSound: false, forceDesignatorDeselect: false); + } + + /// The switch the building's gizmo bar shows while it alone is selected, or null. + private static Command_CourtPlace Switch(Building b) + { + Select(b); + List found = b.GetGizmos().OfType().ToList(); + T.Check(found.Count <= 1, b + " shows " + found.Count + " court place switches"); + return found.FirstOrDefault(); + } + + private static Command_CourtPlace NeedSwitch(Building b, string what) + { + Command_CourtPlace cmd = Switch(b); + T.NotNull(cmd, "the court place switch on " + what); + T.Check(cmd.Building == b, "the switch on " + what + " names " + cmd.Building); + return cmd; + } + + private static string No => "BlaxLaws_NoCourtPlace".Translate(); + + private static string NotRoom => "BlaxLaws_NotProperRoom".Translate(); + + /// Spawns the building's crate on the map and returns it; the building is inside it, unspawned. + private static MinifiedThing Uninstall(Building b, IntVec3 near) + { + MinifiedThing crate = Fixtures.Track(b.MakeMinified()); + T.NotNull(crate, "fixture: the crate of " + b); + GenSpawn.Spawn(crate, DetectionKit.FreeCell(near), Map); + return crate; + } + + /// Installs the crate's building at a free spot near the cell, as Blueprint_Install.MakeSolidThing does (RimWorld/Blueprint_Install.cs:99-112). + private static Building Reinstall(MinifiedThing crate, IntVec3 near, Func also = null) + { + var inner = (Building)crate.InnerThing; + T.NotNull(inner, "fixture: the crate holds nothing"); + crate.InnerThing = null; + crate.Destroy(DestroyMode.Vanish); + GenSpawn.Spawn(inner, DetectionKit.FreeCell(near, inner.def.size, also), Map, Rot4.North); + return inner; + } + + /// Runs the component's ExposeData in Saving mode, as a save does (Verse/ScribeSaver.cs:141-176). + private static string SaveXml() + { + T.Equal(LoadSaveMode.Inactive, Scribe.mode, "fixture: Scribe mode before the save"); + string xml = Scribe.saver.DebugOutputFor(Fixtures.Comp); + T.Equal(LoadSaveMode.Inactive, Scribe.mode, "Scribe mode after the save"); + T.Check(!string.IsNullOrEmpty(xml) && xml.Contains(" ">Thing_" + t.ThingID + "<"; + + private static Building FindBuilding(string thingId) + { + foreach (Map m in Find.Maps) + { + foreach (Thing t in m.listerThings.AllThings) + { + if (t.ThingID == thingId) + return t as Building; + } + } + return null; + } + + // ---- the switch -------------------------------------------------------------------------- + + [BlaxTest("court place: switching it on on a table stores it; on a second table it moves there; off again leaves none")] + public static void SwitchStoresAndMoves() + { + CleanPlace(); + AnyLaw(); + Building t1 = Table(); + Building t2 = Table(near: t1.Position); + + Command_CourtPlace s1 = NeedSwitch(t1, "the first table"); + T.Check(!s1.isActive(), "the switch on the first table is on before it was switched"); + s1.toggleAction(); + T.Equal(t1, CourtPlace.For(Map), "court place after switching it on on the first table"); + T.Check(NeedSwitch(t1, "the first table").isActive(), "the first table's switch is off while it is the place"); + + NeedSwitch(t2, "the second table").toggleAction(); + T.Equal(t2, CourtPlace.For(Map), "court place after switching it on on the second table"); + T.Check(!NeedSwitch(t1, "the first table").isActive(), "the first table's switch is still on after the place moved"); + T.Check(NeedSwitch(t2, "the second table").isActive(), "the second table's switch is off while it is the place"); + T.Equal(1, Fixtures.Comp.CourtPlaceEntries.Count(e => e?.building != null && e.building.MapHeld == Map), "entries stored for the map after the move"); + + NeedSwitch(t2, "the second table").toggleAction(); + T.Equal(null, CourtPlace.For(Map), "court place after switching the second table off"); + T.Check(!NeedSwitch(t1, "the first table").isActive(), "switching the second table off put the place back on the first"); + } + + [BlaxTest("court place: the switch shows only while a law exists and the building alone is selected")] + public static void SwitchNeedsLawAndSingleSelection() + { + CleanPlace(); + T.Equal(0, Lawbook.Laws.Count, "fixture: rows an earlier test kept"); + T.Check(!Watch.AnyLaw, "Watch.AnyLaw is on with an empty lawbook"); + Building t1 = Table(); + Building t2 = Table(near: t1.Position); + T.Check(Switch(t1) == null, "an empty lawbook shows the court place switch"); + + Law row = AnyLaw(); + T.Check(Watch.AnyLaw, "Watch.AnyLaw is off with a row in the book"); + NeedSwitch(t1, "a table with a law in the book"); + + Lawbook.SetEnabled(row, false); + T.Check(Watch.AnyLaw, "Watch.AnyLaw is off while the book holds a switched-off row"); + NeedSwitch(t1, "a table while the only row is switched off"); + Lawbook.SetEnabled(row, true); + + Select(t1, t2); + T.Equal(2, Find.Selector.NumSelected, "fixture: selected tables"); + T.Check(!t1.GetGizmos().OfType().Any() && !t2.GetGizmos().OfType().Any(), + "two selected tables show the court place switch"); + + Lawbook.Delete(row); + T.Check(!Watch.AnyLaw, "Watch.AnyLaw is still on after the last row was deleted"); + T.Check(Switch(t1) == null, "the switch still shows after the last row was deleted"); + } + + [BlaxTest("court place: tables, the party spot and the campfire are offered; walls, enemy and unowned buildings are not")] + public static void KindRule() + { + CleanPlace(); + AnyLaw(); + IntVec3 near = Fixtures.PawnCell(); + Building table = Table(near: near); + Building party = Make(ThingDefOf.PartySpot, Faction.OfPlayer, near: near); + Building campfire = Make(ThingDefOf.Campfire, Faction.OfPlayer, near: near); + Building wall = Make(ThingDefOf.Wall, Faction.OfPlayer, ThingDefOf.WoodLog, near); + Faction hostile = Fixtures.HostileFaction(); + T.NotNull(hostile, "fixture: a hostile faction"); + Building enemy = Table(hostile, near); + Building unowned = Make(ThingDefOf.Table1x2c, null, ThingDefOf.WoodLog, near); + T.Check(unowned.Faction == null, "fixture: the unowned table belongs to " + unowned.Faction); + + foreach (var (b, what) in new[] { (table, "a table"), (party, "the party spot"), (campfire, "the campfire") }) + { + T.Check(CourtPlace.CanBe(b), what + " can't be a court place"); + NeedSwitch(b, what); + } + foreach (var (b, what) in new[] { (wall, "a wall"), (enemy, "an enemy table"), (unowned, "an unowned table") }) + { + T.Check(!CourtPlace.CanBe(b), what + " can be a court place"); + T.Check(Switch(b) == null, what + " shows the court place switch"); + T.Check(!CourtPlace.Set(b), "Set took " + what); + T.Equal(null, CourtPlace.For(Map), "court place after Set refused " + what); + } + T.Check(!CourtPlace.EligibleDef(ThingDefOf.Wall), "the wall def passes the kind rule"); + T.Check(CourtPlace.EligibleDef(ThingDefOf.PartySpot) && CourtPlace.EligibleDef(ThingDefOf.Campfire) && CourtPlace.EligibleDef(ThingDefOf.Table1x2c), + "the party spot, campfire or table def fails the kind rule"); + + // Minifiable but not furniture (Core Buildings_Power.xml, designation category Power): no court place. + T.Check(ThingDefOf.Battery.Minifiable && ThingDefOf.Battery.designationCategory?.defName != "Furniture", "fixture: the battery is not minifiable non-furniture"); + T.Check(!CourtPlace.EligibleDef(ThingDefOf.Battery), "the battery def passes the kind rule"); + Building battery = Make(ThingDefOf.Battery, Faction.OfPlayer, near: near); + T.Check(Switch(battery) == null, "a battery shows the court place switch"); + + // The impassable rule alone: an eating surface passes while standable and fails while impassable. + T.Check(CourtPlace.EligibleDef(EatingSurface(Traversability.Standable)), "a standable eating surface fails the kind rule"); + T.Check(!CourtPlace.EligibleDef(EatingSurface(Traversability.Impassable)), "an impassable eating surface passes the kind rule"); + } + + /// A def made for the kind rule only, never spawned: a building with an eating surface. + private static ThingDef EatingSurface(Traversability passability) => new ThingDef + { + defName = "BlaxLawsTest_EatingSurface_" + passability, + category = ThingCategory.Building, + thingClass = typeof(Building), + building = new BuildingProperties(), + surfaceType = SurfaceType.Eat, + passability = passability, + }; + + [BlaxTest("court place: 200 selected walls get no switch, and the postfix costs under 0.1 ms for all of them per frame")] + public static void TwoHundredWalls() + { + CleanPlace(); + AnyLaw(); + List walls = WallBlock(10, 20); + Select(walls.ToArray()); + // Selector.MaxNumSelected is 200 (RimWorld/Selector.cs:22, 377): the block fills the selection. + T.Equal(200, Find.Selector.NumSelected, "selected walls"); + foreach (Thing w in walls) + T.Check(!w.GetGizmos().OfType().Any(), "a selected wall shows the court place switch: " + w); + + var buildings = walls.Cast().ToArray(); + IEnumerable original = Enumerable.Empty(); + foreach (Building b in buildings) + { + IEnumerable r = original; + Patch_Building_GetGizmos.Postfix(b, ref r); + T.Check(ReferenceEquals(r, original), "the postfix wrapped the gizmos of a wall among 200 selected"); + } + long best = DetectionKit.BestOf(() => + { + for (int i = 0; i < buildings.Length; i++) + { + IEnumerable r = original; + Patch_Building_GetGizmos.Postfix(buildings[i], ref r); + } + }); + double limit = 0.0001 * System.Diagnostics.Stopwatch.Frequency; + T.Info("hook P on 200 selected walls: " + DetectionKit.Ms(best) + " ms per frame"); + T.Check(best <= limit, "hook P on 200 selected walls costs " + DetectionKit.Ms(best) + " ms per frame, over 0.1 ms"); + } + + /// A solid w x h block of player walls on clear ground: solid, so it encloses no room. + private static List WallBlock(int w, int h) + { + Map map = Map; + IntVec3 anchor = Fixtures.PawnCell(); + District district = anchor.GetDistrict(map); + CellRect Rect(IntVec3 o) => new CellRect(o.x, o.z, w, h); + bool Fits(IntVec3 o) => Rect(o).Cells.All(c => Fixtures.Buildable(c, map, district) && c.GetFirstPawn(map) == null); + if (!CellFinder.TryFindRandomCellNear(anchor, map, 60, Fits, out IntVec3 origin)) + T.Fail("fixture: no clear " + w + "x" + h + " block near the colony"); + Fixtures.ClearGround(Rect(origin).Cells, map); + var walls = new List(); + foreach (IntVec3 c in Rect(origin).Cells) + { + Thing wall = ThingMaker.MakeThing(ThingDefOf.Wall, ThingDefOf.WoodLog); + wall.SetFaction(Faction.OfPlayer); + walls.Add(DetectionKit.Place(wall, c)); + } + return walls; + } + + // ---- crates, deconstruction, losing it --------------------------------------------------- + + [BlaxTest("court place: uninstalled into a crate it reads as no place; installed elsewhere it is the place again; a place set meanwhile replaces it")] + public static void CrateFollowsTheBuilding() + { + MinifiedThing crate = null; + CleanPlace(() => crate); + Building t1 = Table(); + Building t2 = Table(near: t1.Position); + T.Check(CourtPlace.Set(t1), "Set refused the first table"); + string id = t1.ThingID; + IntVec3 before = t1.Position; + + crate = Uninstall(t1, t1.Position); + T.Check(!t1.Spawned && crate.InnerThing == t1, "fixture: the table is not inside its crate"); + T.Equal(null, CourtPlace.For(Map), "court place while the table is in its crate"); + T.Equal(No, CourtPlaceUi.Line(Map), "tab line while the table is in its crate"); + T.Check(CourtPlaceUi.CanClear(Map), "Clear is not offered while the crated place is stored"); + + // Never the old footprint, which is free once the table is in its crate. + CellRect old = GenAdj.OccupiedRect(before, Rot4.North, t1.def.size); + bool AwayFromOld(IntVec3 c) => !GenAdj.OccupiedRect(c, Rot4.North, t1.def.size).Overlaps(old); + Building back = Reinstall(crate, t2.Position + new IntVec3(6, 0, 0), AwayFromOld); + T.Equal(id, back.ThingID, "fixture: the installed table"); + T.Check(back.Position != before, "fixture: the table went back to its old spot " + before); + T.Equal(t1, CourtPlace.For(Map), "court place after the table was installed elsewhere"); + + // Crated again; the second table is set meanwhile on the same map, so the crated place is dropped. + crate = Uninstall(t1, t1.Position); + T.Check(CourtPlace.Set(t2), "Set refused the second table"); + Reinstall(crate, t1.Position); + T.Equal(t2, CourtPlace.For(Map), "court place after the old place was installed again"); + T.Check(!SaveXml().Contains(Ref(t1)), "the save still names the old place after a newer one was set"); + } + + [BlaxTest("court place: a crate from elsewhere installed on a map that has a place: the place set last wins, and the save keeps only it")] + public static void ArrivingCrateLoses() + { + MinifiedThing crate = null; + CleanPlace(() => crate); + Building t1 = Table(); + Building t2 = Table(near: t1.Position); + T.Check(CourtPlace.Set(t1), "Set refused the first table"); + // Off this map: the crate is in no holder on this map, as in a caravan or on another map (MapHeld null). + crate = Fixtures.Track(t1.MakeMinified()); + T.Check(crate.MapHeld == null && t1.MapHeld == null, "fixture: the crate is still on the map"); + Fixtures.Tick(1); + T.Check(CourtPlace.Set(t2), "Set refused the second table"); + T.Check(Fixtures.Comp.CourtPlaceEntries.Any(e => e?.building == t1), "fixture: the place set on the first table was dropped while it was away"); + + Building arrived = Reinstall(crate, t1.Position); + T.Equal(t1, arrived, "fixture: the arrived table"); + T.Equal(t2, CourtPlace.For(Map), "court place after an older place arrived in a crate"); + AnyLawOnce(); + T.Check(!NeedSwitch(t1, "the arrived table").isActive(), "the arrived table's switch is on"); + T.Check(!Fixtures.Comp.CourtPlaceEntries.Any(e => e?.building == t1), "the place that arrived in a crate is still stored after it lost"); + string xml = SaveXml(); + T.Check(xml.Contains(Ref(t2)), "the save doesn't name the place set last"); + T.Check(!xml.Contains(Ref(t1)), "the save still names the place that arrived in a crate"); + T.Equal(t2, CourtPlace.For(Map), "court place after the save"); + } + + [BlaxTest("court place: after a crate lost on arrival, destroying the winner before any save leaves no place, never the older one")] + public static void ArrivedLoserNeverFallsBack() + { + MinifiedThing crate = null; + CleanPlace(() => crate); + Building t1 = Table(); + Building t2 = Table(near: t1.Position); + T.Check(CourtPlace.Set(t1), "Set refused the first table"); + crate = Fixtures.Track(t1.MakeMinified()); + T.Check(crate.MapHeld == null, "fixture: the crate is still on the map"); + Fixtures.Tick(1); + T.Check(CourtPlace.Set(t2), "Set refused the second table"); + Reinstall(crate, t1.Position); + T.Equal(t2, CourtPlace.For(Map), "court place after an older place arrived in a crate"); + + t2.Destroy(DestroyMode.Vanish); + T.Equal(null, CourtPlace.For(Map), "court place after the winner was destroyed, before any save"); + T.Check(!CourtPlace.IsPlace(t1), "the older place that arrived in a crate came back"); + T.Equal(No, CourtPlaceUi.Line(Map), "tab line after the winner was destroyed"); + } + + [BlaxTest("court place: a crate set later elsewhere wins on arrival; uninstalled again before any save, the map has no place")] + public static void ArrivingCrateWins() + { + MinifiedThing crate = null, again = null; + CleanPlace(() => crate, () => again); + Building t1 = Table(); + Building t2 = Table(near: t1.Position); + T.Check(CourtPlace.Set(t1), "Set refused the first table"); + crate = Fixtures.Track(t1.MakeMinified()); + T.Check(crate.MapHeld == null, "fixture: the crate is still on the map"); + T.Check(CourtPlace.Set(t2), "Set refused the second table"); + // As if the first table had been set later on another map before it was crated and carried here. + CourtPlaceEntry crated = Fixtures.Comp.CourtPlaceEntries.FirstOrDefault(e => e?.building == t1); + CourtPlaceEntry stays = Fixtures.Comp.CourtPlaceEntries.FirstOrDefault(e => e?.building == t2); + T.Check(crated != null && stays != null, "fixture: the entries of both tables"); + crated.setTick = stays.setTick + 1; + + Reinstall(crate, t1.Position); + T.Equal(t1, CourtPlace.For(Map), "court place after a newer place arrived in a crate"); + T.Check(!Fixtures.Comp.CourtPlaceEntries.Any(e => e?.building == t2), "the older place is still stored after a newer one arrived"); + + again = Uninstall(t1, t1.Position); + T.Equal(null, CourtPlace.For(Map), "court place after the winner went back into its crate, before any save"); + T.Check(!CourtPlace.IsPlace(t2), "the older place came back after the winner was uninstalled"); + } + + private static bool NeedSwitchOrNull(Building b) + { + AnyLawOnce(); + Command_CourtPlace cmd = Switch(b); + return cmd != null && cmd.isActive(); + } + + private static void AnyLawOnce() + { + if (Lawbook.Find(Key, null, LawStage.DidIt) == null) + AnyLaw(); + } + + [BlaxTest("court place: deconstructed, the tab reads 'No court place' at once, and a save written after it holds no reference")] + public static void DeconstructClearsAtOnce() + { + CleanPlace(); + Building t1 = Table(); + T.Check(CourtPlace.Set(t1), "Set refused the table"); + T.Check(SaveXml().Contains(Ref(t1)), "the save doesn't name the place before the deconstruction"); + var items = new HashSet(Map.listerThings.ThingsInGroup(ThingRequestGroup.HaulableEver)); + Fixtures.OnCleanup(() => + { + foreach (Thing t in Map.listerThings.ThingsInGroup(ThingRequestGroup.HaulableEver).ToList()) + { + if (!items.Contains(t) && !t.Destroyed && !Fixtures.IsFixtureThing(t)) + t.Destroy(DestroyMode.Vanish); + } + }); + + t1.Destroy(DestroyMode.Deconstruct); + T.Equal(null, CourtPlace.For(Map), "court place right after the deconstruction"); + T.Equal(No, CourtPlaceUi.Line(Map), "tab line right after the deconstruction"); + T.Check(!CourtPlaceUi.CanClear(Map), "Clear is still offered for a deconstructed place"); + // A destroyed thing saves as "null" anyway (Verse/Scribe_References.cs:60-68): check the save's own drop. + string xml = SaveXml(); + T.Check(!xml.Contains(Ref(t1)), "the save names the deconstructed place"); + T.Check(!Fixtures.Comp.CourtPlaceEntries.Any(e => e?.building == t1), "the deconstructed place is still stored after a save"); + T.Check(!xml.Contains("null"), "the save wrote an entry for the deconstructed place: " + xml); + } + + [BlaxTest("court place: claimed by another faction it reads as no place; Clear works with an empty lawbook")] + public static void ClaimedReadsAsNone() + { + CleanPlace(); + T.Equal(0, Lawbook.Laws.Count, "fixture: rows an earlier test kept"); + Building t1 = Table(); + T.Check(CourtPlace.Set(t1), "Set refused the table with an empty lawbook"); + T.Equal(t1, CourtPlace.For(Map), "court place"); + T.Check(CourtPlace.IsPlace(t1), "IsPlace is false for the place"); + + Faction hostile = Fixtures.HostileFaction(); + T.NotNull(hostile, "fixture: a hostile faction"); + t1.SetFaction(hostile); + T.Equal(null, CourtPlace.For(Map), "court place after another faction claimed it"); + T.Check(!CourtPlace.IsPlace(t1), "IsPlace is true for a claimed place"); + T.Equal(No, CourtPlaceUi.Line(Map), "tab line for a claimed place"); + + T.Check(CourtPlaceUi.CanClear(Map), "Clear is not offered for a claimed place"); + CourtPlace.Clear(Map); + T.Check(!CourtPlaceUi.CanClear(Map), "Clear is still offered after Clear"); + t1.SetFaction(Faction.OfPlayer); + T.Equal(null, CourtPlace.For(Map), "court place after Clear and a reclaim"); + } + + // ---- the Laws tab ------------------------------------------------------------------------ + + [BlaxTest("court place: the tab line reads no place, the place with 'Not a proper room' outdoors, and the room's role, impressiveness label and number in a room")] + public static void TabLine() + { + CleanPlace(); + T.Equal(No, CourtPlaceUi.Line(Map), "tab line without a place"); + T.Check(!CourtPlaceUi.CanClear(Map), "Clear is offered without a place"); + + Building outdoor = Table(); + T.Check(CourtPlace.Set(outdoor), "Set refused the outdoor table"); + T.Equal(null, CourtPlace.RoomOf(outdoor), "court room of a table on open ground"); + string line = CourtPlaceUi.Line(Map); + T.Check(line.Contains(outdoor.LabelCap) && line.Contains(NotRoom), "tab line for a table on open ground: " + line); + T.Check(CourtPlaceUi.CanClear(Map), "Clear is not offered with a place"); + + PrisonRoom cell = EnforceFixtures.PrisonCell(); + var inRoom = (Building)ThingMaker.MakeThing(ThingDefOf.Table1x2c, ThingDefOf.WoodLog); + inRoom.SetFaction(Faction.OfPlayer); + Room room = cell.bed.GetRoom(); + DetectionKit.Place(inRoom, DetectionKit.FreeCell(cell.inside, ThingDefOf.Table1x2c.size, c => c.GetRoom(Map) == room)); + Map.regionAndRoomUpdater.TryRebuildDirtyRegionsAndRooms(); + T.Check(CourtPlace.Set(inRoom), "Set refused the table in the room"); + T.Equal(inRoom, CourtPlace.For(Map), "court place after setting the table in the room"); + Room court = CourtPlace.RoomOf(inRoom); + T.Check(court != null && court == inRoom.GetRoom() && CourtPlace.IsProperRoom(court), "court room of the table in the room: " + court); + float stat = court.GetStat(RoomStatDefOf.Impressiveness); + string stage = RoomStatDefOf.Impressiveness.GetScoreStage(stat)?.label; + string number = RoomStatDefOf.Impressiveness.ScoreToString(stat); + string role = court.Role.PostProcessedLabelCap(court); + line = CourtPlaceUi.Line(Map); + T.Check(!stage.NullOrEmpty(), "fixture: the room's impressiveness has no stage label"); + T.Check(line.Contains(inRoom.LabelCap) && line.Contains(role) && line.Contains(stage) && line.Contains("(" + number + ")") && !line.Contains(NotRoom), + "tab line for the table in the room: '" + line + "', expected " + role + ", " + stage + " (" + number + ")"); + T.Check(NeedSwitchOrNull(inRoom), "the switch on the place in the room is off"); + T.Check(NeedSwitchDesc(inRoom).Contains(stage), "the switch's tooltip doesn't name the room's impressiveness"); + } + + private static string NeedSwitchDesc(Building b) => NeedSwitch(b, "the table").Desc; + + [BlaxTest("court place: the picker takes the player's tables and party spot, refuses walls, enemy tables and pawns, and a pick sets the place")] + public static void Picker() + { + CleanPlace(); + Fixtures.OnCleanup(() => + { + if (Find.Targeter.IsTargeting) + Find.Targeter.StopTargeting(); + Find.MainTabsRoot?.EscapeCurrentTab(false); + }); + IntVec3 near = Fixtures.PawnCell(); + Building table = Table(near: near); + Building party = Make(ThingDefOf.PartySpot, Faction.OfPlayer, near: near); + Building wall = Make(ThingDefOf.Wall, Faction.OfPlayer, ThingDefOf.WoodLog, near); + Faction hostile = Fixtures.HostileFaction(); + T.NotNull(hostile, "fixture: a hostile faction"); + Building enemy = Table(hostile, near); + Pawn colonist = Fixtures.Colonist(); + + TargetingParameters tp = CourtPlace.TargetParams(); + T.Check(tp.CanTarget(new TargetInfo(table)), "the picker refuses a table"); + T.Check(tp.CanTarget(new TargetInfo(party)), "the picker refuses the party spot"); + T.Check(!tp.CanTarget(new TargetInfo(wall)), "the picker takes a wall"); + T.Check(!tp.CanTarget(new TargetInfo(enemy)), "the picker takes an enemy table"); + T.Check(!tp.CanTarget(new TargetInfo(colonist)), "the picker takes a colonist"); + + CourtPlaceUi.BeginPick(); + T.Check(Find.Targeter.IsTargeting, "'Pick court place' started no targeting"); + Find.Targeter.StopTargeting(); + + CourtPlaceUi.Pick(new LocalTargetInfo(wall)); + T.Equal(null, CourtPlace.For(Map), "court place after picking a wall"); + CourtPlaceUi.Pick(new LocalTargetInfo(party)); + T.Equal(party, CourtPlace.For(Map), "court place after picking the party spot"); + T.Check(Find.MainTabsRoot.OpenTab == BlaxLawsDefOf.BlaxLaws_Laws, "the pick didn't reopen the Laws tab"); + } + + // ---- guards ------------------------------------------------------------------------------------ + + [BlaxTest("court place: a throw in hook P's gizmo postfix or in the switch logs once and the gizmo bar keeps vanilla's gizmos")] + public static void ThrowKeepsGizmoBar() + { + CleanPlace(); + AnyLaw(); + Building t1 = Table(); + Select(t1); + List plain = t1.GetGizmos().Where(g => !(g is Command_CourtPlace)).ToList(); + T.Check(plain.Count > 0, "fixture: the table shows no vanilla gizmo"); + LawsLog.ResetOnce(); + + foreach (var (what, where) in new[] { ("switch", Patch_Building_GetGizmos.Where + ", the switch failed"), ("postfix", Patch_Building_GetGizmos.Where + " failed") }) + { + LawsTestHooks.CourtSwitchThrows = what == "switch"; + LawsTestHooks.CourtGizmoThrows = what == "postfix"; + T.ExpectErrors(where, 1); + for (int i = 0; i < 3; i++) + { + List shown = null; + try + { + shown = t1.GetGizmos().ToList(); + } + catch (Exception e) + { + T.Fail("a throw in the " + what + " broke the gizmo bar: " + e.GetType().Name + ": " + e.Message); + } + T.Check(!shown.OfType().Any(), "the gizmo bar shows the switch while the " + what + " throws"); + T.Equal(plain.Count, shown.Count, "vanilla gizmos while the " + what + " throws"); + } + } + LawsTestHooks.CourtSwitchThrows = false; + LawsTestHooks.CourtGizmoThrows = false; + NeedSwitch(t1, "the table after the throws stopped"); + } + + [BlaxTest("court place save: a 1.0.0 save without the courtPlaces node loads with no warning or error, an empty list and no place")] + public static void OldSaveWithoutNode() + { + CleanPlace(); + GameComponent_BlaxLaws game = Fixtures.Comp; + T.NotNull(game, "fixture: the game's component"); + // The component's node as 1.0.0 wrote it: no courtPlaces. + string path = Path.Combine(Path.GetTempPath(), "BlaxLawsTest_court_1.0.0_" + Guid.NewGuid().ToString("N") + ".xml"); + File.WriteAllText(path, + "\n" + + " \n" + + " 12345\n" + + " 1\n" + + " \n" + + " 1\n" + + " \n" + + " \n" + + "\n"); + Fixtures.OnCleanup(() => + { + if (Scribe.mode != LoadSaveMode.Inactive) + Scribe.ForceStop(); + GameComponent_BlaxLaws.Remember(game, Current.Game); + File.Delete(path); + }); + + var logged = new List(); + UnityEngine.Application.LogCallback listen = (text, stack, type) => + { + if (type != UnityEngine.LogType.Log) + lock (logged) logged.Add(type + ": " + text); + }; + GameComponent_BlaxLaws old = null; + UnityEngine.Application.logMessageReceivedThreaded += listen; + try + { + Scribe.loader.InitLoading(path); + Scribe_Deep.Look(ref old, "saveable"); + Scribe.loader.FinalizeLoading(); + } + finally + { + UnityEngine.Application.logMessageReceivedThreaded -= listen; + GameComponent_BlaxLaws.Remember(game, Current.Game); + } + T.Equal(LoadSaveMode.Inactive, Scribe.mode, "Scribe mode after the load"); + T.Check(logged.Count == 0, "loading the 1.0.0 node logged: " + string.Join(" | ", logged.Take(3))); + T.NotNull(old, "the component loaded from the 1.0.0 node"); + T.Check(old.CourtPlaceEntries != null, "the court place list is null after loading a 1.0.0 save"); + T.Equal(0, old.CourtPlaceEntries.Count, "court place entries after loading a 1.0.0 save"); + T.Equal(null, old.CourtPlaceOn(Map), "court place of the 1.0.0 save"); + T.Check(ReferenceEquals(game, GameComponent_BlaxLaws.Instance), "fixture: the game's component was not given back"); + } + + // ---- DLC buildings ------------------------------------------------------------------------- + + [BlaxTest("court place: a throne gets the switch with Royalty; without it there is no throne def")] + public static void Throne() + { + ThingDef def = DefDatabase.GetNamedSilentFail("Throne"); + if (!ModsConfig.RoyaltyActive) + T.Check(def == null, "a Throne def exists without Royalty"); + T.NeedsDlc("Royalty", ModsConfig.RoyaltyActive); + CleanPlace(); + AnyLaw(); + T.NotNull(def, "the Throne def"); + Building throne = Make(def, Faction.OfPlayer); + T.Check(throne is Building_Throne, "fixture: the throne is a " + throne.GetType().Name); + NeedSwitch(throne, "a throne").toggleAction(); + T.Equal(throne, CourtPlace.For(Map), "court place after switching it on on a throne"); + } + + [BlaxTest("court place: the lectern and the ritual spot get the switch with Ideology; without it neither def exists")] + public static void LecternAndRitualSpot() + { + if (!ModsConfig.IdeologyActive) + { + T.Check(ThingDefOf.Lectern == null && DefDatabase.GetNamedSilentFail("Lectern") == null, "a Lectern def exists without Ideology"); + T.Check(ThingDefOf.RitualSpot == null && DefDatabase.GetNamedSilentFail("RitualSpot") == null, "a RitualSpot def exists without Ideology"); + } + T.NeedsDlc("Ideology", ModsConfig.IdeologyActive); + CleanPlace(); + AnyLaw(); + IntVec3 near = Fixtures.PawnCell(); + foreach (ThingDef def in new[] { ThingDefOf.Lectern, ThingDefOf.RitualSpot }) + { + T.NotNull(def, "a ritual def"); + Building b = Make(def, Faction.OfPlayer, near: near); + NeedSwitch(b, def.defName).toggleAction(); + T.Equal(b, CourtPlace.For(Map), "court place after switching it on on the " + def.defName); + } + } + + // ---- save and removal ------------------------------------------------------------------------ + + [BlaxTest("court place save: a table is the court place at the first save (setup)", Order = 1000)] + public static void SaveSetup() + { + CourtPlace.Clear(Map); + Building table = Table(); + Fixtures.Keep(table); + T.Check(CourtPlace.Set(table), "Set refused the kept table"); + T.Carry[CarryPlace] = table.ThingID; + } + + [BlaxTest("court place save: after the reload the same table is the court place", phase: 2, Order = -1)] + public static void SaveKeepsPlace() + { + T.Check(T.Carry.TryGetValue(CarryPlace, out string id), "the setup carried no court place"); + Building place = CourtPlace.For(Map); + T.NotNull(place, "court place after the reload"); + T.Equal(id, place.ThingID, "court place after the reload"); + T.Check(CourtPlace.Valid(place) && CourtPlace.IsPlace(place), "the reloaded place fails the validity check"); + string line = CourtPlaceUi.Line(Map); + T.Check(line.Contains(place.LabelCap) && !line.Contains(No), "tab line after the reload: " + line); + } + + [BlaxTest("removal: a save with a court place loads with exactly the two removal errors, and the table stays the player's", phase: 3)] + public static void RemovalWithPlace() + { + T.Check(T.Carry.TryGetValue(CarryPlace, out string id), "the setup carried no court place"); + string xml = File.ReadAllText(GenFilePaths.FilePathForSavedGame(TestRunner.Phase3SaveName)); + T.Check(xml.Contains("") && xml.Contains(">Thing_" + id + "<"), "the phase-3 save holds no court place naming Thing_" + id); + T.Equal(2, T.Phase3LoadErrors.Count, "errors while loading the phase-3 save (" + string.Join(" | ", T.Phase3LoadErrors.Take(3)) + ")"); + Building table = FindBuilding(id); + T.NotNull(table, "the court place's table after the removal load"); + T.Check(table.Spawned && table.Faction == Faction.OfPlayer, "the table after the removal load: spawned " + table.Spawned + ", faction " + table.Faction); + T.Equal(null, CourtPlace.For(table.Map), "court place in the fresh component"); + } + } +} diff --git a/Tests/BlaxLawsTests/Source/SmokeTests.cs b/Tests/BlaxLawsTests/Source/SmokeTests.cs index 723d9ac..d8aee9d 100644 --- a/Tests/BlaxLawsTests/Source/SmokeTests.cs +++ b/Tests/BlaxLawsTests/Source/SmokeTests.cs @@ -18,6 +18,9 @@ namespace BlaxLawsTests "BlaxLaws_Outcome_Repealed", "BlaxLaws_Outcome_BreakEnded", "BlaxLaws_Outcome_NotEnforced", "BlaxLaws_DrugOption_Any", "BlaxLaws_DrugOption_Hard", "BlaxLaws_DrugOption_Social", "BlaxLaws_EmptyBook", "BlaxLaws_CaseFiled", + "BlaxLaws_CourtPlace", "BlaxLaws_CourtPlaceDesc", "BlaxLaws_CourtPlaceHeader", "BlaxLaws_CourtPlaceLine", + "BlaxLaws_CourtRoomStats", "BlaxLaws_NotProperRoom", "BlaxLaws_NoCourtPlace", "BlaxLaws_CourtPlaceTip", + "BlaxLaws_PickCourtPlace", "BlaxLaws_PickCourtPlaceTip", "BlaxLaws_ClearCourtPlace", "BlaxLaws_ClearCourtPlaceTip", "BlaxLaws_SettingEnforceLaws", "BlaxLaws_SettingShowTab", "BlaxLaws_SettingCaseMessages", "BlaxLaws_SettingJailLetters", "BlaxLaws_SettingEnforcers", "BlaxLaws_EnforcersWardensFirst", "BlaxLaws_EnforcersWardensOnly", "BlaxLaws_SettingSubdueCatharsis", "BlaxLaws_SettingPlayerOrdersExempt", "BlaxLaws_SettingCooldownDays", diff --git a/docs/design.md b/docs/design.md index 8e7b432..d932bff 100644 --- a/docs/design.md +++ b/docs/design.md @@ -148,7 +148,7 @@ All state lives in one `GameComponent_BlaxLaws`. Laws are colony policy across e - A random int token for ids handed to other mods later, as Castes does. - From the 2026-12-03 parts, each a new Scribe field with a default, so a save written before them loads unchanged: - On `Law`: `punishmentOptions` (one string, `key=value;...`, empty means the entry's defaults), `alongside` (a list of PunishmentDef defNames), `instead` (a PunishmentDef defName, default `Warn`) and `where` (`Private` or `CourtPlace`, default `Private`). From Lawbook step 2 `punishment` may also hold `Named/`. - - In the component: the court place per map as `Scribe_References` on the building (see "Court place"), the punishment runs that wait for the court hour, and the reform state: per pawn the expiry ticks of "Paid my debt", the stat part and the break-weight effect, the break def it halves, and the tick of the last trait step. + - In the component: the court places as a deep list of small entries, each a building reference and the tick it was set, with no map key (see "Court place"), the punishment runs that wait for the court hour, and the reform state: per pawn the expiry ticks of "Paid my debt", the stat part and the break-weight effect, the break def it halves, and the tick of the last trait step. - On `Case`: the participants of a group punishment (references plus names), the squad result (struck, spared), the reform roll and its outcome, the snapshot fields of "Lose own bedroom and lose role" (shared with the give-back) and the end tick of a timed status punishment. - Pawn references: Castes' pattern. `Scribe_References` with `logNullErrors` off; on save and after load, references to Discarded or destroyed pawns become null and the case keeps the name. Closed cases older than the retention setting (60 days) are pruned on save. - Not saved: the watched-act flags and sets, the act catalogue and the enforcement queue (all rebuilt), the instance cache (a weak reference, as in Castes). @@ -182,7 +182,7 @@ All state lives in one `GameComponent_BlaxLaws`. Laws are colony policy across e - B. `RecordsUtility.Notify_BillDone(Pawn billDoer, List products)` (RimWorld/RecordsUtility.cs:52), static, two nested loops, not inlinable. Bill category; the offender is `billDoer`, the recipe `billDoer.CurJob?.RecipeDef` (a null files nothing). `Toils_Recipe.FinishRecipeAndStartStoringProduct` calls it right after `bill.Notify_IterationCompleted` for every bill type, surgery and Biotech's mech gestators included, always with the pawn that finished the bill (Verse.AI/Toils_Recipe.cs:197-200), and nothing else calls `Notify_IterationCompleted`. That method itself isn't patched: `Bill`'s version is empty (RimWorld/Bill.cs:278-280) and `Bill_Medical` calls it as a non-virtual base call the JIT may inline (RimWorld/Bill_Medical.cs:129). - Two more hooks serve the jail, not detection (see "Enforcement runs a tick later"): K on `Pawn_GuestTracker.CapturedBy` and L on `GenGuest.PrisonerRelease`. - Hooks of the 2026-12-03 parts, each behind its own static flag, so they cost one field read while no court place, punishment run or reform effect exists: - - P. `Building.GetGizmos` (Verse/Building.cs:401), postfix wrapping the iterator: the "Court place" switch ("Court place"). + - P. `Building.GetGizmos` (Verse/Building.cs:401), postfix wrapping the iterator: the "Court place" switch ("Court place"). Its flag is `Watch.AnyLaw` (the book has a row, disabled ones included), not `Watch.Any`, which is false while every row is off. Its second postfix, on `Building.SpawnSetup` (Verse/Building.cs:113), returns after one count while no court place is stored. - T. `PawnDiedOrDownedThoughtsUtility.GetThoughts` (RimWorld/PawnDiedOrDownedThoughtsUtility.cs:73), postfix: strips the death thoughts for a convict the execution corps killed ("Execution corps"). - W. `MentalBreakWorker.CommonalityFor` (Verse.AI/MentalBreakWorker.cs:11), postfix: halves the weight of a punished or witnessed break ("Reform", "Punishments in public"). - V. `RestUtility.IsValidBedFor` (RimWorld/RestUtility.cs:160), postfix: refuses a bedroom bed to a convict who lost its bedroom ("Lose own bedroom and lose role"). @@ -820,15 +820,17 @@ Not specced yet: the criminal record and probation (step 1), escalation (step 2) #### Court place -- **Players get:** Fabian's first ask of 2026-12-03. Select a building you own (any table, party spot, campfire, a throne with Royalty, a lectern or ritual spot with Ideology, or other furniture) and switch on "Court place". One place per map; switching it on elsewhere moves it. With the mouse over the switch the court room is outlined, the way the room stats button outlines a room. The Laws tab shows the place, its room's impressiveness against the courtroom setting, "Not a proper room" for an outdoor or open space, and a "Pick court place" button that lets you click a building on the map. The convene dialog starts at the place, "Court on its own" uses it, and public punishments (Enforcement, step 5) gather their crowd around it. Uninstalling the table into a crate and placing it again moves the court with it; deconstructing it or losing it clears the place, and the tab says "No court place". +- **Players get:** Fabian's first ask of 2026-12-03. Select a building you own (any table, party spot, campfire, a throne with Royalty, a lectern or ritual spot with Ideology, or other furniture) and switch on "Court place". One place per map; switching it on elsewhere moves it. With the mouse over the switch the court room is outlined, the way the room stats button outlines a room. The Laws tab shows the place, its room's impressiveness (against the courtroom setting once "Courtrooms" is built; 1.1.0 shows the number and vanilla's label), "Not a proper room" for an outdoor or open space, and a "Pick court place" button that lets you click a building on the map. The convene dialog starts at the place, "Court on its own" uses it, and public punishments (Enforcement, step 5) gather their crowd around it. Uninstalling the table into a crate and placing it again moves the court with it; deconstructing it or losing it clears the place, and the tab says "No court place". A crated place reads as no place until it is installed again; a place picked meanwhile on that map replaces it. A crate installed on a map that already has a place: the place set last wins. - **How:** - - Hook P, a postfix on `Building.GetGizmos` (Verse/Building.cs:401) that wraps the iterator (`ref IEnumerable __result`) and catches its own exceptions, since a throw inside an enumerator wrapper breaks the whole gizmo bar. It covers every building: the overrides of `ThingWithComps` and `Building_Throne` yield base first (Verse/ThingWithComps.cs:536; RimWorld/Building_Throne.cs:79-89). Gizmos are rebuilt every frame for every selected object (Verse/GizmoGridDrawer.cs:54-100), so it returns at once unless a law exists, the building's `Faction` is the player's, the def isn't impassable (thrones excepted) and `Find.Selector.SingleSelectedObject == this` (RimWorld/Selector.cs:74), the gate vanilla's room stats button uses (Verse/Building.cs:407). A box-select of 200 walls costs nothing. - - The Laws tab button: `Find.Targeter.BeginTargeting(TargetingParameters, Action, ...)` (RimWorld/Targeter.cs:93) with `canTargetBuildings` and a validator for the player's buildings (RimWorld/TargetingParameters.cs:17, 35). The convene dialog's place picker writes the same stored value. - - The room is read when used, never stored: `Room.ID` comes from a static counter and changes on every region rebuild (Verse/Room.cs:43, 594-600). For a passable building `Thing.GetRoom()` (Verse/RegionAndRoomQuery.cs:53); for impassable furniture vanilla's rule `Gizmo_RoomStats.GetRoomToShowStatsFor(Building)` (Verse/Gizmo_RoomStats.cs:89). Hovering the switch calls `Room.DrawFieldEdges()` (Verse/Room.cs:836). "Not a proper room" when `Room.ProperRoom` (:536) is false. A room of at most 100 cells, not outdoors, is a whole gathering area as vanilla counts it (RimWorld/GatheringsUtility.cs:347). - - Save: one `Scribe_References` per map in the component. It saves as "Thing_" + ThingID (Verse/Thing.cs:798), so the place is still kept by ThingID as before, and a destroyed thing saves as null (Verse/Scribe_References.cs:60-68). A minified place keeps its instance and ID inside the crate (RimWorld/MinifyUtility.cs:15, 23). Between saves every use re-checks `Spawned`, `Map`, `Faction == Faction.OfPlayer` and `Destroyed` (Verse/Thing.cs:180-200); a failed check reads as no place. No Destroy or DeSpawn hook is needed. + - Hook P, a postfix on `Building.GetGizmos` (Verse/Building.cs:401) that wraps the iterator (`ref IEnumerable __result`) and catches its own exceptions: the switch is built in a helper with its own try/catch, since C# allows no `yield` inside a try with a catch and a throw inside an enumerator wrapper breaks the whole gizmo bar. It covers every building: the overrides of `ThingWithComps` and `Building_Throne` yield base first (Verse/ThingWithComps.cs:536; RimWorld/Building_Throne.cs:79-89); `Building_BlastingCharge` alone never yields base (RimWorld/Building_BlastingCharge.cs:9) and gets no switch. Gizmos are rebuilt every frame for every selected object (Verse/GizmoGridDrawer.cs:62-100), so it returns at once unless a law exists (`Watch.AnyLaw`) and `Find.Selector.SingleSelectedObject == this` (RimWorld/Selector.cs:74), the gate vanilla's room stats button uses (Verse/Building.cs:407), and then the kind rule. A box-select of 200 walls costs nothing. + - Kind rule, cached per def: the building is spawned, not destroyed and the player's; impassable defs are refused except thrones (no vanilla throne is impassable: `ThroneBase` sets no passability and the default is Standable, Verse/BuildableDef.cs:13, so the exception only serves modded thrones); then a table (`ThingDef.IsTable`, Verse/ThingDef.cs:1008, or an eating surface), a `CompGatherSpot` (gather tables, campfire, Royalty's instruments, Ideology's autobong), the party spot by def (`ThingDefOf.PartySpot`, RimWorld/ThingDefOf.cs:679; it has no `CompGatherSpot`, Core Buildings_Misc.xml:1188-1215), a `Building_Throne`, Ideology's lectern and ritual spot by def (`ThingDefOf.Lectern` and `RitualSpot`, :813 and :687, `[MayRequireIdeology]`, null without it), or other minifiable furniture (designation category `Furniture`, looked up by name since `DesignationCategoryDefOf` has none). Not the `RitualFocus` building tag or the `ritualFocus` field: the tag sits on graves too (Buildings_Misc.xml:825) and the field on graves, sarcophagi and sculptures. + - The switch is `Command_CourtPlace`, a `Command_Toggle` subclass, since `Command_Toggle` has no hover member (Verse/Command_Toggle.cs:7-60); it overrides `GizmoUpdateOnMouseover` (Verse/Gizmo.cs:49). Icon `TexButton.ShowRoomStats` (Verse/TexButton.cs:146), the room stats button's own texture. Its tooltip names the room state. + - The Laws tab button: closes the tab with `Find.MainTabsRoot.EscapeCurrentTab(false)` (RimWorld/MainTabsRoot.cs:32), as vanilla does before map picking, then `Find.Targeter.BeginTargeting(TargetingParameters, Action, ...)` (RimWorld/Targeter.cs:93) with `canTargetPawns` off, `canTargetBuildings` on, `mapObjectTargetsMustBeAutoAttackable` off (it defaults to true and refuses buildings whose `building.isTargetable` is false, RimWorld/TargetingParameters.cs:55, 277-281) and the kind rule as validator (:35). A pick reopens the tab. The convene dialog's place picker writes the same stored value. Beside it "Clear", drawn while the map has a stored place, also with an empty book, and "Show", which jumps to the place. + - The room is read when used, never stored: `Room.ID` comes from a static counter and changes on every region rebuild (Verse/Room.cs:43, 594-600). For every building vanilla's rule `Gizmo_RoomStats.GetRoomToShowStatsFor(Building)` (Verse/Gizmo_RoomStats.cs:89-132): `GetRoom()` for a passable building, the interaction cell or the edge ring for an impassable one, and null for an unspawned or fogged building, a fogged room or a room whose role is None. A huge room (over 60 regions) or an outdoor space is proper or not but gets no stats and role None (Verse/Room.cs:862-877), so it reads null and never shows a roomless score. "Not a proper room" when that is null or `Room.ProperRoom` (:536) is false. The tab shows `room.Role.PostProcessedLabelCap(room)`, `RoomStatDefOf.Impressiveness.GetScoreStage(stat).label` and `ScoreToString(stat)`, as the room stats button does (Verse/Gizmo_RoomStats.cs:40-42). Hovering the switch calls `Room.DrawFieldEdges()` (Verse/Room.cs:836) only for a proper room. A room of at most 100 cells, not outdoors, is a whole gathering area as vanilla counts it (RimWorld/GatheringsUtility.cs:347). + - Save: a deep list `courtPlaces` of entries with a building reference and the tick it was set, no map key: a `Map` reference fails once that map is removed, and a crate can carry the place to another map. The place of map M is the entry spawned on M that was set last, if it passes the validity check. Deep, not a bare reference list: a save without the node (1.0.0) loads the list as null and registers no ids (Verse/Scribe_Collections.cs:372-379), where a missing reference list would warn "Not all loadIDs which were read were consumed" on every load (Verse/LoadIDsWantedBank.cs:33-55). A reference saves as "Thing_" + ThingID (Verse/Thing.cs:798) and a destroyed thing as null (Verse/Scribe_References.cs:60-78); there is no `logNullErrors` parameter (:7). A minified place keeps its instance and ID inside the crate (RimWorld/MinifyUtility.cs:15, 23) and a reinstall spawns that same instance with the worker's faction (RimWorld/Blueprint_Install.cs:99-112; RimWorld/Blueprint.cs:71-75). On save and in `FinalizeInit` (after the maps spawned their things, Verse/Game.cs:614-636) entries are dropped whose building is null, destroyed (a removed map discards its things, Verse/Thing.cs:1123-1143) or unspawned outside any container, and of the entries spawned on one map only the newest stays; `PostLoadInit` drops only null and destroyed ones. Setting a place on a map drops every entry whose `MapHeld` is that map. A stored place that spawns (a crate installed) settles the conflict at once: a second postfix of hook P on `Building.SpawnSetup` (Verse/Building.cs:113; a reinstall spawns the same instance, RimWorld/Blueprint_Install.cs:99-112) keeps only the newest of the entries spawned on that map, so a winner lost later never brings an older place back and the result never depends on whether a save fell in between. It costs one field read and one count while no place is stored and skips spawns after a load. Between saves every use re-checks `Spawned`, `Map`, `Faction == Faction.OfPlayer` and `Destroyed` (Verse/Thing.cs:180-209); a failed check reads as no place. No Destroy or DeSpawn hook is needed. - No ThingDef, designator or DesignationDef: any of them would stay on the map after a plain unsubscribe. A court place is a building reference, never a zone (Blax Zones) or an allowed area (Blax Castes). - **Settings:** None; the switch is the setting. -- **Save and removal:** One reference per map in the component. After removal the building is just a table. +- **Save and removal:** The `courtPlaces` list in the component. After removal the building is just a table, and the save loads with the same 2 errors. - **Overlaps:** RimCourt's seat spot is its own building; both can stand in one room. - **Replaces:** Picking the place in the convene dialog every time. - **Effort:** S plus S for the tab picker and the outline. diff --git a/docs/features.md b/docs/features.md index 8503741..83a6800 100644 --- a/docs/features.md +++ b/docs/features.md @@ -2,7 +2,7 @@ Write the colony's lawbook from every act the game knows, and the colony enforces it: a warden stops a binge before the first dose, a murderer sits out its sentence and walks back to its own bed and role, and a colonist who keeps doing it gets more each time. Each law picks its punishment from a full catalogue, from a reprimand or bread and water to a group beating or an execution corps, carried out in private or at a court place you set on any table, throne or spot. A served punishment can leave the colonist better than before: steadier for a while, and now and then rid of the vice it was punished for. Grave cases go to a court with a judge the colony elects, attorneys who argue with Social, witnesses and a jury, and the colony votes on the laws themselves. Laws only watches what the game already does: no new crime events, no new mental breaks. -Status: item 1 of "Order" is built as release 1.0.0 (`CHANGELOG.md`); the rest is design. Planned 2026-12-01 and reviewed against the decompiled game the same day. Fabian's request of 2026-12-03 (a room or table as court, a full list of punishments with his four examples among them, punishments that change a colonist's character) is planned in areas 1 and 3 to 6; his decisions on it are under "Decided 2026-12-03". This file is the plan of record for what the mod covers and in which order the parts come. `docs/design.md` holds the spec of every designed feature. +Status: item 1 of "Order" is built as release 1.0.0, and the court place of Court step 2 as release 1.1.0 (`CHANGELOG.md`); the rest is design, the other parts of Court step 2 included. Planned 2026-12-01 and reviewed against the decompiled game the same day. Fabian's request of 2026-12-03 (a room or table as court, a full list of punishments with his four examples among them, punishments that change a colonist's character) is planned in areas 1 and 3 to 6; his decisions on it are under "Decided 2026-12-03". This file is the plan of record for what the mod covers and in which order the parts come. `docs/design.md` holds the spec of every designed feature. ## How this plan is cut @@ -152,7 +152,7 @@ Step 1, Ideology's trial as a punishment: Step 2, court sessions on the core game: -- **Court place.** Fabian's first ask: select any table, party spot, campfire, throne, lectern or ritual spot you own and switch on "Court place", or pick it in the Laws tab. One per map. Its room is the court room: hovering the switch outlines it, and the Laws tab shows its impressiveness. Sessions, "Court on its own" and public punishments use it; nothing is saved on the building. Designed: [Court place](design.md#court-place). +- **Court place.** Fabian's first ask: select any table, party spot, campfire, throne, lectern or ritual spot you own and switch on "Court place", or pick it in the Laws tab. One per map. Its room is the court room: hovering the switch outlines it, and the Laws tab shows its impressiveness. Sessions, "Court on its own" and public punishments use it; nothing is saved on the building. **Built** as 1.1.0, without the courtroom comparison, which comes with Courtrooms. Designed: [Court place](design.md#court-place). - **Court sessions.** Cases wait for trial, a convene dialog of our own with roles, place and the conviction chance, a session with speeches and a verdict letter, a verdict from evidence, Social skill and the judge's bias, and the sentence from the lawbook. The judge is appointed; when the judge is the accused, the victim or family of either, or is dead, jailed or away, the best uninvolved colonist acts as judge and the dialog says why. Designed: [Cases go to trial](design.md#cases-go-to-trial) through [Verdict and sentence](design.md#verdict-and-sentence). - **Jail, then trial.** The offender is arrested at once as for Jail, held on Maintain only and sent to court; a conviction gives the row's days minus the days served, an acquittal releases it. This is "jail and maybe court" for a binger who already took some. Designed: [Jail, then trial](design.md#jail-then-trial). - **Court on its own.** Waiting cases convene at the court hour without a click (off by default), at the court place. Designed: [Court on its own](design.md#court-on-its-own). diff --git a/docs/workshop-description.txt b/docs/workshop-description.txt index 816ee4d..5afa992 100644 --- a/docs/workshop-description.txt +++ b/docs/workshop-description.txt @@ -11,6 +11,7 @@ [*]🎚️ [b]Planning and did it.[/b] Planning is the moment a mental break starts; did it is the act the break is about, such as the first dose of a binge. [*]📋 [b]Cases.[/b] Who, what, when, the punishment and how it ended, with a jump to the pawn and "Arrest now" for cases that wait. [*]🧩 [b]Missing entries wait.[/b] A law whose DLC or mod is gone shows "Needs " or "Missing: " and works again when it is back. +[*]🏛️ [b]Court place.[/b] One table, spot, throne or lectern per map, set on it or in the Laws tab, which shows its room's impressiveness. Later court sessions will use it. [/list] [img]https://cdn.blax.at/blax-gaming/laws/crimes.png[/img]