docs: Blax Zones design and roadmap

This commit is contained in:
Fabian @ Blax Software 2026-11-28 23:22:37 +01:00
commit 4812bc9524
2 changed files with 286 additions and 0 deletions

3
README.md Normal file
View File

@ -0,0 +1,3 @@
# Blax Zones
RimWorld 1.7 mod, planned (Blax Gaming). Delivery zones where bought goods land, and sleeping zones for colonists, slaves, prisoners and animals. Design and roadmap: `docs/design.md`. No code yet.

283
docs/design.md Normal file
View File

@ -0,0 +1,283 @@
# Blax Zones
Drag a delivery zone and everything you buy from orbital or caravan traders, plus quest and royal rewards, lands in it, sorted by item filter: medicine by the hospital, steel by the workshop. Drag a sleeping zone over the barn and every chicken and duck has a bed, so you stop placing sleeping spots one at a time.
Status: not started. RimWorld 1.7, package id `blax.zones`, safe to remove from a save from the first release.
## At a glance
| Version | What players get | Replaces | Days |
|---|---|---|---|
| 1.0 | Delivery zones: orbital buys and caravan buys land in them, by item filter and priority | Trade Ships Drop Spot (206k, no official 1.7), Trading Control drop spot (111k) | 5 |
| 1.1 | Quest and royal rewards land in delivery zones. Trader caravans camp next to a zone you pick | The reward half of Trade Ships Drop Spot and Trading Control, [KV] Trading Spot (126k), [GMT] Trading Spot (117k), Trading Spot (44k), all dead or 1.6-only | 3 |
| 1.2 | Sleeping zones: every cell is a sleeping spot for colonists, slaves, prisoners or animals, with species and size filters | Designator Shapes for spot grids (331k), Barn Stall (29k), Hidden Spots (13k) | 10 |
| 1.3 | Goods go straight into stockpiles, onto shelves and under roofs; orbital traders buy from flagged storage; cargo pods land in a zone | Map Wide Orbital Trade Beacon (51k), Wall-Mounted Orbital Trade Beacon (16k), 3 small pod mods (6.5k combined) | 5 |
| 1.4 | With Blax Castes, sleeping zones limited by caste | none | 1 |
Total: 24 working days. Quest and royal rewards ship in 1.1, so 1.0 fits in a week. If 1.0 still slips, caravan routing moves to 1.0.1 and orbital ships first.
## Defaults I picked
Change if you disagree.
- Caravan purchases route in 1.0, not later. They are half a day of work and players see them every caravan.
- When every zone cell is taken, pods land within 16 cells of the top zone. A setting sends them to the vanilla spot instead.
- Roofed delivery (goods appear, no drop pod) exists, per zone, off by default, from 1.3.
- Sleeping-zone cells match vanilla sleeping spots exactly: 80% rest, "slept on ground" -4 mood, comfort 0.4, count for barracks.
- Max 500 sleeping-zone cells per map, adjustable from 50 to 2000.
- Bought colonists, slaves, prisoners and animals never land in a zone. They arrive as in vanilla.
- Caravan goods appear in the zone. Pack animals don't walk them over; I cut that.
- Odyssey gravships leave Blax zones behind. Beds carried along are removed on arrival.
Everything below is for the modder building it.
## Data model
Three parts carry everything. Build them first, in 1.0 and 1.2.
### Zone store, safe to remove from a save
All Blax state lives in one `MapComponent_BlaxZones` per map: our zones (1.0), the zone beds (1.2), the stockpile and shelf flags (1.3). No Blax zone or Blax field ever enters a vanilla save list.
- Why: `ZoneManager.ExposeData` deep-saves `allZones`, and `UpdateZoneManagerLinks` and `RebuildZoneGrid` read entries without a null check. An unknown zone class loads as null and the next load throws an NRE. A MapComponent with a missing class also loads as null, but `Map.FillComponents` runs `components.RemoveAll(null)`, so nothing breaks.
- Save: a prefix on `ZoneManager.ExposeData`, only when `Scribe.mode == Saving`, swaps the private `allZones` field for a filtered copy without our zones. A finalizer puts the original list object back, even if saving throws.
- Load: a prefix on `Map.FinalizeLoading` re-registers our zones and appends zone beds to the private `loadedFullThings`, so vanilla spawns them and their references resolve.
- Removal: a button in the mod settings strips everything from the loaded game. A plain unsubscribe still loads, with 2 logged errors per map.
### DeliveryRouter, shared by every delivery path
One static class that orbital trade, rewards, caravans, cargo pods, direct delivery and `ZonesApi.TryFindDropSpot` all call. Its build counts in the delivery zone's effort, so each routing feature stays small.
- Refuses: `Pawn`, `Corpse`, Wastepack, and maps with no zones.
- Candidates: delivery zones (from 1.3 also flagged stockpiles and shelves) that accept the source and pass the filter, ordered by priority, then zone ID.
- Cells: sorted by distance to the zone centroid, cached and rebuilt in `AddCell`/`RemoveCell`. Pass 1 takes empty valid cells, pass 2 cells with a mergeable stack. At most 400 checks per stack.
- Pod rule: `DropCellFinder.IsGoodDropSpot(c, map, allowFogged: false, canRoofPunch: false)` and reachable from the colony. Placement rule (caravan, direct delivery): standable, unfogged, reachable, roof ignored.
- Overflow: `DropCellFinder.TryFindDropSpotNear` around the top zone's centroid, radius 16. Then the vanilla spot.
- Context (from 1.1): callers that can't pass a source set a `[ThreadStatic] DeliveryContext` in a prefix and clear it in a finalizer. The `DropPodUtility.DropThingGroupsNear` prefix reads it.
### Zone beds
One invisible bed per sleeping-zone cell: `Building_ZoneBed : Building_Bed`, player faction, not an edifice, def `isSaveable` false.
- Why real beds: ownership, prisoner capture, slave beds, patients, rescue, babies and `Alert_NeedColonistBeds` keep working with no extra patches. Ground sleep without beds covers voluntary sleep only (see Cut).
- Not an edifice: an edifice without a `sowTag` blocks planting and wipes the pasture grass under it.
- Saving: `Map.ExposeData` skips things whose def has `isSaveable` false, so the component deep-saves the beds instead and the load prefix hands them to vanilla. Without the mod they vanish with the component node, and the vanilla things list never holds a missing def.
- Reconcile: `MapComponent.FinalizeInit` spawns missing beds and destroys beds whose cell is no longer in a sleeping zone.
## Releases
### 1.0 Delivery zones (5 days)
#### Save-safe zone storage
- **Players get:** Nothing to see. Zones survive save and load. To remove the mod mid-game, click "Remove Blax Zones from this game" in the mod settings, save, then disable the mod, and the save loads with no errors. A plain unsubscribe also loads: the zones are gone and the log shows 2 errors per map. From 1.2 on it also shows one "Could not resolve reference" warning per bed owner, job target and reservation.
- **How:** Save prefix and finalizer as in the data model, using `AccessTools.FieldRefAccess` for `allZones`. The `Map.FinalizeLoading` prefix runs while `zoneGrid` exists and nothing has spawned yet. It sets each zone's `zoneManager` link, calls `ZoneManager.RegisterZone`, then `AddZoneGridCell` per cell through an `AccessTools` delegate, since that method is internal. The `thingGrid` is still empty there, so don't filter cells by hand. Vanilla's spawn loop calls `ZoneManager.Notify_NoZoneOverlapThingSpawned` and trims our zones exactly as it trims stockpiles. A static loading flag stops `RemoveCell` from unclaiming or destroying beds that haven't spawned yet; reconcile cleans up after. I picked this over registering in `FinalizeInit`, because vanilla then handles overlap for our zones with its own code. Mark the zone mesh dirty; `Map.FinalizeInit` regenerates all meshes anyway. The removal button needs a confirmation dialog and a loaded game. On every map it deregisters our zones (from 1.2 it also unclaims and destroys zone beds and ends LayDown jobs on them), then removes the component from `map.components`, so the next save has no BlaxZones node. It ends with the message "Save now, then disable the mod". A dev debug action does the same.
- **Settings:** The removal button, enabled only while a game is loaded. No toggle, because this is the save format, not a feature.
- **Replaces:** Nothing.
- **Effort:** M, 2 days.
- **Tests:** Phase 1: create two delivery zones with different filters and priorities, save, parse the .rws. No "BlaxZones." inside `<zoneManager>` or `<things>`; both zones sit under the `MapComponent_BlaxZones` node. Phase 2, after reload: both zones are in `map.zoneManager.AllZones` with the same ID, label, cells, filter and priority, and `ZoneAt(cell)` returns them. A wall built on a zone cell before saving leaves that cell out. Phase 3, a new harness step: the runner renames the component's Class attribute in the save to a type that doesn't exist and loads it. Loading finishes, the log has no NRE and no errors beyond the expected "Could not find class", no Blax zones exist and vanilla stockpiles are intact. Removal button: afterwards `map.components` has no `MapComponent_BlaxZones`, and a fresh save contains no "BlaxZones".
- **Risks:** It must ship in 1.0. Zones that vanilla saved in an earlier version would need a migration. Saving runs on the main thread, and the finalizer guarantees the restore. A mod that reads zones during load before `FinalizeLoading` won't see ours (none known). Another mod that also swaps `allZones` while saving composes, since each restores its own list object.
#### Delivery zone
- **Players get:** A new "Delivery zone" in the Zone menu, dragged like a stockpile. Its tab has an item filter (what may land here), a priority from Low to Critical, and source checkboxes for orbital traders and caravan traders (1.1 adds quest and royal rewards). While the zone is selected, red outlines mark cells drop pods can't use (roofed, inside an enclosed pen, blocked, fogged, unreachable), and the inspect pane counts them. Like every vanilla zone, it extends the home area 4 cells around itself; the tooltip says so.
- **How:** `Zone_Delivery : Verse.Zone` with `ThingFilter filter` (all items allowed; Wastepack and corpses hidden and always refused), `StoragePriority priority = Normal`, and `acceptOrbital` and `acceptCaravan`, both true, each scribed with its default. 1.1 adds `acceptRewards` the same way. `Designator_ZoneAdd_Delivery` plus an `_Expand` subclass reached through `Verse.DesignatorUtility.FindAllowedDesignator`, as `Zone_Fishing` does. A namespace-qualified `PatchOperationInsert` adds it after the `Designator_ZoneAdd_Growing` entry in DesignationCategoryDef Zone `specialDesignatorClasses`; anchor on Growing, because the Fishing entry carries `MayRequire`. `ITab_Delivery` holds the priority dropdown, the source checkboxes, `ThingFilterUI.DoThingFilterConfigWindow` and copy/paste gizmos with our own clipboard. Cell validity uses the router's pod rule. Check reachability once per district of the zone, not per cell: `Reachability.CanReachColony` loops over every player pawn and colony building on a miss, and 1.2 adds hundreds of zone beds to that list. Cache the result per zone and recompute every 250 ticks, only while the zone is selected. `MapComponentUpdate` draws `GenDraw.DrawFieldEdges` over invalid cells. Zone color amber at alpha 0.09. Icon: the vanilla `UI/Designators/ZoneCreate_Stockpile` texture tinted amber through `defaultIconColor`. The home-area growth comes from the base `Zone.AddCell` calling `AutoHomeAreaMaker.Notify_ZoneCellAdded`. This feature also builds the DeliveryRouter and `ZonesApi`.
- **Settings:** Global "Delivery zones" master toggle (on). Per zone: filter (all items), priority (Normal), two source checkboxes (both on; 1.1 adds a third for rewards).
- **Replaces:** Together with the routing below: Trade Ships Drop Spot (1969732297, 206,325 subs, no official 1.7) and its unofficial 1.7 ports (3828260574, 124; 3837213962, 67), the orbital drop spot of Trading Control (2007107588, 111,063), Orbital Trade Goods Landing Zone (3015945224, 161).
- **Effort:** M, 2 days, router included.
- **Tests:** Designating unroofed cells creates a `Zone_Delivery`; the expand gizmo grows it. The designator refuses cells in an existing stockpile. Roof 3 cells and `GetInspectString` reports 3 unusable cells. A fenced pen around the zone makes every cell unusable. The default filter allows silver, medicine and steel and refuses Wastepack. Filter, priority and sources persist in phase 2. `ZonesApi.TryFindDropSpot` returns a zone cell for steel and false for a pawn.
- **Risks:** One zone per cell, so a delivery zone can't overlap a stockpile. Goods land and haulers store them; 1.3 lets stockpiles receive deliveries directly. Pods never land in an enclosed pen (vanilla rule). The red overlay shows this instead of failing silently like Trading Control's spot.
#### Orbital purchases land in the zone
- **Players get:** Everything bought from an orbital trader, plus the silver from selling, drops into the best matching delivery zone instead of next to the first unroofed trade beacon. When every zone cell is taken, pods land next to the top zone. With no fitting zone they fall back to vanilla. Raids never come to the zone.
- **How:** A transpiler on `TradeShip.GiveSoldThingToPlayer` replaces its single `TradeUtility.SpawnDropPod(IntVec3, Map, Thing)` call with `DeliveryRouter.DeliverFromOrbit`, which has the same signature. A caller-scoped transpiler is also safer than a prefix on the 4-line `SpawnDropPod`, which the runtime may inline. `DropCellFinder.TradeDropSpot` is never patched, because center-drop raids (40% with a powered beacon), ransom pawns and returning lent colonists use it too. It still runs once per stack to supply the vanilla spot, the same cost as vanilla, and can log vanilla's own "Could find no good TradeDropSpot" error. The router picks a cell, then calls `TradeUtility.SpawnDropPod(cell, map, thing)`. A falling pod already makes its cell fail `IsGoodDropSpot`, so one trade spreads over the zone with no bookkeeping. Overflow within radius 16 lets a 1-cell zone act as a drop spot. Another mod's `TradeDropSpot` prefix (Trade Ships Drop Spot, Trading Control) still supplies the vanilla spot, so their spot becomes our fallback. If def `DropSpotTradeShip` exists, a one-time message says the player can unsubscribe from Trade Ships Drop Spot.
- **Settings:** Global "Route orbital trade" (on), "Overflow lands next to the zone" (on; off sends overflow to vanilla), overflow radius 16 (4 to 30). Per zone: orbital checkbox.
- **Replaces:** With the delivery zone: Trade Ships Drop Spot (206k), Trading Control's drop spot (111k).
- **Effort:** S, half a day.
- **Tests:** Build a `TradeShip` from an orbital TraderKindDef and call `GiveSoldThingToPlayer(steel, 50, negotiator)`. A `DropPodIncoming` skyfaller holding the steel sits on a zone cell. This also proves the transpiler fires; Blax Slaves has no transpiler yet. With a medicine-only zone at Important plus a general zone, medicine lands in the first and steel in the second. Fully roofing the medicine zone sends medicine to the general zone. A 1-cell zone with 5 stacks gets 1 pod in the zone and 4 within 16 cells. With no zones, the pod lands near vanilla `TradeDropSpot`. A bought animal is not routed. With zones placed away from every beacon, 20 calls of `PawnsArrivalModeWorker_CenterDrop.TryResolveRaidSpawnCenter` never return a zone cell; a zone right next to a beacon can be picked by vanilla itself. Composition: a test-only prefix makes `TradeDropSpot` return a fixed cell. With no zone the pod lands there, with a zone it lands in the zone. After 300 ticks the item lies within 1 cell of the zone.
- **Risks:** The transpiler expects exactly one `SpawnDropPod` call. On a different count it logs an error and skips, and one-class-at-a-time patching keeps the rest alive. Mods that replace the trade-ship purchase entirely bypass us, which is fine; Realistic Orbital Trade (3236257897) uses shuttles. Pods spill with `ThingPlaceMode.Near` when they open, so a stack can land one cell past the zone edge, as vanilla pods do.
#### Caravan purchases appear in the zone
- **Players get:** Goods bought from a visiting trader caravan appear in the best matching delivery zone instead of at a pack animal's feet outside the walls, and a message names the zone. Roofs don't matter here, so a medicine zone inside the hospital works for caravan goods. Bought animals and people stay with the caravan, as in vanilla.
- **How:** For items, `Pawn_TraderTracker.GiveSoldThingToPlayer` makes exactly one call to `GenPlace.TryPlaceThing(Thing, IntVec3, Map, ThingPlaceMode, Action<Thing,int>, Predicate<IntVec3>, Rot4?, int)` in Near mode at the carrier's `PositionHeld`. On success it adds the item to `lord.extraForbiddenThings`; on failure it logs an error and destroys the item. Pawns return early and are never touched. A transpiler replaces that call with `DeliveryRouter.PlaceFromCaravan`, same signature. For each candidate zone (caravan ticked, filter, priority) it tries `GenPlace.TryPlaceThing` at the best cell in Near mode with the router's placement rule plus "cell is in this zone" as validator. Next it tries Near at the top zone's centroid with no validator. Last it calls the original with the original arguments, so the vanilla destroy path is reached only where vanilla would reach it. Vanilla then adds the item to `extraForbiddenThings` as before. One message per `TradeSession.deal`, with look targets on the placed things. Vanilla selling also moves colony goods out of stockpiles instantly, so goods appearing matches it. Own patch class and toggle.
- **Settings:** Global "Route caravan purchases" (on), "Message when goods arrive" (on). Per zone: caravan checkbox.
- **Replaces:** Nothing directly. The trading-spot mods only move the caravan; 1.1 covers them.
- **Effort:** S, half a day.
- **Tests:** Force `IncidentWorker_TraderCaravanArrival`, take the trader pawn and a non-pawn Thing from `trader.Goods`, call `GiveSoldThingToPlayer(thing, 1, negotiator)`. The item is spawned in the zone and listed in the lord's `extraForbiddenThings`. A fully roofed zone still receives it. With every zone cell holding a different item, it lands near the zone. With no zones, next to the carrier. A bought animal doesn't move.
- **Risks:** Goods appear instead of being carried; carried delivery is cut. A mod that rewrites `Pawn_TraderTracker.GiveSoldThingToPlayer` would conflict (none in the installed set).
### 1.1 Rewards and caravan camps (3 days)
#### Quest and royal rewards land in the zone
- **Players get:** Item rewards from quests, royal titles and "defeat all enemies" requests drop into a delivery zone that has rewards ticked, and the quest letter points there. Refugees, prisoners, mechs, wastepacks, ransom returns and raids never come to the zone.
- **How:** This feature builds the DeliveryContext from the data model, which caravan camps and cargo pods reuse. A context prefix and finalizer sit on four callers: `QuestPart_DropPods.Notify_QuestSignalReceived`, only when `useTradeDropSpot` is true and `dropSpot` is invalid (exactly the drops vanilla sends to the trade spot); `Pawn_RoyaltyTracker.ApplyRewardsForTitle`, only on player home maps; `QuestPart_GiveNearPawn.Notify_QuestSignalReceived`; and the private `DefeatAllEnemiesQuestComp.GiveRewardsAndSendLetter`. While the context is set, a prefix on `DropPodUtility.DropThingGroupsNear` takes `thingsGroups` as a ref parameter. A group qualifies when it holds no Pawn and no Wastepack and all its things pass one zone (rewards ticked, filter). Each qualifying group goes out as its own pod: an `ActiveTransporterInfo` with the call's `openDelay`, `leaveSlag` and forbid flag (royal rewards pass false, the defeat-all-enemies reward the default true), dropped with `DropPodUtility.MakeDropPodAt(cell, map, info, faction)` using the call's faction, so faction pod skins survive. If the call has `instaDrop`, the group is placed directly, as vanilla does. The prefix then assigns a filtered copy holding the remaining groups, so vanilla drops only those and the caller's list is never changed. The letter needs no patch: `QuestPart_DropPods` builds its look target after dropping, from the first dropped thing's position. Ransom (`ChoiceLetter_RansomDemand` calls `SpawnDropPod`), lent-colonist returns, edge drops and center drops never set the context.
- **Settings:** Global "Route quest and royal rewards" (on). Per zone: rewards checkbox.
- **Replaces:** The quest-reward half of Trade Ships Drop Spot (206k) and Trading Control (111k).
- **Effort:** M, 2 days.
- **Tests:** `Quest.MakeRaw` plus a `QuestPart_DropPods` with `useTradeDropSpot = true`, things gold 50 and medicine 5, inSignal "blax.test". Call `Notify_QuestSignalReceived(new Signal("blax.test"))`. Both pods land on zone cells, split by filter, and the letter's look target lies in the zone. Add a refugee pawn: its pod is not in a zone, the items' pods are. A Wastepack is never routed. The list passed in still holds every group afterwards. With `instaDrop`, items appear with no pod. A faction-skinned call keeps its faction on the pod. `DropThingsNear` without the context, as a raid would call it, is untouched. With Royalty, `ApplyRewardsForTitle(Empire, null, title with rewards)` puts pods in the zone; skip without Royalty.
- **Risks:** Mod quests that drop rewards through their own code aren't covered unless they use `QuestPart_DropPods` with `useTradeDropSpot`. Finalizers keep the context from leaking.
#### Trader caravans camp at a zone
- **Players get:** A per-zone option "Caravans camp here" on delivery zones. Visiting trader caravans gather next to that zone instead of a random spot outside the colony, so the trader is easy to reach and bought goods appear right beside the caravan.
- **How:** A DeliveryContext prefix and finalizer on `IncidentWorker_TraderCaravanArrival.TryExecuteWorker`. A prefix on the overload `RCellFinder.TryFindRandomSpotJustOutsideColony(IntVec3 root, Map, Pawn searcher, out IntVec3, Predicate<IntVec3> extraValidator)` runs while the context is set and a camp zone exists. It tries standable, unfogged, unroofed cells within 6 cells of the zone that pass the caller's `extraValidator`, preferring cells outside enclosed rooms. Vanilla's validator already checks that every caravan pawn can reach the cell. If none passes, vanilla runs. No constructor patch and no re-targeting afterwards: `LordToil_Travel` and `LordToil_DefendTraderCaravan` take the chill spot when the lord is made, so the spot must be right before that. Visitor groups and other lord jobs never set the context. If a known trading-spot mod is active (package ids listed in Compat), the feature stands down and logs once.
- **Settings:** Global "Caravans may camp at zones" (on). Per zone: off.
- **Replaces:** [KV] Trading Spot (1180719658, 125,716 subs) and [GMT] Trading Spot (2874517333, 117,497), both dead before 1.7; Trading Spot (3507108484, 44,228), 1.6 only; Trade Caravan Spot (3733234194, 2,766); Trading Spot Rewritten (3780903689, 2,199); the trade-marker half of Trading Control (2007107588, 111,063).
- **Effort:** S, half a day.
- **Tests:** Caravan arrival with a camp zone: the lord's chill spot is within 6 cells of the zone. A walled-off zone keeps the vanilla spot. Without the option, the vanilla spot. A visitor group ignores the zone.
- **Risks:** Traders still wander within the defend radius of 28. A zone deep inside the base brings visitors inside, which is the player's choice.
### 1.2 Sleeping zones (10 days)
#### Sleeping zones for people and animals
- **Players get:** Two new zone tools, "Sleeping zone" for people and "Animal sleeping zone". Every cell works like a sleeping spot, so one drag over the barn beds every chicken and duck, and colonists claim cells in a dorm zone. A gizmo switches a people zone between colonists, slaves and prisoners, as on a bed. Shrinking or deleting the zone removes its cells.
- **How:** Zone beds as in the data model. `Zone_SleepingBase : Zone` with subclasses `Zone_SleepingPeople` and `Zone_SleepingAnimals`; separate types keep the designators from expanding each other's zones, since `Designator_ZoneAdd` compares the exact type. `AddCell` spawns a `Building_ZoneBed` with `SetFaction(Faction.OfPlayer)`, which `IsValidBedFor` needs, then sets `ForOwnerType` from the zone, because `Building_Bed.SpawnSetup` flips a bed in a prison cell to prisoners. Each bed spawn runs `District.Notify_RoomShapeOrContainedBedsChanged` over every region of the district, so a 500-cell outdoor drag means 500 passes. Measure it in the harness; if it hitches visibly, spawn a drag's beds over several ticks. `RemoveCell` and deregistration unclaim owners first, then destroy, so there is no "lost assignment" spam; the loading flag skips this during load. Owner-type changes unclaim owners silently with `pawn.ownership.UnclaimBed()` before the vanilla setter, whose `RemoveAllOwners` posts one message per owner.
- Defs `BlaxZones_ZoneBed` (`bed_humanlike` true) and `BlaxZones_ZoneAnimalBed` (false): 1x1, Standable, FloorEmplacement, no `sowTag` (so `CanOverlapZones` stays true), `building.isEdifice` false, `selectable` false, `drawGUIOverlay` false, `drawerType` None, `useHitPoints` false, WorkToBuild 0, no cost list (no wealth), no designationCategory, `tickerType` Never, `isSaveable` false, `expandHomeArea` false (or every bed marks home area), `CompAssignableToPawn_Bed`. The uiIcon uses the vanilla AnimalSleepSpot texture.
- Copied from the vanilla spots: SurgerySuccessChanceFactor 0.7, Comfort 0.4 (humanlike def), `scatterableOnMapGen` false (needed for `IsClearableFreeBuilding`), `ai_chillDestination` false, `artificialForMeditationPurposes` false, `wakeDormantPawnsOnConstruction` false. The vanilla spots do carry `sowTag` SupportPlantsOnly; the research note was wrong.
- Bed search order: `RestUtility.Reset` builds the best-to-worst bed lists and runs before `[StaticConstructorOnStartup]`. A postfix moves our defs directly before SleepingSpot and AnimalSleepingSpot, and the patch class calls `RestUtility.Reset()` once after patching. Otherwise unowned pawns walk to any free vanilla spot first.
- A postfix on `EdificeGrid.Register` removes the sleeping-zone cell when any edifice spawns there, so no cell holds two beds. This replaces a hook on the hot virtual `Building.SpawnSetup`. The designator refuses cells with an edifice or bed and enforces the per-map cap. Building over a zone bed needs no patch: `GenConstruct.CanPlaceBlueprintOver` already allows it over non-edifices. Add a postfix only if a test fails.
- **Settings:** Global "Sleeping zones" (on); "Max sleeping-zone cells per map" (500, 50 to 2000); "Zone cells count for bedroom or barracks" (on, as vanilla spots; written to the defs' `bed_countsForBedroomOrBarracks` at startup). Per people zone: owner-type gizmo (colonists, slaves, prisoners).
- **Replaces:** Designator Shapes (1235181370, 331,361 subs), only its spot-grid use; BuilderTweaksReplica (3521096349, 7,982), drag-placing spots; Hidden Spots (3466316759, 13,238); Invisible Animal sleeping spot - Prettier Barn (2571118651, 398).
- **Effort:** L, 5 days.
- **Tests:** A 4x4 animal zone holds 16 `BlaxZones_ZoneAnimalBed`, player faction, not selectable; grass on those cells survives and the home area doesn't grow. A tamed chicken: `RestUtility.FindBedFor` returns a zone bed ahead of a free vanilla AnimalSleepingSpot; after it lies down, it owns the bed. People zone: a colonist gets a bed, and a screenshot shows an adult renders acceptably on the 1x1 bed (vanilla has 1x1 beds only for babies). Switched to slaves (Ideology): the colonist is refused, a slave accepted, and zero `MessageBedLostAssignment` appear. A prisoner zone in a walled room: `FindBedFor(prisoner, warden, Prisoner)` finds a bed. Shrinking by 4 cells removes 4 beds and clears their owners with no messages. A wall on a zone cell removes the cell and the bed. `Alert_NeedColonistBeds` clears with a large enough people zone. The test logs the time of a 500-cell drag. Phase 2: same bed count and ThingIDs, the chicken still owns its bed, no "Could not resolve reference" warnings. Phase 3: no beds, no zones, every former owner's owned bed is null, no NRE.
- **Risks:** Hundreds of Building things add to `listerBuildings` loops and room recalculations; the cell cap, `drawerType` None and `tickerType` Never limit the cost. An unowned pawn's `FindBedFor` scans past owned beds, as with many vanilla spots. Hospitality (753498552) patches `IsValidBedFor`; guests won't use player zone beds, same as vanilla spots. Other mods' bed lists will show zone beds. Odyssey gravships move only stockpile and growing zones, so ours stay behind and reconcile removes beds carried along; untested, because Odyssey isn't installed here.
#### Who may sleep here
- **Players get:** The zone tab lists animal species with checkboxes and a body-size range, so big stalls stay free of chickens. People zones can be limited to babies, children or adults, for example a nursery.
- **How:** `Zone_SleepingAnimals` gets `HashSet<ThingDef> disallowedRaces`, a deny-list so new species are allowed by default, and `FloatRange bodySize` (0 to unlimited). `Zone_SleepingPeople` gets `allowBabies`, `allowChildren`, `allowAdults` by DevelopmentalStage. A postfix on `RestUtility.CanUseBedNow(Thing bedThing, Pawn sleeper, bool checkSocialProperness, bool allowMedBedEvenIfSetToNoCare, GuestStatus? guestStatusOverride)` checks the bed type first. For a `Building_ZoneBed` whose zone rejects the sleeper it returns false. The zone comes from `zoneGrid` in O(1). This one patch covers `FindBedFor`, patients, rescue, capture, `Toils_Bed.BedNoLongerUsable`, childcare and rituals. Changing a filter unclaims owners that no longer pass, and vanilla's `FailOnBedNoLongerUsable` gets a pawn already lying there out of bed. The tab has a search field, the species list (species tamed on this map first, then all animal races) and `Widgets.FloatRange` for size.
- **Settings:** Per zone: species deny-list (empty), body size (any), age stages (all). No global setting.
- **Replaces:** Barn Stall (Continued) (2071768301, 29,299 subs), the size filter its author refused; Chicken nests Continued (3261309547, 5,719), species-only nests. The vanilla animal spot has no size limit (`bed_maxBodySize` 9999).
- **Effort:** M, 2 days.
- **Tests:** Chickens disallowed and only zone beds present: `FindBedFor(chicken)` returns null. Body size max 1.0: a muffalo (2.4) is refused, a chicken accepted. A filter change unclaims the now-refused owner. A babies-only zone refuses an adult colonist (Biotech; skip otherwise). Filters persist in phase 2.
- **Risks:** `CanUseBedNow` is hot; the postfix exits on the type check for every other bed. Ours only ever sets false, so it composes with other postfixes that set false. It runs at `Priority.Low`, after postfixes that allow a bed, such as Blax Slaves' shared infirmary, so a zone filter has the last word.
#### Medical, shared and comfort
- **Players get:** A gizmo makes a whole zone medical, so patients and injured animals are brought there. Another makes it shared: nobody keeps a cell, pawns take the nearest free one each night, and nobody gets a barracks thought. Cells in people zones give the same comfort as a vanilla sleeping spot.
- **How:**
- Medical: unclaim owners silently, then set `Building_Bed.Medical` on every bed through the vanilla setter.
- Shared: vanilla claiming stays. Blocking `ClaimBedIfNonMedical` breaks sleep (see Cut). A MapComponent sweep every 250 ticks unclaims shared-zone beds whose owner isn't lying in them. Shared people zones use a third def, `BlaxZones_ZoneBedShared`, with `bed_countsForBedroomOrBarracks` false; flipping the toggle unclaims silently and respawns the zone's beds with the other def, so no SleptInBarracks or SleptInBedroom thought. The reviewer also offered a `CanUseBedNow` postfix that returns true for an unowned sleeper. I picked the sweep, because it never overrides a false from vanilla or another mod.
- Comfort: `PawnUtility.GainComfortFromCellIfPossible(this Pawn, int delta, bool chairsOnly)` reads only the edifice, so a non-edifice bed gives none. A postfix, gated on the 15-tick hash, `!chairsOnly` and `curDriver is JobDriver_LayDown`, calls `GainComfortFromThingIfPossible(pawn, bed, delta)`, which uses the def's Comfort 0.4.
- Everything else already matches vanilla spots: rest effectiveness 0.8 (`BedRestEffectiveness` valueIfMissing), SleptOnGround -4 (given when the cost list is empty), SleptOutside outdoors. `Toils_LayDown.ApplyBedThoughts` is private and not patched. Animals have no mood need, so for them only location, ownership and medical matter.
- **Settings:** Per zone: Medical (off), Shared (off). Global: "Zone cells give sleeping-spot comfort" (on).
- **Replaces:** Nothing.
- **Effort:** M, 2 days. The design said S; the shared fix adds the sweep and the def swap.
- **Tests:** Medical zone: `RestUtility.FindPatientBedFor` returns a zone bed for an injured colonist, an injured tamed animal goes to a medical animal zone, and no lost-assignment messages appear. Shared zone: a colonist sleeps a full night without `FailOnBedNoLongerUsable` ending the job; 250 ticks after waking, `ownership.OwnedBed` is null; no SleptInBarracks thought in a room of shared cells. Comfort rises over 2500 ticks in a zone bed and stays flat on bare ground. SleptOnGround is present after waking. Toggles persist in phase 2.
- **Risks:** `GainComfortFromCellIfPossible` is called from about 20 job drivers, hence the gate; a signature change breaks only this patch class. A medical prisoner zone still needs a prison cell, as in vanilla. A shared pawn owns its cell while asleep, so bed lists show it as claimed overnight.
#### Visible zone state
- **Players get:** The zone tint shows its type: colonist, slave, prisoner and medical zones each get their own color. The inspect pane shows the owner type, claimed and free cells, and a warning when a prisoner zone isn't in a prison cell.
- **How:** Vanilla shows owner type and medical by sheet color, which `drawerType` None hides. The owner-type and medical gizmos set `Zone.color` from a fixed palette. `GetInspectString` counts owners over the zone's beds and checks `IsPrisonCell` on the zone's rooms, since vanilla prisoner beds need one.
- **Settings:** None.
- **Replaces:** Nothing.
- **Effort:** S, half a day.
- **Tests:** Switching a zone to prisoners changes its color. After 3 chickens sleep in a 16-cell zone, the inspect string says 3 claimed, 13 free. An outdoor prisoner zone shows the warning.
- **Risks:** Two colonist zones share a color; the zone label tells them apart.
### 1.3 Stockpiles, shelves, roofs and selling (5 days)
Stockpile deliveries and direct delivery ship together: most freezers and hospital shelves are roofed, so the flag alone does little for orbital goods.
#### Stockpiles and shelves receive deliveries
- **Players get:** A "Receive deliveries" gizmo on any stockpile or shelf lets bought goods and rewards go straight into it, by its own filter and priority: medicine onto the hospital shelves, food into the freezer, no hauling. Delivery zones and flagged storage compete by priority.
- **How:** Flags live in `MapComponent_BlaxZones` as a `HashSet<int>` of stockpile zone IDs and a set of shelf ThingIDs, never as fields on `Zone_Stockpile` or `Building_Storage`, so removing the mod stays safe. Gizmos come from postfixes on `Zone_Stockpile.GetGizmos` and `Building_Storage.GetGizmos`. The router adds flagged storage as candidates, with accept from `StorageSettings.AllowedToAccept(thing)` and priority from `StorageSettings.Priority`; shelf cells come from `AllSlotCells()`. Pods use only stockpile cells that pass the pod rule. Shelves are roofed edifices, so they get orbital goods only with direct delivery. Caravan placement and direct delivery use any cell that passes the placement rule. Cells holding a different item or a full stack are skipped. A deleted stockpile or shelf drops its ID on the next lookup. The gizmo tooltip says roofed targets need direct delivery for orbital goods and rewards.
- **Settings:** Global "Stockpiles and shelves may receive deliveries" (on). Per stockpile and shelf: gizmo (off).
- **Replaces:** [DHM] Organized Trade Pod System (3490887589, 1,818 subs), Skipdoor Delivery idea for trade goods (3233578663, 2,747).
- **Effort:** M, 2 days.
- **Tests:** An unroofed flagged food stockpile at Important plus a general delivery zone at Normal: bought rice lands in the stockpile, steel in the zone. A flagged medicine shelf in a roofed hospital with direct delivery on: orbital medicine appears on the shelf. Caravan rice goes into a roofed flagged freezer. Flags survive reload. A deleted stockpile is no longer a target. Phase 3 loads with no errors from the flag sets.
- **Risks:** Without direct delivery, roofed freezers and shelves get only caravan goods; the tooltip says so.
#### Delivery under a roof
- **Players get:** An option "No drop pods, goods appear here" on delivery zones, flagged stockpiles and flagged shelves. Roofed warehouses and rooms then receive orbital goods and rewards. Off by default.
- **How:** For targets with direct delivery, orbital and reward routing skip the pod and call `GenPlace.TryPlaceThing(thing, cell, map, Near, null, validator)` with the placement rule, roof ignored. For rewards, the `DropThingGroupsNear` prefix takes the group out of the list and places it. A dust fleck marks the arrival. The stockpile and shelf flags sit in the MapComponent next to the receive flags. No roof punching: `Skyfaller.HitRoof` collapses 3x3.
- **Settings:** Global "Allow direct delivery" (on, makes the per-target option available). Per zone, stockpile and shelf: off.
- **Replaces:** Nothing.
- **Effort:** S, half a day.
- **Tests:** In a fully roofed zone with the option on, orbital steel spawns on a zone cell the same tick with no pod. Without the option, it falls back. A quest reward goes to a roofed direct zone.
- **Risks:** Immersion only. Goods arrive either way, so balance is neutral.
#### Sell zone
- **Players get:** A gizmo "Orbital traders can buy from here" on stockpiles and shelves. While at least one powered trade beacon stands on the map, orbital traders see everything in flagged storage and can take payment silver from it, so goods don't have to be hauled to the beacon. Off by default for balance.
- **How:** Flags (zone IDs and shelf ThingIDs) in the MapComponent. A postfix on `TradeUtility.AllLaunchableThingsForTrade(Map, ITrader)` wraps the result and appends things on flagged cells that pass `TradeUtility.PlayerSellableNow`, only when `Building_OrbitalTradeBeacon.AllPowered(map)` is not empty. It skips pawns and things already in the list. A prefix on `TradeUtility.LaunchThingsOfType(ThingDef, ref int debt, Map, TradeShip)` pays from flagged cells first, the way vanilla pays from beacon cells, lowers `debt`, and lets vanilla pay the rest. Pawns are never offered, so prisoner and slave sales stay with vanilla and Blax Slaves.
- **Settings:** Global "Sell zones" (off). Per stockpile and shelf: off.
- **Replaces:** Map Wide Orbital Trade Beacon (1839069104, 50,596 subs), Wall-Mounted Orbital Trade Beacon (15.9k), Trade Beacon Shapes, Adjustable Trade Beacon Radius.
- **Effort:** M, 2 days. The reviewer said S to M; I took M, because two trade methods change.
- **Tests:** A flagged stockpile far from the beacon holds 100 steel. With a powered beacon the trade dialog lists the steel; with the beacon off it doesn't. Selling it removes it from the stockpile. Buying with silver that sits only in a flagged stockpile pays from it. A prisoner standing in a flagged stockpile isn't offered.
- **Risks:** Beacon mods also patch `AllLaunchableThingsForTrade`; our wrapper skips things already in the list, so running Map Wide Orbital Trade Beacon alongside doesn't list items twice. It removes hauling to the beacon, hence off by default.
#### Cargo pod events land in the zone
- **Players get:** Optional: random cargo pod events drop their goods into a delivery zone that has "Cargo pods" ticked.
- **How:** A DeliveryContext prefix and finalizer on `IncidentWorker_ResourcePodCrash.TryExecuteWorker` with source CargoPod. The `DropThingGroupsNear` prefix from rewards routes the groups and keeps the call's forbid (default true) and `leaveSlag` (true).
- **Settings:** Global "Route cargo pod events" (off). Per zone: "Cargo pods" (off).
- **Replaces:** Resource Drop Pod Redirection (2944180046, 1,986 subs).
- **Effort:** S, half a day.
- **Tests:** The incident with the toggle on puts forbidden pods in the zone. With the toggle off, vanilla.
- **Risks:** It takes the surprise out of cargo pods, hence off by default.
### 1.4 Caste filter (1 day)
Ships once Blax Castes 1.3 publishes `CastesApi`.
#### Sleeping zones by caste
- **Players get:** With Blax Castes active, a people sleeping zone can be limited to castes, for example field hands in the barn dorm. Without Castes the option doesn't show.
- **How:** The Compat helper detects `blax.castes`, resolves `BlaxCastes.CastesApi` with `AccessTools.TypeByName`, checks `Version`, and binds `CasteIdOf(Pawn)` and `CasteLabels()` into cached delegates at startup. A missing type or method is a silent no-op. `Zone_SleepingPeople` gains `HashSet<string> allowedCasteIds` (empty means any), always scribed and ignored while unbound. The `CanUseBedNow` postfix from 1.2 checks it only while bound. A pawn whose `CasteIdOf` returns null fits only zones with no caste limit.
- **Settings:** Per people zone: caste list, hidden without Castes.
- **Replaces:** Nothing.
- **Effort:** S, half a day, rounded up to 1 day.
- **Tests:** With the harness loading Blax Castes: a zone limited to caste A refuses a caste B pawn and accepts a caste A pawn. Without Castes the tab hides the section, the stored ids are ignored, and they survive a save.
- **Risks:** It depends on the Castes release. An older API version means a silent no-op.
## Works with the other Blax mods
- Package ids: `blax.slaves`, `blax.castes`, `blax.zones`. No hard dependencies. About.xml has one sibling entry, loadAfter `blax.castes`. Load order is Castes, Zones, Slaves. Slaves lists `blax.zones`, so Zones doesn't list Slaves back, which would form a loadAfter cycle.
- Detection: one Compat helper calls `ModLister.GetActiveModWithIdentifier(id, ignorePostfix: true)`. Sibling APIs are bound by reflection (`AccessTools.TypeByName`, `AccessTools.Method`) into cached delegates at startup. A missing sibling or method is a silent no-op. APIs change additively only and carry an int `Version`.
- Zones offers `BlaxZones.ZonesApi` (static) from 1.0:
- `Version` (int).
- `TryFindDropSpot(Map map, Thing thing, out IntVec3 cell)`: respects zone filters, priority and drop rules, false if no zone fits. It uses the orbital rules (orbital ticked, pod rule, overflow setting) and always returns false for a Pawn.
- `HasSleepingZoneFor(Map map, BedOwnerType type)`: returns false until 1.2.
- Zones reads from Blax Castes, in 1.4 only: `CastesApi.Version`, `CasteIdOf(Pawn)` and `CasteLabels()`. Castes needs no Zones code. Zones reads nothing from Blax Slaves.
- Ownership: Zones owns sleeping spots, beds by zone and every friendly drop location. Castes owns every per-pawn policy default (apparel, food, drugs, reading, medical care, schedule, area, hostility, self-tend, carried medicine); Zones never touches policies. Slaves owns slave status, trade, prices, suppression, rebellion, slave medicine and slave economy.
- Slaves routes its silver payouts through `ZonesApi.TryFindDropSpot`, with `DropCellFinder.TradeDropSpot` as fallback. Pawns are never routed into zones.
- Buying: Zones never routes bought people. Slaves' buy-mode sets `guest.joinStatus` before vanilla `Pawn.PreTraded`, and Castes classifies by the final status in its own PreTraded scope. Zones touches neither.
- Slave sleeping zones use vanilla `BedOwnerType.Slave`, so `Alert_NeedSlaveBeds` counts them with no patch. No sibling calls `HasSleepingZoneFor` yet; it is not on the Blax Slaves roadmap.
- Blax Slaves' shared infirmary (its 1.5) lets slaves use colonist medical beds, so a colonist sleeping zone set to medical takes slaves too. Zone filters still apply, because the `CanUseBedNow` postfix runs at `Priority.Low`.
- Each mod keeps its state in its own Map or Game components, so removing one leaves the others' saves intact.
- Shared conventions: patches applied one class at a time from a `[StaticConstructorOnStartup]` class, logging "[Blax Zones] N patches applied"; a ModSettings toggle for every feature (zone storage has none, it is the save format); the headless in-game test mod copied from blax-slaves/Tests (BlaxSlavesTests harness, run-tests.ps1) as Tests/BlaxZonesTests, plus a phase 3 that simulates removing the mod.
## Backlog
- Fewer drop pods (pod batching, M): the only consolidating mod has 1.8k subs and nobody asked. It adds a second deferred path through `TradeDeal.TryExecute`, which every trade mod touches, and big pods spill out of small zones. If built: flush per destination with `MakeDropPodAt(cell, map, info, faction)`, cap stacks per pod by zone size, keep a finalizer flush.
- Bought animals land in a zone, for example outside the pen gate (S): the cross-mod contract says pawns are never routed into zones. Narrow that rule to people first; then orbital only, per zone, off by default.
- Animals sleep on a stockpile, so the barn's hay stockpile is also the sleeping area (M): zone beds can't overlap zones, so this needs beds over stockpile cells stored in the MapComponent plus tests for items lying on bed cells. Two zones in one barn work until players ask.
- Returning player caravans unload into a delivery zone (UnloadHere 3699782319, Homecoming 3833735329): small demand.
- Ally drop pods and aid land next to a chosen zone (Allies Spot 2067847359, 3.7k): needs a faction check so hostile drops are never affected; small demand.
- Blax zones fly with Odyssey gravships (`GravshipPlacementUtility`): Odyssey isn't installed here to build or test it.
## Cut
- Pack animals walk purchases to the zone (L): many exit paths (lord transitions, duty reassignment, `ExitMap`, death, hostility), owed items must be hidden from the next trade, and nobody asked. Goods appearing plus caravan camping covers it.
- Shared zones by blocking `Pawn_Ownership.ClaimBedIfNonMedical`: the unowned sleeper fails `CanUseBedNow` and gets kicked out of bed in a loop.
- Letter-target postfix on `QuestPart_DropPods.GetRandomDropSpot`: vanilla already points the letter at the first dropped thing, and the postfix would pull refugees and quest prisoners next to the zone.
- Soft sleeping zone (ground sleep via `JobGiver_GetRest.TryFindGroundSleepSpotFor`, no beds): voluntary sleep only, so no ownership, no prisoner capture, no patients, `Alert_NeedColonistBeds` keeps firing, and any free spot elsewhere wins first.
- Patching `DropCellFinder.TradeDropSpot` globally, as Trade Ships Drop Spot does: center-drop raids, ransom pawns and returning lent colonists use it too, so raiders would drop into the zone.
- Roof-punching delivery pods (Trading Control option): it collapses a 3x3 roof with damage below, and players report rock collapses in mountain bases. Direct delivery covers roofed rooms with no damage.
- Letting `ZoneManager` save Blax zones, with an uninstall button as the only safety net: a plain unsubscribe then throws an NRE on load.
- Edifice zone beds, or reusing vanilla AnimalSleepingSpot things: an edifice without a `sowTag` wipes pasture grass, and vanilla spots carry a `sowTag`, so they can't sit inside a zone.
- Delivery zone as a `Zone_Stockpile` subclass or an `Area`: vanilla designators can't expand a subclass, and an Area has no tab and the same save risk in `AreaManager`.
- People and animals in one sleeping zone (two beds per cell): `bed_humanlike` is per def, and two beds on one cell make `RestUtility.CurrentBed` ambiguous. Players draw two zones.
- Routing ransom returns, lent colonists, quest pawns (refugees, prisoners, mechs), wastepacks and royal permit drops: never wanted in the zone, and the permit drop is already player-targeted.
- Converting Trade Ships Drop Spot markers into zones: one drag replaces a marker, and both mods work side by side.
- Trading Control's marketplace stall and trading buffs: outside zones, and it needs new art.
- Per-cell spot graphics and owner labels in sleeping zones: clutter, the reason Hidden Spots exists. The zone tint and inspect pane carry the state.
- Routing visitor and trader parting gifts: rare, and harmless next to the giver.