# Blax Castes design and roadmap Every slave you buy needs its apparel, food, drug and reading policy set by hand. Blax Castes bundles those policies into castes such as Slave or Miner slave, and puts each new pawn into the right caste the moment it joins. ## At a glance | Version | What players get | Replaces (subs) | Days | |---|---|---|---| | 1.0 | Castes that set apparel, food, drug, reading and medical care in one click. Bought slaves join their caste automatically. | Automatic Slave Outfit (16.7k), PrisonerDefaults (1.1k), and the join defaults of Better Pawn Control (228k), BPC Forked (1.3k) and 1trickPwnyta's Defaults (75k) | 6 | | 1.1 | Ready-made Colonist, Slave and Prisoner castes, a caste button on selected pawns, warnings for clashes | Food Restriction Eleven starting policies, partly (15.4k) | 4 | | 1.2 | Castes also set schedule, allowed area, hostility, self-tend, carried medicine and fire at will | Defaults' area, hostility and medicine defaults (75k), Plug and Play Joiner area (1.5k) | 3 | | 1.3 | A caste for every way a pawn joins, adult and child. Returning pawns get their old caste. Pickers in the prisoner tab. API for Blax Slaves and Zones. | Defaults' child defaults (75k), BPC's rescued-joiner fix (228k), PrisonerDefaults per-prisoner picks (1.1k) | 3 | | 1.4 | Work priorities, shift schedules, default prisoner interaction, DLC switches, API support for a caste picker in Blax Slaves' trade window | Work Manager shifts, partly (14.2k), Plug and Play Joiner work (1.5k), prisoner defaults of Prison Labor and Custom Prisoner Interactions, partly | 4 | | 1.5 | Castes exported to other colonies, caste colours | Better Policies (3.9k), Export Agency (16.3k), Save My Settings (3.8k), all partly | 3 | | Total | | | 23 | Effort: S = 0.5 days, M = 2, L = 5, summed per release and rounded up. ## Defaults I picked Change if you disagree. - In 1.0 every join row starts at No caste, so nothing changes until you pick a caste. - From 1.1, colonist rows use the Colonist caste. It copies your current default policies, so colonists see no change. - Starter Slave caste: Slave outfit, Simple food, No drugs. Reading and medical care stay vanilla. Starter Prisoner caste: Simple food. - Hand changes win. Editing a caste moves only members still on the old value. "Apply to all members" (1.1) forces it. - In an existing save the starter castes appear, but nobody moves until you click "Assign by status". - The name stays Blax Castes, with the subtitle "policy bundles and join defaults", because three other Workshop mods already use "caste". - Castes 1.4 adds `PrePick` so Blax Slaves can put a caste picker next to its buy-as-slave toggle. The picker itself sits in the Blax Slaves backlog. - Not supported for now: multiplayer and animal castes. ## Data model ### Caste - `Caste : Policy` with LoadKey "BlaxCaste". Ids, load IDs, rename (IRenameable) and duplicate (`CopyFrom`) work the vanilla way. - The Policy int id is the caste id. The API passes it as a string. - Slots in 1.0: `ApparelPolicy`, `FoodPolicy`, `DrugPolicy` and `ReadingPolicy` (null = the caste leaves it alone), and medCare as an int (-1 = leave alone, otherwise a `MedicalCareCategory`). - Later slots store defNames, labels or ints, never def references, and resolve with `GetNamedSilentFail`: schedule (24 `TimeAssignmentDef` names), area (label, per map), hostility, self-tend, carried medicine, fire at will, work priorities, prisoner modes, DLC switches. ### Membership store - One `GameComponent_BlaxCastes` holds all state: the caste list, `Dictionary`, the join rows (reason to No caste, Default caste or a caste), the join queue, API hints and pre-picks (1.3), former-caste records (1.3), the next id and a seeded flag (1.1). - `CasteMembership`: caste, auto flag (set by a join row or by hand), reason, tick. Caste = null means "casteless by choice". Later safety nets skip those pawns instead of reassigning them. - No ThingComp and no data on vanilla objects. The only vanilla data Castes writes is the pawn's own policy fields. - Overrides are not stored. A slot value that differs from the caste is an override. ### Join classification and deferral - Classify where the join happens. Apply after the whole call chain returns. - Enqueue only on a real transition into player colonist, player slave or player prisoner. A prefix on `Pawn.SetFaction` and `Pawn_GuestTracker.SetGuestStatus` snapshots faction, guest status and host faction, and the postfix compares. - Reason, first match wins: API hint, innermost scope (for example "bought" from `Pawn.PreTraded`), status fallback. The fallback is resolved at apply time from the final status: new colonist, new slave or new prisoner. - Scopes push in a prefix and pop in a Harmony finalizer, so an exception never leaves the stack dirty. - `GameComponentTick` applies the queue on the first tick after the queueing tick, after checking the pawn is still player-side. Never inside `SetFaction` or `SetGuestStatus`, which reset medical care, areas, work and slave mode right after. - Every hook body sits in try/catch with a one-time log, so a Castes bug can never break a trade. ### Save safety - Memberships save with `Scribe_Collections` (LookMode.Reference / Deep) and `logNullErrors: false`, because world-pawn GC leaves null keys. Null, Discarded and destroyed-but-not-dead keys are purged on save and after load. - PostLoadInit checks every slot with `db.All*.Contains`. A missing policy becomes unmanaged, with one warning per caste. Apply checks the same before every write. - Policy load IDs contain the label. That is safe, because the caste and the policy sit in the same save. - Former-caste records are keyed by ThingID string, not by reference, so a discarded pawn leaves no unresolved reference. - Removing the mod: pawns keep their last policies. The only trace is one "type not found" line for the component. - Adding it mid-save: `Game.ExposeData` creates the component. From 1.1 the starter castes are seeded once on `LoadedGame`. ## 1.0: castes and bought slaves (6 days) Moved to 1.1 to keep 1.0 near a week: starter castes, overlap warnings, the policy delete guard, manager tools and the gizmo. Reviewers wanted starter castes and overlap warnings in 1.0. I picked the safer cut: 1.0 rows start at No caste and change nothing without a pick, and Castes already wins over other mods by applying a tick later. #### Castes - **Players get:** Make castes such as Slave or Miner slave. Putting a pawn in a caste sets its apparel, food, drug and reading policy and its medical care in one step. Change a caste's food policy and every member follows, except pawns you changed by hand. - **How:** - `CasteUtility.Apply(pawn, caste)` writes each managed slot through the vanilla setters: `CurrentApparelPolicy`, `CurrentFoodPolicy`, `CurrentPolicy` (drugs and reading), `playerSettings.medCare`. - Per-slot checks. Apparel, drug and reading need the tracker, `!IsQuestLodger()` and no `disablePolicies` mutant. Food needs `foodRestriction.Configurable` and a non-baby. Medical care needs `playerSettings` and a flesh pawn. Prisoners get food and medical care only. - Assigning a caste, by hand or by a join row, writes every managed slot. - Sync: every slot edit goes through `CasteManager.SetSlot`. Members still on the old value get the new one. Members on another value keep it (the Follow rule from 1trickPwnyta's Defaults). - Edits inside a policy, such as the Slave outfit's filter, reach members through the vanilla reference already. - A sweep every 2500 ticks ends memberships of pawns that are no longer player faction or player prisoners. - **Settings:** `enabled` (on). Off: nothing is applied, castes stay in the save. - **Replaces:** Save My Settings (3648714184, 3,827 subs), applying clothing and food presets to pawns, partly. - **Effort:** M, plus S for sync and S for the save safety in the data model (3 days). - **Tests:** Phase 1: a caste with Slave outfit, Simple food, No drugs, None reading and HerbalOrWorse sets all five on `Fixtures.Colonist`. On a player prisoner, food and medical care change and the outfit tracker is untouched. A quest lodger and a baby skip the right slots. Two members, B set to Worker by hand: changing the caste from Slave to Nudist moves A only. Phase 2: castes, slots and memberships survive save and reload, including a casteless-by-choice entry. - **Risks:** A pawn that happens to match the old value counts as following. Vanilla writes (ResetMedicalCare on a status change, TryDelete nulling fields, the mutant tracker nulling policies) show up as overrides. The column tooltip names the slot and its value, so the cause is visible. #### Caste manager - **Players get:** A window like the vanilla policy managers. On the left, the caste list with new, duplicate, rename, delete and make default. On the right, one row per policy with a "managed" checkbox, a dropdown and a pencil that opens the vanilla editor for that policy. - **How:** - `Dialog_ManageCastes : Dialog_ManagePolicies`. The base class already draws the list and handles duplicate, rename and the delete confirm. - Overrides: `CreateNewPolicy` (next id, label "Caste N", nothing managed), `GetPolicies`, `GetDefaultPolicy` / `SetDefaultPolicy`, `TryDeletePolicy`, `DoContentsRect` (five slot rows), `TitleKey`, `TipKey`. - The default caste is what rows set to "Default caste" use. With no default set, those rows act as No caste. The "Make default" button keeps the vanilla tooltip, which the base class draws. `TipKey` explains the default caste. - Delete: members become casteless and keep their current policies. Rows pointing at the caste fall back to No caste. - Pencils open `Dialog_ManageApparelPolicies`, `Dialog_ManageFoodPolicies`, `Dialog_ManageDrugPolicies` or `Dialog_ManageReadingPolicies` on the slot's policy. - A first-load message points to Assign > Manage castes. - **Settings:** none, covered by `enabled`. - **Replaces:** none. - **Effort:** S (0.5 days). Trimmed: member count, "Apply to all" and "Assign by status" move to 1.1. - **Tests:** CreateNewPolicy gives unique ids. Duplicate copies every slot. TryDeletePolicy removes the caste, empties its memberships, resets its rows to No caste and leaves pawn policies unchanged. SetDefaultPolicy changes what "Default caste" resolves to. - **Risks:** Generic methods over reference types share one JIT body, so another mod's patch on `Dialog_ManagePolicies` (Better Policies, Defaults, both 1.6-only today) also runs here. If a -Compat run shows a break, switch to a plain Window. The base layout changed in 1.6, so keep `DoContentsRect` self-contained. #### Caste column in the Assign tab - **Players get:** A Caste column left of the hostility, medical and policy columns. Click a cell, or drag-paint down the column, to assign. Header buttons open the caste manager and the join defaults. - **How:** - A `PatchOperationInsert` (order Prepend) before `li[text()="HostilityResponse"]` in `PawnTableDef[defName="Assign"]/columns` adds `PawnColumnDef BlaxCastes_Caste` with `PawnColumnWorker_BlaxCaste`. `PawnColumnWorker_Outfit` is the template. - Cell: `Widgets.Dropdown(..., paintable: true)`. The label is the caste name, "*" plus a tooltip naming overridden slots and their values, "(pending)" while a join is queued, or "Unchangeable" for quest lodgers. - Menu: No caste (stored as casteless by choice), each caste, Reset to caste, Edit caste. - `Compare` sorts by caste label, casteless last. Width 100 to 160 px. Header buttons "Manage castes" and "Defaults" sit in the same 65 px area as the outfit column's. - The Assign tab never lists prisoners. In 1.0 prisoners join castes only through the "New prisoner" row. The gizmo adds a manual path in 1.1. - **Settings:** `showAssignColumn` (on). The column is removed from the table def at startup, so a change needs a restart. - **Replaces:** none. - **Effort:** S (0.5 days). - **Tests:** At startup the Assign table def has `BlaxCastes_Caste` right before `HostilityResponse`, with and without the Ideology and Biotech columns. The menu has No caste, one entry per caste and Reset, and invoking an entry assigns. Drawing is checked by hand, since headless runs have no GUI. - **Risks:** Numbers builds its own tables, so the column shows only in vanilla Assign (Numbers has no 1.7 build today). The table gets wider on small screens. #### Join defaults for buying and status changes - **Players get:** A defaults window picks a caste for five rows: bought as slave, bought as colonist, new colonist, new slave, new prisoner. A bought slave arrives already wearing its caste's outfit and eating its food, and a message names the caste. - **How:** - Each row is No caste, Default caste or a specific caste. Rows live in the save component. Layout follows `Dialog_MedicalDefaults`. - Buying: a prefix on `Pawn.PreTraded` with PlayerBuys pushes "bought", a finalizer pops it. At apply time `IsSlave` picks the bought-as-slave or bought-as-colonist row. This covers Blax Slaves' buy mode, which only sets `guest.joinStatus` before `PreTraded`. - Everything else goes to the new colonist, new slave or new prisoner row by final status: enslaving, recruiting, capturing, quest prisoners, slave-born children, Blax Slaves' returned runaways, modded paths. - Transition snapshot and deferral as in the data model. Vanilla's internal `SetGuestStatus(null)` calls on existing members do not re-queue them. A pawn sold between queue and apply is dropped. A specific reason beats a status fallback when a pawn is queued twice. - If the row is No caste and the pawn was in a caste, it leaves the caste, its managed slots return to the database defaults, and `ResetMedicalCare` runs. This is PrisonerDefaults' revert on recruit. - Leaving the player faction, for example by being sold, ends the membership. - Babies and quest lodgers are skipped until 1.3. - **Settings:** `enableJoinDefaults` (on), `joinMessages` (on), `revertOnLeave` (on). - **Replaces:** Automatic Slave Outfit (2912063732, 16,672 subs). PrisonerDefaults (3531556159, 1,086 subs). The join defaults of Better Pawn Control (1541460369, 227,665 subs), Better Pawn Control Forked (3724294345, 1,308 subs) and 1trickPwnyta's Defaults (3285178686, 75,424 subs). - **Effort:** M (2 days). - **Tests:** - A pawn with joinStatus JoinAsSlave through `PreTraded(PlayerBuys, ...)` is queued. After `Fixtures.Tick(1)` it is in the bought-as-slave caste with that caste's outfit and food. - JoinAsColonist ends in the bought-as-colonist caste. - `GenGuest.EnslavePrisoner` on a prisoner fixture ends in the new-slave caste. - `RecruitUtility.Recruit` ends in the new-colonist caste, and the food policy is no longer the prisoner one. - `CapturedBy` on a downed raider ends in the new-prisoner caste. - `SetGuestStatus(null)` on an existing member does not re-queue it. - A pawn sold between queue and apply is dropped without errors. - An exception inside the scope leaves the stack empty. - -Compat with Blax Slaves: its buy mode's slave or colonist choice lands in the right row. - **Risks:** Better Pawn Control and its fork write policies in their own SetGuestStatus postfix. Castes applies a tick later and wins, and 1.1 warns about it. While the game is paused after a trade, the pawn shows "(pending)" until the next tick. ## 1.1: ready out of the box (4 days) #### Starter castes - **Players get:** A new colony starts with Colonist, Slave and Prisoner castes, already wired to the join rows. Colonists see no change. In an existing save the castes appear, but nobody moves until you click "Assign by status". - **How:** - Colonist: each slot is set to the database's current default (`DefaultOutfit()`, `DefaultFoodRestriction()`, `DefaultDrugPolicy()`, `DefaultReadingPolicy()`). These already carry the ideo drug rule set in `PostIdeoChosen` and any earlier "Make default". Medical care is unmanaged. - Slave: the Ideology Slave apparel policy, Simple food, No drugs. Reading stays unmanaged, because slave children need books for the Learning need. Medical care stays unmanaged, so vanilla `defaultCareForSlave` stays in charge. - Prisoner: Simple food. - Lookup: No drugs by `DrugPolicy.sourceDef` defName "NoDrugs", first match (`CopyFrom` copies sourceDef). Slave outfit and Simple food by their translated starting labels (OutfitSlave, FoodRestrictionSimple). On a miss the slot stays unmanaged and the manager shows a "Create Slave outfit" button. Castes never creates vanilla policies silently. - Rows: starting colonists, bought as colonist and new colonist use Default caste (Colonist). Bought as slave and new slave use Slave. New prisoner uses Prisoner. - New game: seeded in `StartedNewGame`, then starting colonists are assigned through the new "starting colonists" row. Existing save: `GameComponent.LoadedGame` seeds once per save, only if the save has no castes, with one message. Not `FinalizeInit`, which also runs on every new game. - The Slave caste's tooltip and the manager warn that the vanilla Slave outfit has no cold protection. - **Settings:** `seedStarterCastes` (on). - **Replaces:** Food Restriction Eleven (2780048210, 15,428 subs), sane starting policies, partly. Automatic Slave Outfit (16,672 subs) in any language, because Castes uses the policy reference, not the label. - **Effort:** S (0.5 days). - **Tests:** A quick-test game has three castes. The Slave caste's apparel is the database's Slave outfit. No drugs is matched by sourceDef. Rows map as listed. Starting colonists are Colonist members with unchanged policies. A start with a drug-prohibiting ideo keeps NoDrugs on the Colonist caste. Phase 2: no second seeding after reload. Removing the Slave outfit before seeding leaves the slot unmanaged. - **Risks:** Policies the player renamed before adding Castes miss the label match. The slot stays unmanaged and the create button shows. Slaves in the Slave outfit freeze in cold biomes; the warning makes that visible. #### Manager tools - **Players get:** The manager footer shows the member count, "Apply to all members" and "Assign pawns without a caste by status". - **How:** "Apply to all members" writes every managed slot to every member, after a confirm that names the member count. "Assign by status" runs the new colonist, new slave and new prisoner rows on pawns with no membership record, and is shown only while such pawns exist. Casteless-by-choice pawns are skipped. - **Settings:** none, covered by `enabled`. - **Replaces:** none. - **Effort:** S (0.5 days). - **Tests:** "Apply to all" clears an override. "Assign by status" puts an unassigned slave in Slave and leaves a casteless-by-choice slave alone. - **Risks:** "Apply to all" overwrites hand changes, hence the confirm. #### Policy delete guard - **Players get:** Deleting a policy a caste uses is refused with "Used by caste Slave", like vanilla's "in use" message. - **How:** Prefixes on `OutfitDatabase.TryDelete`, `FoodRestrictionDatabase.TryDelete`, `DrugPolicyDatabase.TryDelete` and `ReadingPolicyDatabase.TryDelete` return a rejected `AcceptanceReport` when a caste slot uses the policy. With the setting off, a postfix on accept unmanages that slot and posts a message. The four vanilla dialogs are the only callers. - **Settings:** `protectPoliciesInUse` (on). - **Replaces:** none. - **Effort:** S (0.5 days). - **Tests:** TryDelete on a policy used only by a memberless caste is refused and the policy stays in the database. With the setting off it is accepted and the slot is unmanaged. - **Risks:** Mods that delete policies without TryDelete are caught only by the load check. #### Overlap warnings - **Players get:** If Better Pawn Control, its fork, 1trickPwnyta's Defaults, Automatic Slave Outfit or PrisonerDefaults is active, the settings page and a one-time message say which of their join defaults overlap and suggest turning them off. - **How:** Detection through the shared Compat helper (`ModLister.GetActiveModWithIdentifier(id, ignorePostfix: true)`), so a dev copy and a Workshop copy both match. Package ids are read from each mod's About.xml before shipping. No patches against those mods. The message explains that Castes applies one tick after a join, so its choice wins. - **Settings:** `warnOverlaps` (on). - **Replaces:** none. - **Effort:** S (0.5 days). - **Tests:** Inject a fake active id into the detection list. The settings text and the message name it. - **Risks:** A wrong package id misses silently, so check the ids against Workshop copies. #### Caste gizmo - **Players get:** With colonists, slaves or prisoners selected, a "Caste: Slave" button opens one caste menu and assigns the pick to every selected pawn. It is the manual way to put a prisoner in a caste. - **How:** - A postfix on `Pawn.GetGizmos` yields `Command_BlaxCaste : Command`. - It sets `alsoClickIfOtherInGroupClicked = false`, `ProcessInput` only plays the sound, and `ProcessGroupInput(Event, List)` opens one FloatMenu for the whole group. Without the flag the menu opens once per pawn. - `GroupsWith` returns true for any other `Command_BlaxCaste`, because the base matches on the label. - Shown for player colonists, slaves, children and player prisoners. Not for quest lodgers or `disablePolicies` mutants. - Icon: a vanilla texture checked with `ContentFinder` at startup, with a text-only fallback. - **Settings:** `showGizmo` (on). - **Replaces:** none. - **Effort:** S (0.5 days). - **Tests:** GetGizmos yields one `Command_BlaxCaste` on a colonist and on a prisoner, and none on a lodger. Group input with three pawns builds one menu and assigns all three. - **Risks:** Gizmo clutter, hence the toggle. #### New caste from pawn - **Players get:** "New caste from this pawn" in the column menu, the gizmo menu and the manager. It copies a pawn's current apparel, food, drug and reading policy and medical care into a new caste, so an existing colony gets its castes in a few clicks. - **How:** Creates a caste with all five slots managed from the pawn's current values, then makes the pawn a member. Slots the pawn cannot use, such as a prisoner's apparel, stay unmanaged. - **Settings:** none, covered by `enabled`. - **Replaces:** none. - **Effort:** S (0.5 days). - **Tests:** A colonist on Worker, Fine, Social, All and Best gives a caste with those five values, and the colonist is a member with no overrides. - **Risks:** none known. #### Ideo conflict warning - **Players get:** The manager flags a caste whose drug or food policy clashes with a member's ideoligion, for example Social drugs for a drug-prohibiting ideo, or food with meat for a vegetarian ideo. Surprise mood hits are the main reason players blame a defaults mod. - **How:** Drug: the member's ideo has a precept with `defaultDrugPolicyOverride`, and the caste's drug policy is not the matching policy. Food: the ideo has a `MeatEating_Disapproved`, `MeatEating_Horrible` or `MeatEating_Abhorrent` precept, and the caste's food filter allows meat. Checked when the manager opens, a member joins or a slot changes, never per tick. Shown as a warning line in the manager and a "!" in the column tooltip. Ideology only. - **Settings:** `warnIdeoConflicts` (on). - **Replaces:** none. - **Effort:** S (0.5 days). - **Tests:** A member with a drug-prohibiting ideo in a Social drugs caste is flagged, and on No drugs it is not. A member with a vegetarian ideo in a Lavish caste is flagged. Skipped without Ideology. - **Risks:** Modded precepts that forbid drugs without `defaultDrugPolicyOverride` are missed. ## 1.2: more settings per caste (3 days) #### Schedule and allowed area - **Players get:** Castes can also set the daily schedule and the allowed area. Pawns still in a drop pod or caravan, or arriving on another map, get the area when they arrive. - **How:** - Schedule: 24 `TimeAssignmentDef` defNames (null = leave alone), resolved with `GetNamedSilentFail`. Meditate becomes Anything without Royalty. Written with `Pawn_TimetableTracker.SetAssignment`. - Area: the area label, resolved per map with `AreaManager.GetLabeled` and `Area.AssignableAsAllowed()`. Applied when `MapHeld != null`, `SupportsAllowedAreas`, `Faction.IsPlayer` and `HostFaction == null`. Not gated on `RespectsAllowedArea`, which is false for any pawn in a Lord (rituals, parties, caravan forming). - Otherwise the pawn goes on a pending list. A `Pawn.SpawnSetup` postfix applies pending entries, and the area on a map where Castes never set one for that pawn (tracked per pawn per map id), then clears them. A 250-tick sweep retries pending entries. - It never re-applies on every spawn, so manual choices and AAAA's "#safe" swaps survive caravans, transport pods and map moves. - A label missing on the map means leave alone. The manager shows "missing on " with a "Create area" button (`AreaManager.TryMakeNewAllowed`). A renamed area shows as missing until re-picked. - The caste column is also added to `PawnTableDef` Restrict (the Schedule tab). - **Settings:** `allowScheduleAndArea` (on), `applyAreaOnSpawn` (on). - **Replaces:** 1trickPwnyta's Defaults (75,424 subs), default area per pawn type. Plug and Play Joiner (Continued) (3383245777, 1,489 subs), preset area for joiners. - **Effort:** M (2 days). - **Tests:** A caste with a test area and a night schedule. A bought-slave fixture left unspawned gets the schedule at once and the area pending, and spawning applies the area. A second spawn on the same map after a manual change keeps the manual area. Deleting the area makes the slot report missing, and Apply does nothing, without errors. An unknown time defName becomes Anything. - **Risks:** AAAA (3264193512, 100,585 subs) swaps areas on threats. Castes writes areas only on assign, join, first arrival on a map and caste edits. #### Hostility, self-tend, carried medicine, fire at will - **Players get:** Castes can also set the hostility response, self-tend, carried medicine and fire at will. A Guard caste can be set to Attack and carry 2 industrial medicine. - **How:** - Hostility: an int (-1 = leave alone). Attack falls back to Flee when `WorkTagIsDisabled(Violent)`. - Self-tend: -1, 0 or 1, plus an optional "only if Medicine skill is at least N". Skipped when Doctor is disabled. - Carry: a Medicine stock group thing defName and count via `Pawn_InventoryStockTracker.SetThingForGroup` and `SetCountForGroup`, which clamp to the group. - Fire at will: written on assign and restored in the SpawnSetup postfix, because `drafter` is nulled on despawn. - The manager warns when members x count exceeds the colony's medicine. - No slave interaction mode slot. Suppression belongs to Blax Slaves. - **Settings:** `allowBehaviourSlots` (on). - **Replaces:** 1trickPwnyta's Defaults (75,424 subs): default hostility, medicine carry and self-tend at a minimum skill. - **Effort:** S (0.5 days). - **Tests:** A violent colonist gets Attack, 2 industrial medicine and self-tend. A pacifist gets Flee. A pawn with Doctor disabled keeps self-tend off. After despawn and spawn, FireAtWill is restored. - **Risks:** Big castes with carry above 0 drain the hospital, hence the warning. ## 1.3: every join path, Blax Slaves and Zones (3 days) #### Every join path, adult and child - **Players get:** The defaults window lists every way a pawn joins, each with an adult caste and a child caste: wanderer, quest reward, rescued, lodger recruited, freed slave, born, child chosen as colonist or slave, coming of age. Pawns that come back (re-bought, released after arrest, re-enslaved, returned runaways) get their old caste. - **How:** - Rows: starting, boughtSlave, boughtColonist, enslaved, recruitedPrisoner, captured, wanderer, questJoiner, rescued, lodgerArrived (default No caste), lodgerRecruited, emancipated, recruitedSlave, born (incl. growth vat), childColonist, childSlave, cameOfAge, creepjoiner (Anomaly only), and the three status fallbacks. Each row has an adult and a child dropdown; the child one defaults to "same as adult". Picks from 1.0 carry over. - New scopes: `GenGuest.TryEnslavePrisoner` (EnslavePrisoner is a one-line wrapper that CoreCLR may inline), `RecruitUtility.Recruit` (records whether the pawn was a prisoner or a slave), `Pawn_GuestTracker.CapturedBy`. - One scope on `Quest.Notify_SignalReceived` carries `quest.root`: WandererJoins goes to wanderer, creepjoiner roots to creepjoiner, everything else to questJoiner. It is the only dispatcher of `QuestPart.Notify_QuestSignalReceived`, so it covers SetFaction, PawnsArrive, JoinPlayer, DropPods, GiveToCaravan, GiveNearPawn and modded quest parts. - Other hooks: `Pawn_GuestTracker.Notify_PawnUndowned` and `Pawn_MindState.JoinColonyBecauseRescuedBy` (rescued), `GenGuest.EmancipateSlave`, `ChoiceLetter_BabyToChild.ChoseColonist` / `ChoseSlave` (private), `LifeStageWorker_HumanlikeChild` and `LifeStageWorker_HumanlikeAdult.Notify_LifeStageStarted`, `PregnancyUtility.ApplyBirthOutcome`, `Faction.Notify_MemberLeftExtraFaction` (a lodger stops being one). - Status rows always move the pawn. Growth rows move only members whose membership is still auto-assigned. - Previous caste: when a member leaves the player faction, is sold, or becomes a prisoner (arrest, slave Imprison mode), Castes writes a former-caste record (caste id, status class, tick). If the pawn comes back within `formerCasteDays` with the same status class, it gets that caste back. An arrested colonist who is then enslaved goes to the enslaved row instead. - Order at apply time: pre-pick, then previous caste, then the row. - Safety net: on spawn, a player humanlike with no membership record whose `playerSettings.joinTick` is after the component's creation tick gets its status-fallback row once. Casteless-by-choice pawns are skipped. - **Settings:** `returnToPreviousCaste` (on), `formerCasteDays` (60), `catchAllOnSpawn` (on). - **Replaces:** 1trickPwnyta's Defaults (75,424 subs): child colonist defaults and the child-to-adult switch. Better Pawn Control (227,665 subs): its rescued and guest joiners arriving on Lavish food and Glitter medicine. - **Effort:** M (2 days). It would be L with one patch per QuestPart. - **Tests:** - One per path the harness can trigger: `Notify_PawnUndowned` by reflection on a downed friendly pawn (forced roll), `Quest.Notify_SignalReceived` with a fake quest whose root is WandererJoins, `EmancipateSlave` on a colony-born slave, the `ChoiceLetter_BabyToChild` actions on a baby fixture, a life-stage change from setting biological age, `ApplyBirthOutcome` (Biotech only, skipped without it). - A child fixture uses the child dropdown. - A Miner slave sold with `PreTraded(PlayerSells)` and re-bought returns to Miner slave. An arrested Miner colonist who is released returns to Miner. An arrested colonist who is enslaved goes to the enslaved row. - Lodger arrival gives no caste. A recruited lodger gets the lodgerRecruited row. - A casteless-by-choice pawn stays casteless after a caravan returns. - **Risks:** Quest code shifts between 1.7 builds. The status fallbacks and the spawn safety net keep unknown paths working. Hospitality guests are never player faction and are ignored. #### Public API - **Players get:** With Blax Slaves, returned runaways come back into their old caste and indentured pawns are sorted correctly. With Blax Zones, a sleeping zone can be limited to a caste. - **How:** - `BlaxCastes.CastesApi`, Version 1: `HintJoinReason`, `NotifyJoined`, `CasteIdOf`, `CasteLabels`. Signatures and the reason table are in "Works with the other Blax mods". - Hints sit in a per-pawn map. The next classification consumes a hint, and any hint left is cleared at the end of the tick. - `NotifyJoined` queues the pawn with that reason like any other join. The specific reason replaces a status fallback, even if the fallback already ran. - Unknown reasons use the status fallbacks. Castes calls nothing in the other mods. - **Settings:** `enableApi` (on). Off: API calls are ignored. - **Replaces:** none. - **Effort:** S (0.5 days). - **Tests:** `CasteIdOf` and `CasteLabels` round-trip. A hint beats the status fallback and is gone on the next tick. `NotifyJoined` on a pawn the fallback already placed moves it to the reason's row. -Compat with Blax Slaves: a returned runaway lands in its previous caste. - **Risks:** This is a contract across three repos. Add methods only, never change a signature, and raise Version on each addition. #### Pre-pick in the prisoner and slave tabs - **Players get:** The prisoner tab shows the prisoner's caste plus two pickers: caste when recruited and caste when enslaved. The slave tab shows the slave's caste and a "caste when freed" picker. A pick beats every default for that pawn. - **How:** Postfixes on the private `ITab_Pawn_Visitor.DoPrisonerTab(bool, Listing_Standard)` and `DoSlaveTab(Listing_Standard)` append rows at the end. The tab sizes itself from `listing.CurHeight`. Picks are stored in the component as pawn to (reason to caste), saved by reference, and cleared when used, when the pawn leaves, or when the caste is deleted. Hidden for wild men and non-player captives. - **Settings:** `showVisitorTabPickers` (on). - **Replaces:** PrisonerDefaults (1,086 subs): per-prisoner food choice, partly. - **Effort:** S (0.5 days). - **Tests:** A prisoner with "when enslaved" set to Miner slave ends in Miner slave after `EnslavePrisoner`, and the pick is gone. Without a pick, the row applies. Phase 2: the pick survives save and reload. - **Risks:** Prison Labor and Prisoner Realism also draw in this tab. Appending at the end avoids overlap; check with -Compat. ## 1.4: work and prisoners (4 days) #### Work priorities per caste (optional) - **Players get:** A caste can carry work priorities. A Hauler slave caste sets Hauling 1 and Cleaning 2 and leaves the rest alone. Off unless the caste turns it on. - **How:** Each caste holds work type defName to priority 0 to 4 (absent = leave alone). Applied after the status is final, because `SetFaction(player)` runs `EnableAndInitialize` and slaves ignore backstory disables. Types where `Pawn.WorkTypeIsDisabled` is true are skipped, which avoids the `SetPriority` error. With manual priorities off (`PlaySettings.useWorkPriorities`), any nonzero value means "on". Per caste: "Start from vanilla" keeps vanilla's picks, "Start from nothing" runs `DisableAll` first. The caste column is also added to `PawnTableDef` Work. - **Settings:** `allowWorkSlot` (on). The slot is greyed out with a note when WorkRoles, Work Tab, Free Will, Work Manager or AutoPriorities is active. - **Replaces:** Plug and Play Joiner (Continued) (1,489 subs): joiner work priorities. 1trickPwnyta's Defaults (75,424 subs): rule-based default work priorities, done by caste instead. - **Effort:** M (2 days). - **Tests:** A slave fixture in a caste with Hauling 1 has Hauling 1. A disabled work type stays 0 with no log error. "Start from nothing" leaves only the caste's types. With manual priorities off, nonzero becomes 3. - **Risks:** Automatic work managers reset priorities all the time and would fight Castes, hence off per caste plus detection. #### Shift schedules - **Players get:** A caste can hold up to three schedules. New members are dealt out in turn so day and night shifts fill evenly, and "Rebalance" spreads current members again. - **How:** The schedule slot becomes a list of 1 to 3 timetables plus a per-caste counter. Each membership stores its shift index. Rebalance sorts members by ThingID and assigns index i mod n, so the result is the same on every machine. Needs the 1.2 schedule slot. - **Settings:** `allowShifts` (on). - **Replaces:** 1trickPwnyta's Defaults (75,424 subs): round-robin default schedules. Work Manager (2029596262, 14,211 subs): shift schedules, partly. - **Effort:** S (0.5 days). - **Tests:** With two shifts, four assigned pawns split 2 and 2. After removing two and rebalancing, they split 1 and 1. - **Risks:** none known. #### Default prisoner interaction - **Players get:** A prisoner caste can set the interaction mode on capture, such as Reduce resistance, Enslave or Convert, plus Biotech's bloodfeed and hemogen farm toggles. - **How:** An exclusive `PrisonerInteractionModeDef` defName written with `Pawn_GuestTracker.SetExclusiveInteraction`, plus non-exclusive defNames written with `ToggleNonExclusiveInteraction`, each checked against the active DLCs and the def's exclusive flag. Applied on join only, because `SetGuestStatus(Prisoner)` resets the mode first. Existing members change only through "Apply to all members". - **Settings:** `prisonerModeSlot` (on). The slot defaults off when Prison Labor or Custom Prisoner Interactions is active. - **Replaces:** Custom Prisoner Interactions (2841231775): default action for new prisoners, partly. Prison Labor (1899474310): default interaction mode, partly. - **Effort:** S (0.5 days). - **Tests:** A Prisoner caste with Enslave: after `CapturedBy`, the exclusive mode is Enslave. The hemogen farm toggle applies only with Biotech. - **Risks:** Prison Labor sets its own mode on capture. Castes runs a tick later and overrides it, hence the detection. #### DLC switches - **Players get:** Castes can also set Royalty room and apparel requirements, psyfocus target and entropy limit, hemogen pack use and deathrest auto-wake. - **How:** Each is a nullable slot, shown only when its DLC is active and applied only when the pawn has the tracker or gene. Royalty: `allowRoomRequirements`, `allowApparelRequirements`. Psycasters: `limitEntropyAmount`, `SetPsyfocusTarget`. Genes: `Gene_Hemogen.hemogenPacksAllowed`, `Gene_Deathrest.autoWake`, found with `pawn.genes?.GetFirstGeneOfType()`, never by cast. - **Settings:** `allowDlcSlots` (on). - **Replaces:** none. - **Effort:** S (0.5 days). - **Tests:** Each slot is set on a pawn with the tracker or gene and skipped without errors on one without. Slots for a missing DLC are hidden; those tests skip when the DLC is absent. - **Risks:** Xenotype mods vary the gene classes, hence the type check. #### Trade-row caste picker support - **Players get:** Nothing visible yet. Once Blax Slaves adds its trade-row picker (in its backlog), you pick a caste for each pawn you buy, next to the buy-as-slave toggle. - **How:** `CastesApi.PrePick(Pawn, string casteId)`, API Version 2. It writes into the 1.3 pre-pick store under the bought reasons. Blax Slaves owns the picker in its trade row; Castes adds no trade dialog patch. - **Settings:** covered by `enableApi`. - **Replaces:** none. - **Effort:** S (0.5 days). - **Tests:** `PrePick` then `PreTraded(PlayerBuys)`: the pawn lands in the picked caste, not the row's. An unknown id is ignored. - **Risks:** A cancelled trade leaves a pick on a pawn that never joins. The 2500-tick sweep drops picks on pawns that are not player-side after one in-game day. ## 1.5: templates and colours (3 days) #### Caste templates across saves - **Players get:** Export a caste, together with the policies it uses, and import it into another colony. New games can start from your saved castes instead of the starter set. - **How:** Export writes the caste plus deep copies of its policies with `Scribe.saver` to `GenFilePaths.ConfigFolderPath/BlaxCastes/.xml`. Import creates new policies through each database's `MakeNewOutfit`, `MakeNewFoodRestriction`, `MakeNewDrugPolicy` or `MakeNewReadingPolicy` plus `CopyFrom` (label kept, suffixed if taken), then the caste. "Seed new games from templates" replaces the starter castes in `StartedNewGame`. Game data stays in the save; files are read only on an explicit action. - **Settings:** `seedFromTemplates` (off). - **Replaces:** Better Policies (3400923070, 3,857 subs): saving policies across saves, partly. Save My Settings (3,827 subs), partly. Export Agency (1467209473, 16,333 subs): policy export, partly. - **Effort:** M (2 days). - **Tests:** Export the Slave caste to a temp folder, delete it, import: the caste and its three policies come back with equal filters (compare allowed defs). Importing twice suffixes the labels. - **Risks:** Filters that reference defs from removed mods drop entries on load. Report the count. #### Caste colour and inspect line - **Players get:** Each caste can have a colour. The caste name shows in its colour in the Assign column, the gizmo and the pawn's inspect pane, so you see at a glance who is a field slave and who is a house slave. - **How:** A per-caste colour from 12 presets, saved as a Color. The column cell and gizmo label are tinted. A postfix on `Pawn.GetInspectString` adds a "Caste: X" line. No textures. - **Settings:** `showInspectLine` (on). - **Replaces:** none. - **Effort:** S (0.5 days). - **Tests:** The inspect string has the caste line when the setting is on and lacks it when off. - **Risks:** The inspect pane has little room on some UI mods, hence the toggle. ## Works with the other Blax mods ### Detection and binding - Package ids: `blax.slaves`, `blax.castes`, `blax.zones`. No hard dependencies. Siblings appear in About.xml only as loadAfter entries. - Detection: `ModLister.GetActiveModWithIdentifier(id, ignorePostfix: true)` in one shared Compat helper per mod, so a dev copy next to a Workshop copy still matches. - 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. - Castes uses neither ZonesApi nor SlavesApi. The others reach Castes only through `BlaxCastes.CastesApi`. - Load order is Castes, Zones, Slaves. Each mod loads after the APIs it calls: Castes lists no sibling, Zones lists `blax.castes`, Slaves lists `blax.castes` and `blax.zones`. No two mods list each other, so RimWorld reports no cycle. ### CastesApi (static class) | Member | What it does | Since | |---|---|---| | `Version` | int, raised on every addition | 1.3 | | `HintJoinReason(Pawn pawn, string reason)` | Consumed by that pawn's next join classification. Expires at the end of the current tick. | 1.3 | | `NotifyJoined(Pawn pawn, string reason)` | For joins Castes cannot see itself. Called one tick after the status is final. | 1.3 | | `CasteIdOf(Pawn)` | Caste id as a string, or null | 1.3 | | `CasteLabels()` | List of (id, label) | 1.3 | | `PrePick(Pawn, string casteId)` | Pre-pick for Blax Slaves' trade-row picker | 1.4 | ### Join reasons from Blax Slaves | Reason | Castes does | |---|---| | `blax.slaves.runawayReturned` | Previous caste. Without a record, the new-slave row. | | `blax.slaves.slaveRecruited` | Treated as recruited (recruitedSlave row) | | `blax.slaves.indentureServed` | Treated as recruited (recruitedSlave row) | | `blax.slaves.boughtIndentured` | Treated as bought as slave | | `blax.slaves.contractReturned` | Keeps the current caste | - Buying needs no API call. Blax Slaves' buy mode only sets `guest.joinStatus` before vanilla `Pawn.PreTraded`, and Castes classifies by the final status in its own PreTraded scope (1.0). - Before 1.3 there is no API. Purchases and returned runaways still work: runaways end in `SetGuestStatus(player, Slave)` and land in the new-slave row. - Blax Slaves ships no policy defaults. Its README points slave outfit, food and drug automation to Castes. ### Blax Zones - Zones' sleeping-zone filter gains "caste: X" entries when Castes is active, using `CasteLabels` and `CasteIdOf`. Zones stores the caste ids per save. - Castes has no bed or sleep slot. - The caste area slot writes the vanilla allowed area, so Zones would need no API to read it. Zones has no area check planned. ### Ownership - Castes: every per-pawn policy default (apparel, food, drug, reading, medical care, schedule, area, hostility, self-tend, carried medicine). - Zones: sleeping spots, beds by zone and every friendly drop location. - Slaves: slave status, trade, prices, suppression, rebellion, slave medicine and the slave economy. Slaves routes its silver payouts through `ZonesApi.TryFindDropSpot`, with `DropCellFinder.TradeDropSpot` as fallback. Pawns are never routed into zones. ### Shared conventions - Patches are applied one class at a time from a `[StaticConstructorOnStartup]` class, logging "[Blax Castes] N patches applied". One broken patch class does not take the others down. - Every feature has a ModSettings toggle. Reviewers wanted toggles that change the simulation in the save for multiplayer; the shared contract puts them in ModSettings, so they stay there until multiplayer is built. - Tests use the headless in-game test mod from `blax-slaves/Tests` (`BlaxSlavesTests` harness, `run-tests.ps1`), copied into this repo as `BlaxCastesTests`. Phase 1 runs in a fresh game, phase 2 after save and reload, and -Compat with the sibling and overlap mods active. ## Backlog - Multiplayer support: needs a 1.7 build of the Multiplayer mod, and real sync needs two clients. The groundwork is in place (tick-based apply, every write through `CasteManager`). The Workshop page says "Multiplayer: not supported yet" until then. - Colony bar grouped by caste, like [LTO] Colony Groups (231k subs, no 1.7 build): L and UI-heavy, only as a late optional release. - Animal and mech castes: a different set of settings (master, follow, training, control groups) and different tables. - A custom 64x64 gizmo icon: polish only, the vanilla icon works. ## Cut - Strict sync mode: it duplicates "Apply to all members", and as a ModSetting it would differ per client. - Slave interaction mode slot: suppression belongs to Blax Slaves. - Baby autofeed slot: stored per baby and per feeder, so it must be rewritten whenever a feeder joins or leaves. Low value. - Custom "Make default" tooltip: the base dialog always draws the vanilla one. `TipKey` explains the default caste instead. - Creating missing vanilla policies at seed time: it duplicates renamed policies. A "Create" button replaces it. - Reading None in the Slave caste: it does nothing for adult slaves and blocks slave children's learning. - One patch per QuestPart: one `Quest.Notify_SignalReceived` scope covers all of them, modded parts included. - A single "other" fallback row: it filed slave-born children, quest prisoners and returned runaways as colonists. Three status rows replace it. - `RegisterJoinReason` in the API: not in the shared contract. Castes maps the Blax Slaves reasons itself. - Colony-wide presets or emergency mode: a different model (colony modes, not roles). BPC Forked has it on 1.7, and AAAA covers threat areas. - Defaults' non-pawn defaults (storyteller, world, bills, shelves, zones, policy locks): out of scope, and that bulk is why players find Defaults too big. - Ideology roles in a caste: roles are for free colonists only and mostly have one holder, so bulk assignment makes no sense. - A caste picker in the trade dialog owned by Castes: Blax Slaves owns the trade row, and Castes offers `PrePick` instead. - A sleeping-zone or bed slot: beds by zone belong to Blax Zones, which filters by caste instead. - Caste mood, social or precept rules and stat bonuses: that is what Ideology: Social Castes and Caste System do. It is not a policy bundle. - An appearance or style bundle: not a policy. It queues styling-station jobs and has no clean "apply". - Guest and visitor defaults: visitors lack the policy trackers, and Hospitality already handles guests. - A rule engine for assignment: too abstract. Join rows plus pre-picks cover the real cases with far less UI. - Periodic re-sync of members: it would fight AAAA's area swaps and hand changes. Castes writes only on assign, join, first arrival and caste edits. - Policy templates in ModSettings in 1.0: they need policy serialization and label re-linking. Templates arrive in 1.5 as files.