feat: Castes 1.0 scope: schedule, work priorities, loadouts, automatic status changes

Starter castes, join rows on every status change, old caste on return, overlap warnings, review fixes, test runner switches (-NoDlc, -Dlc, -Tasoc), Blax footer, deterministic DLL.
This commit is contained in:
Fabian @ Blax Software 2026-11-29 11:57:22 +01:00
parent afede583e6
commit a0c809a7dd
52 changed files with 5344 additions and 373 deletions

Binary file not shown.

Binary file not shown.

View File

@ -20,15 +20,21 @@
</loadAfter> </loadAfter>
<description>Policy bundles and join defaults. Works without DLCs; slaves need Ideology. <description>Policy bundles and join defaults. Works without DLCs; slaves need Ideology.
- A caste bundles an apparel, food, drug and reading policy and a medical care level. Putting a pawn in a caste sets all five in one step. - A caste bundles an apparel, food, drug and reading policy, a medical care level, a daily schedule and work priorities. Putting a pawn in a caste sets every slot the caste manages in one step.
- Change a caste's policy and its members follow, except pawns you changed by hand. - Work priorities: set only the work types you pick, such as Firefighting 1 for everyone or Growing 1 for field slaves. Work a pawn cannot do is skipped. Off while an automatic work manager (Work Tab, Free Will, Work Manager, AutoPriorities, WorkRoles) is active.
- With [1001] Weapons Tab Reborn, a caste can also set the weapon loadout.
- Change a caste's setting and its members follow, except pawns you changed by hand.
- Ready-made Colonist, Slave and Prisoner castes, already picked for the ways pawns join. Colonist copies your default policies, so in a new game colonists see no change. An existing save gets them too, and nobody moves until you click "Assign by status".
- Every status change uses its join row: bought, recruited, enslaved, freed, arrested, released or captured. A pawn you buy arrives with its caste's outfit and food policy already set, and a message names the caste.
- A colonist or slave that comes back within 60 days (released, bought back) gets its old caste back, with the changes you made by hand.
- Prisoners in a caste get its food policy and medical care only. - Prisoners in a caste get its food policy and medical care only.
- Assign tab: a Caste column (click a cell, or drag down the column to give several pawns the same caste), and the "Manage castes" and "Defaults" buttons above it. The caste manager works like the vanilla policy windows. - Assign, Schedule and Work tabs: a Caste column (click a cell, or drag down the column to give several pawns the same caste), with a "Manage castes" button above it and, in the Assign and Schedule tabs, "Defaults". The caste manager works like the vanilla policy windows, with a schedule painted like the Schedule tab, a member count, "Apply to all members" and "Assign by status".
- Join defaults: pick a caste for bought slaves, bought colonists, new colonists, new slaves and new prisoners. A pawn you buy arrives already wearing its caste's outfit and eating its food, and a message names the caste. Every row starts at No caste, so nothing changes until you pick one.
- A recruited prisoner can leave the prisoner caste and go back to your default policies.
- A pawn that leaves your faction leaves its caste. - A pawn that leaves your faction leaves its caste.
- Covers Automatic Slave Outfit, PrisonerDefaults and the join defaults of Better Pawn Control and 1trickPwnyta's Defaults. - Covers Automatic Slave Outfit, PrisonerDefaults and the join, schedule and work defaults of Better Pawn Control and 1trickPwnyta's Defaults, and warns while one of them is active.
- Turn it off in the mod settings and castes stop changing policies. Removing the mod leaves every pawn on its last policies. - Turn it off in the mod settings and castes stop changing pawns. Removing the mod leaves every pawn on its last settings.
Multiplayer: not supported yet.</description> Multiplayer: not supported yet.
&lt;color=#19C63C&gt;Made by Blax&lt;/color&gt;
Blax Gaming is a project of Blax Software, an Austrian software practice. We write Austrian-quality code in many fields: web platforms, mobile apps, backends, infrastructure, and the mods we play in our own colonies. www.blax.at</description>
</ModMetaData> </ModMetaData>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 65 KiB

After

Width:  |  Height:  |  Size: 68 KiB

View File

@ -2,10 +2,16 @@
## 1.0.0 ## 1.0.0
- Castes: a caste bundles an apparel, food, drug and reading policy and a medical care level. Putting a pawn in a caste sets all five in one step. Prisoners get the food policy and medical care only; quest lodgers skip apparel, drugs and reading; babies skip food. - Castes: a caste bundles an apparel, food, drug and reading policy, a medical care level, a schedule, work priorities and, with [1001] Weapons Tab Reborn, a weapon loadout. Putting a pawn in a caste sets every slot the caste manages in one step. Prisoners get the food policy and medical care only; quest lodgers skip apparel, drugs, reading and the schedule; babies skip food.
- Change a caste's slot and its members follow, except pawns you changed by hand. - Schedule: paint a caste's 24 hours in the caste manager like the vanilla Schedule tab, or copy them from a pawn. Colonists and slaves get it; prisoners keep theirs until they become colonists or slaves.
- Caste manager (Assign tab > Manage castes), built on the vanilla policy window: new, duplicate, rename, delete, make default, and per slot a managed checkbox, a dropdown and a pencil that opens the vanilla editor. - Work priorities: a caste sets only the work types you pick (1 to 4 or off), so every caste can set Firefighting to 1. Work a pawn cannot do is skipped; with manual priorities off, any number means on, and the number is kept for when you turn them on. "Start from nothing" turns all other work off except Patient and Bed rest, so hurt and sick pawns still go to bed. Clicking a work type's button through several values moves only the members that followed it before the first click. Off while Work Tab, Free Will, Work Manager, AutoPriorities or WorkRoles is active.
- Caste column in the Assign tab: click a cell or drag down the column to assign. Shows "*" and a tooltip when a pawn's policies differ from its caste, and "(pending)" until a join is applied. - Weapon loadout: with Weapons Tab Reborn active, a caste can hand out a loadout to its colonists and slaves. A loadout deleted in Weapons Tab Reborn becomes unmanaged. Without the mod the row is hidden.
- Join defaults (Assign tab > Defaults): pick No caste, the default caste or a specific caste for bought slaves, bought colonists, new colonists, new slaves and new prisoners. Every row starts at No caste. A bought slave arrives in its caste, and a message names it. A No caste row takes a pawn out of its old caste and resets its policies. Replaces Automatic Slave Outfit and PrisonerDefaults, and the join defaults of Better Pawn Control, Better Pawn Control Forked and 1trickPwnyta's Defaults. - Change a caste's slot and its members follow, except pawns you changed by hand. Schedules follow as a whole day, work priorities per work type.
- A pawn that leaves your faction leaves its caste. Deleting a caste leaves its members casteless on their current policies. - Starter castes: a new game starts with Colonist (your default policies), Slave (Slave outfit, Simple food, No drugs) and Prisoner (Simple food), already picked in the join defaults, and the starting colonists in Colonist. Their schedule, work priorities and loadout start unmanaged: set them once on the caste and every member follows. A save without castes gets them once, on load; nobody moves until you click "Assign by status", which asks first because it replaces those pawns' own policies. Without Ideology there is no Slave caste.
- Settings: castes on or off, join defaults, join messages, reset policies when a join removes a caste, the Assign column. While a game is loaded, the settings page also opens the caste manager and the join defaults. - Caste manager (Assign tab > Manage castes), built on the vanilla policy window: new, duplicate, rename, delete, make default, and per policy a managed checkbox, a dropdown and a pencil that opens the vanilla editor, plus the schedule grid, the work priority buttons and the loadout. Below the slots: the member count and "Apply to all members" (asks first). "Assign by status" puts pawns without a caste into the caste of their status. "Create Slave outfit" shows when the game has none, and a caste with the Slave outfit warns that it has no cold protection.
- Caste column in the Assign, Schedule and Work tabs (in the Schedule tab right of the timetable, in the Work tab left of the work columns): click a cell or drag down the column to assign; dragging keeps the hand changes of pawns already in that caste. Shows "*" and a tooltip when a pawn's settings differ from its caste, and "(pending)" until a join that changes its caste is applied.
- Join defaults (Assign tab > Defaults): pick No caste, the default caste or a specific caste for bought slaves, bought colonists, new colonists, new slaves and new prisoners. Every status change goes through these rows: buying, recruiting, enslaving, freeing, arresting, releasing, imprisoning a slave and capturing. A bought slave arrives with its caste's outfit and food policy already set, and a message names the caste. A No caste row takes a pawn out of a caste a join row put it in (a caste you picked by hand stays) and, with Reset policies on, resets the policies it still has from that caste; so does a row that moves it on to a caste that leaves those policies alone. Replaces Automatic Slave Outfit and PrisonerDefaults, and the join, schedule and work defaults of Better Pawn Control, Better Pawn Control Forked and 1trickPwnyta's Defaults.
- A colonist or slave that leaves, is sold or becomes a prisoner and comes back within 60 days with the same status gets its old caste (or No caste) back, with the changes you made by hand; what the caste it had while away set goes back to how it was.
- Warnings on the settings page and one message per save when Better Pawn Control, its fork, 1trickPwnyta's Defaults, Automatic Slave Outfit or PrisonerDefaults is active.
- A pawn that leaves your faction leaves its caste. Deleting a caste leaves its members casteless on their current settings.
- Settings: castes on or off, work priorities, weapon loadout, join defaults, join messages, reset policies a caste set when a join moves the pawn on, old caste on return and for how many days, starter castes, overlap warnings, the Caste column. While a game is loaded, the settings page also opens the caste manager and the join defaults.

View File

@ -1,11 +1,11 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Defs> <Defs>
<!-- The Caste column in the Assign tab. Patches/BlaxCastes_Assign.xml adds it to the table. --> <!-- The Caste column in the Assign, Schedule and Work tabs. Patches/BlaxCastes_Assign.xml and BlaxCastes_ScheduleWork.xml add it to the tables. -->
<PawnColumnDef> <PawnColumnDef>
<defName>BlaxCastes_Caste</defName> <defName>BlaxCastes_Caste</defName>
<label>caste</label> <label>caste</label>
<headerTip>The pawn's caste. A caste sets apparel, food, drug and reading policy and medical care at once. Click a cell to pick a caste, or drag down the column to give several pawns the same one.</headerTip> <headerTip>The pawn's caste. A caste sets apparel, food, drug and reading policy, medical care, schedule, work priorities and weapon loadout at once. Click a cell to pick a caste, or drag down the column to give several pawns the same one.</headerTip>
<workerClass>BlaxCastes.PawnColumnWorker_BlaxCaste</workerClass> <workerClass>BlaxCastes.PawnColumnWorker_BlaxCaste</workerClass>
<sortable>true</sortable> <sortable>true</sortable>
</PawnColumnDef> </PawnColumnDef>

View File

@ -9,10 +9,34 @@
<BlaxCastes_SlotDrug>Drugs</BlaxCastes_SlotDrug> <BlaxCastes_SlotDrug>Drugs</BlaxCastes_SlotDrug>
<BlaxCastes_SlotReading>Reading</BlaxCastes_SlotReading> <BlaxCastes_SlotReading>Reading</BlaxCastes_SlotReading>
<BlaxCastes_SlotMedCare>Medical care</BlaxCastes_SlotMedCare> <BlaxCastes_SlotMedCare>Medical care</BlaxCastes_SlotMedCare>
<BlaxCastes_SlotSchedule>Schedule</BlaxCastes_SlotSchedule>
<BlaxCastes_SlotWork>Work priorities</BlaxCastes_SlotWork>
<BlaxCastes_SlotLoadout>Weapon loadout</BlaxCastes_SlotLoadout>
<BlaxCastes_LoadoutUnknown>Loadout {0} (missing)</BlaxCastes_LoadoutUnknown>
<BlaxCastes_WorkOff>off</BlaxCastes_WorkOff>
<BlaxCastes_WorkLeaveAloneShort>-</BlaxCastes_WorkLeaveAloneShort>
<BlaxCastes_WorkManagerActive>{0} is active and changes work priorities itself, so castes leave work priorities alone.</BlaxCastes_WorkManagerActive>
<!-- Starter castes -->
<BlaxCastes_StarterColonist>Colonist</BlaxCastes_StarterColonist>
<BlaxCastes_StarterSlave>Slave</BlaxCastes_StarterSlave>
<BlaxCastes_StarterPrisoner>Prisoner</BlaxCastes_StarterPrisoner>
<BlaxCastes_StarterSeededMessage>Blax Castes added the {CASTES} castes and picked them in the join defaults. Nobody moved yet: open Assign &gt; Manage castes and click "Assign by status" to put your pawns into them. Each pawn then gets its caste's policies in place of its own.</BlaxCastes_StarterSeededMessage>
<BlaxCastes_StarterSeededMessageNoColumn>Blax Castes added the {CASTES} castes and picked them in the join defaults. Nobody moved yet. The Caste column is turned off, so open the Blax Castes mod settings, click Manage castes and then "Assign by status" to put your pawns into them. Each pawn then gets its caste's policies in place of its own.</BlaxCastes_StarterSeededMessageNoColumn>
<BlaxCastes_SlaveOutfitCold>The Slave outfit has no cold protection. In a cold biome, add warm clothes to it or pick another outfit.</BlaxCastes_SlaveOutfitCold>
<!-- Overlap warnings -->
<BlaxCastes_OverlapSettingsIntro>These active mods also set policies when a pawn joins:</BlaxCastes_OverlapSettingsIntro>
<BlaxCastes_OverlapLine>{MOD}: {WHAT}</BlaxCastes_OverlapLine>
<BlaxCastes_OverlapAdvice>Castes applies a join one tick after it happens, so its caste wins. Turn those options off in the other mod so two mods don't set the same policies.</BlaxCastes_OverlapAdvice>
<BlaxCastes_OverlapMessage>Blax Castes: other active mods also set policies when a pawn joins: {MODS}. Castes applies its caste a tick later, so it wins. Turn those options off in the other mod; see the Blax Castes mod settings.</BlaxCastes_OverlapMessage>
<BlaxCastes_OverlapWhatBpc>The policies it gives pawns that join</BlaxCastes_OverlapWhatBpc>
<BlaxCastes_OverlapWhatDefaults>Default policies, medical care, schedule and work priorities for new colonists, slaves and prisoners</BlaxCastes_OverlapWhatDefaults>
<BlaxCastes_OverlapWhatSlaveOutfit>The Slave outfit on new slaves</BlaxCastes_OverlapWhatSlaveOutfit>
<BlaxCastes_OverlapWhatPrisoner>The food policy of new prisoners</BlaxCastes_OverlapWhatPrisoner>
<!-- Join rows --> <!-- Join rows -->
<BlaxCastes_NoCaste>No caste</BlaxCastes_NoCaste> <BlaxCastes_NoCaste>No caste</BlaxCastes_NoCaste>
<BlaxCastes_DefaultCaste>Default caste</BlaxCastes_DefaultCaste>
<BlaxCastes_Row_boughtSlave>Bought as slave</BlaxCastes_Row_boughtSlave> <BlaxCastes_Row_boughtSlave>Bought as slave</BlaxCastes_Row_boughtSlave>
<BlaxCastes_Row_boughtColonist>Bought as colonist</BlaxCastes_Row_boughtColonist> <BlaxCastes_Row_boughtColonist>Bought as colonist</BlaxCastes_Row_boughtColonist>
<BlaxCastes_Row_newColonist>New colonist</BlaxCastes_Row_newColonist> <BlaxCastes_Row_newColonist>New colonist</BlaxCastes_Row_newColonist>
@ -25,15 +49,27 @@
<!-- Settings --> <!-- Settings -->
<BlaxCastes_SettingEnabled>Castes set policies</BlaxCastes_SettingEnabled> <BlaxCastes_SettingEnabled>Castes set policies</BlaxCastes_SettingEnabled>
<BlaxCastes_SettingEnabledTip>Off: castes never change a pawn's apparel, food, drug or reading policy or medical care. Castes and memberships stay in the save.</BlaxCastes_SettingEnabledTip> <BlaxCastes_SettingEnabledTip>Off: castes never change a pawn's apparel, food, drug or reading policy, medical care, schedule, work priorities or weapon loadout. Castes and memberships stay in the save.</BlaxCastes_SettingEnabledTip>
<BlaxCastes_SettingWorkPriorities>Castes set work priorities</BlaxCastes_SettingWorkPriorities>
<BlaxCastes_SettingWorkPrioritiesTip>A caste sets the work priorities you list for it in the caste manager, on its colonists and slaves. Off: castes never change work priorities. Work Tab, Free Will, Work Manager, AutoPriorities and WorkRoles change priorities themselves, so while one of them is active castes leave work priorities alone.</BlaxCastes_SettingWorkPrioritiesTip>
<BlaxCastes_SettingWeaponLoadout>Castes set the weapon loadout (Weapons Tab Reborn)</BlaxCastes_SettingWeaponLoadout>
<BlaxCastes_SettingWeaponLoadoutTip>A caste can set the Weapons Tab Reborn loadout of its colonists and slaves. A caste that sets it writes it one tick after a pawn joins, so its choice wins over Weapons Tab Reborn's default loadout; a caste that leaves it alone leaves Weapons Tab Reborn in charge. Off: castes never change loadouts.</BlaxCastes_SettingWeaponLoadoutTip>
<BlaxCastes_SettingJoinDefaults>Join defaults</BlaxCastes_SettingJoinDefaults> <BlaxCastes_SettingJoinDefaults>Join defaults</BlaxCastes_SettingJoinDefaults>
<BlaxCastes_SettingJoinDefaultsTip>A pawn that joins (bought, recruited, enslaved or captured) goes into the caste its join row picks. Every row starts at No caste.</BlaxCastes_SettingJoinDefaultsTip> <BlaxCastes_SettingJoinDefaultsTip>A pawn that joins or changes status (bought, recruited, enslaved, freed, arrested, released or captured) goes into the caste its join row picks.</BlaxCastes_SettingJoinDefaultsTip>
<BlaxCastes_SettingJoinMessages>Message when a joining pawn gets a caste</BlaxCastes_SettingJoinMessages> <BlaxCastes_SettingJoinMessages>Message when a joining pawn gets a caste</BlaxCastes_SettingJoinMessages>
<BlaxCastes_SettingJoinMessagesTip>A message names the pawn and its new caste.</BlaxCastes_SettingJoinMessagesTip> <BlaxCastes_SettingJoinMessagesTip>A message names the pawn and its new caste.</BlaxCastes_SettingJoinMessagesTip>
<BlaxCastes_SettingRevertOnLeave>Reset policies when a join takes a pawn out of its caste</BlaxCastes_SettingRevertOnLeave> <BlaxCastes_SettingRevertOnLeave>Reset policies a caste set when a join moves the pawn on</BlaxCastes_SettingRevertOnLeave>
<BlaxCastes_SettingRevertOnLeaveTip>When a pawn's join row is No caste and it was in a caste, its managed policies go back to the defaults and its medical care is reset. Off: it keeps them.</BlaxCastes_SettingRevertOnLeaveTip> <BlaxCastes_SettingRevertOnLeaveTip>When a join row takes a pawn out of a caste a join row had put it in, to No caste or to a caste that leaves some policies alone, the policies it still has from the old caste go back to the defaults, and its medical care is reset if the old caste set it. A recruited prisoner then does not keep the prisoner food. Policies you changed by hand stay. Off: it keeps them all. A caste you picked by hand is never taken away by a No caste row.</BlaxCastes_SettingRevertOnLeaveTip>
<BlaxCastes_SettingShowAssignColumn>Caste column in the Assign tab (needs a restart)</BlaxCastes_SettingShowAssignColumn> <BlaxCastes_SettingReturnToPrevious>A pawn that comes back gets its old caste</BlaxCastes_SettingReturnToPrevious>
<BlaxCastes_SettingShowAssignColumnTip>Shows each pawn's caste left of the policy columns. Click a cell to assign a caste.</BlaxCastes_SettingShowAssignColumnTip> <BlaxCastes_SettingReturnToPreviousTip>When a colonist or slave leaves your faction, is sold or becomes a prisoner, Castes remembers its caste (or No caste) and its own settings. If it comes back with the same status within the days below (a released colonist, a slave you buy back), it gets that caste back instead of its join row's, and keeps what you had changed by hand on it. What the caste it had while it was away set goes back to how it was. An arrested colonist who is then enslaved goes to the new slave row.</BlaxCastes_SettingReturnToPreviousTip>
<BlaxCastes_SettingFormerCasteDays>Days to remember the old caste: {0}</BlaxCastes_SettingFormerCasteDays>
<BlaxCastes_SettingFormerCasteDaysTip>After this many days a pawn that comes back uses its join row again.</BlaxCastes_SettingFormerCasteDaysTip>
<BlaxCastes_SettingSeedStarter>Starter castes: Colonist, Slave and Prisoner</BlaxCastes_SettingSeedStarter>
<BlaxCastes_SettingSeedStarterTip>A new game starts with Colonist, Slave and Prisoner castes, already picked in the join defaults, and the starting colonists in the Colonist caste. The Colonist caste copies your default policies, so in a new game colonists see no change. A save without castes gets them once, on load, and nobody moves until you click "Assign by status" in the caste manager; that gives each pawn its caste's policies in place of its own. Without Ideology there is no Slave caste.</BlaxCastes_SettingSeedStarterTip>
<BlaxCastes_SettingWarnOverlaps>Warn about mods that also set join defaults</BlaxCastes_SettingWarnOverlaps>
<BlaxCastes_SettingWarnOverlapsTip>Names active mods that also set policies when a pawn joins, here and in one message per save.</BlaxCastes_SettingWarnOverlapsTip>
<BlaxCastes_SettingShowAssignColumn>Caste column in the Assign, Schedule and Work tabs (needs a restart)</BlaxCastes_SettingShowAssignColumn>
<BlaxCastes_SettingShowAssignColumnTip>Shows each pawn's caste left of the policy columns, the schedule and the work priorities. Click a cell to assign a caste.</BlaxCastes_SettingShowAssignColumnTip>
<BlaxCastes_SettingNoIdeology>Slaves need the Ideology DLC. Without it, castes still work for colonists and prisoners.</BlaxCastes_SettingNoIdeology> <BlaxCastes_SettingNoIdeology>Slaves need the Ideology DLC. Without it, castes still work for colonists and prisoners.</BlaxCastes_SettingNoIdeology>
<BlaxCastes_SettingsReset>Reset to defaults</BlaxCastes_SettingsReset> <BlaxCastes_SettingsReset>Reset to defaults</BlaxCastes_SettingsReset>

View File

@ -4,15 +4,15 @@
<!-- Join defaults window --> <!-- Join defaults window -->
<BlaxCastes_JoinDefaultsDesc>Pick the caste a pawn goes into when it joins your colony this way. Default caste uses the caste marked as default in the caste manager.</BlaxCastes_JoinDefaultsDesc> <BlaxCastes_JoinDefaultsDesc>Pick the caste a pawn goes into when it joins your colony this way. Default caste uses the caste marked as default in the caste manager.</BlaxCastes_JoinDefaultsDesc>
<BlaxCastes_JoinDefaultsOff>Join defaults are off in the mod settings. These picks do nothing until you turn them back on.</BlaxCastes_JoinDefaultsOff> <BlaxCastes_JoinDefaultsOff>Join defaults are off in the mod settings. These picks do nothing until you turn them back on.</BlaxCastes_JoinDefaultsOff>
<BlaxCastes_JoinDefaultsNoCastes>There are no castes yet. Make one in the Assign tab with Manage castes.</BlaxCastes_JoinDefaultsNoCastes> <BlaxCastes_JoinDefaultsNoCastes>There are no castes yet. Make one in the Assign tab with Manage castes (or in the mod settings).</BlaxCastes_JoinDefaultsNoCastes>
<BlaxCastes_DefaultCasteNamed>Default caste ({CASTE})</BlaxCastes_DefaultCasteNamed> <BlaxCastes_DefaultCasteNamed>Default caste ({CASTE})</BlaxCastes_DefaultCasteNamed>
<BlaxCastes_DefaultCasteNone>Default caste (none set)</BlaxCastes_DefaultCasteNone> <BlaxCastes_DefaultCasteNone>Default caste (none set)</BlaxCastes_DefaultCasteNone>
<BlaxCastes_RowTip_boughtSlave>A pawn you buy from a trader that joins as a slave.</BlaxCastes_RowTip_boughtSlave> <BlaxCastes_RowTip_boughtSlave>A pawn you buy from a trader that joins as a slave.</BlaxCastes_RowTip_boughtSlave>
<BlaxCastes_RowTip_boughtColonist>A pawn you buy from a trader that joins as a colonist.</BlaxCastes_RowTip_boughtColonist> <BlaxCastes_RowTip_boughtColonist>A pawn you buy from a trader that joins as a colonist.</BlaxCastes_RowTip_boughtColonist>
<BlaxCastes_RowTip_newColonist>Any other pawn that becomes a colonist: recruited prisoners, freed slaves, rescued pawns, wanderers and quest joiners.\n\nNo caste: a pawn that was in a caste leaves it, for example a recruited prisoner leaves the prisoner caste.</BlaxCastes_RowTip_newColonist> <BlaxCastes_RowTip_newColonist>Any other pawn that becomes a colonist: recruited prisoners, freed slaves, released colonists, rescued pawns, wanderers and quest joiners. A pawn that comes back within the days set in the mod settings gets its old caste (or No caste) back instead, with the changes you made by hand.\n\nNo caste: a pawn a join row had put in a caste leaves it, for example a recruited prisoner leaves the prisoner caste.</BlaxCastes_RowTip_newColonist>
<BlaxCastes_RowTip_newSlave>Any other pawn that becomes a slave: enslaved prisoners, children raised as slaves and returned runaways.\n\nNo caste: a pawn that was in a caste leaves it.</BlaxCastes_RowTip_newSlave> <BlaxCastes_RowTip_newSlave>Any other pawn that becomes a slave: enslaved prisoners, children raised as slaves and returned runaways. A slave that comes back within the days set in the mod settings gets its old caste (or No caste) back instead, with the changes you made by hand.\n\nNo caste: a pawn a join row had put in a caste leaves it.</BlaxCastes_RowTip_newSlave>
<BlaxCastes_RowTip_newPrisoner>Any pawn that becomes your prisoner: captured enemies, quest prisoners and arrested colonists. Prisoners only take the food policy and medical care of a caste.\n\nNo caste: a pawn that was in a caste leaves it.</BlaxCastes_RowTip_newPrisoner> <BlaxCastes_RowTip_newPrisoner>Any pawn that becomes your prisoner: captured enemies, quest prisoners, arrested colonists and imprisoned slaves. Prisoners only take the food policy and medical care of a caste.\n\nNo caste: a pawn a join row had put in a caste leaves it.</BlaxCastes_RowTip_newPrisoner>
<!-- Join messages --> <!-- Join messages -->
<BlaxCastes_JoinedCaste>{PAWN_labelShort} joined the {CASTE} caste.</BlaxCastes_JoinedCaste> <BlaxCastes_JoinedCaste>{PAWN_labelShort} joined the {CASTE} caste.</BlaxCastes_JoinedCaste>

View File

@ -2,26 +2,63 @@
<LanguageData> <LanguageData>
<!-- Caste manager --> <!-- Caste manager -->
<BlaxCastes_ManageCastesTip>A caste sets several policies at once. Join rows set to "Default caste" use the default caste.</BlaxCastes_ManageCastesTip> <BlaxCastes_ManageCastesTip>A caste sets several policies, the schedule and work priorities at once. Join rows set to "Default caste" use the default caste.</BlaxCastes_ManageCastesTip>
<BlaxCastes_ManagedTip>Checked: members of this caste get this setting. Unchecked: the caste leaves it alone.</BlaxCastes_ManagedTip> <BlaxCastes_ManagedTip>Checked: members of this caste get this setting. Unchecked: the caste leaves it alone.</BlaxCastes_ManagedTip>
<BlaxCastes_ManagerHint>Changing a setting here also changes it for members that still have the old value. Pawns you changed by hand keep their own.</BlaxCastes_ManagerHint> <BlaxCastes_ManagerHint>Changing a setting here also changes it for members that still have the old value. Pawns you changed by hand keep their own. Setting something the caste left alone sets it on every member.</BlaxCastes_ManagerHint>
<BlaxCastes_DeleteFailed>Could not delete {0}.</BlaxCastes_DeleteFailed> <BlaxCastes_DeleteFailed>Could not delete {0}.</BlaxCastes_DeleteFailed>
<BlaxCastes_FirstLoadMessage>Blax Castes: make castes in Assign &gt; Manage castes, then use the Defaults button to pick the caste new pawns join.</BlaxCastes_FirstLoadMessage> <BlaxCastes_FirstLoadMessage>Blax Castes: edit your castes in Assign &gt; Manage castes, and use the Defaults button to pick the caste new pawns join.</BlaxCastes_FirstLoadMessage>
<BlaxCastes_CreateSlaveOutfit>Create Slave outfit</BlaxCastes_CreateSlaveOutfit>
<BlaxCastes_CreateSlaveOutfitTip>The game has no Slave outfit (it was renamed or deleted). Creates one that allows the clothes made for slaves, and sets it as this caste's apparel.</BlaxCastes_CreateSlaveOutfitTip>
<BlaxCastes_MakeDefaultTip>Make this the default caste. Join rows set to Default caste use it.</BlaxCastes_MakeDefaultTip>
<BlaxCastes_MemberCount>Members: {0}</BlaxCastes_MemberCount>
<BlaxCastes_ApplyToAll>Apply to all members</BlaxCastes_ApplyToAll>
<BlaxCastes_ApplyToAllTip>Sets every setting this caste manages on every member, including pawns you changed by hand.</BlaxCastes_ApplyToAllTip>
<BlaxCastes_ApplyToAllConfirm>Set everything {CASTE} manages on every member ({COUNT})? Changes you made by hand on those pawns are lost.</BlaxCastes_ApplyToAllConfirm>
<BlaxCastes_AssignByStatus>Assign by status ({0})</BlaxCastes_AssignByStatus>
<BlaxCastes_AssignByStatusTip>Puts every pawn without a caste ({0}) into the caste of its status row in the join defaults: new colonist, new slave or new prisoner. Each pawn gets everything its caste manages, in place of its own policies. Pawns you set to No caste are skipped.</BlaxCastes_AssignByStatusTip>
<BlaxCastes_AssignByStatusConfirm>Put every pawn without a caste ({COUNT}) into the caste of its status row? Each pawn gets everything its caste manages, such as apparel, food, drug and reading policy, in place of what it has now, including changes you made by hand. This cannot be undone.</BlaxCastes_AssignByStatusConfirm>
<BlaxCastes_AssignByStatusDone>Pawns put into the caste of their status: {0}.</BlaxCastes_AssignByStatusDone>
<!-- Caste column in the Assign tab --> <!-- Caste manager: weapon loadout -->
<BlaxCastes_LoadoutTip>The Weapons Tab Reborn loadout members get. Members you gave another loadout by hand keep theirs.</BlaxCastes_LoadoutTip>
<BlaxCastes_LoadoutUnavailable>Weapons Tab Reborn's loadouts could not be read, so castes leave loadouts alone. The game log has the details.</BlaxCastes_LoadoutUnavailable>
<BlaxCastes_LoadoutSettingOff>Weapon loadouts are turned off in the Blax Castes mod settings.</BlaxCastes_LoadoutSettingOff>
<!-- Caste manager: schedule -->
<BlaxCastes_ScheduleTip>Pick an activity above, then click or drag over the hours. Members whose schedule matches the caste's follow each change; pawns you changed by hand keep theirs.</BlaxCastes_ScheduleTip>
<BlaxCastes_ScheduleUnmanagedTip>The caste leaves the schedule alone. Paint an hour, or copy a pawn's schedule, to set one. Painting starts from the game's default schedule, and the first hour you paint gives every member the whole day, in place of its own schedule.</BlaxCastes_ScheduleUnmanagedTip>
<BlaxCastes_ScheduleCopyFromPawn>Copy from pawn</BlaxCastes_ScheduleCopyFromPawn>
<BlaxCastes_ScheduleCopyFromPawnTip>Gives this caste the schedule of one of your colonists or slaves. Members on the caste's old schedule get it too; while the caste left the schedule alone, every member gets it, in place of its own.</BlaxCastes_ScheduleCopyFromPawnTip>
<BlaxCastes_ScheduleLeaveAloneTip>Stop setting the schedule. Every pawn keeps the schedule it has now.</BlaxCastes_ScheduleLeaveAloneTip>
<BlaxCastes_ScheduleNoPawns>No colonists or slaves with a schedule</BlaxCastes_ScheduleNoPawns>
<!-- Caste manager: work priorities -->
<BlaxCastes_WorkStartFromNothing>Start from nothing</BlaxCastes_WorkStartFromNothing>
<BlaxCastes_WorkStartFromNothingTip>When a pawn joins this caste, or you use Reset to caste or Apply to all members, every other work type is turned off first, so the pawn does only the work listed here. These stay as they are, so hurt and sick pawns still go to bed: {KEPT}. List Firefighting if members should still fight fires. It needs at least one work type set below. Ticking the box moves nobody right away.</BlaxCastes_WorkStartFromNothingTip>
<BlaxCastes_WorkTypeTip>{WORK}: {DESC}
Click to cycle: leave alone (-), 1, 2, 3, 4, off. Members whose priority matched the caste's before your first click follow each click; pawns you changed by hand keep theirs. Pawns that cannot do this work are skipped.</BlaxCastes_WorkTypeTip>
<BlaxCastes_WorkSettingOff>Work priorities are turned off in the Blax Castes mod settings.</BlaxCastes_WorkSettingOff>
<BlaxCastes_WorkManualOff>Manual priorities are off in the Work tab, so any number turns the work on. Members keep the number for when you turn manual priorities on.</BlaxCastes_WorkManualOff>
<!-- Caste column in the Assign, Schedule and Work tabs -->
<BlaxCastes_ManageCastesButton>Manage castes</BlaxCastes_ManageCastesButton> <BlaxCastes_ManageCastesButton>Manage castes</BlaxCastes_ManageCastesButton>
<BlaxCastes_ManageCastesButtonTip>Make castes and choose the policies each one sets.</BlaxCastes_ManageCastesButtonTip> <BlaxCastes_ManageCastesButtonTip>Make castes and choose the policies, schedule and work priorities each one sets.</BlaxCastes_ManageCastesButtonTip>
<BlaxCastes_JoinDefaultsButton>Defaults</BlaxCastes_JoinDefaultsButton> <BlaxCastes_JoinDefaultsButton>Defaults</BlaxCastes_JoinDefaultsButton>
<BlaxCastes_JoinDefaultsButtonTip>Choose the caste a pawn joins when it is bought, recruited, enslaved or captured.</BlaxCastes_JoinDefaultsButtonTip> <BlaxCastes_JoinDefaultsButtonTip>Choose the caste a pawn joins when it is bought, recruited, enslaved or captured.</BlaxCastes_JoinDefaultsButtonTip>
<BlaxCastes_CellNone>None</BlaxCastes_CellNone> <BlaxCastes_CellNone>None</BlaxCastes_CellNone>
<BlaxCastes_CellNoneTip>Not in a caste.</BlaxCastes_CellNoneTip> <BlaxCastes_CellNoneTip>Not in a caste.</BlaxCastes_CellNoneTip>
<BlaxCastes_CellCastelessTip>No caste, set by hand. The pawn keeps its current policies.</BlaxCastes_CellCastelessTip> <BlaxCastes_CellCastelessTip>No caste, set by hand. The pawn keeps its current policies.</BlaxCastes_CellCastelessTip>
<BlaxCastes_CellCasteDeletedTip>No caste: its caste was deleted. The pawn keeps its current policies.</BlaxCastes_CellCasteDeletedTip>
<BlaxCastes_CellPending>(pending)</BlaxCastes_CellPending> <BlaxCastes_CellPending>(pending)</BlaxCastes_CellPending>
<BlaxCastes_CellPendingTip>Just joined. Gets its caste on the next tick.</BlaxCastes_CellPendingTip> <BlaxCastes_CellPendingTip>Just joined or changed status. Its caste changes on the next tick.</BlaxCastes_CellPendingTip>
<BlaxCastes_CellLodgerTip>Cannot change the caste of temporary faction members.</BlaxCastes_CellLodgerTip> <BlaxCastes_CellLodgerTip>Cannot change the caste of temporary faction members.</BlaxCastes_CellLodgerTip>
<BlaxCastes_CellCasteTip>Caste: {0}</BlaxCastes_CellCasteTip> <BlaxCastes_CellCasteTip>Caste: {0}</BlaxCastes_CellCasteTip>
<BlaxCastes_CellOverrides>Different from the caste (changed by hand or by the game):</BlaxCastes_CellOverrides> <BlaxCastes_CellOverrides>Different from the caste (changed by hand or by the game):</BlaxCastes_CellOverrides>
<BlaxCastes_CellOverrideLine>{0}: {1} (caste: {2})</BlaxCastes_CellOverrideLine> <BlaxCastes_CellOverrideLine>{0}: {1} (caste: {2})</BlaxCastes_CellOverrideLine>
<BlaxCastes_CellOverrideSchedule>{0}: some hours differ</BlaxCastes_CellOverrideSchedule>
<BlaxCastes_CellOverrideWork>{0}: {1}</BlaxCastes_CellOverrideWork>
<BlaxCastes_CellOverrideWorkType>{0} {1} (caste: {2})</BlaxCastes_CellOverrideWorkType>
<BlaxCastes_CellHint>Click to pick a caste. Drag down the column to give several pawns the same caste.</BlaxCastes_CellHint> <BlaxCastes_CellHint>Click to pick a caste. Drag down the column to give several pawns the same caste.</BlaxCastes_CellHint>
<BlaxCastes_MenuReset>Reset to caste</BlaxCastes_MenuReset> <BlaxCastes_MenuReset>Reset to caste</BlaxCastes_MenuReset>
<BlaxCastes_MenuEdit>Edit caste</BlaxCastes_MenuEdit> <BlaxCastes_MenuEdit>Edit caste</BlaxCastes_MenuEdit>

View File

@ -3,7 +3,7 @@
<!-- The Caste column goes right before the hostility column, left of medical care and the policy columns. <!-- The Caste column goes right before the hostility column, left of medical care and the policy columns.
If another mod removed the hostility column, it goes right after the name column instead. The column is If another mod removed the hostility column, it goes right after the name column instead. The column is
taken out again at startup when the "Caste column in the Assign tab" setting is off (AssignColumn.cs). --> taken out again at startup when the Caste column setting is off (CasteColumns.cs). -->
<Operation Class="PatchOperationConditional"> <Operation Class="PatchOperationConditional">
<xpath>Defs/PawnTableDef[defName="Assign"]/columns/li[text()="HostilityResponse"]</xpath> <xpath>Defs/PawnTableDef[defName="Assign"]/columns/li[text()="HostilityResponse"]</xpath>
<match Class="PatchOperationInsert"> <match Class="PatchOperationInsert">

View File

@ -0,0 +1,63 @@
<?xml version="1.0" encoding="utf-8"?>
<Patch>
<!-- The Caste column in the Schedule tab goes right after the timetable. The tab draws its time assignment
selector over the top of the header left of the timetable, where the column's buttons would sit, so
the column stays clear of it. Without the timetable it goes right before the allowed area column, and
without both right after the name column. -->
<Operation Class="PatchOperationConditional">
<xpath>Defs/PawnTableDef[defName="Restrict"]/columns/li[text()="Timetable"]</xpath>
<match Class="PatchOperationInsert">
<xpath>Defs/PawnTableDef[defName="Restrict"]/columns/li[text()="Timetable"]</xpath>
<order>Append</order>
<value>
<li>BlaxCastes_Caste</li>
</value>
</match>
<nomatch Class="PatchOperationConditional">
<xpath>Defs/PawnTableDef[defName="Restrict"]/columns/li[text()="AllowedArea"]</xpath>
<match Class="PatchOperationInsert">
<xpath>Defs/PawnTableDef[defName="Restrict"]/columns/li[text()="AllowedArea"]</xpath>
<order>Prepend</order>
<value>
<li>BlaxCastes_Caste</li>
</value>
</match>
<nomatch Class="PatchOperationConditional">
<xpath>Defs/PawnTableDef[defName="Restrict"]/columns/li[text()="LabelShortWithIcon"]</xpath>
<match Class="PatchOperationInsert">
<xpath>Defs/PawnTableDef[defName="Restrict"]/columns/li[text()="LabelShortWithIcon"]</xpath>
<order>Append</order>
<value>
<li>BlaxCastes_Caste</li>
</value>
</match>
</nomatch>
</nomatch>
</Operation>
<!-- In the Work tab it goes right before the copy and paste column. The game adds the work columns after
that column when it builds the table, so the Caste column ends up just left of them. Without the copy
and paste column it goes right after the name column. -->
<Operation Class="PatchOperationConditional">
<xpath>Defs/PawnTableDef[defName="Work"]/columns/li[text()="CopyPasteWorkPriorities"]</xpath>
<match Class="PatchOperationInsert">
<xpath>Defs/PawnTableDef[defName="Work"]/columns/li[text()="CopyPasteWorkPriorities"]</xpath>
<order>Prepend</order>
<value>
<li>BlaxCastes_Caste</li>
</value>
</match>
<nomatch Class="PatchOperationConditional">
<xpath>Defs/PawnTableDef[defName="Work"]/columns/li[text()="LabelWithIcon"]</xpath>
<match Class="PatchOperationInsert">
<xpath>Defs/PawnTableDef[defName="Work"]/columns/li[text()="LabelWithIcon"]</xpath>
<order>Append</order>
<value>
<li>BlaxCastes_Caste</li>
</value>
</match>
</nomatch>
</Operation>
</Patch>

View File

@ -1,39 +1,54 @@
![Blax Castes](About/Preview.png)
# Blax Castes # Blax Castes
RimWorld mod (1.7) by Blax Gaming: policy bundles and join defaults. 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. Needs Harmony. Works without DLCs; slaves need Ideology. [![RimWorld 1.7](https://img.shields.io/badge/RimWorld-1.7-19C63C)](https://rimworldgame.com)
[![Needs Harmony](https://img.shields.io/badge/needs-Harmony-050805)](https://steamcommunity.com/sharedfiles/filedetails/?id=2009463077)
[![No DLC needed](https://img.shields.io/badge/DLC-not_needed-5a6b5d)](#features-10)
[![Status: 1.0 in progress](https://img.shields.io/badge/status-1.0_in_progress-CDCDCD)](docs/design.md)
RimWorld mod (1.7) by Blax Gaming: policy bundles and join defaults. Every slave you buy needs its apparel, food, drug and reading policy, its schedule and its work priorities set by hand. Blax Castes bundles those settings into castes such as Slave or Miner slave, and puts each pawn into the right caste the moment it joins or changes status. Needs Harmony. Works without DLCs; slaves need Ideology.
Design and roadmap: `docs/design.md`. Design and roadmap: `docs/design.md`.
## Features (1.0) ## Features (1.0)
- **Castes.** A caste manages up to five slots: apparel, food, drug and reading policy, and medical care. Each slot is either a vanilla policy (or a medical care level) or left alone. Putting a pawn in a caste writes every managed slot through the vanilla setters. `Source/BlaxCastes/Caste.cs`, `CasteUtility.cs` - 📦 **Castes.** A caste manages up to eight slots: apparel, food, drug and reading policy, medical care, schedule, work priorities and, with [1001] Weapons Tab Reborn, the weapon loadout. Each slot is set or left alone. Putting a pawn in a caste writes every managed slot through the vanilla setters (and Weapons Tab Reborn's own API for the loadout). `Source/BlaxCastes/Caste.cs`, `CasteUtility.cs`
- **Per-slot checks.** Apparel, drugs and reading need the pawn's tracker and skip quest lodgers, prisoners and mutants without policies. Food needs a configurable food tracker and skips babies. Medical care needs player settings and a flesh pawn. So a prisoner in a caste gets its food policy and medical care only. - ✅ **Per-slot checks.** Apparel, drugs, reading and the schedule need the pawn's tracker and skip quest lodgers, prisoners and mutants without policies; apparel also skips mutants that wear no apparel, and the schedule skips the mutants the Schedule tab leaves out. Food needs a configurable food tracker and skips babies and mutants without policies. Medical care needs player settings and a flesh pawn. Work priorities and the loadout are for colonists and slaves only. So a prisoner in a caste gets its food policy and medical care only.
- **Members follow their caste.** Change a caste's slot and every member still on the old value gets the new one. Members you changed by hand keep theirs. A slot that was left alone and becomes managed reaches every member; a slot that stops being managed changes nobody. Edits inside a policy (the Slave outfit's filter) reach members through the vanilla reference. `Source/BlaxCastes/CasteManager.cs` - 🕒 **Schedule.** A caste can carry a full day: 24 hours of anything, work, recreation, sleep or meditate. The manager paints it like the vanilla Schedule tab: pick the activity with the vanilla selector, then click or drag over the hours. "Copy from pawn" takes the schedule of one of your colonists or slaves, and "Leave alone" stops managing it. While the caste leaves the schedule alone, the first painted hour (or a copy) gives every member the whole day; the tooltips say so. A pawn whose whole day matches the caste follows every change; one hour changed by hand and the pawn keeps its own. An hour whose activity no longer exists (Meditate without Royalty, a removed mod) becomes Anything. `Source/BlaxCastes/ScheduleSlot.cs`
- **Caste manager.** Assign tab > "Manage castes" above the Caste column. It is the vanilla policy manager: the caste list with new, duplicate, rename, delete and make default on the left, and one row per slot on the right with a "managed" checkbox, a dropdown and a pencil that opens the vanilla editor for that policy. Ticking a slot starts it at the game's default policy (or the colonist default medical care). Deleting a caste leaves its members casteless on their current policies, and join rows that pointed at it fall back to No caste. `Source/BlaxCastes/Dialog_ManageCastes.cs` - 🛠️ **Work priorities.** A caste sets only the work types you pick, each to 1, 2, 3, 4 or off; the rest stay as they are. So every caste can set Firefighting to 1, and a Field slave caste Growing 1 and Plant cutting 2. Work types a pawn cannot do are skipped. With manual priorities off, any number means on; Castes still stores the caste's number, so turning manual priorities on later leaves every member following its caste. "Start from nothing" turns every other work type off first, for castes that should do only their listed work; Patient and Bed rest stay as they are, because they are how a hurt or sick colonist or slave goes to bed. The Follow rule works per work type. The slot turns itself off while Work Tab, Free Will, Work Manager, AutoPriorities or WorkRoles is active, because those set priorities all the time. `Source/BlaxCastes/WorkSlot.cs`
- **Caste column.** A Caste column in the Assign tab, left of hostility, medical care and the policy columns. Click a cell for the menu (No caste, every caste, Reset to caste, Edit caste), or drag down the column to give several pawns the same caste. The cell shows the caste, the caste with "*" when one of the pawn's managed policies differs (the tooltip names each slot with both values), "No caste" when you took the pawn out by hand, "None" when it never had one, "(pending)" while a join waits for the next tick, and "Unchangeable" for quest lodgers. The column sorts by caste, pawns without one last. `Source/BlaxCastes/PawnColumnWorker_BlaxCaste.cs`, `Patches/BlaxCastes_Assign.xml` - 🗡️ **Weapon loadout.** With [1001] Weapons Tab Reborn active, a caste can set the pawn's weapon loadout: a Guard caste the rifle loadout, a Slave caste the unarmed one. Without the mod the row is hidden. Castes calls the API Weapons Tab Reborn publishes for Better Pawn Control, found by reflection; if that API is missing or fails, the slot turns itself off with one warning in the log. A loadout deleted in Weapons Tab Reborn becomes unmanaged in the caste, with one warning. `Source/BlaxCastes/WeaponsTab.cs`
- **Join defaults.** Assign tab > "Defaults" above the Caste column. Five rows pick a caste for bought as slave, bought as colonist, new colonist, new slave and new prisoner: No caste, Default caste (the one marked default in the manager) or a specific caste. Every row starts at No caste, so nothing changes until you pick one. Without Ideology the two slave rows are hidden. `Source/BlaxCastes/JoinDefaults.cs`, `Dialog_JoinDefaults.cs` - 🔗 **Members follow their caste.** Change a caste's slot and every member still on the old value gets the new one. Members you changed by hand keep theirs. A slot that was left alone and becomes managed reaches every member; a slot that stops being managed changes nobody. Edits inside a policy (the Slave outfit's filter) reach members through the vanilla reference. `Source/BlaxCastes/CasteManager.cs`
- Buying a pawn from a trader uses the bought rows; the pawn's final status picks slave or colonist. Everything else goes by final status: recruiting and freeing to new colonist, enslaving and returned runaways to new slave, capturing, quest prisoners and arrests to new prisoner. - 🌱 **Starter castes.** A new game starts with three castes, already picked in the join defaults: Colonist (your current default apparel, food, drug and reading policy, medical care left alone), Slave (the Slave outfit, Simple food, No drugs; reading and medical care left alone) and Prisoner (Simple food). Bought and new colonists use Default caste, which is Colonist; bought and new slaves use Slave; new prisoners use Prisoner. The starting colonists go into Colonist, so their policies do not change. Policies are found by their starting names (No drugs by its source def); one that was renamed or deleted leaves its slot alone. Without Ideology there is no Slave caste and the slave rows stay at No caste. A save without castes gets the starter castes once, on load, with one message (it points to the mod settings while the Caste column is off); nobody moves until you click "Assign by status", which gives each pawn its caste's policies in place of its own. `Source/BlaxCastes/StarterCastes.cs`
- Castes applies a join one tick after it happens, after the game's own status-change resets, so its choice wins over mods that set policies in the same call. A bought slave arrives wearing its caste's outfit and eating its food, and a message names the caste. - 🗂️ **Caste manager.** Assign tab > "Manage castes" above the Caste column. It is the vanilla policy manager: the caste list with new, duplicate, rename, delete and make default on the left, and on the right a scrolling list of the slots: one row per policy with a "managed" checkbox, a dropdown and a pencil that opens the vanilla editor for that policy, the weapon loadout row while Weapons Tab Reborn is active, the schedule grid and a cycle button per work type (leave alone, 1, 2, 3, 4, off) with "Start from nothing". Clicking a cycle button several times in a row moves only the members that followed the work type before the first click, so a pawn you set by hand to a value the cycle passes through keeps it. Ticking a slot starts it at the game's default policy (or the colonist default medical care, or Weapons Tab Reborn's default loadout). The work priorities are greyed out, with a note, while the setting is off or an automatic work manager is active. Below the slots: the member count and "Apply to all members", which asks first, naming the count, and then sets every managed slot on every member, hand changes included. Next to the close button, "Assign by status (N)" shows while pawns without a caste exist: it asks first, because it replaces those pawns' own policies with their caste's, then puts each into the caste of its new colonist, new slave or new prisoner row, and skips pawns you set to No caste. "Make default" explains the default caste in its tooltip. When the game has no Slave outfit, a "Create Slave outfit" button makes one. A caste using the Slave outfit warns that it has no cold protection. Deleting a caste leaves its members casteless on their current policies, and join rows that pointed at it fall back to No caste. `Source/BlaxCastes/Dialog_ManageCastes.cs`
- 📋 **Caste column.** A Caste column in the Assign tab, left of hostility, medical care and the policy columns; the same column sits right of the timetable in the Schedule tab (clear of the tab's activity selector) and left of the work columns in the Work tab. In the Work tab only "Manage castes" sits above it, so the header keeps the work columns' height. Click a cell for the menu (No caste, every caste, Reset to caste, Edit caste), or drag down the column to give several pawns the same caste; pawns already in that caste keep their hand changes while you drag. The cell shows the caste, the caste with "*" when one of the pawn's managed slots differs (the tooltip names each slot with both values; for the schedule it says "Schedule", for work priorities it names each work type that differs), "No caste" when you took the pawn out by hand or its caste was deleted, "None" when it is not in a caste, "(pending)" while a join will change its caste on the next tick, and "Unchangeable" for quest lodgers. The first click on the header sorts by caste, pawns without one last; the second click reverses it. `Source/BlaxCastes/PawnColumnWorker_BlaxCaste.cs`, `CasteColumns.cs`, `Patches/BlaxCastes_Assign.xml`, `Patches/BlaxCastes_ScheduleWork.xml`
- 🚪 **Join defaults and status changes.** Assign tab > "Defaults" above the Caste column. Five rows pick a caste for bought as slave, bought as colonist, new colonist, new slave and new prisoner: No caste, Default caste (the one marked default in the manager) or a specific caste. Without Ideology the two slave rows are hidden. `Source/BlaxCastes/JoinDefaults.cs`, `Dialog_JoinDefaults.cs`
- Buying a pawn from a trader uses the bought rows; the pawn's final status picks slave or colonist. Every other change between colonist, slave and prisoner goes by the final status: recruiting, freeing a slave and releasing an arrested colonist to new colonist; enslaving and returned runaways to new slave; capturing, quest prisoners, arresting a colonist and imprisoning a slave to new prisoner.
- Castes applies a join one tick after it happens, after the game's own status-change resets, so its choice wins over mods that set policies in the same call. A bought slave arrives with its caste's outfit and food policy already set, and a message names the caste.
- A caste you pick by hand before the join is applied wins over the row. A pawn sold or released before then is dropped. - A caste you pick by hand before the join is applied wins over the row. A pawn sold or released before then is dropped.
- A No caste row takes a pawn out of the caste it was in. With "Reset policies" on, the caste's managed policies go back to the game defaults and medical care is reset, so a recruited prisoner does not keep the prisoner food. This also applies to an arrested colonist while the new prisoner row is No caste. - A No caste row takes a pawn out of a caste a join row had put it in; a caste you picked by hand stays. With "Reset policies" on, the policies it still has from that caste go back to the game defaults (medical care to the game's default for its status, if the caste set it); policies you changed by hand stay. The same happens when a row moves a pawn on from a row-set caste to a caste that leaves some of those policies alone, so a recruited prisoner does not keep the prisoner food. The schedule, work priorities and loadout have no game default and stay as they are.
- Babies, quest lodgers and mutants without policies are skipped. - Babies, quest lodgers and mutants without policies are skipped.
- **Leaving.** A pawn that leaves your faction (sold, released, gone to another faction) leaves its caste on the next tick, and a check every 2500 ticks catches the rest. Its policies stay as they are. - ↩️ **The old caste comes back.** When a colonist or slave leaves your faction, is sold or becomes a prisoner, Castes remembers its caste (or No caste, if you set that) and its own settings from just before the change. If it comes back within 60 days (a setting) with the same status, it gets that caste back instead of its row's: an arrested Miner who is released is a Miner again, a Miner slave you sell and buy back is a Miner slave again, and a pawn you set to No caste is back at No caste. It keeps what you had changed by hand: settings that followed the caste get the caste's current value, settings you had changed get your value back. What the caste it had while it was away set (the prisoner caste's food) goes back to how it was. An arrested colonist who is then enslaved goes to the new slave row. Records are saved with the game, keyed by the pawn's ID, and dropped when they are older than the setting or their caste is deleted.
- **First load.** A new game, or the first load of a save with Castes, posts one message that points to Assign > Manage castes. - 👋 **Leaving.** A pawn that leaves your faction (sold, released, gone to another faction) leaves its caste on the next tick, and a check every 2500 ticks catches the rest. Its policies stay as they are.
- **Settings.** `enabled` (off: castes never write a policy; castes and memberships stay in the save), `enableJoinDefaults`, `joinMessages`, `revertOnLeave` ("Reset policies when a join takes a pawn out of its caste"), `showAssignColumn` (needs a restart). All on by default. While a game is loaded, the settings page also has "Manage castes" and "Join defaults" buttons, the way in while the column is off. `Source/BlaxCastes/BlaxCastesMod.cs` - ⚠️ **Overlap warnings.** If Better Pawn Control, Better Pawn Control Forked, 1trickPwnyta's Defaults, Automatic Slave Outfit or PrisonerDefaults is active, the settings page names it and what it sets, and one message per save suggests turning those options off. Castes still wins, because it applies a tick later. Detection only; Castes patches none of them. `Source/BlaxCastes/OverlapWarnings.cs`, `Compat.cs`
- 💬 **First load.** A new game, or the first load of a save that already has castes, posts one message that points to Assign > Manage castes.
- ⚙️ **Settings.** `enabled` (off: castes never write a policy, schedule, work priority or loadout; castes and memberships stay in the save), `manageWorkPriorities`, `manageWeaponLoadout` (shown while Weapons Tab Reborn is active), `enableJoinDefaults`, `joinMessages`, `revertOnLeave` ("Reset policies a caste set when a join moves the pawn on"; only governs that revert), `returnToPreviousCaste` and `formerCasteDays` (60), `seedStarterCastes`, `warnOverlaps`, `showAssignColumn` (the Caste column in the Assign, Schedule and Work tabs; needs a restart). All toggles are on by default. While a game is loaded, the settings page also has "Manage castes" and "Join defaults" buttons, the way in while the column is off. `Source/BlaxCastes/BlaxCastesMod.cs`
Save safety: all state lives in one game component (`GameComponent_BlaxCastes`), nothing is stored on vanilla objects, and the only vanilla data Castes writes is each pawn's own policy fields. Memberships drop pawns that are discarded or destroyed without being dead, on every save and after loading. A policy that left its database (a mod deleting it without `TryDelete`, or a delete in a vanilla editor opened from the manager) becomes unmanaged with one warning per caste. Joins waiting for the next tick are saved with the game. Adding the mod to a running save works; removing it leaves every pawn on its last policies and one "type not found" line for the component. 💾 Save safety: all state lives in one game component (`GameComponent_BlaxCastes`), nothing is stored on vanilla objects, and the only vanilla data Castes writes is each pawn's own policies, medical care, timetable and work priorities (and its Weapons Tab Reborn loadout, through that mod's API). Schedules and work priorities are saved as def names and loadouts as ids, never as references. Memberships drop pawns that are discarded or destroyed without being dead, on every save and after loading. A policy that left its database (a mod deleting it without `TryDelete`, or a delete in a vanilla editor opened from the manager) or a loadout Weapons Tab Reborn no longer has becomes unmanaged with one warning per caste; a schedule hour whose activity is gone becomes Anything, and a work type that is gone is dropped, each with one warning. Without Weapons Tab Reborn a caste keeps its loadout id for when the mod comes back. Joins waiting for the next tick are saved with the game. Former-caste records are keyed by the pawn's ID, not by reference. Adding the mod to a running save works. Removing it leaves every pawn on its last policies; the next load logs two red errors for the missing component ("Could not find class BlaxCastes.GameComponent_BlaxCastes" and "Can't load abstract class Verse.GameComponent"). They do no harm and go away once the game is saved again.
Replaces: Automatic Slave Outfit and PrisonerDefaults, the join defaults of Better Pawn Control, Better Pawn Control Forked and 1trickPwnyta's Defaults, and partly Save My Settings (clothing and food presets per pawn). Replaces: Automatic Slave Outfit and PrisonerDefaults, the join, schedule and work defaults of Better Pawn Control, Better Pawn Control Forked and 1trickPwnyta's Defaults, the joiner work priorities of Plug and Play Joiner, and partly Save My Settings (clothing and food presets per pawn).
Compat: Compat:
- Blax Slaves: its buy-as-slave-or-colonist button lands in the right bought row, and returned runaways land in the new slave row. Castes calls nothing in Blax Slaves. - Blax Slaves: its buy-as-slave-or-colonist button lands in the right bought row, and returned runaways land in the new slave row (or their old caste). Castes calls nothing in Blax Slaves.
- Trade as Slave or Colonist: same as Blax Slaves' buy mode. - Trade as Slave or Colonist: same as Blax Slaves' buy mode. Blax Slaves' buy mode stands down while it is active.
- Better Pawn Control, its fork and 1trickPwnyta's Defaults have join defaults of their own. Castes applies a tick after the join, so its row wins. Turn theirs off so two mods don't write the same policies. - Better Pawn Control, its fork, 1trickPwnyta's Defaults, Automatic Slave Outfit and PrisonerDefaults set policies of their own when a pawn joins. Castes applies a tick after the join, so its row wins, and it warns while one of them is active. Turn theirs off so two mods don't write the same policies.
- Tested next to Hospitality, Custom Prisoner Interactions and Prisoner Realism. - [1001] Weapons Tab Reborn: the weapon loadout slot. It has no 1.7 build; 1.7 loads its 1.6 assembly, and its loadout API works there. A caste that sets the loadout writes it a tick after a join, so it wins over Weapons Tab Reborn's default loadout; a caste that leaves it alone leaves Weapons Tab Reborn in charge.
- Numbers builds its own tables, so the Caste column shows only in the vanilla Assign tab. - Work Tab, Free Will, Work Manager, AutoPriorities and WorkRoles set work priorities themselves, so while one of them is active the work priorities slot is off and greyed out in the manager.
- Tested next to Hospitality, Custom Prisoner Interactions, Prisoner Realism and Weapons Tab Reborn.
- Numbers builds its own tables, so the Caste column shows only in the vanilla Assign, Schedule and Work tabs.
Not supported yet: multiplayer, animal castes. Ready-made castes, a caste button on selected pawns and overlap warnings come in 1.1. Not supported yet: multiplayer, animal castes. A caste button on selected pawns comes in 1.1.
## Development ## Development
@ -65,20 +80,37 @@ Workshop art (`About/Preview.png`, `About/ModIcon.png`) is rendered from `Source
### Tests ### Tests
`Tests/BlaxCastesTests` is a separate test mod. `Tests/run-tests.ps1` builds both projects, links the test mod into the game's Mods folder for the run, and starts RimWorld headless (`-headless -quicktest -blaxcastestests`, no window) with its own save data folder in `%TEMP%\BlaxCastesTest`, so your mod list, saves and settings stay untouched. The suite runs in a quick-test colony, saves and reloads the game, runs the persistence tests, writes `BlaxCastesTestResults.txt` and quits. It takes under a minute and needs Steam running. `Tests/BlaxCastesTests` is a separate test mod. `Tests/run-tests.ps1` builds both projects, links the test mod into the game's Mods folder for the run, and starts RimWorld headless (`-headless -quicktest -blaxcastestests`, no window) with its own save data folder in `%TEMP%\BlaxCastesTest`, so your mod list, saves and settings stay untouched. Every run starts from default mod settings. The suite runs in a quick-test colony, saves and reloads the game, runs the persistence tests, writes `BlaxCastesTestResults.txt` and quits. It takes under a minute and needs Steam running.
```powershell ```powershell
.\Tests\run-tests.ps1 # refuses while RimWorld is open .\Tests\run-tests.ps1 # refuses while RimWorld is open
.\Tests\run-tests.ps1 -AllowWhileRunning # runs next to an open game, at below-normal priority .\Tests\run-tests.ps1 -AllowWhileRunning # runs next to an open game, at below-normal priority
.\Tests\run-tests.ps1 -AllowWhileRunning -Compat -NoBuild .\Tests\run-tests.ps1 -AllowWhileRunning -Compat -NoBuild
.\Tests\run-tests.ps1 -AllowWhileRunning -Compat -Tasoc -NoBuild
.\Tests\run-tests.ps1 -AllowWhileRunning -NoDlc -NoBuild
``` ```
If PowerShell blocks scripts, run it as `powershell -ExecutionPolicy Bypass -File .\Tests\run-tests.ps1 -AllowWhileRunning`. If PowerShell blocks scripts, run it as `powershell -ExecutionPolicy Bypass -File .\Tests\run-tests.ps1 -AllowWhileRunning`.
`-Compat` also loads Blax Slaves and the installed mods Castes overlaps with (Hospitality, Trade as Slave or Colonist, Custom Prisoner Interactions, Prisoner Realism), in the load order Castes, then Slaves. `-NoBuild` skips the build. Only one run at a time: a lock file in the data folder holds the running script's process id, and a lock left by a dead process is taken over. `Mods\BlaxCastes` must be a junction to this repo; the script creates it if missing and stops if a real folder is in the way. Exit code 0 means all passed, 1 failures, 2 the run didn't finish (see `game.log` and `game.err.log` in the data folder). - `-Compat` also loads Blax Slaves and the installed mods Castes is tested next to (Hospitality, Custom Prisoner Interactions, Prisoner Realism, Weapons Tab Reborn), in the load order Castes, then Slaves. Trade as Slave or Colonist stays out, so the buy-mode test drives Blax Slaves' own buy mode. The loadout tests run only here; without Weapons Tab Reborn they skip, and one test checks the slot stays off.
- `-Tasoc` adds Trade as Slave or Colonist; Blax Slaves' buy mode stands down for it, and the buy-mode test drives that mod instead.
- `-NoDlc` runs on the core game alone; `-Dlc Royalty,Biotech` loads only the named installed DLCs. Every installed DLC is still listed as known, so the game does not switch a left-out one on.
- `-NoBuild` skips the build.
Tests are `public static void` methods marked `[BlaxTest("area: what", phase: 1)]`, using `T` for assertions and `Fixtures` for colonists, prisoners, slaves, quest lodgers, babies, castes, policies and ticks. Phase 2 runs after the save and reload; carry ids through `T.Carry`, or `T.CarryAtSave` for values later phase-1 tests may still change. Without Ideology the slave tests skip; without Biotech the baby tests skip. The buy-mode compat test needs `-Compat`. Headless runs have no GUI, so the tests drive the logic behind the windows and the column; drawing is checked by hand. The mods whose join defaults overlap with Castes (Better Pawn Control, its fork, 1trickPwnyta's Defaults, Automatic Slave Outfit, PrisonerDefaults) and the automatic work managers are not installed on the test machine. Their package ids were read from each mod's About.xml in its public source repository (listed in `Source/BlaxCastes/Compat.cs`), and the overlap and work manager tests inject an id into the detection list.
A test fails when Blax Castes logs an error, or when an error's stack passes through the mod or the test code. Errors another mod logs from its own code while a test ticks the game are listed as `LOGERR` lines instead; the harness keeps a short list of them (`KnownForeignErrors` in `Harness.cs`). Today that is Weapons Tab Reborn's "tried to equip loadout" error, which it logs once for the first pawn of another faction that thinks.
Only one run at a time: a lock file in the data folder holds the running script's process id, and a lock left by a dead process is taken over. `Mods\BlaxCastes` must be a junction to this repo; the script creates it if missing and stops if a real folder is in the way. Exit code 0 means all passed, 1 failures, 2 the run didn't finish (see `game.log` and `game.err.log` in the data folder).
Tests are `public static void` methods marked `[BlaxTest("area: what", phase: 1)]`, using `T` for assertions and `Fixtures` for colonists, prisoners, slaves, quest lodgers, babies, castes, policies, ticks and queued joins. Phase 2 runs after the save and reload; carry ids through `T.Carry`, or `T.CarryAtSave` for values later phase-1 tests may still change. Without Ideology the slave tests skip; without Biotech the baby tests skip. The buy-mode compat test needs `-Compat` or `-Tasoc`, the loadout tests `-Compat`. Headless runs have no GUI, so the tests drive the logic behind the windows and the column; drawing is checked by hand.
Useful 1.7 switches for manual runs: `-quicktest` (straight into a generated colony), `-headless`, `-savedatafolder=<dir>`, `-QuitAfterBoot`, `-NoFileLog`. Useful 1.7 switches for manual runs: `-quicktest` (straight into a generated colony), `-headless`, `-savedatafolder=<dir>`, `-QuitAfterBoot`, `-NoFileLog`.
A decompiled copy of the 1.7 game code for reference lives outside the repo in `..\rimworld-src-1.7` (never commit or publish it). ---
## Made by Blax
[![Blax Software Open Source Initiative](docs/art/blax-oss-banner.svg)](https://www.blax.at)
🛠️ **Blax Gaming** is a project of **[Blax Software](https://www.blax.at)**, an Austrian software practice. We write Austrian-quality code in many fields: web platforms, mobile apps, backends, infrastructure, and the mods we play in our own colonies. Need something built? 👉 [www.blax.at](https://www.blax.at)

View File

@ -1,6 +1,6 @@
# Preview art # Preview art
`preview.html` renders `About/Preview.png` (1280x720) and `icon.html` renders `About/ModIcon.png` (256x256) from `icon.svg`. Both follow the Blax CI from https://www.blax.at/ui-ci and match Blax Slaves' art, so the mods read as one label: Blax black `#050805`, Blax green `#19C63C`, logo gray `#CDCDCD`, Geist for the title and subtitle. `geist.woff2` is the file blax.at self-hosts (SIL Open Font License); icons are lucide (ISC license). `preview.html` renders `About/Preview.png` (1280x720) and `icon.html` renders `About/ModIcon.png` (256x256) from `icon.svg`. Both follow the Blax CI from https://www.blax.at/ui-ci and match Blax Slaves' art, so the mods read as one label: Blax black `#050805`, Blax green `#19C63C`, logo gray `#CDCDCD`, Geist for the title and subtitle, Rajdhani for the "Blax Gaming" wordmark. `geist.woff2` and `rajdhani-700.woff2` are the files blax.at self-hosts (SIL Open Font License); icons are lucide (ISC license).
The preview's right column shows three join rows (new colonist, bought slave, new prisoner), each pointing at the policy bundle its caste sets: apparel, food, drugs, reading and medical care. Green slots are managed, gray ones are left alone. The icon is the Blax monogram with a green "layers" badge, so it stands apart from Blax Slaves' plain monogram in the mod list. The preview's right column shows three join rows (new colonist, bought slave, new prisoner), each pointing at the policy bundle its caste sets: apparel, food, drugs, reading and medical care. Green slots are managed, gray ones are left alone. The icon is the Blax monogram with a green "layers" badge, so it stands apart from Blax Slaves' plain monogram in the mod list.

Binary file not shown.

View File

@ -4,6 +4,7 @@
<meta charset="utf-8"> <meta charset="utf-8">
<style> <style>
@font-face { font-family: Geist; src: url(fonts/geist.woff2) format("woff2"); font-weight: 100 900; } @font-face { font-family: Geist; src: url(fonts/geist.woff2) format("woff2"); font-weight: 100 900; }
@font-face { font-family: Rajdhani; src: url(fonts/rajdhani-700.woff2) format("woff2"); font-weight: 700; }
:root { :root {
--background: #050805; /* Blax black */ --background: #050805; /* Blax black */
--accent: #19C63C; /* Blax green */ --accent: #19C63C; /* Blax green */
@ -16,8 +17,10 @@
html, body { width: 1280px; height: 720px; background: var(--background); overflow: hidden; } html, body { width: 1280px; height: 720px; background: var(--background); overflow: hidden; }
body { font-family: Geist, sans-serif; color: var(--heading); position: relative; } body { font-family: Geist, sans-serif; color: var(--heading); position: relative; }
.top { position: absolute; left: 72px; top: 52px; } .top { position: absolute; left: 72px; top: 52px; display: flex; align-items: center; gap: 16px; }
.top img { display: block; width: 56px; height: 56px; } .top img { display: block; width: 56px; height: 56px; }
.wordmark { font-family: Rajdhani, sans-serif; font-weight: 700; font-size: 40px; line-height: 1; letter-spacing: -0.01em; color: var(--heading); }
.wordmark span { color: var(--accent); }
.hero { position: absolute; left: 72px; top: 158px; width: 640px; } .hero { position: absolute; left: 72px; top: 158px; width: 640px; }
h1 { font-weight: 600; font-size: 178px; line-height: .9; letter-spacing: -0.045em; color: var(--heading); } h1 { font-weight: 600; font-size: 178px; line-height: .9; letter-spacing: -0.045em; color: var(--heading); }
@ -47,7 +50,7 @@
</defs> </defs>
</svg> </svg>
<div class="top"><img src="blax-monogram.svg" alt=""></div> <div class="top"><img src="blax-monogram.svg" alt=""><div class="wordmark">Blax <span>Gaming</span></div></div>
<div class="hero"> <div class="hero">
<h1>Blax<br>Castes</h1> <h1>Blax<br>Castes</h1>

View File

@ -1,60 +0,0 @@
using System;
using RimWorld;
using Verse;
namespace BlaxCastes
{
/// <summary>
/// The Caste column in the Assign table. Patches/BlaxCastes_Assign.xml puts it right before
/// HostilityResponse; at startup this removes it again when the showAssignColumn setting is off,
/// so turning the setting on or off takes effect after a restart.
/// </summary>
[StaticConstructorOnStartup]
public static class AssignColumn
{
public const string AnchorColumn = "HostilityResponse";
static AssignColumn()
{
try
{
bool show = BlaxCastesMod.Settings == null || BlaxCastesMod.Settings.showAssignColumn;
PawnTableDef table = Table;
bool missing = show && table?.columns != null && Column != null && !table.columns.Contains(Column);
Apply(show);
if (missing)
Log.Warning("[Blax Castes] The XML patch did not place the Caste column in the Assign table; it was added in code instead.");
}
catch (Exception e)
{
Log.Error("[Blax Castes] Setting up the Caste column failed: " + e);
}
}
public static PawnTableDef Table => PawnTableDefOf.Assign;
public static PawnColumnDef Column => DefDatabase<PawnColumnDef>.GetNamedSilentFail(PawnColumnWorker_BlaxCaste.DefName);
/// <summary>
/// Off: removes the column from the Assign table def. On: adds it back right before
/// HostilityResponse (or after the first column if that is gone) unless it is already there.
/// Returns true if the table changed. Open Assign tabs pick the change up the next time they open.
/// </summary>
public static bool Apply(bool show)
{
PawnTableDef table = Table;
PawnColumnDef column = Column;
if (table?.columns == null || column == null)
return false;
if (!show)
return table.columns.RemoveAll(c => c == column) > 0;
if (table.columns.Contains(column))
return false;
int at = table.columns.FindIndex(c => c != null && c.defName == AnchorColumn);
if (at < 0)
at = Math.Min(1, table.columns.Count);
table.columns.Insert(at, column);
return true;
}
}
}

View File

@ -15,6 +15,9 @@
<CopyLocalLockFileAssemblies>false</CopyLocalLockFileAssemblies> <CopyLocalLockFileAssemblies>false</CopyLocalLockFileAssemblies>
<DebugType>portable</DebugType> <DebugType>portable</DebugType>
<Deterministic>true</Deterministic> <Deterministic>true</Deterministic>
<!-- The SDK appends the git commit to the informational version, so every commit would change the
next build and the committed DLL could never match HEAD. Same source, same bytes. -->
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
<!-- Keep local paths out of the shipped DLL/PDB. --> <!-- Keep local paths out of the shipped DLL/PDB. -->
<PathMap>$(MSBuildProjectDirectory)=Source/BlaxCastes</PathMap> <PathMap>$(MSBuildProjectDirectory)=Source/BlaxCastes</PathMap>
</PropertyGroup> </PropertyGroup>

View File

@ -9,32 +9,65 @@ namespace BlaxCastes
{ {
/// <summary>Off: castes never write a pawn's policies. Castes, rows and memberships stay in the save.</summary> /// <summary>Off: castes never write a pawn's policies. Castes, rows and memberships stay in the save.</summary>
public bool enabled = true; public bool enabled = true;
/// <summary>Castes set the work priorities they list. Off: work priorities are never written.</summary>
public bool manageWorkPriorities = true;
/// <summary>With Weapons Tab Reborn, castes set the weapon loadout. Off: loadouts are never written.</summary>
public bool manageWeaponLoadout = true;
/// <summary>Joining pawns are put into the caste their join row picks.</summary> /// <summary>Joining pawns are put into the caste their join row picks.</summary>
public bool enableJoinDefaults = true; public bool enableJoinDefaults = true;
/// <summary>A message names the caste a joining pawn was put into.</summary> /// <summary>A message names the caste a joining pawn was put into.</summary>
public bool joinMessages = true; public bool joinMessages = true;
/// <summary>A join row set to No caste takes a pawn out of its caste and resets the managed policies.</summary> /// <summary>
/// A join row set to No caste takes a pawn out of a caste a join row put it in, and resets the
/// managed policies it still has from that caste. Only governs that revert.
/// </summary>
public bool revertOnLeave = true; public bool revertOnLeave = true;
/// <summary>The Caste column in the Assign tab. Read once at startup.</summary> /// <summary>A pawn that comes back within formerCasteDays with the same status gets its old caste back.</summary>
public bool returnToPreviousCaste = true;
/// <summary>How long a former-caste record lasts, in days.</summary>
public int formerCasteDays = DefaultFormerCasteDays;
/// <summary>A new game, or a save without castes, gets the Colonist, Slave and Prisoner castes.</summary>
public bool seedStarterCastes = true;
/// <summary>The settings page and a message per save name active mods whose join defaults overlap.</summary>
public bool warnOverlaps = true;
/// <summary>The Caste column in the Assign, Schedule and Work tabs. Read once at startup.</summary>
public bool showAssignColumn = true; public bool showAssignColumn = true;
public const int DefaultFormerCasteDays = 60;
public const int MinFormerCasteDays = 1;
public const int MaxFormerCasteDays = 120;
public override void ExposeData() public override void ExposeData()
{ {
base.ExposeData(); base.ExposeData();
Scribe_Values.Look(ref enabled, "enabled", true); Scribe_Values.Look(ref enabled, "enabled", true);
Scribe_Values.Look(ref manageWorkPriorities, "manageWorkPriorities", true);
Scribe_Values.Look(ref manageWeaponLoadout, "manageWeaponLoadout", true);
Scribe_Values.Look(ref enableJoinDefaults, "enableJoinDefaults", true); Scribe_Values.Look(ref enableJoinDefaults, "enableJoinDefaults", true);
Scribe_Values.Look(ref joinMessages, "joinMessages", true); Scribe_Values.Look(ref joinMessages, "joinMessages", true);
Scribe_Values.Look(ref revertOnLeave, "revertOnLeave", true); Scribe_Values.Look(ref revertOnLeave, "revertOnLeave", true);
Scribe_Values.Look(ref returnToPreviousCaste, "returnToPreviousCaste", true);
Scribe_Values.Look(ref formerCasteDays, "formerCasteDays", DefaultFormerCasteDays);
Scribe_Values.Look(ref seedStarterCastes, "seedStarterCastes", true);
Scribe_Values.Look(ref warnOverlaps, "warnOverlaps", true);
Scribe_Values.Look(ref showAssignColumn, "showAssignColumn", true); Scribe_Values.Look(ref showAssignColumn, "showAssignColumn", true);
if (Scribe.mode == LoadSaveMode.PostLoadInit)
formerCasteDays = Mathf.Clamp(formerCasteDays, MinFormerCasteDays, MaxFormerCasteDays);
} }
public void Reset() public void Reset()
{ {
var d = new BlaxCastesSettings(); var d = new BlaxCastesSettings();
enabled = d.enabled; enabled = d.enabled;
manageWorkPriorities = d.manageWorkPriorities;
manageWeaponLoadout = d.manageWeaponLoadout;
enableJoinDefaults = d.enableJoinDefaults; enableJoinDefaults = d.enableJoinDefaults;
joinMessages = d.joinMessages; joinMessages = d.joinMessages;
revertOnLeave = d.revertOnLeave; revertOnLeave = d.revertOnLeave;
returnToPreviousCaste = d.returnToPreviousCaste;
formerCasteDays = d.formerCasteDays;
seedStarterCastes = d.seedStarterCastes;
warnOverlaps = d.warnOverlaps;
showAssignColumn = d.showAssignColumn; showAssignColumn = d.showAssignColumn;
} }
} }
@ -80,11 +113,37 @@ namespace BlaxCastes
l.Begin(inRect); l.Begin(inRect);
l.CheckboxLabeled("BlaxCastes_SettingEnabled".Translate(), ref s.enabled, "BlaxCastes_SettingEnabledTip".Translate()); l.CheckboxLabeled("BlaxCastes_SettingEnabled".Translate(), ref s.enabled, "BlaxCastes_SettingEnabledTip".Translate());
l.CheckboxLabeled("BlaxCastes_SettingWorkPriorities".Translate(), ref s.manageWorkPriorities, "BlaxCastes_SettingWorkPrioritiesTip".Translate());
string workManager = WorkSlot.ActiveManager();
if (workManager != null)
{
using (new TextBlock(ColorLibrary.Gold))
l.Label("BlaxCastes_WorkManagerActive".Translate(workManager));
}
if (WeaponsTab.ModActive)
l.CheckboxLabeled("BlaxCastes_SettingWeaponLoadout".Translate(), ref s.manageWeaponLoadout, "BlaxCastes_SettingWeaponLoadoutTip".Translate());
l.GapLine(); l.GapLine();
l.CheckboxLabeled("BlaxCastes_SettingJoinDefaults".Translate(), ref s.enableJoinDefaults, "BlaxCastes_SettingJoinDefaultsTip".Translate()); l.CheckboxLabeled("BlaxCastes_SettingJoinDefaults".Translate(), ref s.enableJoinDefaults, "BlaxCastes_SettingJoinDefaultsTip".Translate());
l.CheckboxLabeled("BlaxCastes_SettingJoinMessages".Translate(), ref s.joinMessages, "BlaxCastes_SettingJoinMessagesTip".Translate()); l.CheckboxLabeled("BlaxCastes_SettingJoinMessages".Translate(), ref s.joinMessages, "BlaxCastes_SettingJoinMessagesTip".Translate());
l.CheckboxLabeled("BlaxCastes_SettingRevertOnLeave".Translate(), ref s.revertOnLeave, "BlaxCastes_SettingRevertOnLeaveTip".Translate()); l.CheckboxLabeled("BlaxCastes_SettingRevertOnLeave".Translate(), ref s.revertOnLeave, "BlaxCastes_SettingRevertOnLeaveTip".Translate());
l.CheckboxLabeled("BlaxCastes_SettingReturnToPrevious".Translate(), ref s.returnToPreviousCaste, "BlaxCastes_SettingReturnToPreviousTip".Translate());
if (s.returnToPreviousCaste)
{
s.formerCasteDays = Mathf.RoundToInt(l.SliderLabeled("BlaxCastes_SettingFormerCasteDays".Translate(s.formerCasteDays),
s.formerCasteDays, BlaxCastesSettings.MinFormerCasteDays, BlaxCastesSettings.MaxFormerCasteDays, 0.6f,
"BlaxCastes_SettingFormerCasteDaysTip".Translate()));
}
l.CheckboxLabeled("BlaxCastes_SettingSeedStarter".Translate(), ref s.seedStarterCastes, "BlaxCastes_SettingSeedStarterTip".Translate());
l.GapLine();
l.CheckboxLabeled("BlaxCastes_SettingWarnOverlaps".Translate(), ref s.warnOverlaps, "BlaxCastes_SettingWarnOverlapsTip".Translate());
string overlaps = OverlapWarnings.SettingsText();
if (!overlaps.NullOrEmpty())
{
using (new TextBlock(ColorLibrary.Gold))
l.Label(overlaps);
}
l.GapLine(); l.GapLine();
l.CheckboxLabeled("BlaxCastes_SettingShowAssignColumn".Translate(), ref s.showAssignColumn, "BlaxCastes_SettingShowAssignColumnTip".Translate()); l.CheckboxLabeled("BlaxCastes_SettingShowAssignColumn".Translate(), ref s.showAssignColumn, "BlaxCastes_SettingShowAssignColumnTip".Translate());

View File

@ -1,9 +1,14 @@
using System.Collections.Generic;
using RimWorld; using RimWorld;
using Verse; using Verse;
namespace BlaxCastes namespace BlaxCastes
{ {
/// <summary>The five policy slots a caste can manage in 1.0.</summary> /// <summary>
/// The slots a caste can manage. The first five hold a vanilla policy or a medical care level
/// (CasteUtility.PolicySlots); Schedule holds 24 time assignment defNames, Work a priority per work
/// type, and Loadout a Weapons Tab Reborn loadout id.
/// </summary>
public enum CasteSlot public enum CasteSlot
{ {
Apparel, Apparel,
@ -11,12 +16,17 @@ namespace BlaxCastes
Drug, Drug,
Reading, Reading,
MedCare, MedCare,
Schedule,
Work,
Loadout,
} }
/// <summary> /// <summary>
/// A bundle of policies. Ids, load IDs, rename and duplicate work the vanilla Policy way. A null /// A bundle of policies. Ids, load IDs, rename and duplicate work the vanilla Policy way. A null
/// policy slot, or medCare -1, means the caste leaves that slot alone. /// policy slot, medCare -1, a null schedule, no work priorities or loadout -1 means the caste leaves
/// Read the slots freely; change them only through CasteManager.SetSlot, which keeps members in sync. /// that slot alone. The later slots store defNames and ids, never def references, so a removed mod
/// leaves nothing unresolved in the save.
/// Read the slots freely; change them only through CasteManager, which keeps members in sync.
/// </summary> /// </summary>
public class Caste : Policy public class Caste : Policy
{ {
@ -27,6 +37,10 @@ namespace BlaxCastes
private DrugPolicy drugPolicy; private DrugPolicy drugPolicy;
private ReadingPolicy readingPolicy; private ReadingPolicy readingPolicy;
private int medCare = Unmanaged; private int medCare = Unmanaged;
private List<string> schedule;
private Dictionary<string, int> workPriorities = new Dictionary<string, int>();
private bool workStartFromNothing;
private int loadoutId = Unmanaged;
protected override string LoadKey => "BlaxCaste"; protected override string LoadKey => "BlaxCaste";
@ -48,7 +62,30 @@ namespace BlaxCastes
public MedicalCareCategory? MedCareCategory => medCare < 0 ? (MedicalCareCategory?)null : (MedicalCareCategory)medCare; public MedicalCareCategory? MedCareCategory => medCare < 0 ? (MedicalCareCategory?)null : (MedicalCareCategory)medCare;
/// <summary>The slot's value: a Policy, a boxed int for MedCare (-1 = unmanaged), or null.</summary> /// <summary>The 24 time assignment defNames, hour 0 first, or null when the caste leaves the schedule alone.</summary>
public IReadOnlyList<string> Schedule => schedule;
/// <summary>Work type defName to priority 0 (off) to 4. A work type that is not listed is left alone.</summary>
public IReadOnlyDictionary<string, int> WorkPriorities => workPriorities;
/// <summary>Applying the caste turns every work type off before writing the listed ones.</summary>
public bool WorkStartFromNothing => workStartFromNothing;
/// <summary>A Weapons Tab Reborn loadout id, or -1 (Unmanaged).</summary>
public int LoadoutId => loadoutId;
/// <summary>The priority the caste sets for a work type, or null when it leaves that type alone.</summary>
public int? WorkPriorityOf(string workTypeDefName)
{
if (workTypeDefName != null && workPriorities.TryGetValue(workTypeDefName, out int p))
return p;
return null;
}
/// <summary>
/// The slot's value: a Policy, a boxed int for MedCare and Loadout (-1 = unmanaged), the read-only
/// schedule list, the read-only work priorities (null when none are listed), or null.
/// </summary>
public object GetSlot(CasteSlot slot) public object GetSlot(CasteSlot slot)
{ {
switch (slot) switch (slot)
@ -58,15 +95,23 @@ namespace BlaxCastes
case CasteSlot.Drug: return drugPolicy; case CasteSlot.Drug: return drugPolicy;
case CasteSlot.Reading: return readingPolicy; case CasteSlot.Reading: return readingPolicy;
case CasteSlot.MedCare: return medCare; case CasteSlot.MedCare: return medCare;
case CasteSlot.Schedule: return schedule;
case CasteSlot.Work: return workPriorities.Count == 0 ? null : workPriorities;
case CasteSlot.Loadout: return loadoutId;
default: return null; default: return null;
} }
} }
public bool IsManaged(CasteSlot slot) public bool IsManaged(CasteSlot slot)
{ {
if (slot == CasteSlot.MedCare) switch (slot)
return medCare >= 0; {
return GetSlot(slot) != null; case CasteSlot.MedCare: return medCare >= 0;
case CasteSlot.Schedule: return schedule != null;
case CasteSlot.Work: return workPriorities.Count > 0;
case CasteSlot.Loadout: return loadoutId >= 0;
default: return GetSlot(slot) != null;
}
} }
public bool AnyManaged() public bool AnyManaged()
@ -79,7 +124,11 @@ namespace BlaxCastes
return false; return false;
} }
/// <summary>Raw write without member sync. Only CasteManager calls this.</summary> /// <summary>
/// Raw write without member sync. Only CasteManager and the starter castes call this. Collections
/// are always replaced by a new normalized copy, never changed in place, so a value read before
/// the write stays as it was.
/// </summary>
internal void SetSlotRaw(CasteSlot slot, object value) internal void SetSlotRaw(CasteSlot slot, object value)
{ {
switch (slot) switch (slot)
@ -99,9 +148,21 @@ namespace BlaxCastes
case CasteSlot.MedCare: case CasteSlot.MedCare:
medCare = CasteUtility.ToMedCare(value); medCare = CasteUtility.ToMedCare(value);
break; break;
case CasteSlot.Schedule:
schedule = ScheduleSlot.Normalize(value);
break;
case CasteSlot.Work:
workPriorities = WorkSlot.Normalize(value) ?? new Dictionary<string, int>();
break;
case CasteSlot.Loadout:
loadoutId = CasteUtility.ToLoadoutId(value);
break;
} }
} }
/// <summary>Raw write of the "Start from nothing" flag. It moves no member; it only changes later applies.</summary>
internal void SetWorkStartFromNothingRaw(bool value) => workStartFromNothing = value;
/// <summary>Copies every slot, not the id or the label (vanilla duplicate keeps the new policy's label).</summary> /// <summary>Copies every slot, not the id or the label (vanilla duplicate keeps the new policy's label).</summary>
public override void CopyFrom(Policy other) public override void CopyFrom(Policy other)
{ {
@ -112,6 +173,10 @@ namespace BlaxCastes
drugPolicy = caste.drugPolicy; drugPolicy = caste.drugPolicy;
readingPolicy = caste.readingPolicy; readingPolicy = caste.readingPolicy;
medCare = caste.medCare; medCare = caste.medCare;
schedule = caste.schedule == null ? null : new List<string>(caste.schedule);
workPriorities = new Dictionary<string, int>(caste.workPriorities);
workStartFromNothing = caste.workStartFromNothing;
loadoutId = caste.loadoutId;
} }
} }
@ -123,8 +188,19 @@ namespace BlaxCastes
Scribe_References.Look(ref drugPolicy, "drugPolicy"); Scribe_References.Look(ref drugPolicy, "drugPolicy");
Scribe_References.Look(ref readingPolicy, "readingPolicy"); Scribe_References.Look(ref readingPolicy, "readingPolicy");
Scribe_Values.Look(ref medCare, "medCare", Unmanaged); Scribe_Values.Look(ref medCare, "medCare", Unmanaged);
Scribe_Collections.Look(ref schedule, "schedule", LookMode.Value);
Scribe_Collections.Look(ref workPriorities, "workPriorities", LookMode.Value, LookMode.Value);
Scribe_Values.Look(ref workStartFromNothing, "workStartFromNothing");
Scribe_Values.Look(ref loadoutId, "loadoutId", Unmanaged);
if (Scribe.mode == LoadSaveMode.PostLoadInit) if (Scribe.mode == LoadSaveMode.PostLoadInit)
{
medCare = CasteUtility.ToMedCare(medCare); medCare = CasteUtility.ToMedCare(medCare);
workPriorities ??= new Dictionary<string, int>();
if (schedule != null && schedule.Count != ScheduleSlot.Hours)
schedule = null;
loadoutId = CasteUtility.ToLoadoutId(loadoutId);
// Unknown time assignments and work types are fixed, with a warning, by CasteManager.CheckSlots.
}
} }
public override string ToString() => "Caste(" + id + ", " + label + ")"; public override string ToString() => "Caste(" + id + ", " + label + ")";

View File

@ -0,0 +1,136 @@
using System;
using System.Collections.Generic;
using RimWorld;
using Verse;
namespace BlaxCastes
{
/// <summary>
/// The Caste column in three tables. The XML patches put it in the Assign table right before
/// HostilityResponse (Patches/BlaxCastes_Assign.xml), in the Schedule table right after the timetable
/// (the tab draws its time assignment selector over the top of the header left of the timetable, where
/// the column's buttons would sit), and in the Work table right before the copy and paste column, so
/// just left of the work columns (Patches/BlaxCastes_ScheduleWork.xml). At startup this checks the
/// placement, and removes the column again when the showAssignColumn setting is off, so turning the
/// setting on or off takes effect after a restart.
/// </summary>
[StaticConstructorOnStartup]
public static class CasteColumns
{
/// <summary>The Assign table's anchor: the Caste column goes right before it.</summary>
public const string AnchorColumn = "HostilityResponse";
/// <summary>The Schedule table's column the Caste column goes right after.</summary>
public const string ScheduleAfter = "Timetable";
/// <summary>The Schedule table's anchors without the timetable: the column goes right before the first one found.</summary>
public static readonly string[] ScheduleAnchors = { "AllowedArea" };
/// <summary>The Work table's anchor. Without it the column goes before the first work column.</summary>
public static readonly string[] WorkAnchors = { "CopyPasteWorkPriorities" };
static CasteColumns()
{
try
{
bool show = BlaxCastesMod.Settings == null || BlaxCastesMod.Settings.showAssignColumn;
var notPlaced = new List<string>();
foreach (PawnTableDef table in Tables)
{
if (show && table?.columns != null && Column != null && !table.columns.Contains(Column))
notPlaced.Add(table.defName);
}
ApplyAll(show);
if (notPlaced.Count > 0)
Log.Warning("[Blax Castes] The XML patches did not place the Caste column in " + string.Join(", ", notPlaced) + "; it was added in code instead.");
}
catch (Exception e)
{
Log.Error("[Blax Castes] Setting up the Caste column failed: " + e);
}
}
/// <summary>The Assign tab's table.</summary>
public static PawnTableDef Table => PawnTableDefOf.Assign;
/// <summary>The Schedule tab's table (defName Restrict).</summary>
public static PawnTableDef ScheduleTable => PawnTableDefOf.Restrict;
public static PawnTableDef WorkTable => PawnTableDefOf.Work;
public static IEnumerable<PawnTableDef> Tables
{
get
{
yield return Table;
yield return ScheduleTable;
yield return WorkTable;
}
}
public static PawnColumnDef Column => DefDatabase<PawnColumnDef>.GetNamedSilentFail(PawnColumnWorker_BlaxCaste.DefName);
/// <summary>
/// The Assign table only. Off: removes the column. On: adds it back right before HostilityResponse
/// (or after the first column if that is gone) unless it is already there. Returns true if the
/// table changed. Open tabs pick the change up the next time they open.
/// </summary>
public static bool Apply(bool show) => ApplyTo(Table, show, AnchorColumn);
/// <summary>All three tables. Returns true if any changed.</summary>
public static bool ApplyAll(bool show)
{
bool changed = Apply(show);
changed |= ApplyToSchedule(show);
changed |= ApplyTo(WorkTable, show, WorkAnchors);
return changed;
}
/// <summary>The Schedule table: right after the timetable, else as ApplyTo with ScheduleAnchors.</summary>
public static bool ApplyToSchedule(bool show)
{
PawnTableDef table = ScheduleTable;
PawnColumnDef column = Column;
if (table?.columns == null || column == null)
return false;
if (show && !table.columns.Contains(column))
{
int timetable = table.columns.FindIndex(c => c != null && c.defName == ScheduleAfter);
if (timetable >= 0)
{
table.columns.Insert(timetable + 1, column);
return true;
}
}
return ApplyTo(table, show, ScheduleAnchors);
}
/// <summary>
/// Off: removes the column from the table. On: adds it right before the first anchor found, else
/// before the first work column, else after the first column, unless it is already there.
/// </summary>
public static bool ApplyTo(PawnTableDef table, bool show, params string[] anchors)
{
PawnColumnDef column = Column;
if (table?.columns == null || column == null)
return false;
if (!show)
return table.columns.RemoveAll(c => c == column) > 0;
if (table.columns.Contains(column))
return false;
int at = -1;
foreach (string anchor in anchors)
{
at = table.columns.FindIndex(c => c != null && c.defName == anchor);
if (at >= 0)
break;
}
if (at < 0)
at = table.columns.FindIndex(c => c?.workType != null);
if (at < 0)
at = Math.Min(1, table.columns.Count);
table.columns.Insert(at, column);
return true;
}
}
}

View File

@ -1,3 +1,4 @@
using System.Collections.Generic;
using Verse; using Verse;
namespace BlaxCastes namespace BlaxCastes
@ -77,6 +78,14 @@ namespace BlaxCastes
public string reason; public string reason;
public int tick; public int tick;
/// <summary>
/// The pawn's membership when the join was last queued (not saved). A different membership at
/// apply time means the player picked a caste after the join was queued, even within one tick.
/// After a load, the ticks decide instead.
/// </summary>
public CasteMembership seen;
public bool seenKnown;
public QueuedJoin() public QueuedJoin()
{ {
} }
@ -96,6 +105,86 @@ namespace BlaxCastes
} }
} }
/// <summary>
/// The caste a pawn had when it left the player side, was sold or became a prisoner, or "No caste"
/// when it was casteless by choice. Keyed by ThingID in GameComponent_BlaxCastes, so a discarded pawn
/// leaves no unresolved reference. The caste and the policies are stored by id for the same reason.
/// If the pawn comes back within formerCasteDays with the same status (colonist or slave), it gets
/// that caste (or No caste) back instead of its join row's, and its own settings from when it left
/// (JoinDefaults.Restore): the slots it followed get the caste's current value, the ones it had
/// changed by hand get that value back.
/// </summary>
public class FormerCaste : IExposable
{
public int casteId = Caste.Unmanaged;
/// <summary>The pawn was casteless by choice; casteId is unused.</summary>
public bool casteless;
/// <summary>Colonist or Slave: the status the pawn had in that caste.</summary>
public JoinSide side;
/// <summary>The membership's auto flag, restored with the caste.</summary>
public bool auto;
public int tick;
// The pawn's own settings just before it left; -1 or null where it had none.
public int apparelId = Caste.Unmanaged;
public int foodId = Caste.Unmanaged;
public int drugId = Caste.Unmanaged;
public int readingId = Caste.Unmanaged;
public int medCare = Caste.Unmanaged;
public int loadoutId = Caste.Unmanaged;
public List<string> schedule;
/// <summary>Every work type's priority, as the game read it.</summary>
public Dictionary<string, int> work;
/// <summary>The caste's managed slots where the pawn had the caste's value when it left.</summary>
public List<CasteSlot> followed = new List<CasteSlot>();
/// <summary>The work types the caste decides where the pawn had the caste's value when it left.</summary>
public List<string> followedWork = new List<string>();
public FormerCaste()
{
}
public FormerCaste(int casteId, JoinSide side, bool auto, int tick)
{
this.casteId = casteId;
this.side = side;
this.auto = auto;
this.tick = tick;
}
/// <summary>The pawn followed the caste's value for this slot when it left.</summary>
public bool Followed(CasteSlot slot) => followed != null && followed.Contains(slot);
public bool FollowedWork(string defName) => followedWork != null && followedWork.Contains(defName);
public void ExposeData()
{
Scribe_Values.Look(ref casteId, "casteId", Caste.Unmanaged);
Scribe_Values.Look(ref casteless, "casteless");
Scribe_Values.Look(ref side, "side", JoinSide.None);
Scribe_Values.Look(ref auto, "auto");
Scribe_Values.Look(ref tick, "tick");
Scribe_Values.Look(ref apparelId, "apparelId", Caste.Unmanaged);
Scribe_Values.Look(ref foodId, "foodId", Caste.Unmanaged);
Scribe_Values.Look(ref drugId, "drugId", Caste.Unmanaged);
Scribe_Values.Look(ref readingId, "readingId", Caste.Unmanaged);
Scribe_Values.Look(ref medCare, "medCare", Caste.Unmanaged);
Scribe_Values.Look(ref loadoutId, "loadoutId", Caste.Unmanaged);
Scribe_Collections.Look(ref schedule, "schedule", LookMode.Value);
Scribe_Collections.Look(ref work, "work", LookMode.Value, LookMode.Value);
Scribe_Collections.Look(ref followed, "followed", LookMode.Value);
Scribe_Collections.Look(ref followedWork, "followedWork", LookMode.Value);
if (Scribe.mode == LoadSaveMode.PostLoadInit)
{
followed ??= new List<CasteSlot>();
followedWork ??= new List<string>();
}
}
public override string ToString() =>
"FormerCaste(" + (casteless ? "no caste" : casteId.ToString()) + ", " + side + ", tick " + tick + ")";
}
/// <summary>Reason strings stored in memberships, join rows and the join queue.</summary> /// <summary>Reason strings stored in memberships, join rows and the join queue.</summary>
public static class JoinReason public static class JoinReason
{ {
@ -109,6 +198,8 @@ namespace BlaxCastes
// Reasons that are not join rows. // Reasons that are not join rows.
public const string Manual = "manual"; public const string Manual = "manual";
public const string CasteDeleted = "casteDeleted"; public const string CasteDeleted = "casteDeleted";
/// <summary>A returning pawn got back the caste it had before it left (FormerCaste).</summary>
public const string PreviousCaste = "previousCaste";
/// <summary>The join rows in display order.</summary> /// <summary>The join rows in display order.</summary>
public static readonly string[] Rows = { BoughtSlave, BoughtColonist, NewColonist, NewSlave, NewPrisoner }; public static readonly string[] Rows = { BoughtSlave, BoughtColonist, NewColonist, NewSlave, NewPrisoner };

View File

@ -1,4 +1,5 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using RimWorld; using RimWorld;
using Verse; using Verse;
@ -42,13 +43,15 @@ namespace BlaxCastes
/// <summary> /// <summary>
/// Removes the caste. Its members become casteless and keep their current policies, join rows /// Removes the caste. Its members become casteless and keep their current policies, join rows
/// that point at it fall back to No caste, and it stops being the default. /// that point at it fall back to No caste, it stops being the default, and former-caste records
/// that point at it are dropped.
/// </summary> /// </summary>
public static bool DeleteCaste(Caste caste) public static bool DeleteCaste(Caste caste)
{ {
GameComponent_BlaxCastes comp = Comp; GameComponent_BlaxCastes comp = Comp;
if (comp == null || !comp.HasCaste(caste)) if (comp == null || !comp.HasCaste(caste))
return false; return false;
comp.RemoveFormerCastesOf(caste.id);
foreach (Pawn member in comp.MembersOf(caste)) foreach (Pawn member in comp.MembersOf(caste))
{ {
if (CasteUtility.CanBeMember(member)) if (CasteUtility.CanBeMember(member))
@ -80,7 +83,8 @@ namespace BlaxCastes
/// <summary> /// <summary>
/// Changes one slot. Members still on the old value get the new one; members on another value /// Changes one slot. Members still on the old value get the new one; members on another value
/// keep it (the Follow rule). A slot that was unmanaged had no old value, so every member gets /// keep it (the Follow rule). A slot that was unmanaged had no old value, so every member gets
/// the new one. Unmanaging a slot changes no pawn. Returns how many members were moved. /// the new one. Unmanaging a slot changes no pawn. The schedule compares the whole day; work
/// priorities go type by type (see SetWorkPriority). Returns how many members were moved.
/// </summary> /// </summary>
public static int SetSlot(Caste caste, CasteSlot slot, object newValue) public static int SetSlot(Caste caste, CasteSlot slot, object newValue)
{ {
@ -92,13 +96,17 @@ namespace BlaxCastes
Log.Warning("[Blax Castes] " + newValue.GetType().Name + " does not fit the " + slot + " slot of " + caste.label + "."); Log.Warning("[Blax Castes] " + newValue.GetType().Name + " does not fit the " + slot + " slot of " + caste.label + ".");
return 0; return 0;
} }
if (slot == CasteSlot.MedCare) newValue = CasteUtility.NormalizeSlotValue(slot, newValue);
newValue = CasteUtility.ToMedCare(newValue); if (CasteUtility.IsPolicySlot(slot) && slot != CasteSlot.MedCare && newValue != null && !CasteUtility.PolicyExists((Policy)newValue))
else if (newValue != null && !CasteUtility.PolicyExists((Policy)newValue))
{ {
Log.Warning("[Blax Castes] Policy " + ((Policy)newValue).label + " is not in the game's database; " + caste.label + " keeps its " + slot + " slot."); Log.Warning("[Blax Castes] Policy " + ((Policy)newValue).label + " is not in the game's database; " + caste.label + " keeps its " + slot + " slot.");
return 0; return 0;
} }
if (slot == CasteSlot.Loadout && newValue is int id && id >= 0 && !WeaponsTab.Exists(id))
{
Log.Warning("[Blax Castes] Weapon loadout " + id + " is not one of Weapons Tab Reborn's loadouts; " + caste.label + " keeps its loadout slot.");
return 0;
}
object oldValue = caste.GetSlot(slot); object oldValue = caste.GetSlot(slot);
bool wasManaged = caste.IsManaged(slot); bool wasManaged = caste.IsManaged(slot);
@ -107,13 +115,15 @@ namespace BlaxCastes
caste.SetSlotRaw(slot, newValue); caste.SetSlotRaw(slot, newValue);
if (!caste.IsManaged(slot) || !BlaxCastesMod.Enabled) if (!caste.IsManaged(slot) || !BlaxCastesMod.Enabled)
return 0; return 0;
if (slot == CasteSlot.Work)
return SyncWork(comp, caste, oldValue as IReadOnlyDictionary<string, int>);
int moved = 0; int moved = 0;
foreach (Pawn member in comp.MembersOf(caste)) foreach (Pawn member in comp.MembersOf(caste))
{ {
if (GameComponent_BlaxCastes.IsGone(member) || !CasteUtility.CanUse(member, slot)) if (GameComponent_BlaxCastes.IsGone(member) || !CasteUtility.CanUse(member, slot))
continue; continue;
if (wasManaged && !CasteUtility.SameValue(CasteUtility.CurrentValue(member, slot), oldValue)) if (wasManaged && !CasteUtility.Matches(member, slot, oldValue))
continue; continue;
if (CasteUtility.WriteSlot(member, slot, newValue)) if (CasteUtility.WriteSlot(member, slot, newValue))
moved++; moved++;
@ -121,6 +131,118 @@ namespace BlaxCastes
return moved; return moved;
} }
/// <summary>
/// The Follow rule per work type: for each type whose priority changed, members whose priority equals
/// the old one get the new one; a type that was not listed before reaches every member. A type that
/// is no longer listed moves nobody.
/// </summary>
private static int SyncWork(GameComponent_BlaxCastes comp, Caste caste, IReadOnlyDictionary<string, int> oldValues)
{
int moved = 0;
foreach (Pawn member in comp.MembersOf(caste))
{
if (GameComponent_BlaxCastes.IsGone(member) || !CasteUtility.CanUse(member, CasteSlot.Work))
continue;
bool wrote = false;
foreach (KeyValuePair<string, int> kv in caste.WorkPriorities)
{
if (oldValues != null && oldValues.TryGetValue(kv.Key, out int old))
{
if (old == kv.Value || !WorkSlot.Matches(member, kv.Key, old))
continue;
}
if (WorkSlot.WriteType(member, kv.Key, kv.Value))
wrote = true;
}
if (wrote)
moved++;
}
return moved;
}
/// <summary>
/// Sets one work type's priority (0 to 4), or leaves it alone with null. Members follow per type.
/// Returns how many members were moved.
/// </summary>
public static int SetWorkPriority(Caste caste, string workTypeDefName, int? priority)
{
if (caste == null || workTypeDefName.NullOrEmpty())
return 0;
var values = new Dictionary<string, int>(caste.WorkPriorities);
if (priority == null)
values.Remove(workTypeDefName);
else
values[workTypeDefName] = priority.Value;
return SetSlot(caste, CasteSlot.Work, values);
}
/// <summary>
/// The members that follow one work type of the caste right now: those whose priority equals the
/// caste's value, or every member while the caste leaves the type alone (the next value reaches them
/// all). The manager's cycle button takes them before its first click on a type, so the clicks after
/// it move only them, never a pawn that happens to sit on a value the cycle passes through.
/// </summary>
public static List<Pawn> WorkFollowers(Caste caste, string workTypeDefName)
{
var result = new List<Pawn>();
GameComponent_BlaxCastes comp = Comp;
if (comp == null || !comp.HasCaste(caste) || workTypeDefName.NullOrEmpty())
return result;
int? value = caste.WorkPriorityOf(workTypeDefName);
foreach (Pawn member in comp.MembersOf(caste))
{
if (GameComponent_BlaxCastes.IsGone(member) || !CasteUtility.CanUse(member, CasteSlot.Work))
continue;
if (value == null || WorkSlot.Matches(member, workTypeDefName, value.Value))
result.Add(member);
}
return result;
}
/// <summary>
/// Sets one work type's priority (0 to 4, or null to leave it alone) and writes it to the given
/// members only, those WorkFollowers listed before a run of edits to this type. Members that left the
/// caste since are skipped. Returns how many members were moved.
/// </summary>
public static int SetWorkPriority(Caste caste, string workTypeDefName, int? priority, IEnumerable<Pawn> followers)
{
GameComponent_BlaxCastes comp = Comp;
if (comp == null || !comp.HasCaste(caste) || workTypeDefName.NullOrEmpty())
return 0;
if (priority != null && (priority.Value < WorkSlot.Off || priority.Value > WorkSlot.Lowest))
return 0;
var values = new Dictionary<string, int>(caste.WorkPriorities);
if (priority == null)
values.Remove(workTypeDefName);
else
values[workTypeDefName] = priority.Value;
caste.SetSlotRaw(CasteSlot.Work, WorkSlot.Normalize(values));
if (priority == null || followers == null || !BlaxCastesMod.Enabled)
return 0;
int moved = 0;
foreach (Pawn member in followers)
{
if (GameComponent_BlaxCastes.IsGone(member) || comp.CasteOf(member) != caste || !CasteUtility.CanUse(member, CasteSlot.Work))
continue;
if (WorkSlot.WriteType(member, workTypeDefName, priority.Value))
moved++;
}
return moved;
}
/// <summary>
/// "Start from nothing": applying the caste turns every work type off before writing its listed ones.
/// Moves no member now; it takes effect on the next assign, Reset to caste or Apply to all members.
/// </summary>
public static bool SetWorkStartFromNothing(Caste caste, bool value)
{
GameComponent_BlaxCastes comp = Comp;
if (comp == null || !comp.HasCaste(caste))
return false;
caste.SetWorkStartFromNothingRaw(value);
return true;
}
// ---- memberships ------------------------------------------------------------------- // ---- memberships -------------------------------------------------------------------
/// <summary> /// <summary>
@ -168,6 +290,92 @@ namespace BlaxCastes
return comp != null && comp.RemoveMembership(pawn); return comp != null && comp.RemoveMembership(pawn);
} }
/// <summary>The caste's members that are alive and player-side (the manager's member count).</summary>
public static List<Pawn> LiveMembers(Caste caste)
{
var result = new List<Pawn>();
GameComponent_BlaxCastes comp = Comp;
if (comp == null || caste == null)
return result;
foreach (Pawn p in comp.MembersOf(caste))
{
if (!p.Dead && CasteUtility.CanBeMember(p))
result.Add(p);
}
return result;
}
/// <summary>
/// "Apply to all members": writes every managed slot of the caste to every live member, clearing
/// their hand changes. Returns how many members it wrote to.
/// </summary>
public static int ApplyToAll(Caste caste)
{
GameComponent_BlaxCastes comp = Comp;
if (comp == null || !comp.HasCaste(caste) || !BlaxCastesMod.Enabled)
return 0;
int count = 0;
foreach (Pawn p in LiveMembers(caste))
{
if (CasteUtility.Apply(p, caste).Count > 0)
count++;
}
return count;
}
/// <summary>
/// The pawns "Assign by status" would place: player colonists, slaves and prisoners that can join a
/// caste, have no membership record (casteless-by-choice pawns have one), are not waiting for a join,
/// and whose status row resolves to a caste.
/// </summary>
public static List<Pawn> PawnsToAssignByStatus()
{
var result = new List<Pawn>();
GameComponent_BlaxCastes comp = Comp;
if (comp == null || Current.Game == null)
return result;
var seen = new HashSet<Pawn>();
foreach (Pawn p in PlayerSidePawns())
{
if (!seen.Add(p) || p.Dead || comp.MembershipOf(p) != null || JoinDefaults.IsQueued(p))
continue;
if (!JoinDefaults.Eligible(p) || !CasteUtility.CanBeMember(p))
continue;
string row = JoinDefaults.RowFor(JoinDefaults.StatusFallback, p);
if (row != null && comp.ResolveRow(row) != null)
result.Add(p);
}
return result;
}
private static IEnumerable<Pawn> PlayerSidePawns()
{
foreach (Pawn p in PawnsFinder.AllMapsCaravansAndTravellingTransporters_Alive_OfPlayerFaction.ToArray())
yield return p;
foreach (Pawn p in PawnsFinder.AllMapsCaravansAndTravellingTransporters_Alive_PrisonersOfColony.ToArray())
yield return p;
}
/// <summary>
/// "Assign pawns without a caste by status": puts each pawn of PawnsToAssignByStatus into the caste
/// of its new colonist, new slave or new prisoner row. Returns how many were assigned.
/// </summary>
public static int AssignByStatus()
{
GameComponent_BlaxCastes comp = Comp;
if (comp == null)
return 0;
int count = 0;
foreach (Pawn p in PawnsToAssignByStatus())
{
string row = JoinDefaults.RowFor(JoinDefaults.StatusFallback, p);
Caste caste = row == null ? null : comp.ResolveRow(row);
if (caste != null && Assign(p, caste, true, row))
count++;
}
return count;
}
/// <summary> /// <summary>
/// The managed slots of the pawn's caste where the pawn has another value (a hand change or a /// The managed slots of the pawn's caste where the pawn has another value (a hand change or a
/// vanilla reset). Slots the pawn can't take are never overrides. /// vanilla reset). Slots the pawn can't take are never overrides.
@ -182,12 +390,21 @@ namespace BlaxCastes
{ {
if (!caste.IsManaged(slot) || !CasteUtility.CanUse(pawn, slot)) if (!caste.IsManaged(slot) || !CasteUtility.CanUse(pawn, slot))
continue; continue;
if (!CasteUtility.SameValue(CasteUtility.CurrentValue(pawn, slot), caste.GetSlot(slot))) if (!CasteUtility.Matches(pawn, slot, caste.GetSlot(slot)))
result.Add(slot); result.Add(slot);
} }
return result; return result;
} }
/// <summary>The work types of the pawn's caste where the pawn's priority differs, in the Work tab's order.</summary>
public static List<WorkTypeDef> WorkOverrides(Pawn pawn)
{
Caste caste = Comp?.CasteOf(pawn);
if (caste == null || !caste.IsManaged(CasteSlot.Work) || !CasteUtility.CanUse(pawn, CasteSlot.Work))
return new List<WorkTypeDef>();
return WorkSlot.Differences(pawn, caste.WorkPriorities);
}
// ---- join rows --------------------------------------------------------------------- // ---- join rows ---------------------------------------------------------------------
/// <summary>Sets what a join row does. SpecificCaste needs a caste of this game.</summary> /// <summary>Sets what a join row does. SpecificCaste needs a caste of this game.</summary>
@ -204,22 +421,33 @@ namespace BlaxCastes
// ---- save safety ------------------------------------------------------------------- // ---- save safety -------------------------------------------------------------------
/// <summary>Unmanages every slot whose policy left its database, with one warning per caste.</summary> /// <summary>
internal static void CheckPolicies(GameComponent_BlaxCastes comp) /// Checks every caste's slots after a load, before a save and while the manager is open: a policy
/// that left its database or a loadout Weapons Tab Reborn no longer has becomes unmanaged, a schedule
/// hour with an unknown time assignment becomes Anything, and a work type that no longer exists is
/// dropped. One warning per caste and problem.
/// </summary>
internal static void CheckSlots(GameComponent_BlaxCastes comp)
{ {
if (comp == null) if (comp == null)
return; return;
foreach (Caste caste in comp.Castes) foreach (Caste caste in comp.Castes)
{
UnmanageMissingPolicies(caste); UnmanageMissingPolicies(caste);
FixScheduleAndWork(caste);
}
} }
/// <summary>Unmanages the caste's slots whose policy is no longer in its database. Returns how many.</summary> /// <summary>
/// Unmanages the caste's slots whose policy is no longer in its database, and its loadout when Weapons
/// Tab Reborn is active and no longer has it (without the mod the id is kept). Returns how many.
/// </summary>
internal static int UnmanageMissingPolicies(Caste caste) internal static int UnmanageMissingPolicies(Caste caste)
{ {
if (caste == null || Current.Game == null) if (caste == null || Current.Game == null)
return 0; return 0;
List<string> missing = null; List<string> missing = null;
foreach (CasteSlot slot in CasteUtility.AllSlots) foreach (CasteSlot slot in CasteUtility.PolicySlots)
{ {
if (slot == CasteSlot.MedCare || !(caste.GetSlot(slot) is Policy policy)) if (slot == CasteSlot.MedCare || !(caste.GetSlot(slot) is Policy policy))
continue; continue;
@ -228,11 +456,42 @@ namespace BlaxCastes
(missing ??= new List<string>()).Add(slot + " (" + policy.label + ")"); (missing ??= new List<string>()).Add(slot + " (" + policy.label + ")");
caste.SetSlotRaw(slot, null); caste.SetSlotRaw(slot, null);
} }
if (caste.IsManaged(CasteSlot.Loadout) && WeaponsTab.Available && !WeaponsTab.Exists(caste.LoadoutId))
{
(missing ??= new List<string>()).Add("weapon loadout (id " + caste.LoadoutId + ")");
caste.SetSlotRaw(CasteSlot.Loadout, Caste.Unmanaged);
}
if (missing == null) if (missing == null)
return 0; return 0;
Log.Warning("[Blax Castes] Caste \"" + caste.label + "\": " + string.Join(", ", missing) Log.Warning("[Blax Castes] Caste \"" + caste.label + "\": " + string.Join(", ", missing)
+ " no longer in the game's policies. The slot is now unmanaged."); + " no longer in the game. The slot is now unmanaged.");
return missing.Count; return missing.Count;
} }
/// <summary>
/// Schedule hours whose time assignment no longer exists (a removed mod, Meditate without Royalty)
/// become Anything, and work types that no longer exist are dropped, each with one warning.
/// </summary>
internal static void FixScheduleAndWork(Caste caste)
{
if (caste == null)
return;
IReadOnlyList<string> schedule = caste.Schedule;
if (schedule != null && schedule.Any(n => !ScheduleSlot.IsKnown(n)))
{
List<string> unknown = schedule.Where(n => !ScheduleSlot.IsKnown(n)).Distinct().ToList();
caste.SetSlotRaw(CasteSlot.Schedule, schedule.ToList()); // Normalize turns unknown names into Anything
Log.Warning("[Blax Castes] Caste \"" + caste.label + "\": time assignment " + string.Join(", ", unknown)
+ " no longer in the game. Those schedule hours are now Anything.");
}
if (caste.WorkPriorities.Keys.Any(k => WorkSlot.Resolve(k) == null))
{
List<string> gone = caste.WorkPriorities.Keys.Where(k => WorkSlot.Resolve(k) == null).ToList();
var kept = caste.WorkPriorities.Where(kv => !gone.Contains(kv.Key)).ToDictionary(kv => kv.Key, kv => kv.Value);
caste.SetSlotRaw(CasteSlot.Work, kept);
Log.Warning("[Blax Castes] Caste \"" + caste.label + "\": work type " + string.Join(", ", gone)
+ " no longer in the game. The caste leaves it alone now.");
}
}
} }
} }

View File

@ -1,16 +1,28 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using RimWorld; using RimWorld;
using Verse; using Verse;
namespace BlaxCastes namespace BlaxCastes
{ {
/// <summary> /// <summary>
/// Reads and writes a pawn's policy slots through the vanilla setters, with the checks that decide /// Reads and writes a pawn's slots through the vanilla setters (and Weapons Tab Reborn's API for the
/// which slots a pawn can take. CasteManager decides when to write; nothing else should call Apply. /// loadout), with the checks that decide which slots a pawn can take. CasteManager decides when to
/// write; nothing else should call Apply.
/// </summary> /// </summary>
public static class CasteUtility public static class CasteUtility
{ {
public static readonly CasteSlot[] AllSlots = { CasteSlot.Apparel, CasteSlot.Food, CasteSlot.Drug, CasteSlot.Reading, CasteSlot.MedCare }; /// <summary>Every slot, in the order Apply writes them.</summary>
public static readonly CasteSlot[] AllSlots =
{
CasteSlot.Apparel, CasteSlot.Food, CasteSlot.Drug, CasteSlot.Reading, CasteSlot.MedCare,
CasteSlot.Schedule, CasteSlot.Work, CasteSlot.Loadout,
};
/// <summary>The policy and medical care slots: the ones a No caste row resets and the manager draws as plain rows.</summary>
public static readonly CasteSlot[] PolicySlots = { CasteSlot.Apparel, CasteSlot.Food, CasteSlot.Drug, CasteSlot.Reading, CasteSlot.MedCare };
public static bool IsPolicySlot(CasteSlot slot) => slot <= CasteSlot.MedCare;
/// <summary>Player faction (colonists, slaves, dead colonists) or a prisoner of the player.</summary> /// <summary>Player faction (colonists, slaves, dead colonists) or a prisoner of the player.</summary>
public static bool IsPlayerSide(Pawn pawn) public static bool IsPlayerSide(Pawn pawn)
@ -26,10 +38,28 @@ namespace BlaxCastes
private static bool PoliciesDisabled(Pawn pawn) => pawn.IsMutant && pawn.mutant.Def.disablePolicies; private static bool PoliciesDisabled(Pawn pawn) => pawn.IsMutant && pawn.mutant.Def.disablePolicies;
/// <summary>Apparel, drug and reading: tracker, not a quest lodger, not a prisoner, no policy-less mutant.</summary> /// <summary>Apparel, drug, reading and schedule: not a quest lodger, not a prisoner, no policy-less mutant.</summary>
private static bool CanTakeOwnPolicies(Pawn pawn) => private static bool CanTakeOwnPolicies(Pawn pawn) =>
!pawn.IsQuestLodger() && !pawn.IsPrisoner && !PoliciesDisabled(pawn); !pawn.IsQuestLodger() && !pawn.IsPrisoner && !PoliciesDisabled(pawn);
/// <summary>Work and loadout: colonists and slaves of the player, with the same exclusions.</summary>
private static bool IsColonistOrSlave(Pawn pawn) =>
pawn.Faction == Faction.OfPlayer && pawn.RaceProps != null && pawn.RaceProps.Humanlike && CanTakeOwnPolicies(pawn);
/// <summary>
/// The slot is written at all: work priorities need the manageWorkPriorities setting and no automatic
/// work manager; the loadout needs Weapons Tab Reborn and the manageWeaponLoadout setting.
/// </summary>
public static bool SlotActive(CasteSlot slot)
{
switch (slot)
{
case CasteSlot.Work: return WorkSlot.Active;
case CasteSlot.Loadout: return WeaponsTab.Active;
default: return true;
}
}
/// <summary>Whether the slot can be written on this pawn right now.</summary> /// <summary>Whether the slot can be written on this pawn right now.</summary>
public static bool CanUse(Pawn pawn, CasteSlot slot) public static bool CanUse(Pawn pawn, CasteSlot slot)
{ {
@ -48,12 +78,22 @@ namespace BlaxCastes
&& !pawn.DevelopmentalStage.Baby() && !PoliciesDisabled(pawn); && !pawn.DevelopmentalStage.Baby() && !PoliciesDisabled(pawn);
case CasteSlot.MedCare: case CasteSlot.MedCare:
return pawn.playerSettings != null && pawn.RaceProps != null && pawn.RaceProps.IsFlesh; return pawn.playerSettings != null && pawn.RaceProps != null && pawn.RaceProps.IsFlesh;
case CasteSlot.Schedule:
// Like the vanilla Schedule tab: a timetable, and not a subhuman mutant.
return ScheduleSlot.HasTimetable(pawn) && CanTakeOwnPolicies(pawn) && !pawn.IsSubhuman;
case CasteSlot.Work:
return WorkSlot.Active && WorkSlot.HasWorkSettings(pawn) && IsColonistOrSlave(pawn);
case CasteSlot.Loadout:
return WeaponsTab.Active && IsColonistOrSlave(pawn);
default: default:
return false; return false;
} }
} }
/// <summary>The pawn's current value for a slot (a Policy, or a boxed int for MedCare), or null if it has none.</summary> /// <summary>
/// The pawn's current value for a slot, or null if it has none: a Policy, a boxed int for MedCare and
/// Loadout, the 24 schedule defNames, or the priorities of the work types that are on.
/// </summary>
public static object CurrentValue(Pawn pawn, CasteSlot slot) public static object CurrentValue(Pawn pawn, CasteSlot slot)
{ {
if (pawn == null) if (pawn == null)
@ -65,22 +105,51 @@ namespace BlaxCastes
case CasteSlot.Drug: return pawn.drugs?.CurrentPolicy; case CasteSlot.Drug: return pawn.drugs?.CurrentPolicy;
case CasteSlot.Reading: return pawn.reading?.CurrentPolicy; case CasteSlot.Reading: return pawn.reading?.CurrentPolicy;
case CasteSlot.MedCare: return pawn.playerSettings == null ? (object)null : (int)pawn.playerSettings.medCare; case CasteSlot.MedCare: return pawn.playerSettings == null ? (object)null : (int)pawn.playerSettings.medCare;
case CasteSlot.Schedule: return ScheduleSlot.Of(pawn);
case CasteSlot.Work: return WorkSlot.Of(pawn, activeOnly: true);
case CasteSlot.Loadout: return CanUse(pawn, CasteSlot.Loadout) ? WeaponsTab.LoadoutOf(pawn) : null;
default: return null; default: return null;
} }
} }
/// <summary>Equality for slot values: policies by reference, med care by value.</summary> /// <summary>
/// Equality for slot values: policies by reference, med care and loadout by value, schedules hour by
/// hour, work priorities type by type.
/// </summary>
public static bool SameValue(object a, object b) public static bool SameValue(object a, object b)
{ {
if (a is int ia && b is int ib) if (a is int ia && b is int ib)
return ia == ib; return ia == ib;
if (a is IReadOnlyList<string> la && b is IReadOnlyList<string> lb)
return la.SequenceEqual(lb);
if (a is IReadOnlyDictionary<string, int> da && b is IReadOnlyDictionary<string, int> db)
return da.Count == db.Count && da.All(kv => db.TryGetValue(kv.Key, out int v) && v == kv.Value);
return ReferenceEquals(a, b); return ReferenceEquals(a, b);
} }
/// <summary> /// <summary>
/// Writes every managed slot of the caste the pawn can take, through the vanilla setters, and /// The pawn already has the caste's value for the slot (so it follows the caste). Schedules compare the
/// returns those slots. A policy that is no longer in its database is skipped and unmanaged. /// whole day; work priorities compare each listed type the pawn can do, as the game treats them now.
/// Does nothing while the "enabled" setting is off. /// </summary>
public static bool Matches(Pawn pawn, CasteSlot slot, object casteValue)
{
switch (slot)
{
case CasteSlot.Schedule:
return ScheduleSlot.Matches(pawn, casteValue as IReadOnlyList<string>);
case CasteSlot.Work:
return WorkSlot.MatchesAll(pawn, casteValue as IReadOnlyDictionary<string, int>);
case CasteSlot.Loadout:
return casteValue is int id && WeaponsTab.LoadoutOf(pawn) == id;
default:
return SameValue(CurrentValue(pawn, slot), casteValue);
}
}
/// <summary>
/// Writes every managed slot of the caste the pawn can take and returns those slots. A policy that is
/// no longer in its database, or a loadout Weapons Tab Reborn no longer has, is skipped and unmanaged.
/// Work priorities honour the caste's "Start from nothing". Does nothing while the "enabled" setting is off.
/// </summary> /// </summary>
public static List<CasteSlot> Apply(Pawn pawn, Caste caste) public static List<CasteSlot> Apply(Pawn pawn, Caste caste)
{ {
@ -93,12 +162,20 @@ namespace BlaxCastes
if (!caste.IsManaged(slot)) if (!caste.IsManaged(slot))
continue; continue;
object value = caste.GetSlot(slot); object value = caste.GetSlot(slot);
if (slot != CasteSlot.MedCare && !PolicyExists(value as Policy)) if (IsPolicySlot(slot) && slot != CasteSlot.MedCare && !PolicyExists(value as Policy))
{ {
missing = true; missing = true;
continue; continue;
} }
if (WriteSlot(pawn, slot, value)) if (slot == CasteSlot.Loadout && CanUse(pawn, slot) && !WeaponsTab.Exists(caste.LoadoutId))
{
missing = true;
continue;
}
bool wrote = slot == CasteSlot.Work
? CanUse(pawn, slot) && WorkSlot.Write(pawn, caste.WorkPriorities, caste.WorkStartFromNothing)
: WriteSlot(pawn, slot, value);
if (wrote)
applied.Add(slot); applied.Add(slot);
} }
if (missing) if (missing)
@ -106,7 +183,10 @@ namespace BlaxCastes
return applied; return applied;
} }
/// <summary>Writes one slot value if the pawn can take it. Null policies and medCare -1 are never written.</summary> /// <summary>
/// Writes one slot value if the pawn can take it. Null policies, medCare and loadout -1 and a null
/// schedule are never written. Work writes only the listed types (no "Start from nothing").
/// </summary>
internal static bool WriteSlot(Pawn pawn, CasteSlot slot, object value) internal static bool WriteSlot(Pawn pawn, CasteSlot slot, object value)
{ {
if (!CanUse(pawn, slot)) if (!CanUse(pawn, slot))
@ -139,11 +219,159 @@ namespace BlaxCastes
return false; return false;
pawn.playerSettings.medCare = (MedicalCareCategory)care; pawn.playerSettings.medCare = (MedicalCareCategory)care;
return true; return true;
case CasteSlot.Schedule:
return ScheduleSlot.Write(pawn, value as IReadOnlyList<string>);
case CasteSlot.Work:
return WorkSlot.Write(pawn, value as IReadOnlyDictionary<string, int>, startFromNothing: false);
case CasteSlot.Loadout:
int id = ToLoadoutId(value);
return id >= 0 && WeaponsTab.SetLoadout(pawn, id);
default: default:
return false; return false;
} }
} }
// ---- former-caste records ----------------------------------------------------------------
/// <summary>
/// Fills a former-caste record with the pawn's own settings (the slots it can take now; policies by
/// id) and with the slots and work types of its caste where it has the caste's value. caste is null
/// for a pawn that is casteless by choice.
/// </summary>
internal static void Snapshot(Pawn pawn, Caste caste, FormerCaste record)
{
if (pawn == null || record == null)
return;
foreach (CasteSlot slot in AllSlots)
{
if (!CanUse(pawn, slot))
continue;
switch (slot)
{
case CasteSlot.Apparel: record.apparelId = pawn.outfits.CurrentApparelPolicy?.id ?? Caste.Unmanaged; break;
case CasteSlot.Food: record.foodId = pawn.foodRestriction.CurrentFoodPolicy?.id ?? Caste.Unmanaged; break;
case CasteSlot.Drug: record.drugId = pawn.drugs.CurrentPolicy?.id ?? Caste.Unmanaged; break;
case CasteSlot.Reading: record.readingId = pawn.reading.CurrentPolicy?.id ?? Caste.Unmanaged; break;
case CasteSlot.MedCare: record.medCare = (int)pawn.playerSettings.medCare; break;
case CasteSlot.Schedule: record.schedule = ScheduleSlot.Of(pawn)?.ToList(); break;
case CasteSlot.Work: record.work = WorkSlot.Of(pawn); break;
case CasteSlot.Loadout: record.loadoutId = WeaponsTab.LoadoutOf(pawn) ?? Caste.Unmanaged; break;
}
if (caste == null || !caste.IsManaged(slot) || slot == CasteSlot.Work)
continue;
if (Matches(pawn, slot, caste.GetSlot(slot)))
record.followed.Add(slot);
}
Dictionary<string, int> decided = WorkSlot.Decided(caste);
if (decided != null && CanUse(pawn, CasteSlot.Work))
{
foreach (KeyValuePair<string, int> kv in decided)
{
if (WorkSlot.Matches(pawn, kv.Key, kv.Value))
record.followedWork.Add(kv.Key);
}
}
}
/// <summary>The pawn's own value for a slot from a former-caste record, or null where the record has none or its policy is gone.</summary>
internal static object OwnValue(FormerCaste record, CasteSlot slot)
{
Game game = Current.Game;
switch (slot)
{
case CasteSlot.Apparel: return game?.outfitDatabase?.AllOutfits?.FirstOrDefault(p => p.id == record.apparelId);
case CasteSlot.Food: return game?.foodRestrictionDatabase?.AllFoodRestrictions?.FirstOrDefault(p => p.id == record.foodId);
case CasteSlot.Drug: return game?.drugPolicyDatabase?.AllPolicies?.FirstOrDefault(p => p.id == record.drugId);
case CasteSlot.Reading: return game?.readingPolicyDatabase?.AllReadingPolicies?.FirstOrDefault(p => p.id == record.readingId);
case CasteSlot.MedCare: return ToMedCare(record.medCare) < 0 ? null : (object)record.medCare;
case CasteSlot.Schedule: return record.schedule != null && record.schedule.Count == ScheduleSlot.Hours ? ScheduleSlot.Normalize(record.schedule) : null;
case CasteSlot.Loadout: return record.loadoutId >= 0 ? (object)record.loadoutId : null;
default: return null;
}
}
/// <summary>
/// Gives a returning pawn its own settings back (JoinDefaults.Restore). previous is the caste it
/// returns to (null for No caste), away the caste it got while it was gone (null when none, or the
/// same caste). A slot previous manages gets the caste's current value if the pawn followed it when
/// it left, else the pawn's own value from then. A slot only away manages, where the pawn still has
/// away's value, gets the pawn's own value from then. Everything else stays. Does nothing while the
/// "enabled" setting is off.
/// </summary>
internal static void Restore(Pawn pawn, Caste previous, Caste away, FormerCaste record)
{
if (!BlaxCastesMod.Enabled || pawn == null || record == null || GameComponent_BlaxCastes.IsGone(pawn))
return;
bool missing = false;
foreach (CasteSlot slot in AllSlots)
{
if (!CanUse(pawn, slot))
continue;
if (slot == CasteSlot.Work)
{
RestoreWork(pawn, previous, away, record);
continue;
}
object own = OwnValue(record, slot);
object target;
if (previous != null && previous.IsManaged(slot))
target = record.Followed(slot) || own == null ? previous.GetSlot(slot) : own;
else if (away != null && away.IsManaged(slot) && Matches(pawn, slot, away.GetSlot(slot)))
target = own;
else
continue;
if (target == null)
continue;
if (IsPolicySlot(slot) && slot != CasteSlot.MedCare && !PolicyExists(target as Policy))
{
missing = true;
continue;
}
if (slot == CasteSlot.Loadout && !WeaponsTab.Exists(ToLoadoutId(target)))
{
missing = true;
continue;
}
if (!Matches(pawn, slot, target))
WriteSlot(pawn, slot, target);
}
if (missing && previous != null)
CasteManager.UnmanageMissingPolicies(previous);
}
/// <summary>Restore for work priorities, type by type over the types previous or away decide (WorkSlot.Decided).</summary>
private static void RestoreWork(Pawn pawn, Caste previous, Caste away, FormerCaste record)
{
Dictionary<string, int> mine = WorkSlot.Decided(previous);
Dictionary<string, int> theirs = WorkSlot.Decided(away);
if (mine == null && theirs == null)
return;
foreach (WorkTypeDef def in DefDatabase<WorkTypeDef>.AllDefsListForReading)
{
string name = def.defName;
int own = 0;
bool hasOwn = record.work != null && record.work.TryGetValue(name, out own);
int target;
bool casteValue = false;
if (mine != null && mine.TryGetValue(name, out int value))
{
casteValue = record.FollowedWork(name) || !hasOwn;
target = casteValue ? value : own;
}
else if (theirs != null && hasOwn && theirs.TryGetValue(name, out int awayValue) && WorkSlot.Matches(pawn, name, awayValue))
{
target = own;
}
else
{
continue;
}
// With manual priorities off the game hides the stored number, so a caste value is stored even when it already reads the same.
if (!WorkSlot.Matches(pawn, name, target) || (casteValue && !WorkSlot.ManualPriorities))
WorkSlot.WriteType(pawn, name, target);
}
}
/// <summary>True if the policy is still in its game database.</summary> /// <summary>True if the policy is still in its game database.</summary>
public static bool PolicyExists(Policy policy) public static bool PolicyExists(Policy policy)
{ {
@ -175,6 +403,9 @@ namespace BlaxCastes
return v >= (int)MedicalCareCategory.NoCare && v <= (int)MedicalCareCategory.Best ? v : Caste.Unmanaged; return v >= (int)MedicalCareCategory.NoCare && v <= (int)MedicalCareCategory.Best ? v : Caste.Unmanaged;
} }
/// <summary>A loadout slot value: -1 for unmanaged, otherwise the id (never negative).</summary>
public static int ToLoadoutId(object value) => value is int i && i >= 0 ? i : Caste.Unmanaged;
/// <summary>Which slot type a value belongs in; false for a value that fits no slot.</summary> /// <summary>Which slot type a value belongs in; false for a value that fits no slot.</summary>
public static bool FitsSlot(CasteSlot slot, object value) public static bool FitsSlot(CasteSlot slot, object value)
{ {
@ -187,21 +418,48 @@ namespace BlaxCastes
case CasteSlot.Drug: return value is DrugPolicy; case CasteSlot.Drug: return value is DrugPolicy;
case CasteSlot.Reading: return value is ReadingPolicy; case CasteSlot.Reading: return value is ReadingPolicy;
case CasteSlot.MedCare: return value is int || value is MedicalCareCategory || value is byte; case CasteSlot.MedCare: return value is int || value is MedicalCareCategory || value is byte;
case CasteSlot.Schedule: return ScheduleSlot.Fits(value);
case CasteSlot.Work: return WorkSlot.Fits(value);
case CasteSlot.Loadout: return value is int;
default: return false; default: return false;
} }
} }
/// <summary>A value in the form the caste stores it: med care and loadout as int, a schedule as 24 known names, work priorities without bad entries.</summary>
public static object NormalizeSlotValue(CasteSlot slot, object value)
{
switch (slot)
{
case CasteSlot.MedCare: return ToMedCare(value);
case CasteSlot.Schedule: return ScheduleSlot.Normalize(value);
case CasteSlot.Work: return WorkSlot.Normalize(value);
case CasteSlot.Loadout: return ToLoadoutId(value);
default: return value;
}
}
public static string SlotLabel(CasteSlot slot) => ("BlaxCastes_Slot" + slot).Translate(); public static string SlotLabel(CasteSlot slot) => ("BlaxCastes_Slot" + slot).Translate();
/// <summary>A slot value as the player sees it: the policy label, the med care label, or "unmanaged".</summary> /// <summary>A slot value as the player sees it: the policy label, the med care label, a schedule or priority summary, the loadout name, or "leave alone".</summary>
public static string ValueLabel(CasteSlot slot, object value) public static string ValueLabel(CasteSlot slot, object value)
{ {
if (slot == CasteSlot.MedCare) switch (slot)
{ {
int care = ToMedCare(value); case CasteSlot.MedCare:
return care < 0 ? (string)"BlaxCastes_Unmanaged".Translate() : ((MedicalCareCategory)care).GetLabel(); int care = ToMedCare(value);
return care < 0 ? (string)"BlaxCastes_Unmanaged".Translate() : ((MedicalCareCategory)care).GetLabel();
case CasteSlot.Schedule:
return ScheduleSlot.Summary(value as IReadOnlyList<string>);
case CasteSlot.Work:
return WorkSlot.Summary(value as IReadOnlyDictionary<string, int>);
case CasteSlot.Loadout:
int id = ToLoadoutId(value);
if (id < 0)
return "BlaxCastes_Unmanaged".Translate();
return WeaponsTab.NameOf(id) ?? (string)"BlaxCastes_LoadoutUnknown".Translate(id);
default:
return value is Policy p ? p.label : (string)"BlaxCastes_Unmanaged".Translate();
} }
return value is Policy p ? p.label : (string)"BlaxCastes_Unmanaged".Translate();
} }
} }
} }

View File

@ -5,12 +5,52 @@ namespace BlaxCastes
/// <summary> /// <summary>
/// Shared mod detection. Castes has no hard dependency on any other mod and calls nothing in the /// Shared mod detection. Castes has no hard dependency on any other mod and calls nothing in the
/// sibling Blax mods; they reach Castes, never the other way round. /// sibling Blax mods; they reach Castes, never the other way round.
///
/// Package ids of other mods, each read from the mod's own About/About.xml in its public source
/// repository (checked 2026-11-29):
/// - Better Pawn Control (Workshop 1541460369): github.com/voult2/BetterPawnControl, branch master.
/// - Better Pawn Control Forked (3724294345): github.com/KyleMHB/BetterPawnControlForked, branch master.
/// - 1trickPwnyta's Defaults (3285178686, Experimental 3522445452): github.com/1trickPwnyta/DefaultsMod,
/// branches master, 1.7 and experimental (the same id on all three).
/// - Automatic Slave Outfit (2912063732): github.com/bwiggin10/RimWorld-AutomaticSlaveOutfit, branch main
/// (its About/PublishedFileId.txt is 2912063732).
/// - PrisonerDefaults (3531556159): github.com/MSWS/PrisonerDefaults, branch main (PublishedFileId.txt 3531556159).
/// - Work Tab: github.com/fluffy-mods/WorkTab, branches 1.3 and 1.4 (the master About.xml predates package ids).
/// - Free Will: github.com/paul-freeman/rimworld-freewill, branch main (About and AboutUnstable).
/// - Work Manager (2029596262): github.com/LordKuper/rimworld-workmanager, branch master.
/// - AutoPriorities: github.com/Klok-e/RimWorld_Mod_AutoPriorities, branch master.
/// - WorkRoles: github.com/Spagles/rw.workroles, branch main (mod/About/About.xml).
/// None of these mods is installed on the test machine, so detection is tested with a simulated id.
/// - [1001] Weapons Tab Reborn (Workshop 2573988660): read from the installed Workshop copy's
/// About/About.xml (checked 2026-11-29); the mod's source is github.com/papercrane1001/-1001-WeaponsTabReborn.
/// It is installed on the test machine and loaded by run-tests.ps1 -Compat.
/// </summary> /// </summary>
public static class Compat public static class Compat
{ {
public const string BlaxSlaves = "blax.slaves"; public const string BlaxSlaves = "blax.slaves";
public const string BlaxZones = "blax.zones"; public const string BlaxZones = "blax.zones";
// Mods whose join defaults overlap with Castes (see OverlapWarnings).
public const string BetterPawnControl = "VouLT.BetterPawnControl";
public const string BetterPawnControlForked = "KyleMHB.BetterPawnControlForked";
public const string Defaults1trickPwnyta = "defaults.1trickPwnyta";
public const string AutomaticSlaveOutfit = "ben.automaticslaveoutfit";
public const string PrisonerDefaults = "MSWS.PrisonerDefaults";
// Automatic work managers, for the work priorities slot.
public const string WorkTab = "Fluffy.WorkTab";
public const string FreeWill = "freemapa.freewill";
public const string FreeWillUnstable = "freemapa.freewill.unstable";
public const string WorkManager = "LordKuper.WorkManager";
public const string AutoPriorities = "LokiVKlokeNaAndoke.AutoPriorities";
public const string WorkRoles = "mnmr.workroles";
/// <summary>The work managers that reset priorities on their own, so a fixed caste priority would fight them.</summary>
public static readonly string[] WorkManagers = { WorkTab, FreeWill, FreeWillUnstable, WorkManager, AutoPriorities, WorkRoles };
/// <summary>[1001] Weapons Tab Reborn, for the weapon loadout slot (see WeaponsTab).</summary>
public const string WeaponsTab = "papercrane1001.WeaponsTab";
/// <summary> /// <summary>
/// Active by packageId, local or Steam copy. ModsConfig.IsActive misses a mod that is installed /// Active by packageId, local or Steam copy. ModsConfig.IsActive misses a mod that is installed
/// both ways (the Steam copy gets a "_steam" postfix), so nothing in Blax Castes uses it. /// both ways (the Steam copy gets a "_steam" postfix), so nothing in Blax Castes uses it.

View File

@ -1,4 +1,6 @@
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using RimWorld; using RimWorld;
using UnityEngine; using UnityEngine;
using Verse; using Verse;
@ -107,7 +109,7 @@ namespace BlaxCastes
} }
} }
/// <summary>The picker's menu: No caste, Default caste, then every caste. Public so tests can invoke entries.</summary> /// <summary>The picker's menu: No caste, Default caste, then every caste by label (the Caste column's order). Public so tests can invoke entries.</summary>
public static List<FloatMenuOption> RowMenu(string reason) public static List<FloatMenuOption> RowMenu(string reason)
{ {
var options = new List<FloatMenuOption> var options = new List<FloatMenuOption>
@ -118,7 +120,7 @@ namespace BlaxCastes
GameComponent_BlaxCastes comp = GameComponent_BlaxCastes.Instance; GameComponent_BlaxCastes comp = GameComponent_BlaxCastes.Instance;
if (comp != null) if (comp != null)
{ {
foreach (Caste caste in comp.Castes) foreach (Caste caste in comp.Castes.Where(x => x != null).OrderBy(x => x.label, StringComparer.CurrentCultureIgnoreCase).ThenBy(x => x.id))
{ {
Caste c = caste; Caste c = caste;
options.Add(new FloatMenuOption(c.label, () => CasteManager.SetJoinRow(reason, JoinRowMode.SpecificCaste, c))); options.Add(new FloatMenuOption(c.label, () => CasteManager.SetJoinRow(reason, JoinRowMode.SpecificCaste, c)));

View File

@ -1,14 +1,20 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using RimWorld; using RimWorld;
using UnityEngine; using UnityEngine;
using Verse; using Verse;
using Verse.Sound;
namespace BlaxCastes namespace BlaxCastes
{ {
/// <summary> /// <summary>
/// The caste manager, built on the vanilla policy manager: the base class draws the caste list and /// The caste manager, built on the vanilla policy manager: the base class draws the caste list and
/// handles new, duplicate, rename, delete (with its confirm) and make default. The right side has one /// handles new, duplicate, rename, delete (with its confirm) and make default. The right side scrolls:
/// row per slot: a managed checkbox, a dropdown and a pencil that opens the vanilla policy editor. /// one row per policy slot (a managed checkbox, a dropdown and a pencil that opens the vanilla policy
/// editor), the weapon loadout row while Weapons Tab Reborn is active, the schedule (a 24-hour grid
/// painted like the vanilla Schedule tab, with the vanilla time assignment selector as the brush) and
/// the work priorities (a cycle button per work type). Below the scroll area sit the member count and
/// "Apply to all members"; "Assign by status" sits left of the close button. Both ask first.
/// Every change goes through CasteManager, so member sync and the delete rules always apply. /// Every change goes through CasteManager, so member sync and the delete rules always apply.
/// The base layout changed in 1.6, so DoContentsRect only draws inside the rect it is given. /// The base layout changed in 1.6, so DoContentsRect only draws inside the rect it is given.
/// </summary> /// </summary>
@ -19,10 +25,30 @@ namespace BlaxCastes
private const float SlotLabelWidth = 110f; private const float SlotLabelWidth = 110f;
private const float IconSize = 24f; private const float IconSize = 24f;
private const float Gap = 8f; private const float Gap = 8f;
private const float AssignByStatusWidth = 200f;
private const float CreateButtonWidth = 180f;
private const float FooterHeight = 30f;
private const float ScrollBarWidth = 16f;
private const float ValueX = SlotLabelWidth + IconSize + Gap;
private const float SmallButtonHeight = 26f;
private const float MinBrushWidth = 64f;
private const float MaxBrushWidth = 96f;
private const float BrushHeight = 28f;
private const float HourLabelHeight = 16f;
private const float HourCellHeight = 24f;
private const int WorkColumns = 3;
private const float WorkRowHeight = 26f;
private const float WorkButtonWidth = 44f;
private static readonly List<Caste> NoCastes = new List<Caste>(); private static readonly List<Caste> NoCastes = new List<Caste>();
private static Texture2D[] medCareIcons; private static Texture2D[] medCareIcons;
private Vector2 scrollPosition;
private float contentHeight = 600f;
private readonly WorkCycle workCycle = new WorkCycle();
public Dialog_ManageCastes() : this(null) public Dialog_ManageCastes() : this(null)
{ {
} }
@ -36,7 +62,7 @@ namespace BlaxCastes
protected override string TipKey => "BlaxCastes_ManageCastesTip"; protected override string TipKey => "BlaxCastes_ManageCastesTip";
public override Vector2 InitialSize => new Vector2(700f, 540f); public override Vector2 InitialSize => new Vector2(860f, 700f);
private static GameComponent_BlaxCastes Comp => GameComponent_BlaxCastes.Instance; private static GameComponent_BlaxCastes Comp => GameComponent_BlaxCastes.Instance;
@ -44,12 +70,60 @@ namespace BlaxCastes
{ {
GameComponent_BlaxCastes comp = Comp; GameComponent_BlaxCastes comp = Comp;
// A policy deleted in a vanilla editor opened from here must not stay in a caste slot. // A policy deleted in a vanilla editor opened from here must not stay in a caste slot.
CasteManager.CheckPolicies(comp); CasteManager.CheckSlots(comp);
if (SelectedPolicy != null && (comp == null || !comp.HasCaste(SelectedPolicy))) if (SelectedPolicy != null && (comp == null || !comp.HasCaste(SelectedPolicy)))
SelectedPolicy = null; SelectedPolicy = null;
base.DoWindowContents(inRect); base.DoWindowContents(inRect);
DoMakeDefaultTip(inRect);
DoAssignByStatusButton(inRect);
} }
/// <summary>
/// The base class gives "Make default" the vanilla tooltip about new colonists. Over the same
/// button, that tip is cleared and replaced by one about Default caste rows.
/// </summary>
private void DoMakeDefaultTip(Rect inRect)
{
if (SelectedPolicy == null || GetDefaultPolicy() == SelectedPolicy)
return;
Rect button = MakeDefaultButtonRect(inRect);
if (!Mouse.IsOver(button))
return;
TooltipHandler.ClearTooltipsFrom(button);
TooltipHandler.TipRegion(button, "BlaxCastes_MakeDefaultTip".Translate());
}
/// <summary>Where the base class draws "Make default": the fourth 32 px button from the right, below title and tip.</summary>
public static Rect MakeDefaultButtonRect(Rect inRect) => new Rect(inRect.xMax - 32f - 3 * 42f, inRect.y + 74f, 32f, 32f);
/// <summary>
/// "Assign by status", left of the close button. Shown only while there are pawns without a caste
/// record whose status row gives them a caste. It replaces those pawns' own policies with their
/// caste's, which cannot be undone, so it asks first, like "Apply to all members".
/// </summary>
private static void DoAssignByStatusButton(Rect inRect)
{
if (Comp == null)
return;
int count = CasteManager.PawnsToAssignByStatus().Count;
if (count == 0)
return;
var button = new Rect(inRect.x, inRect.yMax - CloseButSize.y, AssignByStatusWidth, CloseButSize.y);
if (Widgets.ButtonText(button, "BlaxCastes_AssignByStatus".Translate(count)))
{
Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation(AssignByStatusConfirmText(count), () =>
{
int assigned = CasteManager.AssignByStatus();
Messages.Message("BlaxCastes_AssignByStatusDone".Translate(assigned), MessageTypeDefOf.NeutralEvent, historical: false);
}, destructive: true));
}
TooltipHandler.TipRegion(button, "BlaxCastes_AssignByStatusTip".Translate(count));
}
/// <summary>The confirm text for "Assign by status", naming the pawn count.</summary>
public static string AssignByStatusConfirmText(int count) =>
"BlaxCastes_AssignByStatusConfirm".Translate(count.Named("COUNT"));
// ---- base class hooks ------------------------------------------------------------------ // ---- base class hooks ------------------------------------------------------------------
/// <summary>A new caste with the next free id, labelled "Caste N", managing nothing.</summary> /// <summary>A new caste with the next free id, labelled "Caste N", managing nothing.</summary>
@ -74,23 +148,97 @@ namespace BlaxCastes
Caste caste = SelectedPolicy; Caste caste = SelectedPolicy;
if (caste == null) if (caste == null)
return; return;
float y = rect.y; var footer = new Rect(rect.x, rect.yMax - FooterHeight, rect.width, FooterHeight);
foreach (CasteSlot slot in CasteUtility.AllSlots) var outRect = new Rect(rect.x, rect.y, rect.width, footer.y - Gap - rect.y);
var viewRect = new Rect(0f, 0f, outRect.width - ScrollBarWidth, Mathf.Max(contentHeight, outRect.height));
Widgets.BeginScrollView(outRect, ref scrollPosition, viewRect);
contentHeight = DoSlots(viewRect.width, caste, workCycle);
Widgets.EndScrollView();
DoFooter(footer, caste, workCycle);
}
/// <summary>Draws every slot from the top of the scroll view; returns the height used.</summary>
private static float DoSlots(float width, Caste caste, WorkCycle cycle)
{
float y = 0f;
foreach (CasteSlot slot in CasteUtility.PolicySlots)
{ {
DoSlotRow(new Rect(rect.x, y, rect.width, RowHeight), caste, slot); DoSlotRow(new Rect(0f, y, width, RowHeight), caste, slot, active: true, note: null);
y += RowHeight + RowGap; y += RowHeight + RowGap;
} }
y += Gap; if (!caste.IsManaged(CasteSlot.Apparel) && StarterCastes.CanCreateSlaveOutfit)
if (y < rect.yMax)
{ {
using (new TextBlock(GameFont.Tiny, Color.gray)) var create = new Rect(ValueX, y, CreateButtonWidth, FooterHeight - 4f);
Widgets.Label(new Rect(rect.x, y, rect.width, rect.yMax - y), "BlaxCastes_ManagerHint".Translate()); if (Widgets.ButtonText(create, "BlaxCastes_CreateSlaveOutfit".Translate()))
{
ApparelPolicy outfit = StarterCastes.CreateSlaveOutfit();
if (outfit != null)
CasteManager.SetSlot(caste, CasteSlot.Apparel, outfit);
}
TooltipHandler.TipRegion(create, "BlaxCastes_CreateSlaveOutfitTip".Translate());
y += FooterHeight + 2f;
}
if (StarterCastes.IsSlaveOutfit(caste.ApparelPolicy))
y = DoNote(width, y, "BlaxCastes_SlaveOutfitCold".Translate(), ColorLibrary.Gold);
if (ShowsLoadoutRow)
y = DoLoadoutRow(width, y, caste);
y += Gap;
y = DoSchedule(width, y, caste);
y += Gap * 2f;
y = DoWork(width, y, caste, cycle);
y += Gap * 2f;
y = DoNote(width, y, "BlaxCastes_ManagerHint".Translate(), Color.gray);
return y;
}
/// <summary>A Tiny label across the width; returns the y below it.</summary>
private static float DoNote(float width, float y, string text, Color color)
{
using (new TextBlock(GameFont.Tiny, color))
{
float h = Text.CalcHeight(text, width);
Widgets.Label(new Rect(0f, y, width, h), text);
return y + h + 4f;
} }
} }
// ---- slot rows ----------------------------------------------------------------------- /// <summary>The member count and "Apply to all members", which asks first, naming the count.</summary>
private static void DoFooter(Rect footer, Caste caste, WorkCycle cycle)
{
List<Pawn> members = CasteManager.LiveMembers(caste);
const float buttonWidth = 180f;
var button = new Rect(footer.xMax - buttonWidth, footer.y, buttonWidth, footer.height);
var label = new Rect(footer.x, footer.y, button.x - footer.x - Gap, footer.height);
using (new TextBlock(TextAnchor.MiddleLeft))
Widgets.Label(label, "BlaxCastes_MemberCount".Translate(members.Count));
if (members.Count == 0 || !caste.AnyManaged())
return;
if (Widgets.ButtonText(button, "BlaxCastes_ApplyToAll".Translate()))
{
Caste local = caste;
Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation(
ApplyToAllConfirmText(local, members.Count),
() =>
{
CasteManager.ApplyToAll(local);
cycle.End(); // every member follows again, so the next click takes the followers anew
},
destructive: true));
}
TooltipHandler.TipRegion(button, "BlaxCastes_ApplyToAllTip".Translate());
}
private static void DoSlotRow(Rect row, Caste caste, CasteSlot slot) /// <summary>The confirm text for "Apply to all members", naming the caste and the member count.</summary>
public static string ApplyToAllConfirmText(Caste caste, int count) =>
"BlaxCastes_ApplyToAllConfirm".Translate(caste.label.Named("CASTE"), count.Named("COUNT"));
// ---- policy, medical care and loadout rows -------------------------------------------
/// <summary>
/// One row: label, managed checkbox, dropdown and (for policies) the pencil. Inactive: greyed out,
/// with the note as tooltip, and nothing can be changed.
/// </summary>
private static void DoSlotRow(Rect row, Caste caste, CasteSlot slot, bool active, string note)
{ {
float iconY = row.y + (row.height - IconSize) / 2f; float iconY = row.y + (row.height - IconSize) / 2f;
Rect labelRect = new Rect(row.x, row.y, SlotLabelWidth, row.height); Rect labelRect = new Rect(row.x, row.y, SlotLabelWidth, row.height);
@ -102,28 +250,58 @@ namespace BlaxCastes
if (Mouse.IsOver(row)) if (Mouse.IsOver(row))
Widgets.DrawHighlight(row); Widgets.DrawHighlight(row);
using (new TextBlock(TextAnchor.MiddleLeft)) using (new TextBlock(TextAnchor.MiddleLeft, active ? Color.white : Color.gray))
Widgets.Label(labelRect, CasteUtility.SlotLabel(slot).Truncate(labelRect.width)); Widgets.Label(labelRect, CasteUtility.SlotLabel(slot).Truncate(labelRect.width));
bool managed = caste.IsManaged(slot); bool managed = caste.IsManaged(slot);
bool wasManaged = managed; bool wasManaged = managed;
Widgets.Checkbox(checkRect.x, checkRect.y, ref managed, IconSize); Widgets.Checkbox(checkRect.x, checkRect.y, ref managed, IconSize, disabled: !active);
TooltipHandler.TipRegion(checkRect, "BlaxCastes_ManagedTip".Translate()); TooltipHandler.TipRegion(checkRect, "BlaxCastes_ManagedTip".Translate());
if (managed != wasManaged) if (active && managed != wasManaged)
SetManaged(caste, slot, managed); SetManaged(caste, slot, managed);
string valueLabel = CasteUtility.ValueLabel(slot, caste.GetSlot(slot)).CapitalizeFirst(); string valueLabel = CasteUtility.ValueLabel(slot, caste.GetSlot(slot)).CapitalizeFirst();
if (slot == CasteSlot.MedCare) if (!active)
{ {
Widgets.Dropdown(dropRect, caste, c => c.MedCare, c => MedCareMenu(c), valueLabel.Truncate(dropRect.width)); using (new TextBlock(TextAnchor.MiddleLeft, Color.gray))
Widgets.Label(dropRect, valueLabel.Truncate(dropRect.width));
if (!note.NullOrEmpty())
TooltipHandler.TipRegion(row, note);
return; return;
} }
switch (slot)
{
case CasteSlot.MedCare:
Widgets.Dropdown(dropRect, caste, c => c.MedCare, c => MedCareMenu(c), valueLabel.Truncate(dropRect.width));
return;
case CasteSlot.Loadout:
Widgets.Dropdown(dropRect, caste, c => c.LoadoutId, c => LoadoutMenu(c), valueLabel.Truncate(dropRect.width));
TooltipHandler.TipRegion(row, "BlaxCastes_LoadoutTip".Translate());
return;
}
Widgets.Dropdown(dropRect, caste, c => c.GetSlot(slot) as Policy, c => PolicyMenu(c, slot), valueLabel.Truncate(dropRect.width)); Widgets.Dropdown(dropRect, caste, c => c.GetSlot(slot) as Policy, c => PolicyMenu(c, slot), valueLabel.Truncate(dropRect.width));
if (Widgets.ButtonImage(pencilRect, TexButton.Rename, tooltip: EditorTip(slot))) if (Widgets.ButtonImage(pencilRect, TexButton.Rename, tooltip: EditorTip(slot)))
OpenPolicyEditor(slot, caste.GetSlot(slot) as Policy); OpenPolicyEditor(slot, caste.GetSlot(slot) as Policy);
} }
/// <summary>The loadout row is shown only while Weapons Tab Reborn is active.</summary>
public static bool ShowsLoadoutRow => WeaponsTab.ModActive;
/// <summary>The loadout row, greyed out while the setting is off or the mod's API could not be used.</summary>
private static float DoLoadoutRow(float width, float y, Caste caste)
{
string note = null;
if (!WeaponsTab.Available)
note = "BlaxCastes_LoadoutUnavailable".Translate();
else if (!WeaponsTab.SettingOn)
note = "BlaxCastes_LoadoutSettingOff".Translate();
DoSlotRow(new Rect(0f, y, width, RowHeight), caste, CasteSlot.Loadout, note == null, note);
y += RowHeight + RowGap;
if (note != null)
y = DoNote(width, y, note, Color.gray);
return y;
}
/// <summary>The vanilla Assign tab's "Manage ... policies" text for the slot's editor.</summary> /// <summary>The vanilla Assign tab's "Manage ... policies" text for the slot's editor.</summary>
private static string EditorTip(CasteSlot slot) private static string EditorTip(CasteSlot slot)
{ {
@ -173,6 +351,24 @@ namespace BlaxCastes
} }
} }
private static IEnumerable<Widgets.DropdownMenuElement<int>> LoadoutMenu(Caste caste)
{
yield return new Widgets.DropdownMenuElement<int>
{
option = new FloatMenuOption("BlaxCastes_Unmanaged".Translate(), () => CasteManager.SetSlot(caste, CasteSlot.Loadout, Caste.Unmanaged)),
payload = Caste.Unmanaged,
};
foreach (KeyValuePair<int, string> loadout in WeaponsTab.Loadouts())
{
int id = loadout.Key;
yield return new Widgets.DropdownMenuElement<int>
{
option = new FloatMenuOption(loadout.Value, () => CasteManager.SetSlot(caste, CasteSlot.Loadout, id)),
payload = id,
};
}
}
/// <summary>The same icons the vanilla medical care button uses. Loaded on first draw.</summary> /// <summary>The same icons the vanilla medical care button uses. Loaded on first draw.</summary>
private static Texture2D MedCareIcon(MedicalCareCategory care) private static Texture2D MedCareIcon(MedicalCareCategory care)
{ {
@ -210,9 +406,246 @@ namespace BlaxCastes
} }
} }
// ---- schedule ----------------------------------------------------------------------------
/// <summary>
/// The schedule: the vanilla time assignment selector picks the brush; click or drag over the 24
/// cells to paint, the way the vanilla Schedule tab works. While the caste leaves the schedule
/// alone, the cells show the game's starting schedule faded, and painting one starts from it.
/// </summary>
private static float DoSchedule(float width, float y, Caste caste)
{
bool managed = caste.IsManaged(CasteSlot.Schedule);
using (new TextBlock(TextAnchor.MiddleLeft))
Widgets.Label(new Rect(0f, y, SlotLabelWidth, BrushHeight), CasteUtility.SlotLabel(CasteSlot.Schedule));
// The vanilla selector draws one row of brushes in the top half of its rect, each half as wide as the rect.
float brushWidth = BrushWidthFor(width);
TimeAssignmentSelector.DrawTimeAssignmentSelectorGrid(new Rect(ValueX, y, brushWidth * 2f, BrushHeight * 2f + 2f));
y += BrushHeight + 4f;
float cellWidth = (width - ValueX) / ScheduleSlot.Hours;
using (new TextBlock(GameFont.Tiny, TextAnchor.LowerCenter))
{
for (int hour = 0; hour < ScheduleSlot.Hours; hour++)
Widgets.Label(new Rect(ValueX + hour * cellWidth, y, cellWidth, HourLabelHeight), hour.ToString());
}
y += HourLabelHeight;
IReadOnlyList<string> names = caste.Schedule ?? ScheduleSlot.Default();
bool mouseDown = Input.GetMouseButton(0);
TimeAssignmentDef brush = TimeAssignmentSelector.selectedAssignment;
var grid = new Rect(ValueX, y, cellWidth * ScheduleSlot.Hours, HourCellHeight);
for (int hour = 0; hour < ScheduleSlot.Hours; hour++)
{
Rect cell = new Rect(ValueX + hour * cellWidth, y, cellWidth, HourCellHeight).ContractedBy(1f);
TimeAssignmentDef def = ScheduleSlot.Resolve(names[hour]);
GUI.color = managed ? Color.white : new Color(1f, 1f, 1f, 0.35f);
GUI.DrawTexture(cell, def.ColorTexture);
GUI.color = Color.white;
if (!mouseDown)
MouseoverSounds.DoRegion(cell);
if (!Mouse.IsOver(cell))
continue;
Widgets.DrawBox(cell, 2);
if (mouseDown && brush != null && (def != brush || !managed))
{
PaintHour(caste, hour, brush);
SoundDefOf.Designate_DragStandard_Changed_NoCam.PlayOneShotOnCamera();
}
}
TooltipHandler.TipRegion(grid, managed ? "BlaxCastes_ScheduleTip".Translate() : "BlaxCastes_ScheduleUnmanagedTip".Translate());
y += HourCellHeight + 4f;
var copy = new Rect(ValueX, y, 150f, SmallButtonHeight);
if (Widgets.ButtonText(copy, "BlaxCastes_ScheduleCopyFromPawn".Translate()))
Find.WindowStack.Add(new FloatMenu(CopyFromPawnOptions(caste)));
TooltipHandler.TipRegion(copy, "BlaxCastes_ScheduleCopyFromPawnTip".Translate());
var leave = new Rect(copy.xMax + Gap, y, 120f, SmallButtonHeight);
if (Widgets.ButtonText(leave, "BlaxCastes_Unmanaged".Translate(), active: managed) && managed)
CasteManager.SetSlot(caste, CasteSlot.Schedule, null);
TooltipHandler.TipRegion(leave, "BlaxCastes_ScheduleLeaveAloneTip".Translate());
return y + SmallButtonHeight;
}
/// <summary>
/// The width of one schedule brush: the row's width shared by the brushes (four, five with Royalty),
/// between 64 and 96 px. The vanilla Schedule tab gives each about 92 px; 64 is too narrow for
/// "Recreation" in the Small font.
/// </summary>
public static float BrushWidthFor(float width)
{
int brushes = ModsConfig.RoyaltyActive ? 5 : 4;
return Mathf.Clamp((width - ValueX) / brushes, MinBrushWidth, MaxBrushWidth);
}
private static List<FloatMenuOption> CopyFromPawnOptions(Caste caste)
{
var options = new List<FloatMenuOption>();
foreach (Pawn pawn in SchedulePawns())
{
Pawn local = pawn;
options.Add(new FloatMenuOption(local.LabelShortCap, () => CopyScheduleFrom(caste, local)));
}
if (options.Count == 0)
options.Add(new FloatMenuOption("BlaxCastes_ScheduleNoPawns".Translate(), null));
return options;
}
/// <summary>The pawns "Copy from pawn" lists: colonists and slaves of the player that have a schedule, by name.</summary>
public static List<Pawn> SchedulePawns()
{
if (Current.Game == null)
return new List<Pawn>();
return PawnsFinder.AllMapsCaravansAndTravellingTransporters_Alive_OfPlayerFaction
.Where(p => p.RaceProps != null && p.RaceProps.Humanlike && !p.IsPrisoner && ScheduleSlot.HasTimetable(p))
.OrderBy(p => p.LabelShort)
.ToList();
}
/// <summary>"Copy from pawn": the caste takes the pawn's 24 hours; members follow. Returns how many moved.</summary>
public static int CopyScheduleFrom(Caste caste, Pawn pawn)
{
string[] names = ScheduleSlot.Of(pawn);
return caste == null || names == null ? 0 : CasteManager.SetSlot(caste, CasteSlot.Schedule, names);
}
/// <summary>
/// Paints one hour. A caste that left the schedule alone starts from the game's starting schedule.
/// Members follow, hour by hour. Returns how many moved.
/// </summary>
public static int PaintHour(Caste caste, int hour, TimeAssignmentDef def)
{
if (caste == null || def == null || hour < 0 || hour >= ScheduleSlot.Hours)
return 0;
List<string> names = caste.Schedule?.ToList() ?? ScheduleSlot.Default();
names[hour] = def.defName;
return CasteManager.SetSlot(caste, CasteSlot.Schedule, names);
}
// ---- work priorities ---------------------------------------------------------------------
/// <summary>
/// The work priorities: "Start from nothing" and a cycle button per work type (leave alone, 1, 2,
/// 3, 4, off). Greyed out with a note while the setting is off or an automatic work manager is active.
/// </summary>
private static float DoWork(float width, float y, Caste caste, WorkCycle cycle)
{
bool active = WorkSlot.Active;
using (new TextBlock(TextAnchor.MiddleLeft, active ? Color.white : Color.gray))
Widgets.Label(new Rect(0f, y, SlotLabelWidth, RowHeight - 4f), CasteUtility.SlotLabel(CasteSlot.Work));
var startRect = new Rect(ValueX, y + 2f, Mathf.Min(260f, width - ValueX), IconSize);
bool start = caste.WorkStartFromNothing;
bool wasStart = start;
Widgets.CheckboxLabeled(startRect, "BlaxCastes_WorkStartFromNothing".Translate(), ref start, disabled: !active, placeCheckboxNearText: true);
if (active && start != wasStart)
CasteManager.SetWorkStartFromNothing(caste, start);
TooltipHandler.TipRegion(startRect, () => StartFromNothingTip(), 0x5F3A21);
y += RowHeight - 2f;
string note = WorkNote();
if (note != null)
y = DoNote(width, y, note, active ? Color.gray : ColorLibrary.Gold);
List<WorkTypeDef> types = WorkSlot.Types();
float columnWidth = width / WorkColumns;
for (int i = 0; i < types.Count; i++)
{
WorkTypeDef def = types[i];
var cell = new Rect((i % WorkColumns) * columnWidth, y + (i / WorkColumns) * WorkRowHeight, columnWidth - Gap, WorkRowHeight - 2f);
var button = new Rect(cell.xMax - WorkButtonWidth, cell.y, WorkButtonWidth, cell.height);
var label = new Rect(cell.x + 4f, cell.y, button.x - cell.x - 6f, cell.height);
int? priority = caste.WorkPriorityOf(def.defName);
if (Mouse.IsOver(cell))
Widgets.DrawHighlight(cell);
using (new TextBlock(TextAnchor.MiddleLeft, active && priority != null ? Color.white : Color.gray))
Widgets.Label(label, WorkSlot.TypeLabel(def).Truncate(label.width));
if (active)
{
if (Widgets.ButtonText(button, WorkSlot.PriorityLabel(priority)))
cycle.Click(caste, def);
}
else
{
using (new TextBlock(TextAnchor.MiddleCenter, Color.gray))
Widgets.Label(button, WorkSlot.PriorityLabel(priority));
}
if (Mouse.IsOver(cell))
{
WorkTypeDef local = def;
TooltipHandler.TipRegion(cell, () => "BlaxCastes_WorkTypeTip".Translate(
(local.gerundLabel ?? local.label).CapitalizeFirst().Named("WORK"), (local.description ?? "").Named("DESC")), local.index ^ 0x3A71C4);
}
}
int rows = (types.Count + WorkColumns - 1) / WorkColumns;
return y + rows * WorkRowHeight;
}
/// <summary>The line under the work priorities heading, or null: setting off, a work manager, or manual priorities off.</summary>
public static string WorkNote()
{
if (!WorkSlot.SettingOn)
return "BlaxCastes_WorkSettingOff".Translate();
string manager = WorkSlot.ActiveManager();
if (manager != null)
return "BlaxCastes_WorkManagerActive".Translate(manager);
if (!WorkSlot.ManualPriorities)
return "BlaxCastes_WorkManualOff".Translate();
return null;
}
/// <summary>The tooltip of "Start from nothing", naming the work types it keeps (Patient and Bed rest).</summary>
public static string StartFromNothingTip()
{
string kept = WorkSlot.SelfCareTypes().Select(t => WorkSlot.TypeLabel(t)).ToCommaList(useAnd: true);
return "BlaxCastes_WorkStartFromNothingTip".Translate(kept.Named("KEPT"));
}
/// <summary>One click on a cycle button, with no clicks before it: members that follow the type move. Returns how many moved.</summary>
public static int CycleWork(Caste caste, WorkTypeDef def, bool forward = true) => new WorkCycle().Click(caste, def, forward);
/// <summary>
/// A run of clicks on one work type's cycle button (leave alone, 1, 2, 3, 4, off, leave alone). The
/// members that follow the type are taken before the first click, and every click of the run moves
/// only them. Stepping 3, 4, off, leave alone, 1 to reach 1 therefore never picks up a pawn set to 4
/// or off by hand on the way. A click on another type or caste, a change to the type from anywhere
/// else, "Apply to all members" or closing the window starts a new run. Each window has its own.
/// </summary>
public sealed class WorkCycle
{
private Caste caste;
private string defName;
private int? lastValue;
private List<Pawn> followers;
/// <summary>Cycles the type one step and moves the run's followers. Returns how many moved.</summary>
public int Click(Caste target, WorkTypeDef def, bool forward = true)
{
if (target == null || def == null)
return 0;
int? current = target.WorkPriorityOf(def.defName);
if (followers == null || caste != target || defName != def.defName || lastValue != current)
{
caste = target;
defName = def.defName;
followers = CasteManager.WorkFollowers(target, def.defName);
}
int? next = forward ? WorkSlot.Next(current) : WorkSlot.Previous(current);
lastValue = next;
return CasteManager.SetWorkPriority(target, def.defName, next, followers);
}
/// <summary>Ends the run: the next click takes the followers anew.</summary>
public void End()
{
caste = null;
defName = null;
followers = null;
}
}
// ---- helpers the rows use; public so the tests can drive them -------------------------- // ---- helpers the rows use; public so the tests can drive them --------------------------
/// <summary>The game's policies that fit a slot, in database order. Empty for MedCare.</summary> /// <summary>The game's policies that fit a slot, in database order. Empty for the other slots.</summary>
public static IEnumerable<Policy> PoliciesFor(CasteSlot slot) public static IEnumerable<Policy> PoliciesFor(CasteSlot slot)
{ {
Game game = Current.Game; Game game = Current.Game;
@ -237,8 +670,9 @@ namespace BlaxCastes
} }
/// <summary> /// <summary>
/// What ticking the managed box sets: the database's default policy, or the colonist default /// What ticking the managed box sets: the database's default policy, the colonist default medical
/// medical care. Null when no game is loaded. /// care, the game's starting schedule or Weapons Tab Reborn's default loadout. Null when no game is
/// loaded, and for work priorities, which are set type by type.
/// </summary> /// </summary>
public static object DefaultValue(CasteSlot slot) public static object DefaultValue(CasteSlot slot)
{ {
@ -252,6 +686,8 @@ namespace BlaxCastes
case CasteSlot.Drug: return game.drugPolicyDatabase?.DefaultDrugPolicy(); case CasteSlot.Drug: return game.drugPolicyDatabase?.DefaultDrugPolicy();
case CasteSlot.Reading: return game.readingPolicyDatabase?.DefaultReadingPolicy(); case CasteSlot.Reading: return game.readingPolicyDatabase?.DefaultReadingPolicy();
case CasteSlot.MedCare: return (int)(game.playSettings?.defaultCareForColonist ?? MedicalCareCategory.Best); case CasteSlot.MedCare: return (int)(game.playSettings?.defaultCareForColonist ?? MedicalCareCategory.Best);
case CasteSlot.Schedule: return ScheduleSlot.Default();
case CasteSlot.Loadout: return WeaponsTab.DefaultLoadoutId();
default: return null; default: return null;
} }
} }
@ -264,7 +700,10 @@ namespace BlaxCastes
{ {
if (caste == null || caste.IsManaged(slot) == managed) if (caste == null || caste.IsManaged(slot) == managed)
return 0; return 0;
return CasteManager.SetSlot(caste, slot, managed ? DefaultValue(slot) : null); if (!managed)
return CasteManager.SetSlot(caste, slot, null);
object value = DefaultValue(slot);
return value == null ? 0 : CasteManager.SetSlot(caste, slot, value);
} }
// ---- first-load message ---------------------------------------------------------------- // ---- first-load message ----------------------------------------------------------------

View File

@ -6,10 +6,12 @@ using Verse;
namespace BlaxCastes namespace BlaxCastes
{ {
/// <summary> /// <summary>
/// All Blax Castes state for one game: the castes, the default caste, the memberships, the join rows /// All Blax Castes state for one game: the castes, the default caste, the memberships, the join rows,
/// and the join queue. Nothing is stored on vanilla objects; the only vanilla data Castes writes is a /// the join queue and the former-caste records. Nothing is stored on vanilla objects; the only vanilla
/// pawn's own policy fields. Read through the properties; change through CasteManager. /// data Castes writes is a pawn's own policy fields, medical care, timetable and work priorities, plus
/// Added to a running save by Game.ExposeData (FillComponents), so adding the mod mid-save works. /// its Weapons Tab Reborn loadout through that mod's API. Read through the properties; change through
/// CasteManager. Added to a running save by Game.ExposeData (FillComponents), so adding the mod
/// mid-save works.
/// </summary> /// </summary>
public class GameComponent_BlaxCastes : GameComponent public class GameComponent_BlaxCastes : GameComponent
{ {
@ -21,13 +23,23 @@ namespace BlaxCastes
private Dictionary<Pawn, CasteMembership> memberships = new Dictionary<Pawn, CasteMembership>(); private Dictionary<Pawn, CasteMembership> memberships = new Dictionary<Pawn, CasteMembership>();
private List<JoinRow> joinRows = new List<JoinRow>(); private List<JoinRow> joinRows = new List<JoinRow>();
private List<QueuedJoin> joinQueue = new List<QueuedJoin>(); private List<QueuedJoin> joinQueue = new List<QueuedJoin>();
private Dictionary<string, FormerCaste> formerCastes = new Dictionary<string, FormerCaste>();
private bool firstLoadMessageShown; private bool firstLoadMessageShown;
private bool starterCastesSeeded;
private List<string> overlapWarned = new List<string>();
// Pawns that left the player side, checked on the next tick. Not saved: the 2500-tick sweep ends
// any membership a save cut short. Held here so it goes away with the game.
private readonly HashSet<Pawn> leftPawns = new HashSet<Pawn>();
private List<Pawn> membershipKeys; private List<Pawn> membershipKeys;
private List<CasteMembership> membershipValues; private List<CasteMembership> membershipValues;
private List<string> formerKeys;
private List<FormerCaste> formerValues;
private static GameComponent_BlaxCastes cached; // Weak, so the main menu never keeps the last game and its pawns alive.
private static Game cachedGame; private static readonly System.WeakReference<GameComponent_BlaxCastes> cached = new System.WeakReference<GameComponent_BlaxCastes>(null);
private static readonly System.WeakReference<Game> cachedGame = new System.WeakReference<Game>(null);
private static bool tickErrorLogged; private static bool tickErrorLogged;
public GameComponent_BlaxCastes() public GameComponent_BlaxCastes()
@ -35,8 +47,11 @@ namespace BlaxCastes
EnsureRows(); EnsureRows();
} }
/// <summary>Called by the game for a new game and for a loaded one, before anything of the save is read.</summary>
public GameComponent_BlaxCastes(Game game) : this() public GameComponent_BlaxCastes(Game game) : this()
{ {
// A Weapons Tab Reborn call that failed in the last game is tried again in this one.
WeaponsTab.ResetForGame();
} }
/// <summary>The component of the running game, or null when no game is loaded.</summary> /// <summary>The component of the running game, or null when no game is loaded.</summary>
@ -46,24 +61,22 @@ namespace BlaxCastes
{ {
Game game = Current.Game; Game game = Current.Game;
if (game == null) if (game == null)
{
// Don't keep the last game alive from the main menu.
cached = null;
cachedGame = null;
return null; return null;
} if (cachedGame.TryGetTarget(out Game g) && g == game && cached.TryGetTarget(out GameComponent_BlaxCastes c) && c != null)
if (cachedGame == game && cached != null) return c;
return cached;
GameComponent_BlaxCastes found = game.GetComponent<GameComponent_BlaxCastes>(); GameComponent_BlaxCastes found = game.GetComponent<GameComponent_BlaxCastes>();
if (found != null) if (found != null)
{ Remember(found, game);
cached = found;
cachedGame = game;
}
return found; return found;
} }
} }
private static void Remember(GameComponent_BlaxCastes comp, Game game)
{
cached.SetTarget(comp);
cachedGame.SetTarget(game);
}
/// <summary>The castes in display order. Do not change the list; use CasteManager.</summary> /// <summary>The castes in display order. Do not change the list; use CasteManager.</summary>
public List<Caste> Castes => castes; public List<Caste> Castes => castes;
@ -77,11 +90,20 @@ namespace BlaxCastes
/// <summary>Joins waiting for the next tick. Owned by JoinDefaults.</summary> /// <summary>Joins waiting for the next tick. Owned by JoinDefaults.</summary>
public List<QueuedJoin> JoinQueue => joinQueue; public List<QueuedJoin> JoinQueue => joinQueue;
/// <summary>Former-caste records by ThingID. Read here; written through CasteManager and JoinDefaults.</summary>
public IReadOnlyDictionary<string, FormerCaste> FormerCastes => formerCastes;
/// <summary>Pawns that left the player side since the last tick. Owned by JoinDefaults.</summary>
internal HashSet<Pawn> LeftPawns => leftPawns;
public int NextCasteId => nextCasteId; public int NextCasteId => nextCasteId;
/// <summary>The message that points to Assign > Manage castes was posted in this save.</summary> /// <summary>The message that points to Assign > Manage castes was posted in this save.</summary>
public bool FirstLoadMessageShown => firstLoadMessageShown; public bool FirstLoadMessageShown => firstLoadMessageShown;
/// <summary>The starter castes were added to this save (or the save already had castes when it was checked).</summary>
public bool StarterCastesSeeded => starterCastesSeeded;
// ---- lookups ----------------------------------------------------------------------- // ---- lookups -----------------------------------------------------------------------
public CasteMembership MembershipOf(Pawn pawn) public CasteMembership MembershipOf(Pawn pawn)
@ -110,6 +132,25 @@ namespace BlaxCastes
public bool HasCaste(Caste caste) => caste != null && castes.Contains(caste); public bool HasCaste(Caste caste) => caste != null && castes.Contains(caste);
public Caste CasteById(int id)
{
for (int i = 0; i < castes.Count; i++)
{
if (castes[i] != null && castes[i].id == id)
return castes[i];
}
return null;
}
/// <summary>The pawn's former-caste record, or null.</summary>
public FormerCaste FormerOf(Pawn pawn)
{
if (pawn == null)
return null;
formerCastes.TryGetValue(pawn.ThingID, out FormerCaste f);
return f;
}
/// <summary>The row for a join reason, created at No caste if the save has none yet.</summary> /// <summary>The row for a join reason, created at No caste if the save has none yet.</summary>
public JoinRow GetRow(string reason) public JoinRow GetRow(string reason)
{ {
@ -138,7 +179,16 @@ namespace BlaxCastes
} }
} }
// ---- writes, for CasteManager only ------------------------------------------------ public bool OverlapWarned(string packageId) => overlapWarned.Contains(packageId.ToLowerInvariant());
internal void MarkOverlapWarned(string packageId)
{
string id = packageId.ToLowerInvariant();
if (!overlapWarned.Contains(id))
overlapWarned.Add(id);
}
// ---- writes, for CasteManager and JoinDefaults only --------------------------------
internal int TakeNextId() internal int TakeNextId()
{ {
@ -170,12 +220,25 @@ namespace BlaxCastes
row.caste = mode == JoinRowMode.SpecificCaste ? caste : null; row.caste = mode == JoinRowMode.SpecificCaste ? caste : null;
} }
internal void SetFormer(Pawn pawn, FormerCaste record)
{
if (pawn != null && record != null)
formerCastes[pawn.ThingID] = record;
}
internal bool RemoveFormer(Pawn pawn) => pawn != null && formerCastes.Remove(pawn.ThingID);
internal void MarkStarterCastesSeeded() => starterCastesSeeded = true;
internal void MarkFirstLoadMessageShown() => firstLoadMessageShown = true;
// ---- upkeep ------------------------------------------------------------------------ // ---- upkeep ------------------------------------------------------------------------
/// <summary> /// <summary>
/// Drops membership and queue entries whose pawn is null, discarded, or destroyed without being /// Drops membership and queue entries whose pawn is null, discarded, or destroyed without being
/// dead. A dead pawn keeps its caste in case it is resurrected, as long as its corpse or the /// dead, and former-caste records that are stale or point at a deleted caste. A dead pawn keeps its
/// world still holds it, so its reference resolves on load. Returns the number removed. /// caste in case it is resurrected, as long as its corpse or the world still holds it, so its
/// reference resolves on load. Returns the number removed.
/// </summary> /// </summary>
public int Purge() public int Purge()
{ {
@ -195,9 +258,47 @@ namespace BlaxCastes
} }
} }
removed += joinQueue.RemoveAll(q => q == null || IsGone(q.pawn)); removed += joinQueue.RemoveAll(q => q == null || IsGone(q.pawn));
removed += PruneFormerCastes();
return removed; return removed;
} }
/// <summary>
/// Removes former-caste records older than formerCasteDays, and records whose caste is gone (a No
/// caste record has none). Returns the number removed.
/// </summary>
public int PruneFormerCastes()
{
int now = Find.TickManager?.TicksGame ?? 0;
List<string> stale = null;
foreach (KeyValuePair<string, FormerCaste> kv in formerCastes)
{
if (kv.Key.NullOrEmpty() || kv.Value == null || (!kv.Value.casteless && CasteById(kv.Value.casteId) == null)
|| JoinDefaults.FormerExpired(kv.Value, now))
(stale ??= new List<string>()).Add(kv.Key);
}
if (stale == null)
return 0;
foreach (string id in stale)
formerCastes.Remove(id);
return stale.Count;
}
/// <summary>Removes every former-caste record that points at this caste id.</summary>
internal int RemoveFormerCastesOf(int casteId)
{
List<string> hit = null;
foreach (KeyValuePair<string, FormerCaste> kv in formerCastes)
{
if (kv.Value != null && !kv.Value.casteless && kv.Value.casteId == casteId)
(hit ??= new List<string>()).Add(kv.Key);
}
if (hit == null)
return 0;
foreach (string id in hit)
formerCastes.Remove(id);
return hit.Count;
}
public static bool IsGone(Pawn pawn) public static bool IsGone(Pawn pawn)
{ {
if (pawn == null || pawn.Discarded) if (pawn == null || pawn.Discarded)
@ -239,20 +340,61 @@ namespace BlaxCastes
if (!tickErrorLogged) if (!tickErrorLogged)
{ {
tickErrorLogged = true; tickErrorLogged = true;
Log.Error("[Blax Castes] Tick failed (logged once): " + e); Log.Error("[Blax Castes] Tick failed (logged once per game): " + e);
} }
} }
} }
public override void FinalizeInit() public override void FinalizeInit()
{ {
cached = this; Remember(this, Current.Game);
cachedGame = Current.Game; // Log-once flags count per game, so a failure in a later save is not silent.
tickErrorLogged = false;
JoinHooks.ResetLogOnce();
} }
public override void StartedNewGame() => ShowFirstLoadMessageOnce(); /// <summary>
/// A new game: the starter castes, then the starting pawns go into the caste of their status row.
/// Joins queued while the colony was generated are not joins, so the queue starts empty.
/// </summary>
public override void StartedNewGame()
{
try
{
joinQueue.Clear();
leftPawns.Clear();
if (StarterCastes.SeedNewGame(this) && JoinDefaults.Active)
CasteManager.AssignByStatus();
}
catch (Exception e)
{
Log.Error("[Blax Castes] Adding the starter castes failed: " + e);
}
ShowFirstLoadMessageOnce();
ShowOverlapMessage();
}
public override void LoadedGame() => ShowFirstLoadMessageOnce(); /// <summary>
/// A loaded save: the starter castes once, only if the save has no castes, with one message that
/// replaces the first-load message. Nobody is moved; the manager's "Assign by status" does that.
/// </summary>
public override void LoadedGame()
{
bool seeded = false;
try
{
seeded = StarterCastes.SeedOnLoad(this);
}
catch (Exception e)
{
Log.Error("[Blax Castes] Adding the starter castes failed: " + e);
}
if (seeded)
ShowSeededMessage();
else
ShowFirstLoadMessageOnce();
ShowOverlapMessage();
}
/// <summary>The message that points to Assign > Manage castes, once per save.</summary> /// <summary>The message that points to Assign > Manage castes, once per save.</summary>
private void ShowFirstLoadMessageOnce() private void ShowFirstLoadMessageOnce()
@ -268,6 +410,31 @@ namespace BlaxCastes
} }
} }
private void ShowSeededMessage()
{
try
{
StarterCastes.ShowSeededMessage(this);
firstLoadMessageShown = true;
}
catch (Exception e)
{
Log.Error("[Blax Castes] Starter caste message failed: " + e);
}
}
private void ShowOverlapMessage()
{
try
{
OverlapWarnings.ShowMessageOnce(this);
}
catch (Exception e)
{
Log.Error("[Blax Castes] Overlap warning failed: " + e);
}
}
// ---- save -------------------------------------------------------------------------- // ---- save --------------------------------------------------------------------------
public override void ExposeData() public override void ExposeData()
@ -275,7 +442,7 @@ namespace BlaxCastes
if (Scribe.mode == LoadSaveMode.Saving) if (Scribe.mode == LoadSaveMode.Saving)
{ {
Purge(); Purge();
CasteManager.CheckPolicies(this); CasteManager.CheckSlots(this);
} }
Scribe_Collections.Look(ref castes, "castes", LookMode.Deep); Scribe_Collections.Look(ref castes, "castes", LookMode.Deep);
@ -285,18 +452,18 @@ namespace BlaxCastes
ref membershipKeys, ref membershipValues, logNullErrors: false, saveDestroyedKeys: true); ref membershipKeys, ref membershipValues, logNullErrors: false, saveDestroyedKeys: true);
Scribe_Collections.Look(ref joinRows, "joinRows", LookMode.Deep); Scribe_Collections.Look(ref joinRows, "joinRows", LookMode.Deep);
Scribe_Collections.Look(ref joinQueue, "joinQueue", LookMode.Deep); Scribe_Collections.Look(ref joinQueue, "joinQueue", LookMode.Deep);
Scribe_Collections.Look(ref formerCastes, "formerCastes", LookMode.Value, LookMode.Deep, ref formerKeys, ref formerValues);
Scribe_Values.Look(ref firstLoadMessageShown, "firstLoadMessageShown"); Scribe_Values.Look(ref firstLoadMessageShown, "firstLoadMessageShown");
Scribe_Values.Look(ref starterCastesSeeded, "starterCastesSeeded");
Scribe_Collections.Look(ref overlapWarned, "overlapWarned", LookMode.Value);
if (Scribe.mode == LoadSaveMode.LoadingVars) if (Scribe.mode == LoadSaveMode.LoadingVars)
{ Remember(this, Current.Game);
cached = this;
cachedGame = Current.Game;
}
if (Scribe.mode == LoadSaveMode.PostLoadInit) if (Scribe.mode == LoadSaveMode.PostLoadInit)
{ {
EnsureState(); EnsureState();
Purge(); Purge();
CasteManager.CheckPolicies(this); CasteManager.CheckSlots(this);
} }
} }
@ -309,6 +476,8 @@ namespace BlaxCastes
joinRows ??= new List<JoinRow>(); joinRows ??= new List<JoinRow>();
joinRows.RemoveAll(r => r == null || r.reason.NullOrEmpty()); joinRows.RemoveAll(r => r == null || r.reason.NullOrEmpty());
joinQueue ??= new List<QueuedJoin>(); joinQueue ??= new List<QueuedJoin>();
formerCastes ??= new Dictionary<string, FormerCaste>();
overlapWarned ??= new List<string>();
EnsureRows(); EnsureRows();
if (defaultCaste != null && !castes.Contains(defaultCaste)) if (defaultCaste != null && !castes.Contains(defaultCaste))
defaultCaste = null; defaultCaste = null;

View File

@ -16,7 +16,7 @@ namespace BlaxCastes
} }
/// <summary> /// <summary>
/// Join defaults: puts a pawn that joins into the caste of its join row. /// Join defaults: puts a pawn that joins, or changes status, into the caste of its join row.
/// ///
/// The join hooks (JoinHooks: Pawn.SetFaction, Pawn_GuestTracker.SetGuestStatus, Pawn.PreTraded) /// The join hooks (JoinHooks: Pawn.SetFaction, Pawn_GuestTracker.SetGuestStatus, Pawn.PreTraded)
/// classify the join where it happens and call Enqueue with the innermost scope's reason, or with /// classify the join where it happens and call Enqueue with the innermost scope's reason, or with
@ -24,20 +24,18 @@ namespace BlaxCastes
/// GameComponentTick calls ApplyQueue every tick, which applies entries queued on an earlier tick: /// GameComponentTick calls ApplyQueue every tick, which applies entries queued on an earlier tick:
/// never inside SetFaction or SetGuestStatus, and only while the pawn is still player-side. /// never inside SetFaction or SetGuestStatus, and only while the pawn is still player-side.
/// ///
/// Reason to row, first match wins: the scope ("bought": the final status picks bought as slave or /// Order at apply time: a caste picked by hand after the join was queued, then the previous caste or
/// bought as colonist; a row id is used as it is), then the status fallback from the final status: /// No caste (a former-caste record with the same status, younger than formerCasteDays; the pawn's own
/// new colonist, new slave or new prisoner. /// settings from when it left come back with it), then the row. Reason
/// to row, first match wins: the scope ("bought": the final status picks bought as slave or bought
/// as colonist; a row id is used as it is), then the status fallback from the final status: new
/// colonist, new slave or new prisoner.
/// </summary> /// </summary>
public static class JoinDefaults public static class JoinDefaults
{ {
/// <summary>Queue reason when no scope covered the join: the final status picks the row.</summary> /// <summary>Queue reason when no scope covered the join: the final status picks the row.</summary>
public const string StatusFallback = "status"; public const string StatusFallback = "status";
// Pawns that left the player side, checked on the next ApplyQueue. Not saved: the 2500-tick
// sweep ends any membership a save cut short.
private static readonly HashSet<Pawn> left = new HashSet<Pawn>();
private static Game leftGame;
private static GameComponent_BlaxCastes Comp => GameComponent_BlaxCastes.Instance; private static GameComponent_BlaxCastes Comp => GameComponent_BlaxCastes.Instance;
private static int Now => Find.TickManager?.TicksGame ?? 0; private static int Now => Find.TickManager?.TicksGame ?? 0;
@ -46,6 +44,10 @@ namespace BlaxCastes
public static bool Active => public static bool Active =>
BlaxCastesMod.Enabled && (BlaxCastesMod.Settings == null || BlaxCastesMod.Settings.enableJoinDefaults); BlaxCastesMod.Enabled && (BlaxCastesMod.Settings == null || BlaxCastesMod.Settings.enableJoinDefaults);
private static bool ReturnToPrevious => BlaxCastesMod.Settings == null || BlaxCastesMod.Settings.returnToPreviousCaste;
private static int FormerCasteDays => BlaxCastesMod.Settings?.formerCasteDays ?? BlaxCastesSettings.DefaultFormerCasteDays;
// ---- classification ---------------------------------------------------------------- // ---- classification ----------------------------------------------------------------
public static JoinSide SideOf(Pawn pawn) public static JoinSide SideOf(Pawn pawn)
@ -112,6 +114,82 @@ namespace BlaxCastes
} }
} }
// ---- previous caste ----------------------------------------------------------------
/// <summary>A former-caste record older than formerCasteDays.</summary>
public static bool FormerExpired(FormerCaste record, int now) =>
record == null || now - record.tick > FormerCasteDays * GenDate.TicksPerDay;
/// <summary>
/// The former-caste record the pawn would leave right now: its caste, or No caste when it is casteless
/// by choice, the status (colonist or slave), and its own settings with the caste's slots it follows.
/// Null for another status or a pawn with no membership record (it never had a caste, so a status
/// change moves it by its row). The join hooks take it before a status change, because the game
/// resets medical care inside the change.
/// </summary>
internal static FormerCaste Capture(Pawn pawn, JoinSide side)
{
if (side != JoinSide.Colonist && side != JoinSide.Slave)
return null;
GameComponent_BlaxCastes comp = Comp;
CasteMembership m = comp?.MembershipOf(pawn);
if (m == null || (m.caste != null && !comp.HasCaste(m.caste)))
return null;
var record = new FormerCaste(m.caste?.id ?? Caste.Unmanaged, side, m.auto, Now) { casteless = m.caste == null };
CasteUtility.Snapshot(pawn, m.caste, record);
return record;
}
/// <summary>
/// Writes the pawn's former-caste record: it had this status (colonist or slave) and is leaving the
/// player side, being sold or becoming a prisoner. captured is the record taken before the change
/// (Capture); without one it is taken now. A pawn with no membership record writes none.
/// </summary>
internal static void NoteFormer(Pawn pawn, JoinSide side, FormerCaste captured = null)
{
if (side != JoinSide.Colonist && side != JoinSide.Slave)
return;
GameComponent_BlaxCastes comp = Comp;
if (comp == null || pawn == null)
return;
FormerCaste record = captured != null && captured.side == side ? captured : Capture(pawn, side);
if (record == null)
return;
record.tick = Now;
comp.SetFormer(pawn, record);
}
/// <summary>
/// The pawn's former-caste record when it applies now: it has the pawn's current status (colonist or
/// slave), is younger than formerCasteDays, and its caste still exists (a No caste record always
/// does). Null otherwise, or while returnToPreviousCaste is off.
/// </summary>
public static FormerCaste UsableFormer(Pawn pawn)
{
if (!ReturnToPrevious || pawn == null)
return null;
GameComponent_BlaxCastes comp = Comp;
FormerCaste record = comp?.FormerOf(pawn);
if (record == null || FormerExpired(record, Now))
return null;
JoinSide side = SideOf(pawn);
if ((side != JoinSide.Colonist && side != JoinSide.Slave) || record.side != side)
return null;
if (!record.casteless && comp.CasteById(record.casteId) == null)
return null;
return record;
}
/// <summary>
/// The caste a returning pawn gets back (UsableFormer). Null when there is none, and when the pawn
/// goes back to No caste.
/// </summary>
public static Caste PreviousCasteFor(Pawn pawn)
{
FormerCaste record = UsableFormer(pawn);
return record == null || record.casteless ? null : Comp.CasteById(record.casteId);
}
// ---- queue ------------------------------------------------------------------------- // ---- queue -------------------------------------------------------------------------
/// <summary>The pawn's waiting join, or null.</summary> /// <summary>The pawn's waiting join, or null.</summary>
@ -129,9 +207,48 @@ namespace BlaxCastes
return null; return null;
} }
/// <summary>True while the pawn waits for its join to be applied (the column's "pending").</summary> /// <summary>True while the pawn waits for its join to be applied.</summary>
public static bool IsQueued(Pawn pawn) => QueuedFor(pawn) != null; public static bool IsQueued(Pawn pawn) => QueuedFor(pawn) != null;
/// <summary>
/// True while the pawn waits for a join that will change its caste: the previous caste or the row
/// gives it one, or a No caste row will take it out of a caste a join row put it in. The column
/// shows "(pending)" only then.
/// </summary>
public static bool WillChange(Pawn pawn)
{
QueuedJoin q = QueuedFor(pawn);
GameComponent_BlaxCastes comp = Comp;
if (q == null || comp == null || !Active || !Eligible(pawn) || !CasteUtility.IsPlayerSide(pawn))
return false;
CasteMembership m = comp.MembershipOf(pawn);
if (HandPickedSince(m, q))
return false;
FormerCaste record = UsableFormer(pawn);
if (record != null)
return record.casteless ? m == null || m.caste != null : m?.caste == null || m.caste.id != record.casteId;
string row = RowFor(q.reason, pawn);
if (row == null)
return false;
if (comp.ResolveRow(row) != null)
return true;
return m?.caste != null && m.auto;
}
/// <summary>
/// A caste (or No caste) picked by hand after the join was queued: a manual membership that is
/// not the one the pawn had when the join was queued (after a load, one set on or after the
/// queueing tick). A restored previous caste or a deleted caste never counts as a pick.
/// </summary>
private static bool HandPickedSince(CasteMembership m, QueuedJoin q)
{
if (m == null || m.auto || m.reason == JoinReason.CasteDeleted || m.reason == JoinReason.PreviousCaste)
return false;
if (q.seenKnown)
return !ReferenceEquals(m, q.seen);
return m.tick >= q.tick;
}
/// <summary> /// <summary>
/// Queues a join for the next tick: a scope reason, a row id or StatusFallback. One entry per pawn; /// Queues a join for the next tick: a scope reason, a row id or StatusFallback. One entry per pawn;
/// a specific reason replaces a status fallback, never the other way round. Does nothing while /// a specific reason replaces a status fallback, never the other way round. Does nothing while
@ -146,31 +263,32 @@ namespace BlaxCastes
return; return;
if (reason.NullOrEmpty()) if (reason.NullOrEmpty())
reason = StatusFallback; reason = StatusFallback;
left.Remove(pawn); comp.LeftPawns.Remove(pawn);
int now = Now; int now = Now;
QueuedJoin queued = QueuedFor(pawn); QueuedJoin queued = QueuedFor(pawn);
if (queued == null) if (queued == null)
{ {
comp.JoinQueue.Add(new QueuedJoin(pawn, reason, now)); queued = new QueuedJoin(pawn, reason, now);
return; comp.JoinQueue.Add(queued);
} }
if (IsSpecific(reason) || !IsSpecific(queued.reason)) else
queued.reason = reason; {
if (now > queued.tick) if (IsSpecific(reason) || !IsSpecific(queued.reason))
queued.tick = now; queued.reason = reason;
if (now > queued.tick)
queued.tick = now;
}
// A pick made before this status change is not a pick "after the join": the new status moves the pawn.
queued.seen = comp.MembershipOf(pawn);
queued.seenKnown = true;
} }
/// <summary>A pawn left the player side. Its membership ends on the next tick if it has not come back.</summary> /// <summary>A pawn left the player side. Its membership ends on the next tick if it has not come back.</summary>
internal static void NoteLeft(Pawn pawn) internal static void NoteLeft(Pawn pawn)
{ {
if (pawn == null || Current.Game == null) if (pawn == null)
return; return;
if (leftGame != Current.Game) Comp?.LeftPawns.Add(pawn);
{
left.Clear();
leftGame = Current.Game;
}
left.Add(pawn);
} }
/// <summary> /// <summary>
@ -182,7 +300,7 @@ namespace BlaxCastes
GameComponent_BlaxCastes comp = Comp; GameComponent_BlaxCastes comp = Comp;
if (comp == null || Find.TickManager == null) if (comp == null || Find.TickManager == null)
return; return;
EndLeftMemberships(); EndLeftMemberships(comp);
List<QueuedJoin> queue = comp.JoinQueue; List<QueuedJoin> queue = comp.JoinQueue;
if (queue.Count == 0) if (queue.Count == 0)
return; return;
@ -239,41 +357,92 @@ namespace BlaxCastes
return null; return null;
CasteMembership membership = comp.MembershipOf(pawn); CasteMembership membership = comp.MembershipOf(pawn);
// A caste picked by hand after the join was queued wins over the join row. if (HandPickedSince(membership, q))
if (membership != null && !membership.auto && membership.reason != JoinReason.CasteDeleted && membership.tick >= q.tick)
return null; return null;
FormerCaste record = UsableFormer(pawn);
if (record != null)
{
comp.RemoveFormer(pawn);
return Restore(comp, pawn, record, membership);
}
string row = RowFor(q.reason, pawn); string row = RowFor(q.reason, pawn);
if (row == null) if (row == null)
return null; return null;
Caste caste = comp.ResolveRow(row); Caste caste = comp.ResolveRow(row);
bool rowSet = membership?.caste != null && membership.auto;
if (caste != null) if (caste != null)
{
// Moving on from a caste a join row gave it: what that caste set and the new one leaves alone goes back.
if (rowSet && membership.caste != caste)
RevertSlots(pawn, membership.caste, caste);
return CasteManager.Assign(pawn, caste, true, row) ? caste : null; return CasteManager.Assign(pawn, caste, true, row) ? caste : null;
}
if (membership?.caste != null) // A No caste row only undoes what a join row did; a caste picked by hand stays.
if (rowSet)
LeaveCaste(pawn, membership.caste); LeaveCaste(pawn, membership.caste);
return null; return null;
} }
/// <summary> /// <summary>
/// The pawn's join row is No caste while it was in a caste: it leaves the caste. With revertOnLeave /// A returning pawn gets its former caste, or No caste, back, and its own settings from when it
/// the caste's managed slots go back to the database defaults and medical care is reset, so a /// left: each slot of that caste it followed gets the caste's current value (edits made while it was
/// recruited prisoner does not keep the prisoner food. /// away included), each one it had changed by hand gets that value back. A slot the caste leaves
/// alone is touched only to undo the caste the pawn got while it was away (the new-prisoner caste's
/// food): while the pawn still has that caste's value, it gets its own from when it left. So an
/// arrest and release, or a sale and buy-back, keeps the pawn's hand changes. Returns the caste for
/// the join message, or null when the pawn's caste does not change or it goes back to No caste.
/// </summary>
private static Caste Restore(GameComponent_BlaxCastes comp, Pawn pawn, FormerCaste record, CasteMembership membership)
{
if (!CasteUtility.CanBeMember(pawn))
return null;
Caste previous = record.casteless ? null : comp.CasteById(record.casteId);
Caste away = membership?.caste;
comp.SetMembership(pawn, new CasteMembership(previous, record.auto, JoinReason.PreviousCaste, Now));
CasteUtility.Restore(pawn, previous, away == previous ? null : away, record);
return previous != null && previous != away ? previous : null;
}
/// <summary>
/// The pawn's join row is No caste while a join row had put it in a caste: it leaves the caste and
/// RevertSlots runs with no new caste.
/// </summary> /// </summary>
private static void LeaveCaste(Pawn pawn, Caste caste) private static void LeaveCaste(Pawn pawn, Caste caste)
{ {
CasteManager.EndMembership(pawn); CasteManager.EndMembership(pawn);
if (!BlaxCastesMod.Enabled || (BlaxCastesMod.Settings != null && !BlaxCastesMod.Settings.revertOnLeave)) RevertSlots(pawn, caste, null);
}
/// <summary>
/// A join row takes the pawn out of a caste a join row had put it in, to No caste or to another
/// caste. With revertOnLeave, each policy and medical care slot the old caste manages and the new
/// one leaves alone, where the pawn still has the old caste's value, goes back to the database
/// default (medical care to the game's default for its status), so a recruited prisoner does not
/// keep the prisoner food. Slots changed by hand stay (the Follow rule). The schedule, work
/// priorities and loadout have no database default and stay as they are.
/// </summary>
private static void RevertSlots(Pawn pawn, Caste from, Caste to)
{
if (from == null || !BlaxCastesMod.Enabled || (BlaxCastesMod.Settings != null && !BlaxCastesMod.Settings.revertOnLeave))
return; return;
foreach (CasteSlot slot in CasteUtility.AllSlots) foreach (CasteSlot slot in CasteUtility.PolicySlots)
{ {
if (slot == CasteSlot.MedCare || !caste.IsManaged(slot)) if (!from.IsManaged(slot) || (to != null && to.IsManaged(slot)) || !CasteUtility.CanUse(pawn, slot))
continue; continue;
if (!CasteUtility.SameValue(CasteUtility.CurrentValue(pawn, slot), from.GetSlot(slot)))
continue;
if (slot == CasteSlot.MedCare)
{
pawn.playerSettings.ResetMedicalCare();
continue;
}
object value = DatabaseDefault(slot); object value = DatabaseDefault(slot);
if (value != null) if (value != null)
CasteUtility.WriteSlot(pawn, slot, value); CasteUtility.WriteSlot(pawn, slot, value);
} }
pawn.playerSettings?.ResetMedicalCare();
} }
private static object DatabaseDefault(CasteSlot slot) private static object DatabaseDefault(CasteSlot slot)
@ -289,15 +458,11 @@ namespace BlaxCastes
} }
} }
private static void EndLeftMemberships() private static void EndLeftMemberships(GameComponent_BlaxCastes comp)
{ {
HashSet<Pawn> left = comp.LeftPawns;
if (left.Count == 0) if (left.Count == 0)
return; return;
if (leftGame != Current.Game)
{
left.Clear();
return;
}
List<Pawn> pawns = left.ToList(); List<Pawn> pawns = left.ToList();
left.Clear(); left.Clear();
foreach (Pawn pawn in pawns) foreach (Pawn pawn in pawns)

View File

@ -14,6 +14,8 @@ namespace BlaxCastes
public bool hasGuest; public bool hasGuest;
public GuestStatus status; public GuestStatus status;
public Faction host; public Faction host;
/// <summary>The former-caste record the pawn would leave, taken before the change (colonists and slaves with a record only).</summary>
public FormerCaste former;
public static JoinSnapshot Of(Pawn pawn) public static JoinSnapshot Of(Pawn pawn)
{ {
@ -35,42 +37,72 @@ namespace BlaxCastes
/// Shared bodies of the join hooks. The prefixes snapshot the pawn, the postfixes compare. Only a /// Shared bodies of the join hooks. The prefixes snapshot the pawn, the postfixes compare. Only a
/// change into player colonist, player slave or player prisoner queues a join, so the /// change into player colonist, player slave or player prisoner queues a join, so the
/// SetGuestStatus(null) that vanilla runs on existing members (inside SetFaction, before a trade) /// SetGuestStatus(null) that vanilla runs on existing members (inside SetFaction, before a trade)
/// queues nothing. A change out of the player side is noted, and the membership ends on the next /// queues nothing. Every change between colonist, slave and prisoner queues one, so the status rows
/// tick if the pawn is still gone by then. Nothing is applied here: SetFaction and SetGuestStatus /// see arrests, releases, recruiting, enslaving and freeing. A change out of the player side is
/// reset medical care, areas, work and slave mode right after, so joins wait for the next tick. /// noted, and the membership ends on the next tick if the pawn is still gone by then. A colonist or
/// slave that leaves the player side or becomes a prisoner leaves a former-caste record, taken in the
/// prefix, so it holds the pawn's settings from before the game changed any of them. Inside a
/// sale nothing is queued; the sale writes the record itself. Nothing is applied here: SetFaction
/// and SetGuestStatus reset medical care, areas, work and slave mode right after, so joins wait for
/// the next tick.
/// </summary> /// </summary>
internal static class JoinHooks internal static class JoinHooks
{ {
private static readonly HashSet<string> logged = new HashSet<string>(); private static readonly HashSet<string> logged = new HashSet<string>();
/// <summary>Logs a hook failure once per hook, so a Castes bug can never break a trade or a capture.</summary> /// <summary>Logs a hook failure once per hook and game, so a Castes bug can never break a trade or a capture.</summary>
public static void LogOnce(string where, Exception e) public static void LogOnce(string where, Exception e)
{ {
try try
{ {
if (logged.Add(where)) if (logged.Add(where))
Log.Error("[Blax Castes] " + where + " failed (logged once): " + e); Log.Error("[Blax Castes] " + where + " failed (logged once per game): " + e);
} }
catch catch
{ {
} }
} }
private static bool Watching(Pawn pawn) => /// <summary>Called when a game starts or loads, so a failure in a later game is logged again.</summary>
public static void ResetLogOnce() => logged.Clear();
internal static bool Watching(Pawn pawn) =>
pawn != null && Current.Game != null && Scribe.mode == LoadSaveMode.Inactive pawn != null && Current.Game != null && Scribe.mode == LoadSaveMode.Inactive
&& pawn.RaceProps != null && pawn.RaceProps.Humanlike; && pawn.RaceProps != null && pawn.RaceProps.Humanlike;
public static JoinSnapshot Before(Pawn pawn) public static JoinSnapshot Before(Pawn pawn)
{ {
JoinSnapshot snapshot;
try try
{ {
return Watching(pawn) ? JoinSnapshot.Of(pawn) : default; if (!Watching(pawn))
return default;
snapshot = JoinSnapshot.Of(pawn);
} }
catch (Exception e) catch (Exception e)
{ {
LogOnce("Join snapshot", e); LogOnce("Join snapshot", e);
return default; return default;
} }
snapshot.former = CaptureFormer(pawn, snapshot.Side);
return snapshot;
}
/// <summary>
/// The former-caste record, taken before the game changes anything (it resets medical care inside
/// SetFaction and SetGuestStatus). A failure here only loses the record, never the join.
/// </summary>
public static FormerCaste CaptureFormer(Pawn pawn, JoinSide side)
{
try
{
return JoinDefaults.Capture(pawn, side);
}
catch (Exception e)
{
LogOnce("Former caste snapshot", e);
return null;
}
} }
public static void After(Pawn pawn, JoinSnapshot before) public static void After(Pawn pawn, JoinSnapshot before)
@ -83,8 +115,17 @@ namespace BlaxCastes
JoinSide now = JoinSnapshot.Of(pawn).Side; JoinSide now = JoinSnapshot.Of(pawn).Side;
if (was == now) if (was == now)
return; return;
string scope = JoinScopes.ReasonFor(pawn);
if (scope == JoinScopes.Sold)
{
if (now == JoinSide.None)
JoinDefaults.NoteLeft(pawn);
return;
}
if ((was == JoinSide.Colonist || was == JoinSide.Slave) && (now == JoinSide.None || now == JoinSide.Prisoner))
JoinDefaults.NoteFormer(pawn, was, before.former);
if (now != JoinSide.None) if (now != JoinSide.None)
JoinDefaults.Enqueue(pawn, JoinScopes.ReasonFor(pawn) ?? JoinDefaults.StatusFallback); JoinDefaults.Enqueue(pawn, scope ?? JoinDefaults.StatusFallback);
else else
JoinDefaults.NoteLeft(pawn); JoinDefaults.NoteLeft(pawn);
} }
@ -93,6 +134,29 @@ namespace BlaxCastes
LogOnce("Join check", e); LogOnce("Join check", e);
} }
} }
/// <summary>A sale finished: a colonist or slave that left the player side leaves the former-caste record taken before the sale.</summary>
public static void AfterSale(Pawn pawn, JoinSide before, FormerCaste former)
{
try
{
if (JoinDefaults.SideOf(pawn) == JoinSide.None)
JoinDefaults.NoteFormer(pawn, before, former);
}
catch (Exception e)
{
LogOnce("Sale check", e);
}
}
}
/// <summary>What the PreTraded prefix hands its finalizer.</summary>
internal struct TradeState
{
public int token;
public bool selling;
public JoinSide side;
public FormerCaste former;
} }
[HarmonyPatch(typeof(Pawn), nameof(Pawn.SetFaction), new[] { typeof(Faction), typeof(Pawn) })] [HarmonyPatch(typeof(Pawn), nameof(Pawn.SetFaction), new[] { typeof(Faction), typeof(Pawn) })]
@ -112,36 +176,49 @@ namespace BlaxCastes
} }
/// <summary> /// <summary>
/// Buying: the pawn's status changes inside Pawn.PreTraded, so a "bought" scope covers it. The /// Buying: the pawn's status changes inside Pawn.PreTraded, so a "bought" scope covers it. Blax Slaves
/// finalizer pops the scope even when PreTraded throws. Blax Slaves and Trade as Slave or Colonist /// and Trade as Slave or Colonist only set guest.joinStatus before this call, so the final status
/// only set guest.joinStatus before this call, so the final status (slave or not) picks the row. /// (slave or not) picks the row. Selling: a "sold" scope keeps the slave-to-free step inside the sale
/// from queueing a join, and the finalizer writes the former-caste record with the status the pawn
/// had before the sale. The finalizer pops the scope even when PreTraded throws.
/// </summary> /// </summary>
[HarmonyPatch(typeof(Pawn), nameof(Pawn.PreTraded))] [HarmonyPatch(typeof(Pawn), nameof(Pawn.PreTraded))]
internal static class Patch_Pawn_PreTraded internal static class Patch_Pawn_PreTraded
{ {
public static void Prefix(Pawn __instance, TradeAction action, out int __state) public static void Prefix(Pawn __instance, TradeAction action, out TradeState __state)
{ {
__state = 0; __state = default;
try try
{ {
if (action == TradeAction.PlayerBuys) if (action == TradeAction.PlayerBuys)
__state = JoinScopes.Push(JoinScopes.Bought, __instance); {
__state.token = JoinScopes.Push(JoinScopes.Bought, __instance);
}
else if (action == TradeAction.PlayerSells && JoinHooks.Watching(__instance))
{
__state.selling = true;
__state.side = JoinDefaults.SideOf(__instance);
__state.former = JoinHooks.CaptureFormer(__instance, __state.side);
__state.token = JoinScopes.Push(JoinScopes.Sold, __instance);
}
} }
catch (Exception e) catch (Exception e)
{ {
JoinHooks.LogOnce("Buy scope", e); JoinHooks.LogOnce("Trade scope", e);
} }
} }
public static Exception Finalizer(Exception __exception, int __state) public static Exception Finalizer(Exception __exception, Pawn __instance, TradeState __state)
{ {
try try
{ {
JoinScopes.Pop(__state); JoinScopes.Pop(__state.token);
if (__state.selling && __exception == null)
JoinHooks.AfterSale(__instance, __state.side, __state.former);
} }
catch (Exception e) catch (Exception e)
{ {
JoinHooks.LogOnce("Buy scope", e); JoinHooks.LogOnce("Trade scope", e);
} }
return __exception; return __exception;
} }

View File

@ -15,6 +15,12 @@ namespace BlaxCastes
/// <summary>Pawn.PreTraded while the player buys. Resolves to bought as slave or bought as colonist.</summary> /// <summary>Pawn.PreTraded while the player buys. Resolves to bought as slave or bought as colonist.</summary>
public const string Bought = "bought"; public const string Bought = "bought";
/// <summary>
/// Pawn.PreTraded while the player sells. Status changes inside it queue nothing (selling a slave
/// briefly frees it before the faction changes); the sale itself writes the former-caste record.
/// </summary>
public const string Sold = "sold";
private struct Scope private struct Scope
{ {
public string reason; public string reason;

View File

@ -0,0 +1,107 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RimWorld;
using Verse;
namespace BlaxCastes
{
/// <summary>A mod whose join defaults overlap with Castes: its package id, name and what it sets.</summary>
public sealed class OverlapMod
{
public readonly string PackageId;
public readonly string Name;
/// <summary>Keyed string naming the defaults that overlap.</summary>
public readonly string WhatKey;
public OverlapMod(string packageId, string name, string whatKey)
{
PackageId = packageId;
Name = name;
WhatKey = whatKey;
}
public string What => WhatKey.Translate();
}
/// <summary>
/// Names active mods that also set policies when a pawn joins: on the settings page and in one message
/// per save. Castes applies a join one tick after it happens, so its choice wins; the warning makes the
/// double work visible. No patches against those mods. Detection goes through Compat.IsActive.
/// </summary>
public static class OverlapWarnings
{
public static readonly OverlapMod[] Mods =
{
new OverlapMod(Compat.BetterPawnControl, "Better Pawn Control", "BlaxCastes_OverlapWhatBpc"),
new OverlapMod(Compat.BetterPawnControlForked, "Better Pawn Control Forked", "BlaxCastes_OverlapWhatBpc"),
new OverlapMod(Compat.Defaults1trickPwnyta, "1trickPwnyta's Defaults", "BlaxCastes_OverlapWhatDefaults"),
new OverlapMod(Compat.AutomaticSlaveOutfit, "Automatic Slave Outfit", "BlaxCastes_OverlapWhatSlaveOutfit"),
new OverlapMod(Compat.PrisonerDefaults, "PrisonerDefaults", "BlaxCastes_OverlapWhatPrisoner"),
};
/// <summary>Package ids treated as active on top of the real mod list. For tests only.</summary>
public static readonly HashSet<string> SimulatedActive = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
// The mod list can't change without a restart, so the real detection runs once.
private static List<OverlapMod> detected;
/// <summary>The overlapping mods that are active, in list order.</summary>
public static List<OverlapMod> Active()
{
detected ??= Mods.Where(m => Compat.IsActive(m.PackageId)).ToList();
if (SimulatedActive.Count == 0)
return detected;
return Mods.Where(m => detected.Contains(m) || SimulatedActive.Contains(m.PackageId)).ToList();
}
/// <summary>The settings page text, or null when no overlapping mod is active or the warnings are off.</summary>
public static string SettingsText()
{
if (BlaxCastesMod.Settings != null && !BlaxCastesMod.Settings.warnOverlaps)
return null;
List<OverlapMod> active = Active();
if (active.Count == 0)
return null;
var sb = new StringBuilder();
sb.Append("BlaxCastes_OverlapSettingsIntro".Translate());
foreach (OverlapMod mod in active)
sb.Append("\n- " + "BlaxCastes_OverlapLine".Translate(mod.Name.Named("MOD"), mod.What.Named("WHAT")));
sb.Append("\n" + "BlaxCastes_OverlapAdvice".Translate());
return sb.ToString();
}
/// <summary>The message text for these mods, or null for none.</summary>
public static string MessageText(List<OverlapMod> mods)
{
if (mods == null || mods.Count == 0)
return null;
string names = mods.Select(m => m.Name).ToCommaList(useAnd: true);
return "BlaxCastes_OverlapMessage".Translate(names.Named("MODS"));
}
/// <summary>
/// Posts one message naming the active overlapping mods this save has not been warned about yet, and
/// remembers them in the save. Returns the mods it named.
/// </summary>
public static List<OverlapMod> ShowMessageOnce(GameComponent_BlaxCastes comp)
{
var named = new List<OverlapMod>();
if (comp == null || (BlaxCastesMod.Settings != null && !BlaxCastesMod.Settings.warnOverlaps))
return named;
foreach (OverlapMod mod in Active())
{
if (!comp.OverlapWarned(mod.PackageId))
named.Add(mod);
}
string text = MessageText(named);
if (text.NullOrEmpty())
return named;
foreach (OverlapMod mod in named)
comp.MarkOverlapWarned(mod.PackageId);
LongEventHandler.ExecuteWhenFinished(() => Messages.Message(text, MessageTypeDefOf.CautionInput, historical: true));
return named;
}
}
}

View File

@ -2,6 +2,7 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using HarmonyLib;
using RimWorld; using RimWorld;
using UnityEngine; using UnityEngine;
using Verse; using Verse;
@ -54,10 +55,11 @@ namespace BlaxCastes
/// <summary> /// <summary>
/// The Caste column in the Assign tab, modelled on the vanilla apparel policy column. A cell shows /// The Caste column in the Assign tab, modelled on the vanilla apparel policy column. A cell shows
/// the pawn's caste ("*" when a managed slot differs from the caste), "(pending)" while a join waits /// the pawn's caste ("*" when a managed slot differs from the caste), "(pending)" while a join that changes its caste waits
/// for the next tick, or "Unchangeable" for quest lodgers. Click to pick, or drag down to paint. /// for the next tick, or "Unchangeable" for quest lodgers. Click to pick, or drag down to paint.
/// The header holds the "Manage castes" and "Defaults" buttons in the same 65 px area the apparel /// The header holds the "Manage castes" and "Defaults" buttons in the same 65 px area the apparel
/// column uses for its button. /// column uses for its button. In the Work tab the header stays as tall as the work columns' (50 px),
/// so their label guide lines still reach the cells; there only "Manage castes" sits above the label.
/// </summary> /// </summary>
public class PawnColumnWorker_BlaxCaste : PawnColumnWorker public class PawnColumnWorker_BlaxCaste : PawnColumnWorker
{ {
@ -69,6 +71,8 @@ namespace BlaxCastes
private const float HeaderButtonHeight = 19f; private const float HeaderButtonHeight = 19f;
private const float HeaderButtonGap = 2f; private const float HeaderButtonGap = 2f;
/// <summary>The bottom of the header the base class makes clickable for sorting (PawnColumnWorker.GetInteractableHeaderRect).</summary>
private const int SortAreaHeight = 25;
private static GameComponent_BlaxCastes Comp => GameComponent_BlaxCastes.Instance; private static GameComponent_BlaxCastes Comp => GameComponent_BlaxCastes.Instance;
@ -78,22 +82,70 @@ namespace BlaxCastes
{ {
base.DoHeader(rect, table); base.DoHeader(rect, table);
MouseoverSounds.DoRegion(rect); MouseoverSounds.DoRegion(rect);
// Two stacked buttons above the 25 px sort area at the bottom of the header. Rect manage;
float top = rect.y + (rect.height - TopAreaHeight); Rect defaults = default;
Rect manage = new Rect(rect.x, top, rect.width, HeaderButtonHeight); bool compact = IsWorkTable(table);
Rect defaults = new Rect(rect.x, manage.yMax + HeaderButtonGap, rect.width, HeaderButtonHeight); if (compact)
{
// One button right above the label and the sort area, inside the work columns' 50 px.
manage = new Rect(rect.x, rect.yMax - CompactBottom(table) - HeaderButtonGap - HeaderButtonHeight, rect.width, HeaderButtonHeight);
}
else
{
// Two stacked buttons above the 25 px sort area at the bottom of the header.
float top = rect.y + (rect.height - TopAreaHeight);
manage = new Rect(rect.x, top, rect.width, HeaderButtonHeight);
defaults = new Rect(rect.x, manage.yMax + HeaderButtonGap, rect.width, HeaderButtonHeight);
}
using (new TextBlock(GameFont.Tiny)) using (new TextBlock(GameFont.Tiny))
{ {
if (Widgets.ButtonText(manage, "BlaxCastes_ManageCastesButton".Translate().Truncate(manage.width - 4f))) if (Widgets.ButtonText(manage, "BlaxCastes_ManageCastesButton".Translate().Truncate(manage.width - 4f)))
Find.WindowStack.Add(new Dialog_ManageCastes()); Find.WindowStack.Add(new Dialog_ManageCastes());
if (Widgets.ButtonText(defaults, "BlaxCastes_JoinDefaultsButton".Translate().Truncate(defaults.width - 4f))) if (!compact && Widgets.ButtonText(defaults, "BlaxCastes_JoinDefaultsButton".Translate().Truncate(defaults.width - 4f)))
Find.WindowStack.Add(new Dialog_JoinDefaults()); Find.WindowStack.Add(new Dialog_JoinDefaults());
} }
TooltipHandler.TipRegion(manage, "BlaxCastes_ManageCastesButtonTip".Translate()); TooltipHandler.TipRegion(manage, "BlaxCastes_ManageCastesButtonTip".Translate());
TooltipHandler.TipRegion(defaults, "BlaxCastes_JoinDefaultsButtonTip".Translate()); if (!compact)
TooltipHandler.TipRegion(defaults, "BlaxCastes_JoinDefaultsButtonTip".Translate());
} }
public override int GetMinHeaderHeight(PawnTable table) => Mathf.Max(base.GetMinHeaderHeight(table), TopAreaHeight); /// <summary>
/// 65 px for the two buttons, as the outfit column. In the Work tab only the label and one button,
/// which fit in the work columns' 50 px, so the header does not grow there.
/// </summary>
public override int GetMinHeaderHeight(PawnTable table)
{
if (IsWorkTable(table))
return CompactBottom(table) + Mathf.CeilToInt(HeaderButtonGap * 2f + HeaderButtonHeight);
return Mathf.Max(base.GetMinHeaderHeight(table), TopAreaHeight);
}
/// <summary>What the compact header keeps free at its bottom: the label, at least the 25 px sort area the base class makes clickable.</summary>
private int CompactBottom(PawnTable table) => Mathf.Max(base.GetMinHeaderHeight(table), SortAreaHeight);
private static AccessTools.FieldRef<PawnTable, PawnTableDef> tableDefField;
private static bool tableDefFieldFailed;
/// <summary>The table's def (PawnTable keeps it private), or null if it cannot be read.</summary>
public static PawnTableDef TableDefOf(PawnTable table)
{
if (table == null || tableDefFieldFailed)
return null;
try
{
tableDefField ??= AccessTools.FieldRefAccess<PawnTable, PawnTableDef>("def");
return tableDefField(table);
}
catch (Exception e)
{
tableDefFieldFailed = true;
Log.Warning("[Blax Castes] Could not read a pawn table's def; the Caste column uses its full header everywhere: " + e.Message);
return null;
}
}
/// <summary>The Work tab's table, where the header keeps the work columns' height.</summary>
public static bool IsWorkTable(PawnTable table) => TableDefOf(table) == PawnTableDefOf.Work;
public override int GetMinWidth(PawnTable table) => Mathf.Max(base.GetMinWidth(table), MinCellWidth); public override int GetMinWidth(PawnTable table) => Mathf.Max(base.GetMinWidth(table), MinCellWidth);
@ -123,7 +175,7 @@ namespace BlaxCastes
} }
/// <summary> /// <summary>
/// The cell text: "Unchangeable" for quest lodgers, "(pending)" while a join is queued, the caste /// The cell text: "Unchangeable" for quest lodgers, "(pending)" while a queued join will change the caste, the caste
/// label with "*" when a managed slot differs, "No caste" when casteless by choice, else "None". /// label with "*" when a managed slot differs, "No caste" when casteless by choice, else "None".
/// </summary> /// </summary>
public static string CellLabel(Pawn pawn) public static string CellLabel(Pawn pawn)
@ -155,22 +207,22 @@ namespace BlaxCastes
} }
else if (m.caste == null) else if (m.caste == null)
{ {
sb.AppendLine("BlaxCastes_CellCastelessTip".Translate()); sb.AppendLine(m.reason == JoinReason.CasteDeleted
? "BlaxCastes_CellCasteDeletedTip".Translate()
: "BlaxCastes_CellCastelessTip".Translate());
} }
else else
{ {
sb.AppendLine("BlaxCastes_CellCasteTip".Translate(m.caste.label)); sb.AppendLine("BlaxCastes_CellCasteTip".Translate(m.caste.label));
if (StarterCastes.IsSlaveOutfit(m.caste.ApparelPolicy))
sb.AppendLine("BlaxCastes_SlaveOutfitCold".Translate());
List<CasteSlot> overrides = CasteManager.Overrides(pawn); List<CasteSlot> overrides = CasteManager.Overrides(pawn);
if (overrides.Count > 0) if (overrides.Count > 0)
{ {
sb.AppendLine(); sb.AppendLine();
sb.AppendLine("BlaxCastes_CellOverrides".Translate()); sb.AppendLine("BlaxCastes_CellOverrides".Translate());
foreach (CasteSlot slot in overrides) foreach (CasteSlot slot in overrides)
{ sb.AppendLine(" " + OverrideLine(pawn, m.caste, slot));
string mine = CasteUtility.ValueLabel(slot, CasteUtility.CurrentValue(pawn, slot));
string casteValue = CasteUtility.ValueLabel(slot, m.caste.GetSlot(slot));
sb.AppendLine(" " + "BlaxCastes_CellOverrideLine".Translate(CasteUtility.SlotLabel(slot), mine, casteValue));
}
} }
} }
sb.AppendLine(); sb.AppendLine();
@ -178,8 +230,30 @@ namespace BlaxCastes
return sb.ToString(); return sb.ToString();
} }
/// <summary>True while the pawn waits in the join queue for the next tick.</summary> /// <summary>
public static bool IsPending(Pawn pawn) => JoinDefaults.IsQueued(pawn); /// One overridden slot in the cell tooltip: the slot with both values; "Schedule" alone (24 hours do
/// not fit a line); the work types that differ, each with both priorities.
/// </summary>
public static string OverrideLine(Pawn pawn, Caste caste, CasteSlot slot)
{
switch (slot)
{
case CasteSlot.Schedule:
return "BlaxCastes_CellOverrideSchedule".Translate(CasteUtility.SlotLabel(slot));
case CasteSlot.Work:
IEnumerable<string> types = CasteManager.WorkOverrides(pawn).Select(def => (string)"BlaxCastes_CellOverrideWorkType".Translate(
WorkSlot.TypeLabel(def), WorkSlot.PriorityLabel(WorkSlot.Effective(pawn.workSettings.GetPriority(def))),
WorkSlot.PriorityLabel(caste.WorkPriorityOf(def.defName))));
return "BlaxCastes_CellOverrideWork".Translate(CasteUtility.SlotLabel(slot), string.Join(", ", types));
default:
string mine = CasteUtility.ValueLabel(slot, CasteUtility.CurrentValue(pawn, slot));
string casteValue = CasteUtility.ValueLabel(slot, caste.GetSlot(slot));
return "BlaxCastes_CellOverrideLine".Translate(CasteUtility.SlotLabel(slot), mine, casteValue);
}
}
/// <summary>True while the pawn waits for a join that will change its caste on the next tick.</summary>
public static bool IsPending(Pawn pawn) => JoinDefaults.WillChange(pawn);
// ---- menu and painting ------------------------------------------------------------------- // ---- menu and painting -------------------------------------------------------------------
@ -238,14 +312,33 @@ namespace BlaxCastes
{ {
foreach (CasteMenuEntry entry in MenuEntries(pawn)) foreach (CasteMenuEntry entry in MenuEntries(pawn))
{ {
CasteMenuEntry local = entry;
Action action = local.Action == null ? null : () =>
{
if (!SkipWhilePainting(pawn, local.Choice, Widgets.Painting))
local.Action();
};
yield return new Widgets.DropdownMenuElement<CasteChoice> yield return new Widgets.DropdownMenuElement<CasteChoice>
{ {
option = new FloatMenuOption(entry.Label, entry.Action), option = new FloatMenuOption(local.Label, action),
payload = entry.Choice, payload = local.Choice,
}; };
} }
} }
/// <summary>
/// Painting runs the matching menu entry on every GUI event over a cell, the start cell included.
/// Assigning rewrites every managed slot, so a pawn already in the painted caste (or already
/// casteless) is skipped while painting, and its hand changes stay. A click still rewrites.
/// </summary>
public static bool SkipWhilePainting(Pawn pawn, CasteChoice choice, bool painting)
{
if (!painting || pawn == null)
return false;
CasteChoice current = ChoiceOf(pawn);
return (choice.Kind == CasteChoiceKind.Caste || choice.Kind == CasteChoiceKind.Casteless) && current.Equals(choice);
}
// ---- sorting ----------------------------------------------------------------------------- // ---- sorting -----------------------------------------------------------------------------
public override int Compare(Pawn a, Pawn b) => CompareCastes(Comp?.CasteOf(a), Comp?.CasteOf(b)); public override int Compare(Pawn a, Pawn b) => CompareCastes(Comp?.CasteOf(a), Comp?.CasteOf(b));

View File

@ -0,0 +1,127 @@
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RimWorld;
using Verse;
namespace BlaxCastes
{
/// <summary>
/// The schedule slot: 24 TimeAssignmentDef defNames, hour 0 first. Names resolve with
/// GetNamedSilentFail; an unknown name, and Meditate without Royalty, becomes Anything. Written with
/// Pawn_TimetableTracker.SetAssignment, only on pawns that have a timetable (prisoners from other
/// factions have none). The Follow rule looks at the whole day.
/// </summary>
public static class ScheduleSlot
{
public const int Hours = 24;
/// <summary>The time assignment for a stored name: unknown names, and Meditate without Royalty, become Anything.</summary>
public static TimeAssignmentDef Resolve(string defName)
{
TimeAssignmentDef def = defName.NullOrEmpty() ? null : DefDatabase<TimeAssignmentDef>.GetNamedSilentFail(defName);
if (def != null && def == TimeAssignmentDefOf.Meditate && !ModsConfig.RoyaltyActive)
def = null;
return def ?? TimeAssignmentDefOf.Anything;
}
/// <summary>True when the name resolves to itself (not to the Anything fallback).</summary>
public static bool IsKnown(string defName) => !defName.NullOrEmpty() && Resolve(defName).defName == defName;
/// <summary>
/// 24 stored names from a value: a list of names or of TimeAssignmentDefs. Unknown names become
/// Anything. Null for null or anything that is not 24 entries long.
/// </summary>
public static List<string> Normalize(object value)
{
IEnumerable<string> names;
switch (value)
{
case IEnumerable<string> s: names = s; break;
case IEnumerable<TimeAssignmentDef> d: names = d.Select(x => x?.defName); break;
default: return null;
}
List<string> result = names.Select(n => Resolve(n).defName).ToList();
return result.Count == Hours ? result : null;
}
/// <summary>True for a value Normalize accepts or null.</summary>
public static bool Fits(object value)
{
switch (value)
{
case null: return true;
case IEnumerable<string> s: return s.Count() == Hours;
case IEnumerable<TimeAssignmentDef> d: return d.Count() == Hours;
default: return false;
}
}
/// <summary>The game's starting schedule for a new pawn: sleep from 22 to 5, anything else the rest of the day.</summary>
public static List<string> Default()
{
var result = new List<string>(Hours);
for (int i = 0; i < Hours; i++)
result.Add((i > 5 && i <= 21 ? TimeAssignmentDefOf.Anything : TimeAssignmentDefOf.Sleep).defName);
return result;
}
public static bool HasTimetable(Pawn pawn) => pawn?.timetable?.times != null && pawn.timetable.times.Count == Hours;
/// <summary>The pawn's 24 time assignment defNames, or null without a timetable.</summary>
public static string[] Of(Pawn pawn)
{
if (!HasTimetable(pawn))
return null;
return pawn.timetable.times.Select(t => (t ?? TimeAssignmentDefOf.Anything).defName).ToArray();
}
/// <summary>True when every hour of the pawn's timetable is the caste's resolved assignment.</summary>
public static bool Matches(Pawn pawn, IReadOnlyList<string> names)
{
if (names == null || names.Count != Hours || !HasTimetable(pawn))
return false;
for (int hour = 0; hour < Hours; hour++)
{
if (pawn.timetable.times[hour] != Resolve(names[hour]))
return false;
}
return true;
}
/// <summary>Writes all 24 hours through SetAssignment. False when the pawn has no timetable.</summary>
public static bool Write(Pawn pawn, IReadOnlyList<string> names)
{
if (names == null || names.Count != Hours || !HasTimetable(pawn))
return false;
for (int hour = 0; hour < Hours; hour++)
{
TimeAssignmentDef def = Resolve(names[hour]);
if (pawn.timetable.GetAssignment(hour) != def)
pawn.timetable.SetAssignment(hour, def);
}
return true;
}
/// <summary>The day as runs of the same assignment, for tooltips and logs: "sleep 0-5, anything 6-21, sleep 22-23".</summary>
public static string Summary(IReadOnlyList<string> names)
{
if (names == null || names.Count != Hours)
return "BlaxCastes_Unmanaged".Translate();
var sb = new StringBuilder();
int start = 0;
for (int hour = 1; hour <= Hours; hour++)
{
if (hour < Hours && Resolve(names[hour]) == Resolve(names[start]))
continue;
if (sb.Length > 0)
sb.Append(", ");
sb.Append(Resolve(names[start]).label).Append(' ').Append(start);
if (hour - 1 != start)
sb.Append('-').Append(hour - 1);
start = hour;
}
return sb.ToString();
}
}
}

View File

@ -0,0 +1,176 @@
using System.Collections.Generic;
using System.Linq;
using RimWorld;
using Verse;
namespace BlaxCastes
{
/// <summary>
/// The ready-made Colonist, Slave and Prisoner castes, wired to the join rows.
/// - Colonist: the database's current default apparel, food, drug and reading policy (which already
/// carry the ideo drug rule and any earlier "Make default"). Medical care unmanaged.
/// - Slave (Ideology only): the Slave outfit, Simple food, No drugs. Reading stays unmanaged, because
/// slave children need books to learn; medical care stays unmanaged, so the game's default care for
/// slaves stays in charge.
/// - Prisoner: Simple food.
/// Policies are found by their translated starting labels, No drugs by its source def. A miss leaves
/// the slot unmanaged; Castes never creates vanilla policies itself.
/// Rows: bought as colonist and new colonist use Default caste (Colonist); bought as slave and new
/// slave use Slave; new prisoner uses Prisoner.
/// </summary>
public static class StarterCastes
{
public const string NoDrugsSourceDef = "NoDrugs";
private static bool SettingOn => BlaxCastesMod.Settings == null || BlaxCastesMod.Settings.seedStarterCastes;
public static string ColonistLabel => "BlaxCastes_StarterColonist".Translate();
public static string SlaveLabel => "BlaxCastes_StarterSlave".Translate();
public static string PrisonerLabel => "BlaxCastes_StarterPrisoner".Translate();
// ---- policy lookups ------------------------------------------------------------------
public static ApparelPolicy SlaveOutfit() => Current.Game?.outfitDatabase?.AllOutfits?.FirstOrDefault(o => o != null && o.label == (string)"OutfitSlave".Translate());
public static FoodPolicy SimpleFood() => Current.Game?.foodRestrictionDatabase?.AllFoodRestrictions?.FirstOrDefault(f => f != null && f.label == (string)"FoodRestrictionSimple".Translate());
public static DrugPolicy NoDrugs() => Current.Game?.drugPolicyDatabase?.AllPolicies?.FirstOrDefault(d => d?.sourceDef != null && d.sourceDef.defName == NoDrugsSourceDef);
/// <summary>True for the game's Slave outfit (by its starting label), which has no cold protection.</summary>
public static bool IsSlaveOutfit(Policy policy) => policy is ApparelPolicy a && a.label == (string)"OutfitSlave".Translate();
/// <summary>Ideology is active and the game has no Slave outfit (renamed or deleted): the manager offers to create one.</summary>
public static bool CanCreateSlaveOutfit => ModsConfig.IdeologyActive && Current.Game?.outfitDatabase != null && SlaveOutfit() == null;
/// <summary>
/// The manager's "Create Slave outfit" button: a new apparel policy named like the game's starting
/// Slave outfit that allows the apparel the game tags for slaves, the way a new game sets it up.
/// Only on the player's click; seeding never creates policies. Returns the existing outfit if there
/// is one, or null without Ideology.
/// </summary>
public static ApparelPolicy CreateSlaveOutfit()
{
if (!ModsConfig.IdeologyActive)
return null;
ApparelPolicy existing = SlaveOutfit();
OutfitDatabase db = Current.Game?.outfitDatabase;
if (existing != null || db == null)
return existing;
ApparelPolicy policy = db.MakeNewOutfit();
policy.label = "OutfitSlave".Translate();
policy.filter.SetDisallowAll();
if (SpecialThingFilterDefOf.AllowDeadmansApparel != null)
policy.filter.SetAllow(SpecialThingFilterDefOf.AllowDeadmansApparel, allow: false);
foreach (ThingDef def in DefDatabase<ThingDef>.AllDefs)
{
if (def.apparel?.defaultOutfitTags != null && def.apparel.defaultOutfitTags.Contains("Slave"))
policy.filter.SetAllow(def, allow: true);
}
return policy;
}
// ---- seeding -------------------------------------------------------------------------
/// <summary>
/// A new game: adds the starter castes and wires the rows, unless the setting is off or the
/// component already has castes. Returns true if it seeded.
/// </summary>
public static bool SeedNewGame(GameComponent_BlaxCastes comp)
{
if (comp == null || !SettingOn || comp.StarterCastesSeeded)
return false;
if (comp.Castes.Count > 0)
{
comp.MarkStarterCastesSeeded();
return false;
}
Seed(comp);
return true;
}
/// <summary>
/// A loaded save: adds the starter castes once per save, only if the save has no castes. A save
/// that already has castes is marked, so deleting them later does not bring the starters back.
/// Nobody is moved. Returns true if it seeded.
/// </summary>
public static bool SeedOnLoad(GameComponent_BlaxCastes comp) => SeedNewGame(comp);
/// <summary>Creates the castes in the component and wires the rows. Writes the component directly, so it works on any component.</summary>
internal static void Seed(GameComponent_BlaxCastes comp)
{
Game game = Current.Game;
Caste colonist = NewCaste(comp, ColonistLabel);
SetIfFound(colonist, CasteSlot.Apparel, game?.outfitDatabase?.DefaultOutfit());
SetIfFound(colonist, CasteSlot.Food, game?.foodRestrictionDatabase?.DefaultFoodRestriction());
SetIfFound(colonist, CasteSlot.Drug, game?.drugPolicyDatabase?.DefaultDrugPolicy());
SetIfFound(colonist, CasteSlot.Reading, game?.readingPolicyDatabase?.DefaultReadingPolicy());
Caste slave = null;
if (ModsConfig.IdeologyActive)
{
slave = NewCaste(comp, SlaveLabel);
SetIfFound(slave, CasteSlot.Apparel, SlaveOutfit());
SetIfFound(slave, CasteSlot.Food, SimpleFood());
SetIfFound(slave, CasteSlot.Drug, NoDrugs());
}
Caste prisoner = NewCaste(comp, PrisonerLabel);
SetIfFound(prisoner, CasteSlot.Food, SimpleFood());
comp.SetDefaultRaw(colonist);
comp.SetRowRaw(JoinReason.BoughtColonist, JoinRowMode.DefaultCaste, null);
comp.SetRowRaw(JoinReason.NewColonist, JoinRowMode.DefaultCaste, null);
if (slave != null)
{
comp.SetRowRaw(JoinReason.BoughtSlave, JoinRowMode.SpecificCaste, slave);
comp.SetRowRaw(JoinReason.NewSlave, JoinRowMode.SpecificCaste, slave);
}
comp.SetRowRaw(JoinReason.NewPrisoner, JoinRowMode.SpecificCaste, prisoner);
comp.MarkStarterCastesSeeded();
List<string> missing = new List<string>();
if (slave != null)
{
if (!slave.IsManaged(CasteSlot.Apparel)) missing.Add(SlaveLabel + ": " + CasteUtility.SlotLabel(CasteSlot.Apparel));
if (!slave.IsManaged(CasteSlot.Food)) missing.Add(SlaveLabel + ": " + CasteUtility.SlotLabel(CasteSlot.Food));
if (!slave.IsManaged(CasteSlot.Drug)) missing.Add(SlaveLabel + ": " + CasteUtility.SlotLabel(CasteSlot.Drug));
}
if (!prisoner.IsManaged(CasteSlot.Food)) missing.Add(PrisonerLabel + ": " + CasteUtility.SlotLabel(CasteSlot.Food));
if (missing.Count > 0)
Log.Message("[Blax Castes] Starter castes added; policies not found (renamed or removed), left unmanaged: " + string.Join(", ", missing));
}
private static Caste NewCaste(GameComponent_BlaxCastes comp, string label)
{
var caste = new Caste(comp.TakeNextId(), label);
comp.AddCaste(caste);
return caste;
}
/// <summary>No members exist yet, so the raw write needs no member sync.</summary>
private static void SetIfFound(Caste caste, CasteSlot slot, Policy policy)
{
if (policy != null && CasteUtility.PolicyExists(policy))
caste.SetSlotRaw(slot, policy);
}
/// <summary>The one message for a save that just got the starter castes.</summary>
public static void ShowSeededMessage(GameComponent_BlaxCastes comp)
{
string text = SeededMessageText(comp);
LongEventHandler.ExecuteWhenFinished(() => Messages.Message(text, MessageTypeDefOf.NeutralEvent));
}
/// <summary>
/// The seeding message. It points to Assign > Manage castes, or, while the Caste column is turned off
/// (so that button is not there), to the mod settings, which open the same window.
/// </summary>
public static string SeededMessageText(GameComponent_BlaxCastes comp)
{
string names = comp.Castes.Select(c => c.label).ToCommaList(useAnd: true);
bool column = BlaxCastesMod.Settings == null || BlaxCastesMod.Settings.showAssignColumn;
string key = column ? "BlaxCastes_StarterSeededMessage" : "BlaxCastes_StarterSeededMessageNoColumn";
return key.Translate(names.Named("CASTES"));
}
}
}

View File

@ -0,0 +1,218 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using HarmonyLib;
using Verse;
namespace BlaxCastes
{
/// <summary>
/// The weapon loadout slot's link to [1001] Weapons Tab Reborn (packageId papercrane1001.WeaponsTab).
/// Bound by reflection to the static API it publishes for Better Pawn Control, in
/// WeaponsTabReborn.LoadoutDictionary (read from its 1.6 assembly, which 1.7 loads):
/// - int BPC_GetLoadoutId(Pawn): the pawn's loadout id; a pawn without one gets the default loadout.
/// - void BPC_SetLoadoutId(Pawn, int): an id that does not exist clears the pawn's loadout, so Castes
/// checks the id first.
/// - int BPC_GetDefaultLoadoutId(): the first loadout.
/// - string BPC_GetLoadoutNamebyId(int): throws InvalidOperationException for an id that does not exist.
/// - Dictionary&lt;string, int&gt; BPC_GetWeaponsLoadoutsDatabase(): label to id. It only ever grows
/// (deleted and renamed loadouts stay in it, and a new loadout whose label is already a key is left
/// out), so every id in it is checked by name, and the ids just above the highest one are probed.
/// Loadout ids are the highest id plus one, so an id freed by deleting the newest loadout can come back.
/// A missing type or method turns the slot off for the session; a call that throws anything else turns
/// it off for the rest of the game. Either logs one warning and never throws.
/// </summary>
public static class WeaponsTab
{
public const string ApiTypeName = "WeaponsTabReborn.LoadoutDictionary";
/// <summary>How many ids above the highest known one Loadouts() checks.</summary>
private const int ProbeAhead = 16;
private static bool? modActive;
private static bool bound;
private static bool bindFailed;
private static bool callFailed;
private static Func<Pawn, int> getLoadoutId;
private static Action<Pawn, int> setLoadoutId;
private static Func<int> getDefaultLoadoutId;
private static Func<int, string> getLoadoutName;
private static Func<Dictionary<string, int>> getDatabase;
/// <summary>Weapons Tab Reborn is in the active mod list. The manager hides the loadout row without it.</summary>
public static bool ModActive => modActive ??= Compat.IsActive(Compat.WeaponsTab);
/// <summary>The mod is active and its API is bound and has not failed in this game.</summary>
public static bool Available => ModActive && Bind() && !callFailed;
public static bool SettingOn => BlaxCastesMod.Settings == null || BlaxCastesMod.Settings.manageWeaponLoadout;
/// <summary>The slot is written: the API works and the manageWeaponLoadout setting is on.</summary>
public static bool Active => SettingOn && Available;
/// <summary>Called when a game starts or loads, so a call that failed in an earlier game is tried again.</summary>
internal static void ResetForGame() => callFailed = false;
// ---- binding -----------------------------------------------------------------------------
private static bool Bind()
{
if (bound)
return !bindFailed;
bound = true;
try
{
Type api = AccessTools.TypeByName(ApiTypeName);
if (api == null)
return BindFailed("type " + ApiTypeName + " not found");
getLoadoutId = Make<Func<Pawn, int>>(api, "BPC_GetLoadoutId", typeof(int), typeof(Pawn));
setLoadoutId = Make<Action<Pawn, int>>(api, "BPC_SetLoadoutId", typeof(void), typeof(Pawn), typeof(int));
getDefaultLoadoutId = Make<Func<int>>(api, "BPC_GetDefaultLoadoutId", typeof(int));
getLoadoutName = Make<Func<int, string>>(api, "BPC_GetLoadoutNamebyId", typeof(string), typeof(int));
getDatabase = Make<Func<Dictionary<string, int>>>(api, "BPC_GetWeaponsLoadoutsDatabase", typeof(Dictionary<string, int>));
var missing = new List<string>();
if (getLoadoutId == null) missing.Add("BPC_GetLoadoutId");
if (setLoadoutId == null) missing.Add("BPC_SetLoadoutId");
if (getDefaultLoadoutId == null) missing.Add("BPC_GetDefaultLoadoutId");
if (getLoadoutName == null) missing.Add("BPC_GetLoadoutNamebyId");
if (getDatabase == null) missing.Add("BPC_GetWeaponsLoadoutsDatabase");
return missing.Count == 0 || BindFailed(string.Join(", ", missing) + " not found");
}
catch (Exception e)
{
return BindFailed(e.GetType().Name + ": " + e.Message);
}
}
private static TDelegate Make<TDelegate>(Type api, string name, Type returnType, params Type[] parameters) where TDelegate : Delegate
{
MethodInfo method = api.GetMethod(name, BindingFlags.Public | BindingFlags.Static, null, parameters, null);
if (method == null || method.ReturnType != returnType)
return null;
return (TDelegate)Delegate.CreateDelegate(typeof(TDelegate), method, throwOnBindFailure: false);
}
private static bool BindFailed(string why)
{
bindFailed = true;
Log.Warning("[Blax Castes] Weapons Tab Reborn is active, but its loadout API could not be used (" + why + "). The weapon loadout slot is off.");
return false;
}
private static void CallFailed(string call, Exception e)
{
if (callFailed)
return;
callFailed = true;
Log.Warning("[Blax Castes] Weapons Tab Reborn's " + call + " failed (" + e.GetType().Name + ": " + e.Message
+ "). The weapon loadout slot is off until the next game is loaded.");
}
// ---- calls -------------------------------------------------------------------------------
/// <summary>The pawn's loadout id, or null when the API is not available.</summary>
public static int? LoadoutOf(Pawn pawn)
{
if (pawn == null || !Available)
return null;
try
{
return getLoadoutId(pawn);
}
catch (Exception e)
{
CallFailed("BPC_GetLoadoutId", e);
return null;
}
}
/// <summary>Sets the pawn's loadout. False when the API is not available or the id does not exist.</summary>
public static bool SetLoadout(Pawn pawn, int id)
{
if (pawn == null || !Exists(id))
return false;
try
{
setLoadoutId(pawn, id);
return true;
}
catch (Exception e)
{
CallFailed("BPC_SetLoadoutId", e);
return false;
}
}
/// <summary>The default loadout's id (what a pawn without one uses), or null.</summary>
public static int? DefaultLoadoutId()
{
if (!Available)
return null;
try
{
return getDefaultLoadoutId();
}
catch (Exception e)
{
CallFailed("BPC_GetDefaultLoadoutId", e);
return null;
}
}
/// <summary>The loadout's label, or null when it does not exist or the API is not available.</summary>
public static string NameOf(int id)
{
if (id < 0 || !Available)
return null;
try
{
return getLoadoutName(id);
}
catch (InvalidOperationException)
{
// Enumerable.First found no loadout with that id: it was deleted.
return null;
}
catch (Exception e)
{
CallFailed("BPC_GetLoadoutNamebyId", e);
return null;
}
}
public static bool Exists(int id) => NameOf(id) != null;
/// <summary>The loadouts that exist now, as (id, label), by id.</summary>
public static List<KeyValuePair<int, string>> Loadouts()
{
var result = new List<KeyValuePair<int, string>>();
if (!Available)
return result;
Dictionary<string, int> database;
try
{
database = getDatabase();
}
catch (Exception e)
{
CallFailed("BPC_GetWeaponsLoadoutsDatabase", e);
return result;
}
if (database == null)
return result;
// A loadout whose label an older entry already holds never gets into the database dictionary.
// New loadouts get the highest id plus one, so the ids just above the known ones are probed too.
int highest = database.Count == 0 ? 0 : database.Values.Max();
IEnumerable<int> ids = database.Values.Concat(Enumerable.Range(0, Math.Max(0, highest) + ProbeAhead + 1));
foreach (int id in ids.Where(i => i >= 0).Distinct().OrderBy(i => i))
{
string name = NameOf(id);
if (name != null)
result.Add(new KeyValuePair<int, string>(id, name));
}
return result;
}
}
}

View File

@ -0,0 +1,281 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RimWorld;
using Verse;
namespace BlaxCastes
{
/// <summary>
/// The work priorities slot: work type defName to priority 0 (off) to 4; a type that is not listed is
/// left alone. Names resolve with GetNamedSilentFail. Work types the pawn cannot do
/// (Pawn.WorkTypeIsDisabled) are skipped, which avoids the SetPriority error. The caste's own number is
/// stored even while manual priorities are off: the game then reads any nonzero value as on, and the
/// number takes effect once manual priorities are turned on, so members still match the caste after the
/// switch. The Follow rule works per type. The slot is off while the manageWorkPriorities setting is
/// off or an automatic work manager is active.
/// </summary>
public static class WorkSlot
{
public const int Off = 0;
public const int Highest = 1;
public const int Lowest = Pawn_WorkSettings.LowestPriority;
/// <summary>The automatic work managers, by package id, with the names the player sees.</summary>
public static readonly KeyValuePair<string, string>[] Managers =
{
new KeyValuePair<string, string>(Compat.WorkTab, "Work Tab"),
new KeyValuePair<string, string>(Compat.FreeWill, "Free Will"),
new KeyValuePair<string, string>(Compat.FreeWillUnstable, "Free Will"),
new KeyValuePair<string, string>(Compat.WorkManager, "Work Manager"),
new KeyValuePair<string, string>(Compat.AutoPriorities, "AutoPriorities"),
new KeyValuePair<string, string>(Compat.WorkRoles, "WorkRoles"),
};
/// <summary>Package ids treated as active on top of the real mod list. For tests only.</summary>
public static readonly HashSet<string> SimulatedActive = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
// The mod list can't change without a restart, so the real detection runs once.
private static string detectedManager;
private static bool detectionDone;
/// <summary>The name of the first active automatic work manager, or null.</summary>
public static string ActiveManager()
{
if (!detectionDone)
{
detectionDone = true;
detectedManager = Managers.Where(m => Compat.IsActive(m.Key)).Select(m => m.Value).FirstOrDefault();
}
if (detectedManager != null || SimulatedActive.Count == 0)
return detectedManager;
return Managers.Where(m => SimulatedActive.Contains(m.Key)).Select(m => m.Value).FirstOrDefault();
}
public static bool SettingOn => BlaxCastesMod.Settings == null || BlaxCastesMod.Settings.manageWorkPriorities;
/// <summary>The slot is written: the setting is on and no automatic work manager is active.</summary>
public static bool Active => SettingOn && ActiveManager() == null;
/// <summary>The game's "manual priorities" switch. Off: a work type is only on or off.</summary>
public static bool ManualPriorities => Current.Game?.playSettings == null || Current.Game.playSettings.useWorkPriorities;
/// <summary>A priority as the game treats it right now: with manual priorities off, any nonzero value is 3.</summary>
public static int Effective(int priority)
{
if (priority <= Off)
return Off;
return ManualPriorities ? priority : Pawn_WorkSettings.DefaultPriority;
}
/// <summary>The work types the manager lists: the visible ones, in the Work tab's order.</summary>
public static List<WorkTypeDef> Types() => WorkTypeDefsUtility.WorkTypeDefsInPriorityOrder.Where(d => d.visible).ToList();
public static WorkTypeDef Resolve(string defName) => defName.NullOrEmpty() ? null : DefDatabase<WorkTypeDef>.GetNamedSilentFail(defName);
/// <summary>
/// Work type defName to priority from a value: a dictionary or any list of name and priority pairs.
/// Entries without a name or outside 0 to 4 are dropped. Null for null, anything else, or no entries.
/// </summary>
public static Dictionary<string, int> Normalize(object value)
{
if (!(value is IEnumerable<KeyValuePair<string, int>> pairs))
return null;
var result = new Dictionary<string, int>();
foreach (KeyValuePair<string, int> kv in pairs)
{
if (!kv.Key.NullOrEmpty() && kv.Value >= Off && kv.Value <= Lowest)
result[kv.Key] = kv.Value;
}
return result.Count == 0 ? null : result;
}
public static bool Fits(object value) => value == null || value is IEnumerable<KeyValuePair<string, int>>;
/// <summary>The pawn has initialized work settings.</summary>
public static bool HasWorkSettings(Pawn pawn) => pawn?.workSettings != null && pawn.workSettings.EverWork;
/// <summary>The pawn can take this work type: it exists and is not disabled for the pawn.</summary>
public static bool CanDo(Pawn pawn, WorkTypeDef def) => def != null && HasWorkSettings(pawn) && !pawn.WorkTypeIsDisabled(def);
/// <summary>
/// The pawn already has the caste's value for this type, as the game treats both right now. A type
/// the pawn cannot do, or that no longer exists, never counts as different.
/// </summary>
public static bool Matches(Pawn pawn, string defName, int casteValue)
{
WorkTypeDef def = Resolve(defName);
if (!CanDo(pawn, def))
return true;
return Effective(pawn.workSettings.GetPriority(def)) == Effective(casteValue);
}
public static bool MatchesAll(Pawn pawn, IReadOnlyDictionary<string, int> values)
{
if (values == null || !HasWorkSettings(pawn))
return false;
foreach (KeyValuePair<string, int> kv in values)
{
if (!Matches(pawn, kv.Key, kv.Value))
return false;
}
return true;
}
/// <summary>The listed types where the pawn's priority differs from the caste's, in the Work tab's order.</summary>
public static List<WorkTypeDef> Differences(Pawn pawn, IReadOnlyDictionary<string, int> values)
{
var result = new List<WorkTypeDef>();
if (values == null || !HasWorkSettings(pawn))
return result;
foreach (WorkTypeDef def in WorkTypeDefsUtility.WorkTypeDefsInPriorityOrder)
{
if (values.TryGetValue(def.defName, out int v) && !Matches(pawn, def.defName, v))
result.Add(def);
}
return result;
}
/// <summary>
/// Writes one type. Skipped (false) when the type is gone or disabled for the pawn. The value is
/// stored as it is, also while manual priorities are off (the game then reads any nonzero value as
/// on, and GetPriority hides the stored number, so it is always written).
/// </summary>
public static bool WriteType(Pawn pawn, string defName, int value)
{
WorkTypeDef def = Resolve(defName);
if (!CanDo(pawn, def) || value < Off || value > Lowest)
return false;
if (!ManualPriorities || pawn.workSettings.GetPriority(def) != value)
pawn.workSettings.SetPriority(def, value);
return true;
}
/// <summary>
/// Patient and Bed rest: the work types that send a hurt or sick pawn to bed. Every pawn starts with
/// them on and no backstory can turn them off (alwaysStartActive and no work tags), and a colonist or
/// slave has no other way to go to bed for treatment or rest. "Start from nothing" keeps them.
/// </summary>
public static bool IsSelfCare(WorkTypeDef def) => def != null && def.alwaysStartActive && def.workTags == WorkTags.None;
/// <summary>The self-care work types (IsSelfCare), in the Work tab's order.</summary>
public static List<WorkTypeDef> SelfCareTypes() => WorkTypeDefsUtility.WorkTypeDefsInPriorityOrder.Where(IsSelfCare).ToList();
/// <summary>
/// Writes the listed types. startFromNothing first turns off every other work type except the
/// self-care ones (IsSelfCare), which stay as they are, for castes that should do only their listed
/// work. True when anything was written.
/// </summary>
public static bool Write(Pawn pawn, IReadOnlyDictionary<string, int> values, bool startFromNothing)
{
if (!HasWorkSettings(pawn) || values == null || values.Count == 0)
return false;
bool any = false;
if (startFromNothing)
{
foreach (WorkTypeDef def in DefDatabase<WorkTypeDef>.AllDefsListForReading)
{
if (values.ContainsKey(def.defName) || IsSelfCare(def) || pawn.workSettings.GetPriority(def) == Off)
continue;
pawn.workSettings.SetPriority(def, Off);
}
any = true;
}
foreach (KeyValuePair<string, int> kv in values)
{
if (WriteType(pawn, kv.Key, kv.Value))
any = true;
}
return any;
}
/// <summary>
/// Every work type the caste decides, with its value: the listed ones, and with "Start from nothing"
/// every other one except the self-care types, at off. Null while the caste leaves work alone.
/// </summary>
public static Dictionary<string, int> Decided(Caste caste)
{
if (caste == null || !caste.IsManaged(CasteSlot.Work))
return null;
var result = new Dictionary<string, int>(caste.WorkPriorities);
if (caste.WorkStartFromNothing)
{
foreach (WorkTypeDef def in DefDatabase<WorkTypeDef>.AllDefsListForReading)
{
if (!result.ContainsKey(def.defName) && !IsSelfCare(def))
result[def.defName] = Off;
}
}
return result;
}
/// <summary>The pawn's priority for every work type (activeOnly: only the types that are on), or null without work settings.</summary>
public static Dictionary<string, int> Of(Pawn pawn, bool activeOnly = false)
{
if (!HasWorkSettings(pawn))
return null;
var result = new Dictionary<string, int>();
foreach (WorkTypeDef def in DefDatabase<WorkTypeDef>.AllDefsListForReading)
{
int priority = pawn.workSettings.GetPriority(def);
if (!activeOnly || priority > Off)
result[def.defName] = priority;
}
return result;
}
/// <summary>The cycle of the manager's button: leave alone, 1, 2, 3, 4, off, leave alone.</summary>
public static int? Next(int? priority)
{
if (priority == null)
return Highest;
if (priority.Value == Off)
return null;
return priority.Value >= Lowest ? Off : priority.Value + 1;
}
/// <summary>The cycle backwards: leave alone, off, 4, 3, 2, 1, leave alone.</summary>
public static int? Previous(int? priority)
{
if (priority == null)
return Off;
if (priority.Value == Off)
return Lowest;
return priority.Value <= Highest ? (int?)null : priority.Value - 1;
}
/// <summary>A priority as the manager shows it: "-" for leave alone, "off", or the number.</summary>
public static string PriorityLabel(int? priority)
{
if (priority == null)
return "BlaxCastes_WorkLeaveAloneShort".Translate();
return priority.Value == Off ? (string)"BlaxCastes_WorkOff".Translate() : priority.Value.ToString();
}
public static string TypeLabel(WorkTypeDef def) => def == null ? "" : (def.labelShort.NullOrEmpty() ? def.label : def.labelShort).CapitalizeFirst();
public static string TypeLabel(string defName) => Resolve(defName) is WorkTypeDef def ? TypeLabel(def) : defName;
/// <summary>The listed types with their priority, in the Work tab's order: "Firefight 1, Grow 1". Off types say "off".</summary>
public static string Summary(IReadOnlyDictionary<string, int> values)
{
if (values == null || values.Count == 0)
return "BlaxCastes_Unmanaged".Translate();
var parts = new List<string>();
var listed = new HashSet<string>();
foreach (WorkTypeDef def in WorkTypeDefsUtility.WorkTypeDefsInPriorityOrder)
{
if (!values.TryGetValue(def.defName, out int v))
continue;
listed.Add(def.defName);
parts.Add(TypeLabel(def) + " " + PriorityLabel(v));
}
foreach (KeyValuePair<string, int> kv in values)
{
if (!listed.Contains(kv.Key))
parts.Add(kv.Key + " " + PriorityLabel(kv.Value));
}
return string.Join(", ", parts);
}
}
}

View File

@ -33,7 +33,7 @@ namespace BlaxCastesTests
CasteManager.SetSlot(c, CasteSlot.Drug, drug); CasteManager.SetSlot(c, CasteSlot.Drug, drug);
CasteManager.SetSlot(c, CasteSlot.Reading, reading); CasteManager.SetSlot(c, CasteSlot.Reading, reading);
CasteManager.SetSlot(c, CasteSlot.MedCare, care); CasteManager.SetSlot(c, CasteSlot.MedCare, care);
foreach (CasteSlot slot in CasteUtility.AllSlots) foreach (CasteSlot slot in CasteUtility.PolicySlots)
T.Check(c.IsManaged(slot), "setup: " + slot + " slot of " + c.label + " is not managed after SetSlot"); T.Check(c.IsManaged(slot), "setup: " + slot + " slot of " + c.label + " is not managed after SetSlot");
return c; return c;
} }
@ -43,21 +43,69 @@ namespace BlaxCastesTests
// ---- tests --------------------------------------------------------------------------- // ---- tests ---------------------------------------------------------------------------
[BlaxTest("join rows: a new game has no castes, no default caste and five No caste rows")] // Runs first in the whole suite (class and source order), before any fixture joins the colony.
[BlaxTest("starter castes: a new game has Colonist, Slave (Ideology) and Prisoner, wired rows, and the starting colonists in Colonist with unchanged policies")]
public static void NewGameState() public static void NewGameState()
{ {
GameComponent_BlaxCastes comp = Fixtures.Comp; GameComponent_BlaxCastes comp = Fixtures.Comp;
Game game = Current.Game;
T.NotNull(comp, "GameComponent_BlaxCastes.Instance"); T.NotNull(comp, "GameComponent_BlaxCastes.Instance");
T.Equal(0, comp.Castes.Count, "castes in a new game"); T.Check(comp.StarterCastesSeeded, "the new game is not marked as seeded");
T.Check(comp.DefaultCaste == null, "a new game has a default caste: " + comp.DefaultCaste); T.Equal(ModsConfig.IdeologyActive ? 3 : 2, comp.Castes.Count, "castes in a new game (" + string.Join(", ", comp.Castes.Select(c => c.label)) + ")");
foreach (string reason in JoinReason.Rows) Caste colonist = comp.Castes.FirstOrDefault(c => c.label == StarterCastes.ColonistLabel);
Caste slave = comp.Castes.FirstOrDefault(c => c.label == StarterCastes.SlaveLabel);
Caste prisoner = comp.Castes.FirstOrDefault(c => c.label == StarterCastes.PrisonerLabel);
T.NotNull(colonist, "Colonist caste");
T.NotNull(prisoner, "Prisoner caste");
T.Check(comp.DefaultCaste == colonist, "the default caste is " + comp.DefaultCaste + ", not Colonist");
// Colonist: the database defaults, medical care unmanaged.
T.Check(colonist.ApparelPolicy == game.outfitDatabase.DefaultOutfit(), "Colonist apparel: " + colonist.ApparelPolicy?.label);
T.Check(colonist.FoodPolicy == game.foodRestrictionDatabase.DefaultFoodRestriction(), "Colonist food: " + colonist.FoodPolicy?.label);
T.Check(colonist.DrugPolicy == game.drugPolicyDatabase.DefaultDrugPolicy(), "Colonist drugs: " + colonist.DrugPolicy?.label);
T.Check(colonist.ReadingPolicy == game.readingPolicyDatabase.DefaultReadingPolicy(), "Colonist reading: " + colonist.ReadingPolicy?.label);
T.Check(!colonist.IsManaged(CasteSlot.MedCare), "Colonist manages medical care");
// Prisoner: Simple food only.
T.Check(prisoner.FoodPolicy == Simple(), "Prisoner food: " + prisoner.FoodPolicy?.label);
T.Check(!prisoner.IsManaged(CasteSlot.Apparel) && !prisoner.IsManaged(CasteSlot.Drug) && !prisoner.IsManaged(CasteSlot.Reading) && !prisoner.IsManaged(CasteSlot.MedCare),
"Prisoner manages more than food");
// Rows.
T.Equal(JoinRowMode.DefaultCaste, comp.GetRow(JoinReason.BoughtColonist).mode, "bought-as-colonist row");
T.Equal(JoinRowMode.DefaultCaste, comp.GetRow(JoinReason.NewColonist).mode, "new-colonist row");
T.Check(comp.ResolveRow(JoinReason.NewPrisoner) == prisoner, "new-prisoner row does not resolve to Prisoner");
if (slave != null)
{ {
JoinRow row = comp.JoinRows.FirstOrDefault(r => r.reason == reason); // Slave: the database's Slave outfit, Simple food, No drugs by source def; reading and medical care unmanaged.
T.NotNull(row, "join row " + reason); T.Check(slave.ApparelPolicy != null && slave.ApparelPolicy == StarterCastes.SlaveOutfit(), "Slave apparel: " + slave.ApparelPolicy?.label);
T.Equal(JoinRowMode.NoCaste, row.mode, "mode of join row " + reason); T.Check(game.outfitDatabase.AllOutfits.Contains(slave.ApparelPolicy), "Slave apparel is not the database's own outfit");
T.Check(comp.ResolveRow(reason) == null, "join row " + reason + " resolves to a caste"); T.Check(slave.FoodPolicy == Simple(), "Slave food: " + slave.FoodPolicy?.label);
T.Check(slave.DrugPolicy != null && slave.DrugPolicy.sourceDef?.defName == "NoDrugs", "Slave drugs: " + slave.DrugPolicy?.label);
T.Check(!slave.IsManaged(CasteSlot.Reading) && !slave.IsManaged(CasteSlot.MedCare), "Slave manages reading or medical care");
T.Check(comp.ResolveRow(JoinReason.BoughtSlave) == slave, "bought-as-slave row does not resolve to Slave");
T.Check(comp.ResolveRow(JoinReason.NewSlave) == slave, "new-slave row does not resolve to Slave");
}
else
{
T.Check(!ModsConfig.IdeologyActive, "no Slave caste although Ideology is active");
T.Equal(JoinRowMode.NoCaste, comp.GetRow(JoinReason.BoughtSlave).mode, "bought-as-slave row without Ideology");
T.Equal(JoinRowMode.NoCaste, comp.GetRow(JoinReason.NewSlave).mode, "new-slave row without Ideology");
} }
T.Equal(JoinReason.Rows.Length, comp.JoinRows.Count, "join rows in a new game"); T.Equal(JoinReason.Rows.Length, comp.JoinRows.Count, "join rows in a new game");
// Starting colonists: Colonist members, set by the new-colonist row, with no overrides.
List<Pawn> starting = Fixtures.Map.mapPawns.FreeColonists.Where(p => JoinDefaults.Eligible(p)).ToList();
T.Check(starting.Count > 0, "no starting colonists on the map");
foreach (Pawn p in starting)
{
CasteMembership m = comp.MembershipOf(p);
T.Check(m != null && m.caste == colonist && m.auto && m.reason == JoinReason.NewColonist,
p.LabelShort + "'s membership: " + (m == null ? "none" : $"caste={m.caste}, auto={m.auto}, reason={m.reason}"));
T.Equal(0, CasteManager.Overrides(p).Count, p.LabelShort + "'s overrides (" + Values(p) + ")");
}
T.Equal(0, comp.JoinQueue.Count(q => q != null && starting.Contains(q.pawn)), "starting colonists still queued");
T.Info("starting colonists: " + string.Join(", ", starting.Select(p => p.LabelShort)));
} }
[BlaxTest("castes: assigning sets apparel, food, drugs, reading and medical care on a colonist")] [BlaxTest("castes: assigning sets apparel, food, drugs, reading and medical care on a colonist")]

View File

@ -177,6 +177,21 @@ namespace BlaxCastesTests
return policy; return policy;
} }
/// <summary>A def that must exist; fails the test otherwise.</summary>
public static TD NeedDef<TD>(TD def, string what) where TD : Def
{
T.NotNull(def, what);
return def;
}
/// <summary>A caste made elsewhere (DuplicateCaste), deleted after the test like NewCaste's.</summary>
public static Caste Track(Caste c)
{
T.NotNull(c, "caste to track");
madeCastes.Add(c);
return c;
}
// ---- time ------------------------------------------------------------------------ // ---- time ------------------------------------------------------------------------
public static void Tick(int ticks) public static void Tick(int ticks)
@ -184,6 +199,39 @@ namespace BlaxCastesTests
for (int i = 0; i < ticks; i++) Find.TickManager.DoSingleTick(); for (int i = 0; i < ticks; i++) Find.TickManager.DoSingleTick();
} }
/// <summary>
/// Applies the queued joins of the given pawns now, as the next tick would, without ticking the
/// game: fixture prisoners outside a prison cell make vanilla's prisoner job givers throw when the
/// game ticks. Other pawns' queued joins (kept fixtures of earlier tests) stay queued untouched.
/// </summary>
public static void ApplyJoins(params Pawn[] pawns)
{
List<QueuedJoin> queue = Comp.JoinQueue;
var others = queue.Where(q => q == null || !pawns.Contains(q.pawn)).ToList();
queue.RemoveAll(q => others.Contains(q));
int now = Find.TickManager.TicksGame;
foreach (QueuedJoin q in queue)
{
if (q.tick >= now)
q.tick = now - 1;
}
try
{
JoinDefaults.ApplyQueue();
}
finally
{
foreach (QueuedJoin q in others)
{
if (q != null && !queue.Any(x => x != null && x.pawn == q.pawn))
queue.Add(q);
}
}
}
/// <summary>Removes the pawn's queued join (fixtures can be queued when they are generated into the colony).</summary>
public static void Unqueue(Pawn p) => Comp.JoinQueue.RemoveAll(q => q != null && q.pawn == p);
/// <summary>Ticks until the 2500-tick sweep has run once.</summary> /// <summary>Ticks until the 2500-tick sweep has run once.</summary>
public static void TickThroughSweep() public static void TickThroughSweep()
{ {
@ -245,7 +293,7 @@ namespace BlaxCastesTests
foreach (Pawn p in made) foreach (Pawn p in made)
{ {
if (p == null || kept.Contains(p)) continue; if (p == null || kept.Contains(p)) continue;
if (p.Dead) DropRitualObligations(p); DropRitualObligations(p);
if (p.Corpse != null && p.Corpse.Spawned) p.Corpse.Destroy(DestroyMode.Vanish); if (p.Corpse != null && p.Corpse.Spawned) p.Corpse.Destroy(DestroyMode.Vanish);
else if (p.Spawned) p.Destroy(DestroyMode.Vanish); else if (p.Spawned) p.Destroy(DestroyMode.Vanish);
else if (p.IsWorldPawn()) Find.WorldPawns.RemoveAndDiscardPawnViaGC(p); else if (p.IsWorldPawn()) Find.WorldPawns.RemoveAndDiscardPawnViaGC(p);
@ -254,8 +302,9 @@ namespace BlaxCastesTests
} }
/// <summary> /// <summary>
/// A fixture colonist that died gets a funeral obligation (Ideology). The cleanup destroys its corpse, /// A fixture colonist that died gets a funeral obligation, and a living one can get a scarification or
/// so drop the obligation too, or the save warns about a reference to a discarded pawn. /// blinding obligation when it joins or changes status (Ideology). The cleanup destroys the pawn or its
/// corpse, so drop those obligations too, or the save warns about a reference to a discarded pawn.
/// </summary> /// </summary>
private static void DropRitualObligations(Pawn p) private static void DropRitualObligations(Pawn p)
{ {

View File

@ -161,11 +161,37 @@ namespace BlaxCastesTests
if (type != LogType.Error && type != LogType.Exception) return; if (type != LogType.Error && type != LogType.Exception) return;
string where = currentTest ?? "(between tests)"; string where = currentTest ?? "(between tests)";
string entry = where + ": " + OneLine(text); string entry = where + ": " + OneLine(text);
bool ours = (text != null && (text.Contains("BlaxCastes") || text.Contains("Blax Castes"))) || (stack != null && stack.Contains("BlaxCastes")); bool ours = !IsKnownForeignError(text, stack)
&& ((text != null && (text.Contains("BlaxCastes") || text.Contains("Blax Castes"))) || (stack != null && stack.Contains("BlaxCastes")));
lock (modErrors) (ours ? modErrors : otherErrors).Add(entry); lock (modErrors) (ours ? modErrors : otherErrors).Add(entry);
}; };
} }
/// <summary>
/// Errors another mod logs from its own code while a test ticks the game. The test's frames are in the
/// stack, so the check above would blame Blax Castes; these show as LOGERR lines instead. Each entry is a
/// text fragment and the frame that logs it:
/// - Weapons Tab Reborn (-Compat): its JobGiver_EquipLoadout sits in the Humanlike_PreMain think tree
/// hook, which every humanlike runs, and logs "Non-colonist X tried to equip loadout." once for the
/// first pawn of another faction that thinks (a fixture that left the colony, a visitor, a raider).
/// </summary>
private static readonly (string text, string frame)[] KnownForeignErrors =
{
("tried to equip loadout", "WeaponsTabReborn.JobGiver_EquipLoadout.TryGiveJob"),
};
private static bool IsKnownForeignError(string text, string stack)
{
if (text == null || stack == null)
return false;
foreach (var (fragment, frame) in KnownForeignErrors)
{
if (text.Contains(fragment) && stack.Contains(frame))
return true;
}
return false;
}
private static void RunPhase(int phase) private static void RunPhase(int phase)
{ {
var tests = typeof(TestRunner).Assembly.GetTypes() var tests = typeof(TestRunner).Assembly.GetTypes()

View File

@ -73,7 +73,7 @@ namespace BlaxCastesTests
/// A trader that hands pawns over the way Pawn_TraderTracker does (PreTraded, nothing else), so /// A trader that hands pawns over the way Pawn_TraderTracker does (PreTraded, nothing else), so
/// Tradeable_Pawn.ResolveTrade and the buy-mode patches on it run without a ship or a caravan. /// Tradeable_Pawn.ResolveTrade and the buy-mode patches on it run without a ship or a caravan.
/// </summary> /// </summary>
private sealed class TestTrader : ITrader internal sealed class TestTrader : ITrader
{ {
private readonly Faction faction; private readonly Faction faction;
private readonly TraderKindDef kind; private readonly TraderKindDef kind;
@ -103,7 +103,7 @@ namespace BlaxCastesTests
} }
/// <summary>An unspawned, recruitable pawn as trader stock holds it.</summary> /// <summary>An unspawned, recruitable pawn as trader stock holds it.</summary>
private static Pawn StockPawn(JoinStatus status) internal static Pawn StockPawn(JoinStatus status)
{ {
Faction from = Fixtures.FriendlyFaction(); Faction from = Fixtures.FriendlyFaction();
if (from == null) if (from == null)
@ -115,7 +115,7 @@ namespace BlaxCastesTests
} }
/// <summary>Buys the pawn through vanilla Pawn.PreTraded(PlayerBuys), then lets it arrive on the map.</summary> /// <summary>Buys the pawn through vanilla Pawn.PreTraded(PlayerBuys), then lets it arrive on the map.</summary>
private static void Buy(Pawn p, Pawn negotiator, ITrader trader) internal static void Buy(Pawn p, Pawn negotiator, ITrader trader)
{ {
p.PreTraded(TradeAction.PlayerBuys, negotiator, trader); p.PreTraded(TradeAction.PlayerBuys, negotiator, trader);
if (!p.Spawned) if (!p.Spawned)
@ -124,7 +124,7 @@ namespace BlaxCastesTests
private static readonly FieldInfo LiveMessages = AccessTools.Field(typeof(Messages), "liveMessages"); private static readonly FieldInfo LiveMessages = AccessTools.Field(typeof(Messages), "liveMessages");
private static bool MessageShown(string part) internal static bool MessageShown(string part)
{ {
T.NotNull(LiveMessages, "Messages.liveMessages (renamed in this game version?)"); T.NotNull(LiveMessages, "Messages.liveMessages (renamed in this game version?)");
var live = (List<Message>)LiveMessages.GetValue(null); var live = (List<Message>)LiveMessages.GetValue(null);
@ -492,6 +492,9 @@ namespace BlaxCastesTests
const string reason = JoinReason.NewColonist; const string reason = JoinReason.NewColonist;
List<FloatMenuOption> menu = Dialog_JoinDefaults.RowMenu(reason); List<FloatMenuOption> menu = Dialog_JoinDefaults.RowMenu(reason);
T.Equal(2 + Fixtures.Comp.Castes.Count, menu.Count, "menu entries (No caste, Default caste, one per caste)"); T.Equal(2 + Fixtures.Comp.Castes.Count, menu.Count, "menu entries (No caste, Default caste, one per caste)");
List<string> casteLabels = menu.Skip(2).Select(o => o.Label).ToList();
T.Check(casteLabels.SequenceEqual(casteLabels.OrderBy(l => l, StringComparer.CurrentCultureIgnoreCase)),
"castes not sorted by label like the Caste column: " + string.Join(", ", casteLabels));
menu.First(o => o.Label == c.label).action(); menu.First(o => o.Label == c.label).action();
T.Check(Fixtures.Comp.ResolveRow(reason) == c, "picking a caste did not set the row"); T.Check(Fixtures.Comp.ResolveRow(reason) == c, "picking a caste did not set the row");

View File

@ -126,6 +126,71 @@ namespace BlaxCastesTests
T.Check(CasteManager.SetJoinRow(JoinReason.NewColonist, JoinRowMode.SpecificCaste, one) && comp.ResolveRow(JoinReason.NewColonist) == one, "SpecificCaste row does not resolve to its caste"); T.Check(CasteManager.SetJoinRow(JoinReason.NewColonist, JoinRowMode.SpecificCaste, one) && comp.ResolveRow(JoinReason.NewColonist) == one, "SpecificCaste row does not resolve to its caste");
} }
[BlaxTest("manager: Apply to all members clears an override on every member; the confirm names the member count")]
public static void ApplyToAllClearsOverrides()
{
Caste c = Full("Apply to all");
Pawn a = Fixtures.Colonist();
Pawn b = Fixtures.Colonist();
foreach (Pawn p in new[] { a, b })
{
Fixtures.Unqueue(p);
T.Check(CasteManager.Assign(p, c, false, JoinReason.Manual), "setup: Assign failed");
}
FoodPolicy lavish = Fixtures.Need(Fixtures.Food("FoodRestrictionLavish"), "Lavish food");
b.foodRestriction.CurrentFoodPolicy = lavish; // by hand
T.Equal(1, CasteManager.Overrides(b).Count, "setup: B's overrides");
T.Equal(2, CasteManager.LiveMembers(c).Count, "live members");
string confirm = Dialog_ManageCastes.ApplyToAllConfirmText(c, CasteManager.LiveMembers(c).Count);
T.Check(confirm.Contains("2") && confirm.Contains(c.label), "confirm text does not name the count and the caste: " + confirm);
T.Equal(2, CasteManager.ApplyToAll(c), "members written by Apply to all");
T.Equal(0, CasteManager.Overrides(b).Count, "B's overrides after Apply to all (" + Policies(b) + ")");
T.Check(b.foodRestriction.CurrentFoodPolicy == c.FoodPolicy, "B's food after Apply to all");
Fixtures.Settings.enabled = false;
b.foodRestriction.CurrentFoodPolicy = lavish;
T.Equal(0, CasteManager.ApplyToAll(c), "members written by Apply to all with Castes off");
T.Check(b.foodRestriction.CurrentFoodPolicy == lavish, "Apply to all wrote a policy with Castes off");
}
[BlaxTest("manager: Assign by status puts a pawn without a caste into its status row's caste and leaves a casteless-by-choice pawn alone")]
public static void AssignByStatus()
{
bool slaves = ModsConfig.IdeologyActive;
string row = slaves ? JoinReason.NewSlave : JoinReason.NewColonist;
Caste c = Fixtures.NewCaste("Assign by status");
CasteManager.SetSlot(c, CasteSlot.Food, Fixtures.Need(Fixtures.Food("FoodRestrictionSimple"), "Simple food"));
T.Check(CasteManager.SetJoinRow(row, JoinRowMode.SpecificCaste, c), "setup: SetJoinRow failed");
Pawn unassigned = slaves ? Fixtures.ColonySlave() : Fixtures.Colonist();
Pawn casteless = slaves ? Fixtures.ColonySlave() : Fixtures.Colonist();
Pawn queued = slaves ? Fixtures.ColonySlave() : Fixtures.Colonist();
Fixtures.Unqueue(unassigned);
Fixtures.Unqueue(casteless);
Fixtures.Unqueue(queued);
JoinDefaults.Enqueue(queued, JoinDefaults.StatusFallback);
T.Check(CasteManager.MakeCasteless(casteless), "setup: MakeCasteless failed");
var waiting = CasteManager.PawnsToAssignByStatus();
T.Check(waiting.Contains(unassigned), "a pawn without a record is not offered");
T.Check(!waiting.Contains(casteless), "a casteless-by-choice pawn is offered");
T.Check(!waiting.Contains(queued), "a pawn waiting for its join is offered");
string confirm = Dialog_ManageCastes.AssignByStatusConfirmText(waiting.Count);
T.Check(confirm.Contains(waiting.Count.ToString()), "the confirm does not name the count: " + confirm);
int assigned = CasteManager.AssignByStatus();
T.Check(assigned >= 1, "Assign by status assigned " + assigned);
CasteMembership m = Fixtures.Comp.MembershipOf(unassigned);
T.Check(m != null && m.caste == c && m.auto && m.reason == row, $"unassigned pawn after Assign by status: caste={m?.caste}, auto={m?.auto}, reason={m?.reason}");
T.Check(unassigned.foodRestriction.CurrentFoodPolicy == c.FoodPolicy, "Assign by status did not write the caste's food");
T.Check(Fixtures.Comp.MembershipOf(casteless).Casteless, "the casteless-by-choice pawn got a caste");
T.Check(!CasteManager.PawnsToAssignByStatus().Contains(unassigned), "the assigned pawn is still offered");
Fixtures.Unqueue(queued);
if (!slaves)
T.Info("Ideology off: checked with colonists and the new colonist row");
}
[BlaxTest("manager: only player-side humanlikes can be members; MakeCasteless keeps policies")] [BlaxTest("manager: only player-side humanlikes can be members; MakeCasteless keeps policies")]
public static void MembershipRules() public static void MembershipRules()
{ {

View File

@ -0,0 +1,70 @@
using System.Collections.Generic;
using System.Linq;
using BlaxCastes;
using RimWorld;
using Verse;
namespace BlaxCastesTests
{
/// <summary>
/// Overlap warnings. None of the overlapping mods is installed on the test machine, so a package id is
/// injected into the detection list (OverlapWarnings.SimulatedActive). The message goes to a fresh
/// component, so the running save's "warned" list stays as it is.
/// </summary>
public static class OverlapTests
{
[BlaxTest("overlap: every overlapping mod has a distinct package id, a name and a Keyed description; the work managers are listed")]
public static void ListIsSane()
{
OverlapMod[] mods = OverlapWarnings.Mods;
T.Equal(5, mods.Length, "overlapping mods");
T.Equal(mods.Length, mods.Select(m => m.PackageId.ToLowerInvariant()).Distinct().Count(), "distinct package ids");
foreach (OverlapMod m in mods)
{
T.Check(!m.Name.NullOrEmpty() && m.PackageId.Contains("."), "bad entry: " + m.Name + " / " + m.PackageId);
T.Check(m.WhatKey.CanTranslate(), m.Name + ": " + m.WhatKey + " missing from Keyed");
}
T.Equal(6, Compat.WorkManagers.Distinct().Count(), "work manager package ids");
string[] keys = { "BlaxCastes_OverlapSettingsIntro", "BlaxCastes_OverlapLine", "BlaxCastes_OverlapAdvice", "BlaxCastes_OverlapMessage",
"BlaxCastes_SettingWarnOverlaps", "BlaxCastes_SettingWarnOverlapsTip" };
List<string> missing = keys.Where(k => !k.CanTranslate()).ToList();
T.Check(missing.Count == 0, "strings missing from Keyed: " + string.Join(", ", missing));
List<OverlapMod> real = OverlapWarnings.Active();
T.Info("overlapping mods active in this run: " + (real.Count == 0 ? "none" : string.Join(", ", real.Select(m => m.Name))));
}
[BlaxTest("overlap: an injected active id shows in the settings text and in one message per save; warnOverlaps off hides both")]
public static void InjectedIdIsNamed()
{
OverlapMod target = OverlapWarnings.Mods.First(m => m.PackageId == Compat.AutomaticSlaveOutfit);
bool hadReal = OverlapWarnings.Active().Contains(target);
OverlapWarnings.SimulatedActive.Add(target.PackageId.ToUpperInvariant()); // the id matches in any case, as RimWorld does
try
{
T.Check(OverlapWarnings.Active().Contains(target), "the injected id is not detected");
string text = OverlapWarnings.SettingsText();
T.NotNull(text, "settings text with an overlapping mod active");
T.Check(text.Contains(target.Name) && text.Contains(target.What), "settings text does not name " + target.Name + ": " + text);
Messages.Clear();
var fresh = new GameComponent_BlaxCastes(Current.Game);
List<OverlapMod> named = OverlapWarnings.ShowMessageOnce(fresh);
T.Check(named.Contains(target), "the message did not name " + target.Name);
T.Check(fresh.OverlapWarned(target.PackageId), "the save does not remember the warning");
string message = ((string)OverlapWarnings.MessageText(named)).CapitalizeFirst();
T.Check(message.Contains(target.Name), "message text: " + message);
T.Equal(1, Find.Archive.ArchivablesListForReading.OfType<Message>().Count(m => m.text == message), "overlap messages posted");
T.Equal(0, OverlapWarnings.ShowMessageOnce(fresh).Count, "mods named by a second call in the same save");
Fixtures.Settings.warnOverlaps = false;
T.Check(OverlapWarnings.SettingsText() == null, "settings text with warnOverlaps off");
T.Equal(0, OverlapWarnings.ShowMessageOnce(new GameComponent_BlaxCastes(Current.Game)).Count, "mods named with warnOverlaps off");
}
finally
{
OverlapWarnings.SimulatedActive.Clear();
}
T.Equal(hadReal, OverlapWarnings.Active().Contains(target), "detection after removing the injected id");
}
}
}

View File

@ -82,6 +82,8 @@ namespace BlaxCastesTests
Pawn casteless = Fixtures.Keep(Fixtures.Colonist()); Pawn casteless = Fixtures.Keep(Fixtures.Colonist());
Pawn prisoner = Fixtures.Keep(Fixtures.Prisoner()); Pawn prisoner = Fixtures.Keep(Fixtures.Prisoner());
Pawn gone = Fixtures.Colonist(); // destroyed by the cleanup after this test; its record must not survive the save Pawn gone = Fixtures.Colonist(); // destroyed by the cleanup after this test; its record must not survive the save
foreach (Pawn kept in new[] { member, casteless, prisoner, gone })
Fixtures.Unqueue(kept); // assigned directly below; a queued join would move them by whatever rows later tests set
T.Check(CasteManager.Assign(member, full, true, JoinReason.NewColonist), "Assign member failed"); T.Check(CasteManager.Assign(member, full, true, JoinReason.NewColonist), "Assign member failed");
T.Check(CasteManager.Assign(casteless, full, false, JoinReason.Manual) && CasteManager.MakeCasteless(casteless), "casteless setup failed"); T.Check(CasteManager.Assign(casteless, full, false, JoinReason.Manual) && CasteManager.MakeCasteless(casteless), "casteless setup failed");
T.Check(CasteManager.Assign(prisoner, partial, true, JoinReason.NewPrisoner), "Assign prisoner failed"); T.Check(CasteManager.Assign(prisoner, partial, true, JoinReason.NewPrisoner), "Assign prisoner failed");

View File

@ -20,13 +20,21 @@ namespace BlaxCastesTests
private const string TestModId = "BlaxCastesSettingsTest"; private const string TestModId = "BlaxCastesSettingsTest";
private const string Handle = nameof(BlaxCastesMod); private const string Handle = nameof(BlaxCastesMod);
private static readonly string[] Expected = { "enabled", "enableJoinDefaults", "joinMessages", "revertOnLeave", "showAssignColumn" }; private static readonly string[] Expected =
{
"enabled", "manageWorkPriorities", "manageWeaponLoadout", "enableJoinDefaults", "joinMessages", "revertOnLeave",
"returnToPreviousCaste", "formerCasteDays", "seedStarterCastes", "warnOverlaps", "showAssignColumn",
};
private static readonly string[] SettingsUiKeys = private static readonly string[] SettingsUiKeys =
{ {
"BlaxCastes_SettingEnabled", "BlaxCastes_SettingEnabledTip", "BlaxCastes_SettingJoinDefaults", "BlaxCastes_SettingJoinDefaultsTip", "BlaxCastes_SettingEnabled", "BlaxCastes_SettingEnabledTip", "BlaxCastes_SettingJoinDefaults", "BlaxCastes_SettingJoinDefaultsTip",
"BlaxCastes_SettingJoinMessages", "BlaxCastes_SettingJoinMessagesTip", "BlaxCastes_SettingRevertOnLeave", "BlaxCastes_SettingRevertOnLeaveTip", "BlaxCastes_SettingJoinMessages", "BlaxCastes_SettingJoinMessagesTip", "BlaxCastes_SettingRevertOnLeave", "BlaxCastes_SettingRevertOnLeaveTip",
"BlaxCastes_SettingReturnToPrevious", "BlaxCastes_SettingReturnToPreviousTip", "BlaxCastes_SettingFormerCasteDays", "BlaxCastes_SettingFormerCasteDaysTip",
"BlaxCastes_SettingSeedStarter", "BlaxCastes_SettingSeedStarterTip", "BlaxCastes_SettingWarnOverlaps", "BlaxCastes_SettingWarnOverlapsTip",
"BlaxCastes_SettingShowAssignColumn", "BlaxCastes_SettingShowAssignColumnTip", "BlaxCastes_SettingNoIdeology", "BlaxCastes_SettingsReset", "BlaxCastes_SettingShowAssignColumn", "BlaxCastes_SettingShowAssignColumnTip", "BlaxCastes_SettingNoIdeology", "BlaxCastes_SettingsReset",
"BlaxCastes_SettingWorkPriorities", "BlaxCastes_SettingWorkPrioritiesTip", "BlaxCastes_SettingWeaponLoadout", "BlaxCastes_SettingWeaponLoadoutTip",
"BlaxCastes_WorkManagerActive",
}; };
private static FieldInfo[] Fields => typeof(BlaxCastesSettings).GetFields(BindingFlags.Public | BindingFlags.Instance); private static FieldInfo[] Fields => typeof(BlaxCastesSettings).GetFields(BindingFlags.Public | BindingFlags.Instance);
@ -44,15 +52,19 @@ namespace BlaxCastesTests
T.Check(missing.Count == 0, "settings window strings missing from Keyed: " + string.Join(", ", missing)); T.Check(missing.Count == 0, "settings window strings missing from Keyed: " + string.Join(", ", missing));
} }
[BlaxTest("settings: the five 1.0 toggles exist and default to on")] [BlaxTest("settings: the 1.0 settings exist; the toggles default to on and formerCasteDays to 60")]
public static void DefaultsOn() public static void DefaultsOn()
{ {
var names = Fields.Select(f => f.Name).ToList(); var names = Fields.Select(f => f.Name).ToList();
T.Check(Expected.All(names.Contains), "missing settings fields: " + string.Join(", ", Expected.Where(n => !names.Contains(n)))); T.Check(Expected.All(names.Contains), "missing settings fields: " + string.Join(", ", Expected.Where(n => !names.Contains(n))));
T.Check(names.All(Expected.Contains), "settings fields this test doesn't know (extend it): " + string.Join(", ", names.Where(n => !Expected.Contains(n)))); T.Check(names.All(Expected.Contains), "settings fields this test doesn't know (extend it): " + string.Join(", ", names.Where(n => !Expected.Contains(n))));
var d = new BlaxCastesSettings(); var d = new BlaxCastesSettings();
var off = Fields.Where(f => !(f.GetValue(d) is bool b && b)).Select(f => f.Name).ToList(); var off = Fields.Where(f => f.FieldType == typeof(bool) && !(bool)f.GetValue(d)).Select(f => f.Name).ToList();
T.Check(off.Count == 0, "settings not defaulting to on: " + string.Join(", ", off)); T.Check(off.Count == 0, "settings not defaulting to on: " + string.Join(", ", off));
T.Equal(60, d.formerCasteDays, "formerCasteDays default");
T.Equal(BlaxCastesSettings.DefaultFormerCasteDays, d.formerCasteDays, "DefaultFormerCasteDays");
var other = Fields.Where(f => f.FieldType != typeof(bool) && f.Name != "formerCasteDays").Select(f => f.Name).ToList();
T.Check(other.Count == 0, "settings of another type this test does not know: " + string.Join(", ", other));
} }
[BlaxTest("settings: every field round-trips through the settings file, and Reset restores the defaults")] [BlaxTest("settings: every field round-trips through the settings file, and Reset restores the defaults")]
@ -60,7 +72,7 @@ namespace BlaxCastesTests
{ {
var src = new BlaxCastesSettings(); var src = new BlaxCastesSettings();
foreach (FieldInfo f in Fields) foreach (FieldInfo f in Fields)
f.SetValue(src, false); f.SetValue(src, f.FieldType == typeof(int) ? (object)7 : false);
string path = SettingsPath(); string path = SettingsPath();
try try
{ {

View File

@ -0,0 +1,866 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using BlaxCastes;
using HarmonyLib;
using RimWorld;
using Verse;
namespace BlaxCastesTests
{
/// <summary>
/// The schedule, work priorities and weapon loadout slots: what they write, who they skip, the Follow
/// rule, the checks against missing defs and loadouts, and the Caste column in the Schedule and Work tabs.
/// The loadout tests need Weapons Tab Reborn (run-tests.ps1 -Compat) and skip without it, except the one
/// that checks the slot stays off without the mod.
/// </summary>
public static class SlotTests
{
// ---- schedule helpers --------------------------------------------------------------------
/// <summary>Work from 22 to 5, joy 6 and 7, sleep 8 to 15, anything the rest: nothing like the starting schedule.</summary>
private static List<string> NightSchedule()
{
var names = new List<string>();
for (int h = 0; h < ScheduleSlot.Hours; h++)
{
TimeAssignmentDef d = h >= 22 || h <= 5 ? TimeAssignmentDefOf.Work
: h <= 7 ? TimeAssignmentDefOf.Joy
: h <= 15 ? TimeAssignmentDefOf.Sleep
: TimeAssignmentDefOf.Anything;
names.Add(d.defName);
}
return names;
}
private static string Hours(Pawn p) => ScheduleSlot.Summary(ScheduleSlot.Of(p));
private static void CheckSchedule(Pawn p, IReadOnlyList<string> names, string who)
{
T.Check(ScheduleSlot.HasTimetable(p), who + " has no timetable");
for (int h = 0; h < ScheduleSlot.Hours; h++)
{
string mine = p.timetable.GetAssignment(h).defName;
T.Check(mine == names[h], $"{who} hour {h}: {mine}, the caste says {names[h]} ({who}: {Hours(p)})");
}
}
// ---- work helpers ------------------------------------------------------------------------
private static WorkTypeDef Work(string defName) => Fixtures.NeedDef(DefDatabase<WorkTypeDef>.GetNamedSilentFail(defName), "work type " + defName);
private static WorkTypeDef Growing => Work("Growing");
private static WorkTypeDef Firefighter => Work("Firefighter");
private static WorkTypeDef Cooking => Work("Cooking");
/// <summary>A pawn from the factory that can do every given work type (backstories and traits can disable some).</summary>
private static Pawn PawnThatCan(Func<Pawn> make, params WorkTypeDef[] types)
{
for (int i = 0; i < 12; i++)
{
Pawn p = make();
Fixtures.Unqueue(p);
if (WorkSlot.HasWorkSettings(p) && types.All(t => !p.WorkTypeIsDisabled(t)))
return p;
}
T.Fail("no generated pawn could do " + string.Join(", ", types.Select(t => t.defName)) + " in 12 tries");
return null;
}
/// <summary>Runs the body with the game's manual priorities switch set, and puts it back afterwards.</summary>
private static void WithManualPriorities(bool on, Action body)
{
PlaySettings play = Find.PlaySettings;
bool before = play.useWorkPriorities;
play.useWorkPriorities = on;
try
{
body();
}
finally
{
play.useWorkPriorities = before;
}
}
private static int Priority(Pawn p, WorkTypeDef def) => p.workSettings.GetPriority(def);
private static Dictionary<WorkTypeDef, int> AllPriorities(Pawn p) =>
DefDatabase<WorkTypeDef>.AllDefsListForReading.ToDictionary(d => d, d => p.workSettings.GetPriority(d));
private static void CheckWorkSlotUsable()
{
if (WorkSlot.ActiveManager() != null)
T.Skip(WorkSlot.ActiveManager() + " is active, so the work slot is off");
T.Check(WorkSlot.Active, "the work slot is off (manageWorkPriorities " + Fixtures.Settings.manageWorkPriorities + ")");
}
// ---- loadout helpers (Weapons Tab Reborn, by reflection) ---------------------------------
private static void NeedWeaponsTab()
{
if (!WeaponsTab.ModActive)
T.Skip("needs Weapons Tab Reborn (run-tests.ps1 -Compat)");
T.Check(WeaponsTab.Available, "Weapons Tab Reborn is active but its loadout API is not available (see the warning in the log)");
}
private static object LoadoutDatabase()
{
Type dictionary = AccessTools.TypeByName(WeaponsTab.ApiTypeName);
T.NotNull(dictionary, WeaponsTab.ApiTypeName);
object db = AccessTools.Field(dictionary, "CurrentLoadoutDatabase")?.GetValue(null);
T.NotNull(db, "Weapons Tab Reborn's loadout database (its Game patch did not run?)");
return db;
}
/// <summary>A new Weapons Tab Reborn loadout with this label; returns its id.</summary>
private static int MakeLoadout(string label)
{
object db = LoadoutDatabase();
object loadout = AccessTools.Method(db.GetType(), "MakeNewLoadout").Invoke(db, null);
T.NotNull(loadout, "MakeNewLoadout result");
AccessTools.Field(loadout.GetType(), "label").SetValue(loadout, label);
return (int)AccessTools.Field(loadout.GetType(), "uniqueID").GetValue(loadout);
}
/// <summary>Deletes a loadout the way Weapons Tab Reborn's window does (refused while a live pawn uses it).</summary>
private static AcceptanceReport DeleteLoadout(int id)
{
object db = LoadoutDatabase();
var all = (System.Collections.IList)AccessTools.Property(db.GetType(), "AllLoadouts").GetValue(db);
object loadout = all.Cast<object>().FirstOrDefault(l => (int)AccessTools.Field(l.GetType(), "uniqueID").GetValue(l) == id);
T.NotNull(loadout, "loadout " + id);
return (AcceptanceReport)AccessTools.Method(db.GetType(), "TryDelete").Invoke(db, new[] { loadout });
}
private static void SetLoadoutIdRaw(Caste c, int id) => AccessTools.Field(typeof(Caste), "loadoutId").SetValue(c, id);
private static void CheckSlots() => AccessTools.Method(typeof(CasteManager), "CheckSlots").Invoke(null, new object[] { Fixtures.Comp });
// ---- schedule ----------------------------------------------------------------------------
[BlaxTest("schedule: a caste's night schedule sets all 24 hours on a colonist and on a slave")]
public static void ScheduleOnColonistAndSlave()
{
List<string> night = NightSchedule();
Caste c = Fixtures.NewCaste("Night shift");
T.Equal(0, CasteManager.SetSlot(c, CasteSlot.Schedule, night), "members moved on a caste without members");
T.Check(c.IsManaged(CasteSlot.Schedule) && c.Schedule.SequenceEqual(night), "the caste does not hold the night schedule: " + ScheduleSlot.Summary(c.Schedule));
Pawn colonist = Fixtures.Colonist();
T.Check(!ScheduleSlot.Matches(colonist, night), "setup: the colonist already works nights");
T.Check(CasteManager.Assign(colonist, c, false, JoinReason.Manual), "Assign failed for the colonist");
CheckSchedule(colonist, night, "colonist");
T.Equal(0, CasteManager.Overrides(colonist).Count, "colonist's overrides right after Assign");
Pawn slave = Fixtures.ColonySlave(); // skips here without Ideology; the colonist part passed
T.Check(CasteManager.Assign(slave, c, true, JoinReason.NewSlave), "Assign failed for the slave");
CheckSchedule(slave, night, "slave");
}
[BlaxTest("schedule: a prisoner skips the schedule without errors, even with a timetable; its food is still set")]
public static void SchedulePrisonerSkips()
{
Pawn p = Fixtures.Prisoner();
T.Info("a captured raider's timetable: " + (p.timetable == null ? "none" : "present"));
T.Check(!CasteUtility.CanUse(p, CasteSlot.Schedule), "CanUse(Schedule) is true for a prisoner without a timetable");
Caste c = Fixtures.NewCaste("Prisoner night shift");
CasteManager.SetSlot(c, CasteSlot.Schedule, NightSchedule());
FoodPolicy food = Fixtures.Need(Fixtures.Food(p.foodRestriction.CurrentFoodPolicy == Fixtures.Food("FoodRestrictionPaste") ? "FoodRestrictionSimple" : "FoodRestrictionPaste"), "food policy");
CasteManager.SetSlot(c, CasteSlot.Food, food);
T.Check(CasteManager.Assign(p, c, true, JoinReason.NewPrisoner), "Assign failed for the prisoner");
T.Check(p.foodRestriction.CurrentFoodPolicy == food, "the prisoner's food was not set next to the skipped schedule");
// An arrested colonist keeps a timetable; the slot still skips it.
p.timetable ??= new Pawn_TimetableTracker(p);
string[] before = ScheduleSlot.Of(p);
List<CasteSlot> applied = CasteUtility.Apply(p, c);
T.Check(!applied.Contains(CasteSlot.Schedule), "Apply wrote the schedule on a prisoner");
T.Check(ScheduleSlot.Of(p).SequenceEqual(before), "the prisoner's timetable changed: " + Hours(p));
T.Check(!CasteManager.Overrides(p).Contains(CasteSlot.Schedule), "a prisoner's schedule counts as an override");
}
[BlaxTest("schedule: Follow rule on the whole day: A follows a schedule change, B with one hour changed keeps its own; the tooltip names Schedule")]
public static void ScheduleFollowRule()
{
List<string> start = ScheduleSlot.Default();
Caste c = Fixtures.NewCaste("Schedule follow");
CasteManager.SetSlot(c, CasteSlot.Schedule, start);
Pawn a = Fixtures.Colonist();
Pawn b = Fixtures.Colonist();
T.Check(CasteManager.Assign(a, c, false, JoinReason.Manual) && CasteManager.Assign(b, c, false, JoinReason.Manual), "Assign failed");
CheckSchedule(a, start, "A");
b.timetable.SetAssignment(12, TimeAssignmentDefOf.Joy); // by hand
List<CasteSlot> overrides = CasteManager.Overrides(b);
T.Check(overrides.Count == 1 && overrides[0] == CasteSlot.Schedule, "B's overrides: " + string.Join(", ", overrides));
string tip = PawnColumnWorker_BlaxCaste.CellTip(b);
T.Check(tip.Contains(CasteUtility.SlotLabel(CasteSlot.Schedule)), "B's tooltip does not name the schedule: " + tip);
string[] bBefore = ScheduleSlot.Of(b);
List<string> night = NightSchedule();
T.Equal(1, CasteManager.SetSlot(c, CasteSlot.Schedule, night), "members moved by the schedule change");
CheckSchedule(a, night, "A");
T.Check(ScheduleSlot.Of(b).SequenceEqual(bBefore), "B lost its own schedule: " + Hours(b));
// Painting one hour in the manager moves the followers the same way.
T.Equal(1, Dialog_ManageCastes.PaintHour(c, 16, TimeAssignmentDefOf.Joy), "members moved by painting an hour");
T.Equal(TimeAssignmentDefOf.Joy, a.timetable.GetAssignment(16), "A's hour 16 after painting");
T.Check(ScheduleSlot.Of(b).SequenceEqual(bBefore), "painting changed B's schedule: " + Hours(b));
// Apply to all members writes the caste's schedule over B's hand change.
CasteManager.ApplyToAll(c);
CheckSchedule(b, c.Schedule, "B after Apply to all");
// Leaving the schedule alone moves nobody.
T.Equal(0, CasteManager.SetSlot(c, CasteSlot.Schedule, null), "members moved by leaving the schedule alone");
T.Check(!c.IsManaged(CasteSlot.Schedule), "the schedule is still managed");
T.Equal(TimeAssignmentDefOf.Joy, a.timetable.GetAssignment(16), "A's schedule changed when the caste let go of it");
}
[BlaxTest("schedule: an unknown time assignment becomes Anything (on set, on apply and in the load check); Meditate without Royalty too")]
public static void ScheduleUnknownName()
{
const string unknown = "BlaxCastesNoSuchAssignment";
string anything = TimeAssignmentDefOf.Anything.defName;
List<string> names = NightSchedule();
names[2] = unknown;
names[3] = "Meditate";
Caste c = Fixtures.NewCaste("Unknown hours");
CasteManager.SetSlot(c, CasteSlot.Schedule, names);
T.Equal(anything, c.Schedule[2], "stored hour with an unknown assignment");
string meditate = ModsConfig.RoyaltyActive ? "Meditate" : anything;
T.Equal(meditate, c.Schedule[3], "stored Meditate hour (Royalty " + ModsConfig.RoyaltyActive + ")");
Pawn p = Fixtures.Colonist();
T.Check(CasteManager.Assign(p, c, false, JoinReason.Manual), "Assign failed");
T.Equal(anything, p.timetable.GetAssignment(2).defName, "pawn's hour 2");
T.Equal(meditate, p.timetable.GetAssignment(3).defName, "pawn's hour 3");
// A name that went missing after it was stored (a removed mod): Apply writes Anything, the load check fixes the slot.
List<string> stored = c.Schedule.ToList();
stored[5] = unknown;
AccessTools.Field(typeof(Caste), "schedule").SetValue(c, stored);
p.timetable.SetAssignment(5, TimeAssignmentDefOf.Sleep);
T.Check(CasteUtility.Apply(p, c).Contains(CasteSlot.Schedule), "Apply skipped the schedule with an unknown hour");
T.Equal(anything, p.timetable.GetAssignment(5).defName, "pawn's hour 5 from an unknown stored name");
T.Equal(0, CasteManager.Overrides(p).Count, "an unknown stored hour counts as an override");
CheckSlots();
T.Equal(anything, c.Schedule[5], "stored hour 5 after the load check");
}
// ---- work priorities ---------------------------------------------------------------------
[BlaxTest("work: a slave in a caste with Growing 1 and Firefighting 1 has both; every other work type is unchanged")]
public static void WorkOnSlave()
{
CheckWorkSlotUsable();
WithManualPriorities(true, () =>
{
Pawn s = PawnThatCan(() => Fixtures.ColonySlave(), Growing, Firefighter);
s.workSettings.SetPriority(Growing, 3);
s.workSettings.SetPriority(Firefighter, 4);
Dictionary<WorkTypeDef, int> before = AllPriorities(s);
Caste c = Fixtures.NewCaste("Field slave");
CasteManager.SetWorkPriority(c, Growing.defName, 1);
CasteManager.SetWorkPriority(c, Firefighter.defName, 1);
T.Check(c.IsManaged(CasteSlot.Work) && c.WorkPriorities.Count == 2, "the caste's work priorities: " + WorkSlot.Summary(c.WorkPriorities));
T.Check(CasteManager.Assign(s, c, true, JoinReason.NewSlave), "Assign failed for the slave");
T.Equal(1, Priority(s, Growing), "slave's Growing");
T.Equal(1, Priority(s, Firefighter), "slave's Firefighting");
var changed = before.Where(kv => kv.Key != Growing && kv.Key != Firefighter && Priority(s, kv.Key) != kv.Value)
.Select(kv => kv.Key.defName + " " + kv.Value + " to " + Priority(s, kv.Key)).ToList();
T.Check(changed.Count == 0, "other work types changed: " + string.Join(", ", changed));
T.Equal(0, CasteManager.Overrides(s).Count, "slave's overrides right after Assign");
});
}
[BlaxTest("work: a work type the pawn cannot do stays 0, with no error; the others are set")]
public static void WorkDisabledTypeSkipped()
{
CheckWorkSlotUsable();
WithManualPriorities(true, () =>
{
Pawn p = null;
WorkTypeDef disabled = null;
for (int i = 0; i < 12 && disabled == null; i++)
{
p = Fixtures.Colonist();
Fixtures.Unqueue(p);
disabled = DefDatabase<WorkTypeDef>.AllDefsListForReading.FirstOrDefault(w => p.WorkTypeIsDisabled(w));
}
if (disabled == null)
{
TraitDef pyromaniac = DefDatabase<TraitDef>.GetNamedSilentFail("Pyromaniac");
T.NotNull(pyromaniac, "no colonist with a disabled work type in 12 tries, and no Pyromaniac trait");
p.story.traits.GainTrait(new Trait(pyromaniac));
p.Notify_DisabledWorkTypesChanged();
disabled = DefDatabase<WorkTypeDef>.AllDefsListForReading.FirstOrDefault(w => p.WorkTypeIsDisabled(w));
T.NotNull(disabled, "a disabled work type after adding Pyromaniac");
}
WorkTypeDef able = DefDatabase<WorkTypeDef>.AllDefsListForReading.FirstOrDefault(w => !p.WorkTypeIsDisabled(w) && w != disabled);
T.NotNull(able, "a work type the pawn can do");
T.Equal(0, Priority(p, disabled), "setup: the disabled type's priority");
T.Info("disabled: " + disabled.defName + ", set: " + able.defName);
Caste c = Fixtures.NewCaste("Disabled work");
CasteManager.SetWorkPriority(c, disabled.defName, 1);
CasteManager.SetWorkPriority(c, able.defName, 2);
T.Check(CasteManager.Assign(p, c, false, JoinReason.Manual), "Assign failed");
T.Equal(0, Priority(p, disabled), "the disabled type's priority after Assign");
T.Equal(2, Priority(p, able), "the other type's priority");
T.Check(!CasteManager.Overrides(p).Contains(CasteSlot.Work), "a disabled type counts as an override");
// Changing the caste's value for the disabled type reaches nobody and logs nothing.
CasteManager.SetWorkPriority(c, disabled.defName, 3);
T.Equal(0, Priority(p, disabled), "the disabled type's priority after a caste change");
});
}
[BlaxTest("work: Start from nothing leaves only the caste's work types on, plus Patient and Bed rest as they were; ticking it moves nobody")]
public static void WorkStartFromNothing()
{
CheckWorkSlotUsable();
List<WorkTypeDef> selfCare = WorkSlot.SelfCareTypes();
T.Check(selfCare.Contains(Work("Patient")) && selfCare.Contains(Work("PatientBedRest")), "self-care work types: " + string.Join(", ", selfCare.Select(t => t.defName)));
T.Check(!selfCare.Contains(Firefighter) && !selfCare.Any(t => t.defName == "Hauling" || t.defName == "Cleaning"), "work types kept by Start from nothing: " + string.Join(", ", selfCare.Select(t => t.defName)));
string tip = Dialog_ManageCastes.StartFromNothingTip();
T.Check(selfCare.All(t => tip.Contains(WorkSlot.TypeLabel(t))), "the Start from nothing tooltip does not name the kept types: " + tip);
WithManualPriorities(true, () =>
{
Pawn p = PawnThatCan(Fixtures.Colonist, Growing, Cooking);
p.workSettings.SetPriority(Cooking, 2);
int activeBefore = DefDatabase<WorkTypeDef>.AllDefsListForReading.Count(w => Priority(p, w) > 0);
T.Check(activeBefore > 1, "setup: the colonist does only " + activeBefore + " work types");
Dictionary<WorkTypeDef, int> selfCareBefore = selfCare.ToDictionary(t => t, t => Priority(p, t));
T.Check(selfCareBefore.Values.All(v => v > 0), "setup: Patient or Bed rest is off: " + string.Join(", ", selfCareBefore.Select(kv => kv.Key.defName + " " + kv.Value)));
Caste c = Fixtures.NewCaste("Only growing");
CasteManager.SetWorkPriority(c, Growing.defName, 1);
Pawn member = PawnThatCan(Fixtures.Colonist, Growing);
T.Check(CasteManager.Assign(member, c, false, JoinReason.Manual), "Assign failed for the member");
Dictionary<WorkTypeDef, int> memberBefore = AllPriorities(member);
T.Check(CasteManager.SetWorkStartFromNothing(c, true) && c.WorkStartFromNothing, "Start from nothing not set");
T.Check(AllPriorities(member).All(kv => memberBefore[kv.Key] == kv.Value), "ticking Start from nothing changed a member's priorities");
T.Check(CasteManager.Assign(p, c, false, JoinReason.Manual), "Assign failed");
var wrong = DefDatabase<WorkTypeDef>.AllDefsListForReading
.Where(w => Priority(p, w) != (w == Growing ? 1 : selfCareBefore.TryGetValue(w, out int kept) ? kept : 0))
.Select(w => w.defName + " " + Priority(p, w)).ToList();
T.Check(wrong.Count == 0, "after Start from nothing: " + string.Join(", ", wrong));
T.Equal(0, CasteManager.Overrides(p).Count, "overrides right after Start from nothing");
});
}
[BlaxTest("work: with manual priorities off, a nonzero caste value turns the work on and 0 turns it off; turning them on detaches nobody")]
public static void WorkManualPrioritiesOff()
{
CheckWorkSlotUsable();
Pawn p = null;
Caste c = null;
WithManualPriorities(false, () =>
{
p = PawnThatCan(Fixtures.Colonist, Growing, Cooking);
p.workSettings.SetPriority(Growing, 0);
p.workSettings.SetPriority(Cooking, 3);
c = Fixtures.NewCaste("Simple work");
CasteManager.SetWorkPriority(c, Growing.defName, 1);
CasteManager.SetWorkPriority(c, Cooking.defName, 0);
T.Check(CasteManager.Assign(p, c, false, JoinReason.Manual), "Assign failed");
T.Check(p.workSettings.WorkIsActive(Growing), "Growing is not on");
T.Equal(3, Priority(p, Growing), "Growing with manual priorities off");
T.Equal(0, Priority(p, Cooking), "Cooking with manual priorities off");
T.Equal(0, CasteManager.Overrides(p).Count, "overrides with manual priorities off (1 and on are the same)");
T.Check(Dialog_ManageCastes.WorkNote() == (string)"BlaxCastes_WorkManualOff".Translate(), "manager note: " + Dialog_ManageCastes.WorkNote());
});
// The caste's own number was stored, so turning manual priorities on leaves the member following.
WithManualPriorities(true, () =>
{
T.Equal(1, Priority(p, Growing), "Growing once manual priorities are on (the caste's number)");
T.Equal(0, CasteManager.Overrides(p).Count, "overrides once manual priorities are on: " + string.Join(", ", CasteManager.Overrides(p)));
T.Equal(1, CasteManager.SetWorkPriority(c, Growing.defName, 2), "members moved by Growing 1 to 2 after the switch");
T.Equal(2, Priority(p, Growing), "Growing after the caste change");
});
}
[BlaxTest("work: Follow rule per work type: A follows each change, B keeps the type it changed by hand; the tooltip names it")]
public static void WorkFollowRule()
{
CheckWorkSlotUsable();
WithManualPriorities(true, () =>
{
Caste c = Fixtures.NewCaste("Work follow");
CasteManager.SetWorkPriority(c, Growing.defName, 1);
CasteManager.SetWorkPriority(c, Cooking.defName, 2);
Pawn a = PawnThatCan(Fixtures.Colonist, Growing, Cooking);
Pawn b = PawnThatCan(Fixtures.Colonist, Growing, Cooking);
T.Check(CasteManager.Assign(a, c, false, JoinReason.Manual) && CasteManager.Assign(b, c, false, JoinReason.Manual), "Assign failed");
b.workSettings.SetPriority(Growing, 3); // by hand
List<CasteSlot> overrides = CasteManager.Overrides(b);
T.Check(overrides.Count == 1 && overrides[0] == CasteSlot.Work, "B's overrides: " + string.Join(", ", overrides));
List<WorkTypeDef> types = CasteManager.WorkOverrides(b);
T.Check(types.Count == 1 && types[0] == Growing, "B's work overrides: " + string.Join(", ", types.Select(t => t.defName)));
string tip = PawnColumnWorker_BlaxCaste.CellTip(b);
T.Check(tip.Contains(WorkSlot.TypeLabel(Growing)), "B's tooltip does not name Growing: " + tip);
T.Equal(1, CasteManager.SetWorkPriority(c, Growing.defName, 2), "members moved by the Growing change");
T.Equal(2, Priority(a, Growing), "A's Growing");
T.Equal(3, Priority(b, Growing), "B's hand-set Growing");
T.Equal(2, CasteManager.SetWorkPriority(c, Cooking.defName, 1), "members moved by the Cooking change");
T.Check(Priority(a, Cooking) == 1 && Priority(b, Cooking) == 1, "Cooking: A " + Priority(a, Cooking) + ", B " + Priority(b, Cooking));
// The manager's cycle button goes 2 -> 3 and moves A only.
T.Equal(1, Dialog_ManageCastes.CycleWork(c, Growing), "members moved by the cycle button");
T.Equal(3, c.WorkPriorityOf(Growing.defName) ?? -1, "Growing after the cycle button");
T.Equal(3, Priority(a, Growing), "A's Growing after the cycle button");
// Leaving a type alone moves nobody.
T.Equal(0, CasteManager.SetWorkPriority(c, Cooking.defName, null), "members moved by leaving Cooking alone");
T.Check(c.WorkPriorityOf(Cooking.defName) == null, "Cooking is still listed");
T.Check(Priority(a, Cooking) == 1 && Priority(b, Cooking) == 1, "leaving Cooking alone changed a member");
// Apply to all members clears B's hand change.
b.workSettings.SetPriority(Growing, 4);
CasteManager.ApplyToAll(c);
T.Equal(3, Priority(b, Growing), "B's Growing after Apply to all");
});
}
[BlaxTest("work: clicking the cycle button through other values moves only the members that followed before the first click")]
public static void WorkCycleRunKeepsHandChanges()
{
CheckWorkSlotUsable();
WithManualPriorities(true, () =>
{
Caste c = Fixtures.NewCaste("Work cycle run");
CasteManager.SetWorkPriority(c, Growing.defName, 3);
Pawn a = PawnThatCan(Fixtures.Colonist, Growing);
Pawn b = PawnThatCan(Fixtures.Colonist, Growing);
Pawn d = PawnThatCan(Fixtures.Colonist, Growing);
foreach (Pawn p in new[] { a, b, d })
T.Check(CasteManager.Assign(p, c, false, JoinReason.Manual), "setup: Assign failed");
b.workSettings.SetPriority(Growing, 1); // by hand
d.workSettings.SetPriority(Growing, 4); // by hand
// 3 -> 4 -> off -> leave alone -> 1 -> 2, the way the button gets from 3 to 2.
var run = new Dialog_ManageCastes.WorkCycle();
var moved = new List<int>();
for (int i = 0; i < 5; i++)
moved.Add(run.Click(c, Growing));
T.Equal(2, c.WorkPriorityOf(Growing.defName) ?? -1, "Growing after five clicks");
T.Equal("1,1,0,1,1", string.Join(",", moved), "members moved per click (A only; nobody while leaving alone)");
T.Equal(2, Priority(a, Growing), "A's Growing (followed)");
T.Equal(1, Priority(b, Growing), "B's hand-set Growing");
T.Equal(4, Priority(d, Growing), "D's hand-set Growing (the run passed 4)");
// A change from elsewhere ends the run: the next click takes the followers anew.
d.workSettings.SetPriority(Growing, 2);
T.Equal(2, CasteManager.SetWorkPriority(c, Growing.defName, 1), "members moved by Growing 2 to 1 from elsewhere (A and D)");
T.Equal(1, Priority(a, Growing), "A after Growing 2 to 1 from elsewhere");
T.Equal(1, Priority(d, Growing), "D followed 2 to 1");
T.Equal(3, run.Click(c, Growing), "members moved by the next click (A, B and D all on 1 now)");
});
}
[BlaxTest("work: the cycle runs leave alone, 1, 2, 3, 4, off and back; labels are -, numbers and off")]
public static void WorkCycle()
{
int? v = null;
var seen = new List<string>();
for (int i = 0; i < 6; i++)
{
v = WorkSlot.Next(v);
seen.Add(v?.ToString() ?? "null");
}
T.Equal("1,2,3,4,0,null", string.Join(",", seen), "forward cycle from leave alone");
for (int i = 0; i < 6; i++)
v = WorkSlot.Previous(v);
T.Check(v == null, "six steps back did not come back to leave alone: " + v);
T.Equal((string)"BlaxCastes_WorkLeaveAloneShort".Translate(), WorkSlot.PriorityLabel(null), "label for leave alone");
T.Equal((string)"BlaxCastes_WorkOff".Translate(), WorkSlot.PriorityLabel(0), "label for off");
T.Equal("2", WorkSlot.PriorityLabel(2), "label for 2");
List<WorkTypeDef> types = WorkSlot.Types();
T.Check(types.Count > 0 && types.All(t => t.visible), "the manager's work types are not the visible ones");
T.Check(types.SequenceEqual(types.OrderByDescending(t => t.naturalPriority)), "the manager's work types are not in the Work tab's order");
}
[BlaxTest("work: an active work manager, or the setting off, greys the slot out and Castes writes no priority")]
public static void WorkManagerTurnsSlotOff()
{
CheckWorkSlotUsable();
WithManualPriorities(true, () =>
{
Pawn p = PawnThatCan(Fixtures.Colonist, Growing);
p.workSettings.SetPriority(Growing, 4);
Caste c = Fixtures.NewCaste("Managed elsewhere");
CasteManager.SetWorkPriority(c, Growing.defName, 1);
WorkSlot.SimulatedActive.Add(Compat.FreeWill);
try
{
T.Equal("Free Will", WorkSlot.ActiveManager(), "detected work manager");
T.Check(!WorkSlot.Active && !CasteUtility.SlotActive(CasteSlot.Work), "the work slot is on next to Free Will");
T.Check(Dialog_ManageCastes.WorkNote()?.Contains("Free Will") == true, "manager note: " + Dialog_ManageCastes.WorkNote());
T.Check(CasteManager.Assign(p, c, false, JoinReason.Manual), "Assign failed");
T.Equal(4, Priority(p, Growing), "Growing written next to Free Will");
T.Check(!CasteManager.Overrides(p).Contains(CasteSlot.Work), "work counts as an override while the slot is off");
}
finally
{
WorkSlot.SimulatedActive.Remove(Compat.FreeWill);
}
Fixtures.Settings.manageWorkPriorities = false;
T.Check(!WorkSlot.Active, "the work slot is on with manageWorkPriorities off");
T.Equal((string)"BlaxCastes_WorkSettingOff".Translate(), Dialog_ManageCastes.WorkNote(), "manager note with the setting off");
CasteManager.ResetToCaste(p);
T.Equal(4, Priority(p, Growing), "Growing written with manageWorkPriorities off");
Fixtures.Settings.manageWorkPriorities = true;
CasteManager.ResetToCaste(p);
T.Equal(1, Priority(p, Growing), "Growing after turning the setting back on and Reset to caste");
});
}
// ---- weapon loadout ----------------------------------------------------------------------
[BlaxTest("loadout: without Weapons Tab Reborn the slot is off, the row is hidden and a stored id is kept but not applied")]
public static void LoadoutWithoutMod()
{
if (WeaponsTab.ModActive)
T.Skip("Weapons Tab Reborn is active in this run");
T.Check(!WeaponsTab.Available && !CasteUtility.SlotActive(CasteSlot.Loadout), "the loadout slot is on without Weapons Tab Reborn");
T.Check(!Dialog_ManageCastes.ShowsLoadoutRow, "the manager shows the loadout row without Weapons Tab Reborn");
Caste c = Fixtures.NewCaste("No weapons tab");
T.Equal(0, CasteManager.SetSlot(c, CasteSlot.Loadout, 1), "members moved by setting a loadout without the mod");
T.Check(!c.IsManaged(CasteSlot.Loadout), "a loadout was stored without the mod");
// A save made with the mod keeps its id while the mod is away.
SetLoadoutIdRaw(c, 3);
Pawn p = Fixtures.Colonist();
T.Check(!CasteUtility.CanUse(p, CasteSlot.Loadout), "CanUse(Loadout) without the mod");
T.Check(CasteManager.Assign(p, c, false, JoinReason.Manual), "Assign failed");
T.Check(!CasteUtility.Apply(p, c).Contains(CasteSlot.Loadout), "Apply wrote a loadout without the mod");
CheckSlots();
T.Equal(3, c.LoadoutId, "the stored loadout id after the load check without the mod");
T.Equal(0, CasteManager.Overrides(p).Count, "overrides from a loadout without the mod");
}
[BlaxTest("loadout: with Weapons Tab Reborn a caste sets its loadout on a colonist and a slave; a prisoner is skipped")]
public static void LoadoutSetsIt()
{
NeedWeaponsTab();
int rifle = MakeLoadout("Blax test rifles");
T.Check(WeaponsTab.Exists(rifle) && WeaponsTab.NameOf(rifle) == "Blax test rifles", "the new loadout is not visible through the API");
T.Check(WeaponsTab.Loadouts().Any(l => l.Key == rifle), "the new loadout is not in the manager's list");
Caste c = Fixtures.NewCaste("Guards");
CasteManager.SetSlot(c, CasteSlot.Loadout, rifle);
T.Equal(rifle, c.LoadoutId, "the caste's loadout");
T.Equal("Blax test rifles", CasteUtility.ValueLabel(CasteSlot.Loadout, c.LoadoutId), "the loadout's label in the manager");
Pawn colonist = Fixtures.Colonist();
T.Check(WeaponsTab.LoadoutOf(colonist) != rifle, "setup: the colonist already has the new loadout");
T.Check(CasteManager.Assign(colonist, c, false, JoinReason.Manual), "Assign failed for the colonist");
T.Equal((int?)rifle, WeaponsTab.LoadoutOf(colonist), "colonist's loadout");
T.Equal(0, CasteManager.Overrides(colonist).Count, "colonist's overrides right after Assign");
Pawn prisoner = Fixtures.Prisoner();
T.Check(!CasteUtility.CanUse(prisoner, CasteSlot.Loadout), "CanUse(Loadout) is true for a prisoner");
CasteManager.Assign(prisoner, c, true, JoinReason.NewPrisoner);
T.Check(!CasteUtility.Apply(prisoner, c).Contains(CasteSlot.Loadout), "Apply wrote a loadout on a prisoner");
Pawn slave = Fixtures.ColonySlave(); // skips here without Ideology; the colonist part passed
T.Check(CasteManager.Assign(slave, c, true, JoinReason.NewSlave), "Assign failed for the slave");
T.Equal((int?)rifle, WeaponsTab.LoadoutOf(slave), "slave's loadout");
}
[BlaxTest("loadout: Follow rule: A follows a loadout change, B with a loadout set by hand keeps it")]
public static void LoadoutFollowRule()
{
NeedWeaponsTab();
int first = MakeLoadout("Blax test first");
int other = MakeLoadout("Blax test other");
int? fallback = WeaponsTab.DefaultLoadoutId();
T.NotNull(fallback, "default loadout id");
Caste c = Fixtures.NewCaste("Loadout follow");
CasteManager.SetSlot(c, CasteSlot.Loadout, first);
Pawn a = Fixtures.Colonist();
Pawn b = Fixtures.Colonist();
T.Check(CasteManager.Assign(a, c, false, JoinReason.Manual) && CasteManager.Assign(b, c, false, JoinReason.Manual), "Assign failed");
T.Check(WeaponsTab.SetLoadout(b, other), "setting B's loadout by hand failed");
List<CasteSlot> overrides = CasteManager.Overrides(b);
T.Check(overrides.Count == 1 && overrides[0] == CasteSlot.Loadout, "B's overrides: " + string.Join(", ", overrides));
T.Equal(1, CasteManager.SetSlot(c, CasteSlot.Loadout, fallback.Value), "members moved by the loadout change");
T.Equal(fallback, WeaponsTab.LoadoutOf(a), "A's loadout");
T.Equal((int?)other, WeaponsTab.LoadoutOf(b), "B's hand-set loadout");
T.Equal(0, CasteManager.SetSlot(c, CasteSlot.Loadout, Caste.Unmanaged), "members moved by leaving the loadout alone");
T.Equal(fallback, WeaponsTab.LoadoutOf(a), "A's loadout after the caste let go of it");
}
[BlaxTest("loadout: a deleted loadout becomes unmanaged (on apply and in the load check), without errors")]
public static void LoadoutDeleted()
{
NeedWeaponsTab();
int doomed = MakeLoadout("Blax test doomed");
Caste c = Fixtures.NewCaste("Doomed loadout");
CasteManager.SetSlot(c, CasteSlot.Loadout, doomed);
int doomed2 = MakeLoadout("Blax test doomed too");
Caste c2 = Fixtures.NewCaste("Doomed loadout too");
CasteManager.SetSlot(c2, CasteSlot.Loadout, doomed2);
T.Check(c.IsManaged(CasteSlot.Loadout) && c2.IsManaged(CasteSlot.Loadout), "setup: loadouts not managed");
AcceptanceReport deleted = DeleteLoadout(doomed);
T.Check(deleted.Accepted, "Weapons Tab Reborn refused to delete the loadout: " + deleted.Reason);
T.Check(!WeaponsTab.Exists(doomed), "the deleted loadout still exists");
T.Check(!WeaponsTab.Loadouts().Any(l => l.Key == doomed), "the deleted loadout is still in the manager's list");
T.Check(CasteUtility.ValueLabel(CasteSlot.Loadout, doomed).Contains(doomed.ToString()), "label of a missing loadout: " + CasteUtility.ValueLabel(CasteSlot.Loadout, doomed));
Pawn p = Fixtures.Colonist();
int? before = WeaponsTab.LoadoutOf(p);
T.Check(CasteManager.Assign(p, c, false, JoinReason.Manual), "Assign failed");
T.Equal(before, WeaponsTab.LoadoutOf(p), "the pawn's loadout after assigning a caste with a deleted loadout");
T.Check(!c.IsManaged(CasteSlot.Loadout), "the deleted loadout is still managed after Apply");
T.Check(DeleteLoadout(doomed2).Accepted, "Weapons Tab Reborn refused to delete the second loadout");
CheckSlots();
T.Check(!c2.IsManaged(CasteSlot.Loadout), "the deleted loadout is still managed after the load check");
}
// ---- every slot --------------------------------------------------------------------------
[BlaxTest("slots: duplicating a caste copies the schedule, work priorities, Start from nothing and loadout as separate copies")]
public static void DuplicateCopiesNewSlots()
{
Caste src = Fixtures.NewCaste("New slot source");
CasteManager.SetSlot(src, CasteSlot.Schedule, NightSchedule());
CasteManager.SetWorkPriority(src, Growing.defName, 1);
CasteManager.SetWorkStartFromNothing(src, true);
if (WeaponsTab.Available)
CasteManager.SetSlot(src, CasteSlot.Loadout, WeaponsTab.DefaultLoadoutId() ?? Caste.Unmanaged);
Caste dup = CasteManager.DuplicateCaste(src);
Fixtures.Track(dup);
foreach (CasteSlot slot in CasteUtility.AllSlots)
T.Check(CasteUtility.SameValue(src.GetSlot(slot), dup.GetSlot(slot)), $"{slot}: source {CasteUtility.ValueLabel(slot, src.GetSlot(slot))}, duplicate {CasteUtility.ValueLabel(slot, dup.GetSlot(slot))}");
T.Check(dup.WorkStartFromNothing, "Start from nothing not copied");
Dialog_ManageCastes.PaintHour(dup, 0, TimeAssignmentDefOf.Sleep);
CasteManager.SetWorkPriority(dup, Growing.defName, 4);
T.Equal(TimeAssignmentDefOf.Work.defName, src.Schedule[0], "painting the duplicate changed the source's schedule");
T.Equal(1, src.WorkPriorityOf(Growing.defName) ?? -1, "changing the duplicate's work changed the source's");
}
[BlaxTest("slots: the starter castes leave the schedule, work priorities and loadout alone")]
public static void StarterCastesLeaveNewSlotsAlone()
{
var starters = Fixtures.Comp.Castes.Where(c => c.label == StarterCastes.ColonistLabel || c.label == StarterCastes.SlaveLabel || c.label == StarterCastes.PrisonerLabel).ToList();
if (starters.Count == 0)
T.Skip("this game has no starter castes (seedStarterCastes off?)");
foreach (Caste c in starters)
{
T.Check(!c.IsManaged(CasteSlot.Schedule) && !c.IsManaged(CasteSlot.Work) && !c.IsManaged(CasteSlot.Loadout) && !c.WorkStartFromNothing,
c.label + " manages " + string.Join(", ", new[] { CasteSlot.Schedule, CasteSlot.Work, CasteSlot.Loadout }.Where(c.IsManaged)));
}
}
[BlaxTest("slots: every string the new slots use is in Keyed, and the slots have labels")]
public static void Strings()
{
string[] keys =
{
"BlaxCastes_SlotSchedule", "BlaxCastes_SlotWork", "BlaxCastes_SlotLoadout", "BlaxCastes_LoadoutUnknown", "BlaxCastes_WorkOff",
"BlaxCastes_WorkLeaveAloneShort", "BlaxCastes_WorkManagerActive", "BlaxCastes_LoadoutTip", "BlaxCastes_LoadoutUnavailable",
"BlaxCastes_LoadoutSettingOff", "BlaxCastes_ScheduleTip", "BlaxCastes_ScheduleUnmanagedTip", "BlaxCastes_ScheduleCopyFromPawn",
"BlaxCastes_ScheduleCopyFromPawnTip", "BlaxCastes_ScheduleLeaveAloneTip", "BlaxCastes_ScheduleNoPawns", "BlaxCastes_WorkStartFromNothing",
"BlaxCastes_WorkStartFromNothingTip", "BlaxCastes_WorkTypeTip", "BlaxCastes_WorkSettingOff", "BlaxCastes_WorkManualOff",
"BlaxCastes_CellOverrideSchedule", "BlaxCastes_CellOverrideWork", "BlaxCastes_CellOverrideWorkType",
};
var missing = keys.Where(k => !k.CanTranslate()).ToList();
T.Check(missing.Count == 0, "strings missing from Keyed: " + string.Join(", ", missing));
}
[BlaxTest("schedule: Copy from pawn lists colonists and slaves with a schedule and copies all 24 hours")]
public static void ScheduleCopyFromPawn()
{
Pawn source = Fixtures.Colonist();
List<string> night = NightSchedule();
for (int h = 0; h < ScheduleSlot.Hours; h++)
source.timetable.SetAssignment(h, ScheduleSlot.Resolve(night[h]));
Pawn prisoner = Fixtures.Prisoner();
List<Pawn> listed = Dialog_ManageCastes.SchedulePawns();
T.Check(listed.Contains(source), "Copy from pawn does not list a colonist");
T.Check(!listed.Contains(prisoner), "Copy from pawn lists a prisoner");
Caste c = Fixtures.NewCaste("Copied schedule");
Pawn member = Fixtures.Colonist();
CasteManager.Assign(member, c, false, JoinReason.Manual);
T.Equal(1, Dialog_ManageCastes.CopyScheduleFrom(c, source), "members moved by Copy from pawn");
T.Check(c.Schedule.SequenceEqual(night), "the caste's schedule after Copy from pawn: " + ScheduleSlot.Summary(c.Schedule));
CheckSchedule(member, night, "member");
}
[BlaxTest("schedule: the manager's brushes share the row, wide enough for Recreation (about 68 px in the Small font plus the 4 px border)")]
public static void ScheduleBrushWidth()
{
// The manager's scroll view is about 598 px wide at its starting size.
float width = Dialog_ManageCastes.BrushWidthFor(598f);
T.Check(width >= 88f && width <= 96f, "brush width in the manager: " + width);
T.Equal(64f, Dialog_ManageCastes.BrushWidthFor(200f), "brush width in a very narrow window");
}
// ---- the Caste column in the Schedule and Work tabs --------------------------------------
private static string ColumnList(PawnTableDef table) => string.Join(", ", table.columns.Select(c => c?.defName ?? "null"));
/// <summary>
/// Right after the timetable: the Schedule tab draws its time assignment selector over the top of the
/// header from x 0 to about 476 px, which covers every column left of the timetable (name 80 px or
/// more, ideo, xenotype, copy and paste, then the timetable of 360 px or more).
/// </summary>
private static void CheckScheduleColumn(PawnColumnDef col)
{
PawnTableDef table = CasteColumns.ScheduleTable;
int at = table.columns.IndexOf(col);
int timetable = table.columns.FindIndex(c => c?.defName == "Timetable");
T.Check(at >= 0, "Caste column not in the Schedule table: " + ColumnList(table));
T.Check(timetable >= 0, "the Schedule table has no timetable: " + ColumnList(table));
T.Equal(timetable + 1, at, "Caste column index, right after the timetable (columns: " + ColumnList(table) + ")");
T.Equal(1, table.columns.Count(c => c == col), "times the Caste column is in the Schedule table");
}
private static void CheckWorkColumn(PawnColumnDef col)
{
PawnTableDef table = CasteColumns.WorkTable;
int at = table.columns.IndexOf(col);
int firstWork = table.columns.FindIndex(c => c?.workType != null);
T.Check(at >= 0, "Caste column not in the Work table: " + ColumnList(table));
T.Check(firstWork > at, "Caste column not left of the work columns: " + ColumnList(table));
int copyPaste = table.columns.FindIndex(c => c?.defName == "CopyPasteWorkPriorities");
if (copyPaste >= 0)
T.Equal(at + 1, copyPaste, "copy and paste column index (columns: " + ColumnList(table) + ")");
T.Equal(1, table.columns.Count(c => c == col), "times the Caste column is in the Work table");
}
[BlaxTest("ui: in the Work tab the Caste column keeps the header at the work columns' height; elsewhere it asks for its 65 px")]
public static void WorkHeaderHeight()
{
PawnColumnDef col = CasteColumns.Column;
T.NotNull(col, "PawnColumnDef " + PawnColumnWorker_BlaxCaste.DefName);
var work = new PawnTable_PlayerPawns(PawnTableDefOf.Work, () => Enumerable.Empty<Pawn>(), 1200, 800);
var assign = new PawnTable_PlayerPawns(PawnTableDefOf.Assign, () => Enumerable.Empty<Pawn>(), 1200, 800);
var schedule = new PawnTable_PlayerPawnsTimetable(PawnTableDefOf.Restrict, () => Enumerable.Empty<Pawn>(), 1200, 800);
T.Check(PawnColumnWorker_BlaxCaste.IsWorkTable(work), "the Work tab's table is not recognised");
T.Check(!PawnColumnWorker_BlaxCaste.IsWorkTable(assign) && !PawnColumnWorker_BlaxCaste.IsWorkTable(schedule), "another table counts as the Work tab's");
PawnColumnDef workColumn = PawnTableDefOf.Work.columns.FirstOrDefault(c => c?.workType != null);
T.NotNull(workColumn, "a work priority column in the Work table");
int workHeight = workColumn.Worker.GetMinHeaderHeight(work);
int mine = col.Worker.GetMinHeaderHeight(work);
T.Check(mine <= workHeight, "the Caste column asks for " + mine + " px in the Work tab, the work columns for " + workHeight);
T.Equal(PawnColumnWorker_BlaxCaste.TopAreaHeight, col.Worker.GetMinHeaderHeight(assign), "header height in the Assign tab");
T.Equal(PawnColumnWorker_BlaxCaste.TopAreaHeight, col.Worker.GetMinHeaderHeight(schedule), "header height in the Schedule tab");
}
[BlaxTest("ui: at startup the Caste column sits right after the timetable in the Schedule table and left of the work columns in the Work table")]
public static void ScheduleAndWorkColumns()
{
if (!Fixtures.Settings.showAssignColumn)
T.Skip("showAssignColumn is off in this run");
PawnColumnDef col = CasteColumns.Column;
T.NotNull(col, "PawnColumnDef " + PawnColumnWorker_BlaxCaste.DefName);
CheckScheduleColumn(col);
CheckWorkColumn(col);
T.Info("Schedule: " + ColumnList(CasteColumns.ScheduleTable));
}
[BlaxTest("ui: showAssignColumn off removes the column from all three tables; on puts each back in place")]
public static void ColumnsToggle()
{
PawnColumnDef col = CasteColumns.Column;
T.NotNull(col, "PawnColumnDef " + PawnColumnWorker_BlaxCaste.DefName);
var had = CasteColumns.Tables.ToDictionary(t => t, t => t.columns.Contains(col));
try
{
CasteColumns.ApplyAll(false);
T.Check(CasteColumns.Tables.All(t => !t.columns.Contains(col)), "ApplyAll(false) left the column in a table");
T.Check(CasteColumns.ApplyAll(true), "ApplyAll(true) changed nothing");
CheckScheduleColumn(col);
CheckWorkColumn(col);
T.Check(!CasteColumns.ApplyAll(true), "adding present columns reported a change");
}
finally
{
foreach (KeyValuePair<PawnTableDef, bool> kv in had)
{
if (!kv.Value)
kv.Key.columns.Remove(col);
}
}
}
// ---- save and reload ---------------------------------------------------------------------
// Runs last among this class's phase-1 tests (source order).
[BlaxTest("slots: set up a caste with a schedule, work priorities and a loadout for the reload")]
public static void ReloadSetup()
{
Caste c = Fixtures.KeepCaste(Fixtures.NewCaste("Reload slots"));
CasteManager.SetSlot(c, CasteSlot.Schedule, NightSchedule());
Pawn member = null;
WithManualPriorities(true, () =>
{
member = Fixtures.Keep(PawnThatCan(Fixtures.Colonist, Growing, Firefighter));
CasteManager.SetWorkPriority(c, Growing.defName, 1);
CasteManager.SetWorkPriority(c, Firefighter.defName, 1);
CasteManager.SetWorkStartFromNothing(c, true);
if (WeaponsTab.Available)
{
int loadout = MakeLoadout("Blax test reload");
CasteManager.SetSlot(c, CasteSlot.Loadout, loadout);
T.Carry["slotsLoadout"] = loadout.ToString();
}
T.Check(CasteManager.Assign(member, c, false, JoinReason.Manual), "Assign failed");
});
T.Equal(0, CasteManager.Overrides(member).Count, "member's overrides before the save");
T.Carry["slotsCaste"] = c.id.ToString();
T.Carry["slotsMember"] = member.ThingID;
}
[BlaxTest("slots: the schedule, work priorities, Start from nothing and loadout survive save and reload, on the caste and the member", phase: 2)]
public static void SlotsSurvive()
{
T.Check(T.Carry.TryGetValue("slotsCaste", out string id), "phase 1 did not set up the caste");
Caste c = Fixtures.Comp.Castes.FirstOrDefault(x => x.id.ToString() == id);
T.NotNull(c, "caste " + id + " after reload");
List<string> night = NightSchedule();
T.Check(c.Schedule != null && c.Schedule.SequenceEqual(night), "schedule after reload: " + ScheduleSlot.Summary(c.Schedule));
T.Equal(2, c.WorkPriorities.Count, "work types after reload (" + WorkSlot.Summary(c.WorkPriorities) + ")");
T.Equal(1, c.WorkPriorityOf(Growing.defName) ?? -1, "Growing after reload");
T.Equal(1, c.WorkPriorityOf(Firefighter.defName) ?? -1, "Firefighting after reload");
T.Check(c.WorkStartFromNothing, "Start from nothing lost over the reload");
Pawn member = Fixtures.FindPawnById(T.Carry["slotsMember"]);
T.NotNull(member, "member after reload");
T.Check(Fixtures.Comp.CasteOf(member) == c, "member's caste after reload: " + Fixtures.Comp.CasteOf(member));
CheckSchedule(member, night, "member");
if (CasteUtility.CanUse(member, CasteSlot.Work))
T.Check(WorkSlot.MatchesAll(member, c.WorkPriorities), "member's work after reload: " + WorkSlot.Summary(WorkSlot.Of(member, activeOnly: true)));
if (T.Carry.TryGetValue("slotsLoadout", out string loadout))
{
T.Equal(loadout, c.LoadoutId.ToString(), "loadout after reload");
T.Equal(loadout, WeaponsTab.LoadoutOf(member)?.ToString(), "member's loadout after reload");
}
else
{
T.Check(!c.IsManaged(CasteSlot.Loadout), "a loadout appeared without Weapons Tab Reborn");
}
T.Equal(0, CasteManager.Overrides(member).Count, "member's overrides after reload");
}
}
}

View File

@ -11,7 +11,8 @@ namespace BlaxCastesTests
private static readonly string[] CoreKeys = private static readonly string[] CoreKeys =
{ {
"BlaxCastes_NewCasteLabel", "BlaxCastes_Unmanaged", "BlaxCastes_SlotApparel", "BlaxCastes_SlotFood", "BlaxCastes_SlotDrug", "BlaxCastes_NewCasteLabel", "BlaxCastes_Unmanaged", "BlaxCastes_SlotApparel", "BlaxCastes_SlotFood", "BlaxCastes_SlotDrug",
"BlaxCastes_SlotReading", "BlaxCastes_SlotMedCare", "BlaxCastes_NoCaste", "BlaxCastes_DefaultCaste", "BlaxCastes_SlotReading", "BlaxCastes_SlotMedCare", "BlaxCastes_NoCaste", "BlaxCastes_StarterColonist", "BlaxCastes_StarterSlave",
"BlaxCastes_StarterPrisoner", "BlaxCastes_StarterSeededMessage",
"BlaxCastes_ManageCastesTitle", "BlaxCastes_JoinDefaultsTitle", "BlaxCastes_ManageCastesTitle", "BlaxCastes_JoinDefaultsTitle",
}; };

View File

@ -0,0 +1,185 @@
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using BlaxCastes;
using HarmonyLib;
using RimWorld;
using Verse;
namespace BlaxCastesTests
{
/// <summary>
/// Starter castes on a loaded save. These seed a fresh component that is not part of the game, so the
/// running game's castes stay as they are. The new-game seeding is checked by CasteTests.NewGameState.
/// </summary>
public static class StarterTests
{
private static FoodPolicy Simple() => Fixtures.Need(Fixtures.Food("FoodRestrictionSimple"), "Simple food policy");
private static GameComponent_BlaxCastes Fresh() => new GameComponent_BlaxCastes(Current.Game);
private static Caste ByLabel(GameComponent_BlaxCastes comp, string label) => comp.Castes.FirstOrDefault(c => c.label == label);
private static string SeededMessageText(GameComponent_BlaxCastes comp)
{
string names = comp.Castes.Select(c => c.label).ToCommaList(useAnd: true);
return ((string)"BlaxCastes_StarterSeededMessage".Translate(names.Named("CASTES"))).CapitalizeFirst();
}
private static int MessagesWithText(string text) =>
Find.Archive.ArchivablesListForReading.OfType<Message>().Count(m => m.text == text);
[BlaxTest("starter: loading a save without castes adds them once, wires the rows, posts one message and moves nobody")]
public static void SeedOnLoad()
{
Messages.Clear();
GameComponent_BlaxCastes fresh = Fresh();
T.Equal(0, fresh.Castes.Count, "setup: castes of a fresh component");
fresh.LoadedGame();
T.Check(fresh.StarterCastesSeeded, "the save is not marked as seeded");
T.Equal(ModsConfig.IdeologyActive ? 3 : 2, fresh.Castes.Count, "castes after the first load (" + string.Join(", ", fresh.Castes.Select(c => c.label)) + ")");
Caste colonist = ByLabel(fresh, StarterCastes.ColonistLabel);
Caste prisoner = ByLabel(fresh, StarterCastes.PrisonerLabel);
T.NotNull(colonist, "Colonist caste");
T.NotNull(prisoner, "Prisoner caste");
T.Check(fresh.DefaultCaste == colonist, "default caste: " + fresh.DefaultCaste);
T.Check(fresh.ResolveRow(JoinReason.NewColonist) == colonist && fresh.ResolveRow(JoinReason.BoughtColonist) == colonist, "colonist rows do not resolve to Colonist");
T.Check(fresh.ResolveRow(JoinReason.NewPrisoner) == prisoner, "new-prisoner row does not resolve to Prisoner");
if (ModsConfig.IdeologyActive)
{
Caste slave = ByLabel(fresh, StarterCastes.SlaveLabel);
T.NotNull(slave, "Slave caste");
T.Check(fresh.ResolveRow(JoinReason.NewSlave) == slave && fresh.ResolveRow(JoinReason.BoughtSlave) == slave, "slave rows do not resolve to Slave");
}
T.Equal(0, fresh.Memberships.Count, "memberships after seeding on load (nobody moves)");
T.Check(fresh.FirstLoadMessageShown, "the seeding message does not count as the first-load message");
string text = SeededMessageText(fresh);
T.Equal(1, MessagesWithText(text), "seeding messages after the first load");
int count = fresh.Castes.Count;
fresh.LoadedGame();
T.Equal(count, fresh.Castes.Count, "castes after a second load");
T.Equal(1, MessagesWithText(text), "seeding messages after a second load");
}
[BlaxTest("starter: with the Caste column off, the seeding message points to the mod settings instead of the missing button")]
public static void SeededMessageWithoutColumn()
{
Messages.Clear();
Fixtures.Settings.showAssignColumn = false;
GameComponent_BlaxCastes fresh = Fresh();
// The message history keeps earlier tests' messages, so look only at what this load adds.
var before = new HashSet<Message>(Find.Archive.ArchivablesListForReading.OfType<Message>());
fresh.LoadedGame();
List<string> added = Find.Archive.ArchivablesListForReading.OfType<Message>().Where(m => !before.Contains(m)).Select(m => m.text).ToList();
T.Check(fresh.StarterCastesSeeded, "the save is not marked as seeded");
string names = fresh.Castes.Select(c => c.label).ToCommaList(useAnd: true);
string expected = ((string)"BlaxCastes_StarterSeededMessageNoColumn".Translate(names.Named("CASTES"))).CapitalizeFirst();
T.Equal(expected, ((string)StarterCastes.SeededMessageText(fresh)).CapitalizeFirst(), "seeding message text with the column off");
T.Equal(1, added.Count(t => t == expected), "seeding messages with the column off (added: " + string.Join(" | ", added) + ")");
T.Equal(0, added.Count(t => t == SeededMessageText(fresh)), "messages pointing to Assign > Manage castes after a load with the column off");
}
[BlaxTest("starter: a save that already has castes, or seedStarterCastes off, gets no starter castes")]
public static void NoSeedWhenCastesOrOff()
{
GameComponent_BlaxCastes withCastes = Fresh();
MethodInfo add = AccessTools.Method(typeof(GameComponent_BlaxCastes), "AddCaste");
T.NotNull(add, "GameComponent_BlaxCastes.AddCaste");
add.Invoke(withCastes, new object[] { new Caste(1, "Own caste") });
T.Check(!StarterCastes.SeedOnLoad(withCastes), "seeded a save that already has a caste");
T.Equal(1, withCastes.Castes.Count, "castes of a save that had one");
T.Check(withCastes.StarterCastesSeeded, "a save with castes is not marked, so deleting them later would bring the starters back");
Fixtures.Settings.seedStarterCastes = false;
GameComponent_BlaxCastes off = Fresh();
T.Check(!StarterCastes.SeedOnLoad(off) && !StarterCastes.SeedNewGame(off), "seeded with seedStarterCastes off");
T.Equal(0, off.Castes.Count, "castes with seedStarterCastes off");
T.Check(!off.StarterCastesSeeded, "marked as seeded with the setting off, so turning it on later would do nothing");
}
[BlaxTest("starter: with the Slave outfit gone before seeding, the Slave caste leaves apparel unmanaged, and Create Slave outfit makes one")]
public static void MissingSlaveOutfit()
{
if (!ModsConfig.IdeologyActive)
T.Skip("the Slave caste needs Ideology");
ApparelPolicy slaveOutfit = Fixtures.Need(StarterCastes.SlaveOutfit(), "Slave outfit");
T.Check(!StarterCastes.CanCreateSlaveOutfit, "Create Slave outfit is offered while the game has one");
var outfits = Current.Game.outfitDatabase.AllOutfits;
int at = outfits.IndexOf(slaveOutfit);
GameComponent_BlaxCastes fresh = Fresh();
ApparelPolicy created = null;
try
{
outfits.RemoveAt(at);
T.Check(StarterCastes.SeedNewGame(fresh), "did not seed");
T.Check(StarterCastes.CanCreateSlaveOutfit, "Create Slave outfit is not offered without a Slave outfit");
created = StarterCastes.CreateSlaveOutfit();
T.NotNull(created, "the created Slave outfit");
T.Check(outfits.Contains(created) && StarterCastes.IsSlaveOutfit(created), "the created outfit is not in the database under the Slave outfit's name: " + created.label);
T.Check(created != slaveOutfit, "Create Slave outfit returned the removed outfit"); // the id may repeat: the removed outfit can be the newest
ThingDef slaveApparel = DefDatabase<ThingDef>.AllDefs.FirstOrDefault(d => d.apparel?.defaultOutfitTags != null && d.apparel.defaultOutfitTags.Contains("Slave"));
if (slaveApparel != null)
T.Check(created.filter.Allows(slaveApparel), "the created outfit does not allow " + slaveApparel.defName);
T.Check(!created.filter.Allows(ThingDefOf.Apparel_Parka), "the created outfit allows a parka");
T.Check(StarterCastes.CreateSlaveOutfit() == created, "a second click made another outfit");
}
finally
{
if (created != null)
outfits.Remove(created);
outfits.Insert(at, slaveOutfit);
}
Caste slave = ByLabel(fresh, StarterCastes.SlaveLabel);
T.NotNull(slave, "Slave caste");
T.Check(!slave.IsManaged(CasteSlot.Apparel), "the Slave caste manages apparel without a Slave outfit: " + slave.ApparelPolicy?.label);
T.Check(slave.FoodPolicy == Simple(), "the Slave caste lost its food next to the missing outfit");
T.Check(slave.DrugPolicy?.sourceDef?.defName == StarterCastes.NoDrugsSourceDef, "the Slave caste lost No drugs next to the missing outfit");
T.Check("BlaxCastes_CreateSlaveOutfit".CanTranslate() && "BlaxCastes_CreateSlaveOutfitTip".CanTranslate(), "Create Slave outfit strings missing from Keyed");
}
[BlaxTest("starter: the Colonist caste copies the default drug policy, so a drug-prohibiting ideo's No drugs stays")]
public static void ColonistKeepsIdeoDrugDefault()
{
DrugPolicyDatabase db = Current.Game.drugPolicyDatabase;
DrugPolicy noDrugs = Fixtures.Need(StarterCastes.NoDrugs(), "No drugs policy (source def NoDrugs)");
DrugPolicy before = db.DefaultDrugPolicy();
GameComponent_BlaxCastes fresh = Fresh();
try
{
db.SetDefault(noDrugs);
T.Check(StarterCastes.SeedNewGame(fresh), "did not seed");
}
finally
{
db.SetDefault(before);
}
Caste colonist = ByLabel(fresh, StarterCastes.ColonistLabel);
T.NotNull(colonist, "Colonist caste");
T.Check(colonist.DrugPolicy == noDrugs, "Colonist drugs: " + colonist.DrugPolicy?.label + ", expected " + noDrugs.label);
T.Check(db.DefaultDrugPolicy() == before, "the test did not restore the default drug policy");
}
[BlaxTest("starter: the Slave outfit warning names the vanilla Slave outfit only")]
public static void SlaveOutfitWarning()
{
ApparelPolicy worker = Fixtures.Need(Fixtures.Outfit("OutfitWorker"), "Worker outfit");
T.Check(!StarterCastes.IsSlaveOutfit(worker), "the Worker outfit counts as the Slave outfit");
T.Check(!StarterCastes.IsSlaveOutfit(null), "null counts as the Slave outfit");
if (!ModsConfig.IdeologyActive)
T.Skip("the Slave outfit needs Ideology; the other checks passed");
T.Check(StarterCastes.IsSlaveOutfit(StarterCastes.SlaveOutfit()), "the Slave outfit does not count as the Slave outfit");
T.Check("BlaxCastes_SlaveOutfitCold".CanTranslate(), "the cold warning is missing from Keyed");
}
[BlaxTest("starter: the save is still seeded after the reload, with one of each starter caste", phase: 2)]
public static void NoSecondSeeding()
{
GameComponent_BlaxCastes comp = Fixtures.Comp;
T.Check(comp.StarterCastesSeeded, "the seeded flag did not survive the reload");
T.Equal(1, comp.Castes.Count(c => c.label == StarterCastes.ColonistLabel), "Colonist castes after the reload");
T.Equal(1, comp.Castes.Count(c => c.label == StarterCastes.PrisonerLabel), "Prisoner castes after the reload");
T.Equal(ModsConfig.IdeologyActive ? 1 : 0, comp.Castes.Count(c => c.label == StarterCastes.SlaveLabel), "Slave castes after the reload");
}
}
}

View File

@ -0,0 +1,514 @@
using System.Collections.Generic;
using System.Linq;
using BlaxCastes;
using RimWorld;
using Verse;
namespace BlaxCastesTests
{
/// <summary>
/// Status changes between player colonist, slave and prisoner go through the status rows, and a
/// pawn that comes back gets its previous caste. Arrests and imprisonments go through
/// Pawn_GuestTracker.CapturedBy, as the arrest job does. Joins are applied with Fixtures.ApplyJoins,
/// because fixture prisoners must not be ticked.
/// </summary>
public static class StatusTests
{
private static ApparelPolicy Worker() => Fixtures.Need(Fixtures.Outfit("OutfitWorker"), "Worker outfit");
private static ApparelPolicy Nudist() => Fixtures.Need(Fixtures.Outfit("OutfitNudist"), "Nudist outfit");
private static FoodPolicy Simple() => Fixtures.Need(Fixtures.Food("FoodRestrictionSimple"), "Simple food policy");
private static FoodPolicy Fine() => Fixtures.Need(Fixtures.Food("FoodRestrictionFine"), "Fine food policy");
private static FoodPolicy Paste() => Fixtures.Need(Fixtures.Food("FoodRestrictionPaste"), "Paste food policy");
private static FoodPolicy Lavish() => Fixtures.Need(Fixtures.Food("FoodRestrictionLavish"), "Lavish food policy");
private static Caste Make(string label, ApparelPolicy apparel, FoodPolicy food)
{
Caste c = Fixtures.NewCaste(label);
if (apparel != null)
CasteManager.SetSlot(c, CasteSlot.Apparel, apparel);
CasteManager.SetSlot(c, CasteSlot.Food, food);
return c;
}
private static void Row(string reason, Caste caste) =>
T.Check(CasteManager.SetJoinRow(reason, JoinRowMode.SpecificCaste, caste), "setup: SetJoinRow " + reason + " failed");
private static void NoCasteRow(string reason) =>
T.Check(CasteManager.SetJoinRow(reason, JoinRowMode.NoCaste), "setup: SetJoinRow " + reason + " failed");
private static string Who(Pawn p) => p.LabelShort + " [" + p.ThingID + "]";
private static string State(Pawn p)
{
CasteMembership m = Fixtures.Comp.MembershipOf(p);
return m == null ? "no record" : $"caste={m.caste?.label ?? "none"}, auto={m.auto}, reason={m.reason}";
}
private static void CheckIn(Pawn p, Caste caste, string reason, string when)
{
CasteMembership m = Fixtures.Comp.MembershipOf(p);
T.Check(m != null && m.caste == caste, Who(p) + " " + when + ": expected " + caste.label + ", got " + State(p));
if (reason != null)
T.Equal(reason, m.reason, Who(p) + "'s membership reason " + when);
}
private static Pawn Warden() => Fixtures.Colonist();
/// <summary>A spawned slave whose own faction is the colony, so freeing it keeps it as a colonist.</summary>
private static Pawn HomeSlave()
{
if (!ModsConfig.IdeologyActive)
T.Skip("slaves need Ideology");
Pawn p = Fixtures.Spawn(Fixtures.Generate(PawnKindDefOf.Slave, Faction.OfPlayer));
p.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Slave);
T.Check(p.IsSlaveOfColony && p.HomeFaction == Faction.OfPlayer, "setup: home slave fixture: slave=" + p.IsSlaveOfColony + ", home=" + p.HomeFaction);
Fixtures.Unqueue(p);
return p;
}
// ---- every transition goes through the status rows ---------------------------------------
[BlaxTest("status: an arrested Miner colonist goes to the new-prisoner caste, and once released returns to Miner")]
public static void ArrestAndRelease()
{
Caste miner = Make("Miner (status test)", Worker(), Fine());
Caste prisoners = Make("Prisoners (status test)", null, Paste());
Caste wrong = Make("Wrong row (status test)", Nudist(), Lavish());
Row(JoinReason.NewPrisoner, prisoners);
Row(JoinReason.NewColonist, wrong);
Pawn p = Fixtures.Colonist();
Fixtures.Unqueue(p);
T.Check(CasteManager.Assign(p, miner, false, JoinReason.Manual), "setup: Assign Miner failed");
p.guest.CapturedBy(Faction.OfPlayer, Warden());
T.Check(p.IsPrisonerOfColony && p.Faction == Faction.OfPlayer, Who(p) + " is not an arrested colonist after CapturedBy");
FormerCaste record = Fixtures.Comp.FormerOf(p);
T.NotNull(record, Who(p) + "'s former-caste record after the arrest");
T.Check(record.casteId == miner.id && record.side == JoinSide.Colonist && !record.auto, "former-caste record: " + record);
T.Equal(JoinDefaults.StatusFallback, JoinDefaults.QueuedFor(p)?.reason, "queued reason after the arrest");
Fixtures.ApplyJoins(p);
CheckIn(p, prisoners, JoinReason.NewPrisoner, "after the arrest");
T.Check(p.foodRestriction.CurrentFoodPolicy == Paste(), Who(p) + " does not eat the prisoner food");
GenGuest.PrisonerRelease(p);
T.Check(p.IsColonist && !p.IsPrisoner, Who(p) + " is not a free colonist after the release");
T.Check(JoinDefaults.IsQueued(p), Who(p) + " was not queued by the release");
Fixtures.ApplyJoins(p);
CheckIn(p, miner, JoinReason.PreviousCaste, "after the release");
T.Check(!Fixtures.Comp.MembershipOf(p).auto, "the restored hand-picked caste is marked as set by a join row");
T.Check(p.foodRestriction.CurrentFoodPolicy == Fine() && p.outfits.CurrentApparelPolicy == Worker(), Who(p) + " does not have Miner's policies back");
T.Check(Fixtures.Comp.FormerOf(p) == null, "the used former-caste record is still there");
}
[BlaxTest("status: freeing a slave whose home is the colony lands in the new-colonist row and leaves no record")]
public static void FreedSlave()
{
Caste slaves = Make("Slaves (freed test)", null, Paste());
Caste colonists = Make("Colonists (freed test)", Worker(), Fine());
Row(JoinReason.NewColonist, colonists);
Pawn p = HomeSlave();
T.Check(CasteManager.Assign(p, slaves, true, JoinReason.NewSlave), "setup: Assign failed");
GenGuest.EmancipateSlave(Warden(), p);
T.Check(p.IsColonist && !p.IsSlave, Who(p) + " is not a free colonist after EmancipateSlave");
T.Check(Fixtures.Comp.FormerOf(p) == null, "freeing a slave wrote a former-caste record");
Fixtures.ApplyJoins(p);
CheckIn(p, colonists, JoinReason.NewColonist, "after being freed");
T.Check(p.foodRestriction.CurrentFoodPolicy == Fine(), Who(p) + " still eats the slave food");
}
[BlaxTest("status: imprisoning a slave (the Imprison mode's arrest) goes to the new-prisoner row and records its slave caste")]
public static void ImprisonedSlave()
{
Caste minerSlaves = Make("Miner slaves (imprison test)", null, Simple());
Caste prisoners = Make("Prisoners (imprison test)", null, Paste());
Row(JoinReason.NewPrisoner, prisoners);
Pawn p = Fixtures.ColonySlave();
Fixtures.Unqueue(p);
T.Check(CasteManager.Assign(p, minerSlaves, true, JoinReason.NewSlave), "setup: Assign failed");
p.guest.CapturedBy(Faction.OfPlayer, Warden());
T.Check(p.IsPrisonerOfColony, Who(p) + " is not a prisoner of the colony after CapturedBy");
FormerCaste record = Fixtures.Comp.FormerOf(p);
T.Check(record != null && record.casteId == minerSlaves.id && record.side == JoinSide.Slave, "former-caste record: " + (record?.ToString() ?? "none"));
Fixtures.ApplyJoins(p);
CheckIn(p, prisoners, JoinReason.NewPrisoner, "after being imprisoned");
T.Check(p.foodRestriction.CurrentFoodPolicy == Paste(), Who(p) + " does not eat the prisoner food");
}
[BlaxTest("status: an arrested colonist who is then enslaved goes to the new-slave row, not its old colonist caste")]
public static void ArrestedThenEnslaved()
{
if (!ModsConfig.IdeologyActive)
T.Skip("slaves need Ideology");
Caste miner = Make("Miner (enslave test)", Worker(), Fine());
Caste prisoners = Make("Prisoners (enslave test)", null, Paste());
Caste slaves = Make("Slaves (enslave test)", null, Simple());
Row(JoinReason.NewPrisoner, prisoners);
Row(JoinReason.NewSlave, slaves);
Pawn p = Fixtures.Colonist();
Fixtures.Unqueue(p);
CasteManager.Assign(p, miner, false, JoinReason.Manual);
Pawn warden = Warden();
p.guest.CapturedBy(Faction.OfPlayer, warden);
Fixtures.ApplyJoins(p);
CheckIn(p, prisoners, JoinReason.NewPrisoner, "after the arrest");
GenGuest.EnslavePrisoner(warden, p);
T.Check(p.IsSlaveOfColony, Who(p) + " is not a slave after EnslavePrisoner");
Fixtures.ApplyJoins(p);
CheckIn(p, slaves, JoinReason.NewSlave, "after being enslaved");
T.Check(p.foodRestriction.CurrentFoodPolicy == Simple(), Who(p) + " does not eat the slave food");
}
[BlaxTest("status: a Miner slave sold and bought back returns to Miner slave, not the bought-as-slave row")]
public static void SoldAndBoughtBack()
{
if (!ModsConfig.IdeologyActive)
T.Skip("slaves need Ideology");
Caste minerSlaves = Make("Miner slaves (sale test)", Worker(), Simple());
Caste wrong = Make("Wrong row (sale test)", Nudist(), Paste());
Row(JoinReason.BoughtSlave, wrong);
Row(JoinReason.NewColonist, wrong);
Row(JoinReason.NewSlave, wrong);
Pawn p = Fixtures.ColonySlave();
Fixtures.Unqueue(p);
T.Check(CasteManager.Assign(p, minerSlaves, true, JoinReason.NewSlave), "setup: Assign failed");
p.foodRestriction.CurrentFoodPolicy = Fine(); // by hand
var trader = new JoinTests.TestTrader();
Pawn negotiator = Fixtures.Colonist();
p.PreTraded(TradeAction.PlayerSells, negotiator, trader);
T.Check(p.Faction != Faction.OfPlayer, Who(p) + " is still in the player faction after being sold");
T.Equal(0, JoinScopes.Depth, "open join scopes after the sale");
T.Check(!JoinDefaults.IsQueued(p), "the sale queued a join (the slave-to-free step inside the sale)");
FormerCaste record = Fixtures.Comp.FormerOf(p);
T.Check(record != null && record.casteId == minerSlaves.id && record.side == JoinSide.Slave, "former-caste record after the sale: " + (record?.ToString() ?? "none"));
Fixtures.ApplyJoins(p);
T.Check(Fixtures.Comp.MembershipOf(p) == null, "the sold slave kept its membership: " + State(p));
p.guest.Recruitable = true;
p.guest.joinStatus = JoinStatus.JoinAsSlave;
p.PreTraded(TradeAction.PlayerBuys, negotiator, trader);
T.Check(p.IsSlaveOfColony, Who(p) + " is not a slave of the colony after the purchase");
T.Equal(JoinScopes.Bought, JoinDefaults.QueuedFor(p)?.reason, "queued reason after buying back");
T.Check(JoinDefaults.WillChange(p), "the bought-back slave does not show as pending");
Fixtures.ApplyJoins(p);
CheckIn(p, minerSlaves, JoinReason.PreviousCaste, "after buying it back");
T.Check(Fixtures.Comp.MembershipOf(p).auto, "the restored row-set caste is marked as set by hand");
T.Check(p.outfits.CurrentApparelPolicy == Worker(), Who(p) + " does not have Miner slave's outfit back: " + p.outfits.CurrentApparelPolicy.label);
T.Check(p.foodRestriction.CurrentFoodPolicy == Fine(), Who(p) + " lost its hand-set food: " + p.foodRestriction.CurrentFoodPolicy.label);
}
[BlaxTest("status: a former-caste record older than formerCasteDays is ignored and pruned; with the setting off the row applies")]
public static void StaleRecordIgnored()
{
Caste miner = Make("Miner (stale test)", Worker(), Fine());
Caste prisoners = Make("Prisoners (stale test)", null, Paste());
Caste colonists = Make("Colonists (stale test)", Nudist(), Simple());
Row(JoinReason.NewPrisoner, prisoners);
Row(JoinReason.NewColonist, colonists);
GameComponent_BlaxCastes comp = Fixtures.Comp;
Pawn p = Fixtures.Colonist();
Fixtures.Unqueue(p);
CasteManager.Assign(p, miner, false, JoinReason.Manual);
p.guest.CapturedBy(Faction.OfPlayer, Warden());
Fixtures.ApplyJoins(p);
FormerCaste record = comp.FormerOf(p);
T.NotNull(record, "setup: former-caste record after the arrest");
record.tick = Find.TickManager.TicksGame - (Fixtures.Settings.formerCasteDays + 1) * GenDate.TicksPerDay;
T.Check(JoinDefaults.PreviousCasteFor(p) == null, "a stale record still gives a previous caste");
GenGuest.PrisonerRelease(p);
Fixtures.ApplyJoins(p);
CheckIn(p, colonists, JoinReason.NewColonist, "after the release with a stale record");
T.Check(comp.PruneFormerCastes() >= 1 && comp.FormerOf(p) == null, "the stale record was not pruned");
// The setting off: a fresh record is ignored too.
Fixtures.Settings.returnToPreviousCaste = false;
Pawn q = Fixtures.Colonist();
Fixtures.Unqueue(q);
CasteManager.Assign(q, miner, false, JoinReason.Manual);
q.guest.CapturedBy(Faction.OfPlayer, Warden());
Fixtures.ApplyJoins(q);
T.NotNull(comp.FormerOf(q), "no record was written with returnToPreviousCaste off (records are kept for when it is turned on)");
GenGuest.PrisonerRelease(q);
Fixtures.ApplyJoins(q);
CheckIn(q, colonists, JoinReason.NewColonist, "after the release with returnToPreviousCaste off");
}
[BlaxTest("status: deleting a caste drops the former-caste records that point at it")]
public static void DeletedCasteDropsRecords()
{
Caste doomed = Make("Doomed (record test)", null, Fine());
Pawn p = Fixtures.Colonist();
Fixtures.Unqueue(p);
CasteManager.Assign(p, doomed, false, JoinReason.Manual);
Faction other = Fixtures.FriendlyFaction();
T.NotNull(other, "a friendly faction");
p.SetFaction(other);
T.NotNull(Fixtures.Comp.FormerOf(p), "leaving the faction wrote no former-caste record");
CasteManager.DeleteCaste(doomed);
T.Check(Fixtures.Comp.FormerOf(p) == null, "the record of a deleted caste survived");
}
// ---- hand changes survive a return ----------------------------------------------------
private static DrugPolicy NoDrugs() => Fixtures.Need(Fixtures.Drug("NoDrugs"), "No drugs policy");
private static DrugPolicy Social() => Fixtures.Need(Fixtures.Drug("SocialDrugs"), "Social drugs policy");
/// <summary>Work from 22 to 5, sleep the rest: nothing like the starting schedule.</summary>
private static List<string> NightShift() =>
Enumerable.Range(0, ScheduleSlot.Hours).Select(h => (h >= 22 || h <= 5 ? TimeAssignmentDefOf.Work : TimeAssignmentDefOf.Sleep).defName).ToList();
[BlaxTest("status: an arrested and released colonist gets its caste back with its hand changes; followed slots get the caste's value")]
public static void ReturnKeepsHandChanges()
{
Caste colonists = Make("Colonists (hand change test)", Worker(), Fine());
CasteManager.SetSlot(colonists, CasteSlot.Drug, NoDrugs());
CasteManager.SetSlot(colonists, CasteSlot.MedCare, MedicalCareCategory.NoMeds);
CasteManager.SetSlot(colonists, CasteSlot.Schedule, NightShift());
Caste prisoners = Make("Prisoners (hand change test)", null, Paste());
Caste wrong = Make("Wrong row (hand change test)", Nudist(), Lavish());
Row(JoinReason.NewPrisoner, prisoners);
Row(JoinReason.NewColonist, wrong);
Pawn p = Fixtures.Colonist();
Fixtures.Unqueue(p);
T.Check(CasteManager.Assign(p, colonists, true, JoinReason.NewColonist), "setup: Assign failed");
// By hand: another outfit, Social drugs, best care and one hour of the schedule.
p.outfits.CurrentApparelPolicy = Nudist();
p.drugs.CurrentPolicy = Social();
p.playerSettings.medCare = MedicalCareCategory.Best;
TimeAssignmentDef hour3 = TimeAssignmentDefOf.Joy;
p.timetable.SetAssignment(3, hour3);
T.Equal(4, CasteManager.Overrides(p).Count, "setup: hand changes (" + string.Join(", ", CasteManager.Overrides(p)) + ")");
p.guest.CapturedBy(Faction.OfPlayer, Warden());
FormerCaste record = Fixtures.Comp.FormerOf(p);
T.NotNull(record, "former-caste record after the arrest");
T.Check(record.Followed(CasteSlot.Food) && !record.Followed(CasteSlot.Apparel) && !record.Followed(CasteSlot.MedCare),
"followed slots in the record: " + string.Join(", ", record.followed));
T.Equal((int)MedicalCareCategory.Best, record.medCare, "medical care in the record (taken before the game's reset)");
Fixtures.ApplyJoins(p);
CheckIn(p, prisoners, JoinReason.NewPrisoner, "after the arrest");
T.Check(p.foodRestriction.CurrentFoodPolicy == Paste(), Who(p) + " does not eat the prisoner food");
// While it was away the caste's food changed: a follower gets the new value.
CasteManager.SetSlot(colonists, CasteSlot.Food, Simple());
GenGuest.PrisonerRelease(p);
Fixtures.ApplyJoins(p);
CheckIn(p, colonists, JoinReason.PreviousCaste, "after the release");
T.Check(Fixtures.Comp.MembershipOf(p).auto, "the restored row-set caste is marked as set by hand");
T.Check(p.outfits.CurrentApparelPolicy == Nudist(), Who(p) + " lost its hand-set outfit: " + p.outfits.CurrentApparelPolicy.label);
T.Check(p.drugs.CurrentPolicy == Social(), Who(p) + " lost its hand-set drug policy: " + p.drugs.CurrentPolicy.label);
T.Equal(MedicalCareCategory.Best, p.playerSettings.medCare, Who(p) + "'s hand-set medical care");
T.Equal(hour3, p.timetable.GetAssignment(3), Who(p) + "'s hand-set hour 3");
T.Equal(TimeAssignmentDefOf.Work, p.timetable.GetAssignment(23), Who(p) + "'s hour 23 (the caste's)");
T.Check(p.foodRestriction.CurrentFoodPolicy == Simple(), Who(p) + " does not follow the caste's new food: " + p.foodRestriction.CurrentFoodPolicy.label);
}
[BlaxTest("status: with No caste rows, an arrest and release rewrites nothing on a pawn that never left its caste")]
public static void NeverLeftKeepsHandChanges()
{
Caste miner = Make("Miner (never left test)", Worker(), Fine());
CasteManager.SetSlot(miner, CasteSlot.Schedule, NightShift());
NoCasteRow(JoinReason.NewPrisoner);
NoCasteRow(JoinReason.NewColonist);
Pawn p = Fixtures.Colonist();
Fixtures.Unqueue(p);
CasteManager.Assign(p, miner, false, JoinReason.Manual);
p.outfits.CurrentApparelPolicy = Nudist();
p.foodRestriction.CurrentFoodPolicy = Lavish();
p.timetable.SetAssignment(12, TimeAssignmentDefOf.Joy);
p.guest.CapturedBy(Faction.OfPlayer, Warden());
Fixtures.ApplyJoins(p);
CheckIn(p, miner, JoinReason.Manual, "after the arrest with a No caste prisoner row");
GenGuest.PrisonerRelease(p);
Fixtures.ApplyJoins(p);
CheckIn(p, miner, JoinReason.PreviousCaste, "after the release");
T.Check(!Fixtures.Comp.MembershipOf(p).auto, "the hand-picked caste is marked as set by a join row");
T.Check(p.outfits.CurrentApparelPolicy == Nudist() && p.foodRestriction.CurrentFoodPolicy == Lavish(),
Who(p) + " lost its hand-set policies: " + p.outfits.CurrentApparelPolicy.label + ", " + p.foodRestriction.CurrentFoodPolicy.label);
T.Equal(TimeAssignmentDefOf.Joy, p.timetable.GetAssignment(12), Who(p) + "'s hand-set hour 12");
}
[BlaxTest("status: a pawn set to No caste goes back to No caste after an arrest and release, with its own policies")]
public static void CastelessComesBack()
{
Caste prisoners = Make("Prisoners (casteless test)", null, Paste());
Caste colonists = Make("Colonists (casteless test)", Worker(), Fine());
Row(JoinReason.NewPrisoner, prisoners);
Row(JoinReason.NewColonist, colonists);
Pawn p = Fixtures.Colonist();
Fixtures.Unqueue(p);
p.outfits.CurrentApparelPolicy = Nudist();
p.foodRestriction.CurrentFoodPolicy = Lavish();
T.Check(CasteManager.MakeCasteless(p), "setup: MakeCasteless failed");
p.guest.CapturedBy(Faction.OfPlayer, Warden());
FormerCaste record = Fixtures.Comp.FormerOf(p);
T.Check(record != null && record.casteless && record.side == JoinSide.Colonist, "former-caste record: " + (record?.ToString() ?? "none"));
Fixtures.ApplyJoins(p);
CheckIn(p, prisoners, JoinReason.NewPrisoner, "after the arrest");
T.Check(p.foodRestriction.CurrentFoodPolicy == Paste(), Who(p) + " does not eat the prisoner food");
GenGuest.PrisonerRelease(p);
T.Check(JoinDefaults.WillChange(p), Who(p) + " does not show as pending before going back to No caste");
Fixtures.ApplyJoins(p);
CasteMembership m = Fixtures.Comp.MembershipOf(p);
T.Check(m != null && m.Casteless, Who(p) + " is not back at No caste: " + State(p));
T.Check(p.outfits.CurrentApparelPolicy == Nudist(), Who(p) + "'s outfit: " + p.outfits.CurrentApparelPolicy.label);
T.Check(p.foodRestriction.CurrentFoodPolicy == Lavish(), Who(p) + "'s food (the prisoner caste's should be undone): " + p.foodRestriction.CurrentFoodPolicy.label);
T.Check(!CasteManager.PawnsToAssignByStatus().Contains(p), "Assign by status offers the pawn set to No caste");
}
[BlaxTest("status: the prisoner caste's food is undone when the pawn returns to a caste that leaves food alone")]
public static void PrisonerFoodUndone()
{
Caste miner = Make("Miner (food undo test)", Worker(), null);
CasteManager.SetSlot(miner, CasteSlot.Food, null);
T.Check(!miner.IsManaged(CasteSlot.Food), "setup: the Miner caste manages food");
Caste prisoners = Make("Prisoners (food undo test)", null, Paste());
Row(JoinReason.NewPrisoner, prisoners);
Pawn p = Fixtures.Colonist();
Fixtures.Unqueue(p);
CasteManager.Assign(p, miner, false, JoinReason.Manual);
p.foodRestriction.CurrentFoodPolicy = Fine();
p.guest.CapturedBy(Faction.OfPlayer, Warden());
Fixtures.ApplyJoins(p);
T.Check(p.foodRestriction.CurrentFoodPolicy == Paste(), Who(p) + " does not eat the prisoner food");
GenGuest.PrisonerRelease(p);
Fixtures.ApplyJoins(p);
CheckIn(p, miner, JoinReason.PreviousCaste, "after the release");
T.Check(p.foodRestriction.CurrentFoodPolicy == Fine(), Who(p) + " kept the prisoner food: " + p.foodRestriction.CurrentFoodPolicy.label);
}
[BlaxTest("status: a row that moves a pawn on from a row-set caste resets what that caste set and the new one leaves alone")]
public static void RowMoveRevertsOldCaste()
{
FoodPolicy defaultFood = Current.Game.foodRestrictionDatabase.DefaultFoodRestriction();
T.Check(defaultFood != Paste(), "setup: Paste is the default food");
Caste prisoners = Make("Prisoners (row move test)", null, Paste());
Caste colonists = Make("Colonists (row move test)", Worker(), null);
CasteManager.SetSlot(colonists, CasteSlot.Food, null);
Row(JoinReason.NewPrisoner, prisoners);
Row(JoinReason.NewColonist, colonists);
// No record at all, so nothing comes back: the rows move it.
Pawn p = Fixtures.Colonist();
Fixtures.Unqueue(p);
T.Check(Fixtures.Comp.MembershipOf(p) == null, "setup: the colonist has a membership record");
p.guest.CapturedBy(Faction.OfPlayer, Warden());
T.Check(Fixtures.Comp.FormerOf(p) == null, "a pawn without a record left a former-caste record");
Fixtures.ApplyJoins(p);
CheckIn(p, prisoners, JoinReason.NewPrisoner, "after the arrest");
GenGuest.PrisonerRelease(p);
Fixtures.ApplyJoins(p);
CheckIn(p, colonists, JoinReason.NewColonist, "after the release");
T.Check(p.foodRestriction.CurrentFoodPolicy == defaultFood, Who(p) + " kept the prisoner food: " + p.foodRestriction.CurrentFoodPolicy.label);
// revertOnLeave off: the food stays.
Fixtures.Settings.revertOnLeave = false;
Pawn q = Fixtures.Colonist();
Fixtures.Unqueue(q);
q.guest.CapturedBy(Faction.OfPlayer, Warden());
Fixtures.ApplyJoins(q);
GenGuest.PrisonerRelease(q);
Fixtures.ApplyJoins(q);
CheckIn(q, colonists, JoinReason.NewColonist, "after the release with revertOnLeave off");
T.Check(q.foodRestriction.CurrentFoodPolicy == Paste(), Who(q) + "'s food with revertOnLeave off: " + q.foodRestriction.CurrentFoodPolicy.label);
}
// ---- the No caste rows ---------------------------------------------------------------
[BlaxTest("status: with No caste rows, an arrested and released colonist keeps its hand-picked caste and its policies")]
public static void HandPickSurvivesNoCasteRows()
{
Caste miner = Make("Miner (no caste rows test)", Worker(), Fine());
CasteManager.SetSlot(miner, CasteSlot.MedCare, MedicalCareCategory.HerbalOrWorse);
NoCasteRow(JoinReason.NewPrisoner);
NoCasteRow(JoinReason.NewColonist);
Pawn p = Fixtures.Colonist();
Fixtures.Unqueue(p);
CasteManager.Assign(p, miner, false, JoinReason.Manual);
p.guest.CapturedBy(Faction.OfPlayer, Warden());
Fixtures.ApplyJoins(p);
CheckIn(p, miner, JoinReason.Manual, "after the arrest with a No caste prisoner row");
T.Check(p.foodRestriction.CurrentFoodPolicy == Fine(), Who(p) + "'s food changed: " + p.foodRestriction.CurrentFoodPolicy.label);
GenGuest.PrisonerRelease(p);
Fixtures.ApplyJoins(p);
T.Check(Fixtures.Comp.CasteOf(p) == miner, Who(p) + " lost Miner after the release: " + State(p));
T.Check(p.foodRestriction.CurrentFoodPolicy == Fine() && p.outfits.CurrentApparelPolicy == Worker(), Who(p) + " lost Miner's policies");
}
[BlaxTest("status: a No caste row reverts only the slots still on the caste's value; a hand-changed slot stays")]
public static void RevertKeepsHandChanges()
{
Caste slaves = Make("Slaves (revert test)", Worker(), Paste());
NoCasteRow(JoinReason.NewColonist);
ApparelPolicy defaultOutfit = Current.Game.outfitDatabase.DefaultOutfit();
T.Check(defaultOutfit != Worker(), "setup: Worker is the default outfit");
// Freeing a home slave changes neither faction nor medical care, so only Castes touches the policies.
Pawn p = HomeSlave();
T.Check(CasteManager.Assign(p, slaves, true, JoinReason.NewSlave), "setup: Assign failed");
p.foodRestriction.CurrentFoodPolicy = Lavish(); // by hand
GenGuest.EmancipateSlave(Warden(), p);
Fixtures.ApplyJoins(p);
T.Check(Fixtures.Comp.MembershipOf(p) == null, Who(p) + " is still in a caste: " + State(p));
T.Check(p.outfits.CurrentApparelPolicy == defaultOutfit, Who(p) + "'s outfit did not return to the default: " + p.outfits.CurrentApparelPolicy.label);
T.Check(p.foodRestriction.CurrentFoodPolicy == Lavish(), Who(p) + " lost its hand-set food: " + p.foodRestriction.CurrentFoodPolicy.label);
}
// ---- save and reload -----------------------------------------------------------------
// Runs last in this class (source order): the record is checked after the reload.
[BlaxTest("status: set up a former-caste record for the reload")]
public static void ReloadSetup()
{
Caste c = Fixtures.KeepCaste(Make("Former caste reload test", null, Fine()));
Pawn p = Fixtures.Colonist(); // destroyed by the cleanup: the record is keyed by ThingID, not by reference
Fixtures.Unqueue(p);
CasteManager.Assign(p, c, true, JoinReason.NewColonist);
Faction other = Fixtures.FriendlyFaction();
T.NotNull(other, "a friendly faction");
p.SetFaction(other);
FormerCaste record = Fixtures.Comp.FormerOf(p);
T.NotNull(record, "setup: no former-caste record");
T.Check(record.Followed(CasteSlot.Food) && record.foodId == Fine().id, "setup: the record's food: id " + record.foodId + ", followed " + string.Join(", ", record.followed));
T.Carry["formerPawn"] = p.ThingID;
T.Carry["formerCaste"] = c.id.ToString();
T.Carry["formerFood"] = record.foodId.ToString();
T.Carry["formerSchedule"] = record.schedule == null ? "none" : string.Join(",", record.schedule);
}
[BlaxTest("status: former-caste records survive save and reload, keyed by ThingID", phase: 2)]
public static void RecordSurvives()
{
string casteId = null;
T.Check(T.Carry.TryGetValue("formerPawn", out string pawnId) && T.Carry.TryGetValue("formerCaste", out casteId), "phase 1 setup did not run");
T.Check(Fixtures.Comp.FormerCastes.TryGetValue(pawnId, out FormerCaste record), "the record for " + pawnId + " did not survive the reload");
T.Equal(casteId, record.casteId.ToString(), "record caste id");
T.Equal(JoinSide.Colonist, record.side, "record status");
T.Check(record.auto, "record auto flag");
T.NotNull(Fixtures.Comp.CasteById(record.casteId), "the record's caste after the reload");
T.Check(!record.casteless, "record turned into a No caste record");
T.Equal(T.Carry["formerFood"], record.foodId.ToString(), "record food id");
T.Check(record.Followed(CasteSlot.Food), "record lost its followed slots: " + string.Join(", ", record.followed));
T.Equal(T.Carry["formerSchedule"], record.schedule == null ? "none" : string.Join(",", record.schedule), "record schedule");
}
}
}

View File

@ -20,7 +20,7 @@ namespace BlaxCastesTests
private static PawnColumnDef NeedColumn() private static PawnColumnDef NeedColumn()
{ {
PawnColumnDef col = AssignColumn.Column; PawnColumnDef col = CasteColumns.Column;
T.NotNull(col, "PawnColumnDef " + PawnColumnWorker_BlaxCaste.DefName); T.NotNull(col, "PawnColumnDef " + PawnColumnWorker_BlaxCaste.DefName);
return col; return col;
} }
@ -30,7 +30,7 @@ namespace BlaxCastesTests
private static void CheckRightBeforeHostility(PawnTableDef table, PawnColumnDef col) private static void CheckRightBeforeHostility(PawnTableDef table, PawnColumnDef col)
{ {
int at = table.columns.IndexOf(col); int at = table.columns.IndexOf(col);
int hostility = table.columns.FindIndex(c => c != null && c.defName == AssignColumn.AnchorColumn); int hostility = table.columns.FindIndex(c => c != null && c.defName == CasteColumns.AnchorColumn);
T.Check(at >= 0, "Caste column not in the Assign table: " + ColumnList(table)); T.Check(at >= 0, "Caste column not in the Assign table: " + ColumnList(table));
T.Check(hostility >= 0, "HostilityResponse not in the Assign table: " + ColumnList(table)); T.Check(hostility >= 0, "HostilityResponse not in the Assign table: " + ColumnList(table));
T.Equal(hostility - 1, at, "Caste column index (columns: " + ColumnList(table) + ")"); T.Equal(hostility - 1, at, "Caste column index (columns: " + ColumnList(table) + ")");
@ -88,17 +88,17 @@ namespace BlaxCastesTests
bool had = table.columns.Contains(col); bool had = table.columns.Contains(col);
try try
{ {
AssignColumn.Apply(false); CasteColumns.Apply(false);
T.Check(!table.columns.Contains(col), "Apply(false) left the column in the table"); T.Check(!table.columns.Contains(col), "Apply(false) left the column in the table");
T.Check(!AssignColumn.Apply(false), "removing a missing column reported a change"); T.Check(!CasteColumns.Apply(false), "removing a missing column reported a change");
T.Check(AssignColumn.Apply(true), "Apply(true) did not add the column back"); T.Check(CasteColumns.Apply(true), "Apply(true) did not add the column back");
CheckRightBeforeHostility(table, col); CheckRightBeforeHostility(table, col);
T.Check(!AssignColumn.Apply(true), "adding a present column reported a change"); T.Check(!CasteColumns.Apply(true), "adding a present column reported a change");
CheckRightBeforeHostility(table, col); CheckRightBeforeHostility(table, col);
} }
finally finally
{ {
AssignColumn.Apply(had); CasteColumns.Apply(had);
} }
} }
@ -185,6 +185,39 @@ namespace BlaxCastesTests
T.Check(comp.MembershipOf(target) != null && comp.MembershipOf(target).caste == null, "painting No caste did not make the pawn casteless"); T.Check(comp.MembershipOf(target) != null && comp.MembershipOf(target).caste == null, "painting No caste did not make the pawn casteless");
} }
[BlaxTest("ui: painting skips pawns already in the painted caste, so their hand changes stay; a click still rewrites")]
public static void PaintKeepsOverrides()
{
Caste a = Fixtures.NewCaste("Paint keep A");
Caste b = Fixtures.NewCaste("Paint keep B");
CasteManager.SetSlot(a, CasteSlot.Food, Simple);
Pawn member = Fixtures.Colonist();
Pawn other = Fixtures.Colonist();
Pawn casteless = Fixtures.Colonist();
CasteManager.Assign(member, a, false, JoinReason.Manual);
CasteManager.Assign(other, b, false, JoinReason.Manual);
CasteManager.MakeCasteless(casteless);
member.foodRestriction.CurrentFoodPolicy = Lavish; // by hand
var paintA = new CasteChoice(CasteChoiceKind.Caste, a);
var paintNone = new CasteChoice(CasteChoiceKind.Casteless);
T.Check(PawnColumnWorker_BlaxCaste.SkipWhilePainting(member, paintA, true), "painting A over a member of A is not skipped");
T.Check(!PawnColumnWorker_BlaxCaste.SkipWhilePainting(other, paintA, true), "painting A over a member of B is skipped");
T.Check(!PawnColumnWorker_BlaxCaste.SkipWhilePainting(member, paintA, false), "a click on A is skipped for a member of A");
T.Check(PawnColumnWorker_BlaxCaste.SkipWhilePainting(casteless, paintNone, true), "painting No caste over a casteless pawn is not skipped");
T.Check(!PawnColumnWorker_BlaxCaste.SkipWhilePainting(member, paintNone, true), "painting No caste over a member is skipped");
// What the paint stroke does to each cell it passes, start cell included.
foreach (Pawn p in new[] { member, other })
{
CasteMenuEntry hit = PawnColumnWorker_BlaxCaste.MenuEntries(p).First(e => Equals(e.Choice, paintA));
if (!PawnColumnWorker_BlaxCaste.SkipWhilePainting(p, paintA, true))
hit.Action();
}
T.Check(member.foodRestriction.CurrentFoodPolicy == Lavish, "painting wiped the member's hand-set food: " + Policies(member));
T.Check(Fixtures.Comp.CasteOf(other) == a && other.foodRestriction.CurrentFoodPolicy == Simple, "painting did not move the other pawn into A: " + Policies(other));
}
[BlaxTest("ui: sorting orders by caste label, pawns without a caste last")] [BlaxTest("ui: sorting orders by caste label, pawns without a caste last")]
public static void CompareOrder() public static void CompareOrder()
{ {
@ -233,18 +266,35 @@ namespace BlaxCastesTests
CasteManager.MakeCasteless(p); CasteManager.MakeCasteless(p);
T.Equal((string)"BlaxCastes_NoCaste".Translate(), PawnColumnWorker_BlaxCaste.CellLabel(p), "label when casteless by choice"); T.Equal((string)"BlaxCastes_NoCaste".Translate(), PawnColumnWorker_BlaxCaste.CellLabel(p), "label when casteless by choice");
// "(pending)" only while the queued join will change the caste.
CasteManager.EndMembership(p);
var queued = new QueuedJoin(p, JoinReason.NewColonist, Find.TickManager.TicksGame); var queued = new QueuedJoin(p, JoinReason.NewColonist, Find.TickManager.TicksGame);
comp.JoinQueue.Add(queued); comp.JoinQueue.Add(queued);
try try
{ {
T.Check(PawnColumnWorker_BlaxCaste.IsPending(p), "IsPending false for a queued pawn"); T.Check(CasteManager.SetJoinRow(JoinReason.NewColonist, JoinRowMode.SpecificCaste, c), "setup: SetJoinRow failed");
T.Check(PawnColumnWorker_BlaxCaste.IsPending(p), "IsPending false for a queued pawn whose row gives a caste");
T.Equal((string)"BlaxCastes_CellPending".Translate(), PawnColumnWorker_BlaxCaste.CellLabel(p), "label while queued"); T.Equal((string)"BlaxCastes_CellPending".Translate(), PawnColumnWorker_BlaxCaste.CellLabel(p), "label while queued");
T.Check(CasteManager.SetJoinRow(JoinReason.NewColonist, JoinRowMode.NoCaste), "setup: SetJoinRow failed");
T.Check(!PawnColumnWorker_BlaxCaste.IsPending(p), "IsPending true for a queued pawn without a caste whose row is No caste");
T.Equal((string)"BlaxCastes_CellNone".Translate(), PawnColumnWorker_BlaxCaste.CellLabel(p), "label while a join that changes nothing is queued");
CasteManager.Assign(p, c, true, JoinReason.NewColonist);
T.Check(PawnColumnWorker_BlaxCaste.IsPending(p), "IsPending false for a row-set member whose row is now No caste (it will leave)");
CasteManager.Assign(p, c, false, JoinReason.Manual);
T.Check(!PawnColumnWorker_BlaxCaste.IsPending(p), "IsPending true for a caste picked by hand after the join was queued");
} }
finally finally
{ {
comp.JoinQueue.Remove(queued); comp.JoinQueue.Remove(queued);
} }
T.Check(!PawnColumnWorker_BlaxCaste.IsPending(p), "IsPending true after the queue entry left"); T.Check(!PawnColumnWorker_BlaxCaste.IsPending(p), "IsPending true after the queue entry left");
// A caste deleted from under a pawn has its own tooltip.
Caste doomed = Fixtures.NewCaste("Label doomed caste");
CasteManager.Assign(p, doomed, false, JoinReason.Manual);
CasteManager.DeleteCaste(doomed);
tip = PawnColumnWorker_BlaxCaste.CellTip(p);
T.Check(tip.Contains("BlaxCastes_CellCasteDeletedTip".Translate()), "tooltip after the caste was deleted: " + tip);
} }
[BlaxTest("ui: a quest lodger's cell says Unchangeable")] [BlaxTest("ui: a quest lodger's cell says Unchangeable")]
@ -390,12 +440,39 @@ namespace BlaxCastesTests
"BlaxCastes_CellCastelessTip", "BlaxCastes_CellPending", "BlaxCastes_CellPendingTip", "BlaxCastes_CellLodgerTip", "BlaxCastes_CellCastelessTip", "BlaxCastes_CellPending", "BlaxCastes_CellPendingTip", "BlaxCastes_CellLodgerTip",
"BlaxCastes_CellCasteTip", "BlaxCastes_CellOverrides", "BlaxCastes_CellOverrideLine", "BlaxCastes_CellHint", "BlaxCastes_CellCasteTip", "BlaxCastes_CellOverrides", "BlaxCastes_CellOverrideLine", "BlaxCastes_CellHint",
"BlaxCastes_MenuReset", "BlaxCastes_MenuEdit", "BlaxCastes_SettingOpenWindows", "BlaxCastes_MenuReset", "BlaxCastes_MenuEdit", "BlaxCastes_SettingOpenWindows",
"BlaxCastes_CellCasteDeletedTip", "BlaxCastes_MakeDefaultTip", "BlaxCastes_MemberCount", "BlaxCastes_ApplyToAll",
"BlaxCastes_ApplyToAllTip", "BlaxCastes_ApplyToAllConfirm", "BlaxCastes_AssignByStatus", "BlaxCastes_AssignByStatusTip",
"BlaxCastes_AssignByStatusDone", "BlaxCastes_AssignByStatusConfirm", "BlaxCastes_SlaveOutfitCold",
"BlaxCastes_StarterSeededMessage", "BlaxCastes_StarterSeededMessageNoColumn",
"Unchangeable", "ManageApparelPolicies", "ManageFoodPolicies", "ManageDrugPolicies", "ManageReadingPolicies", "Unchangeable", "ManageApparelPolicies", "ManageFoodPolicies", "ManageDrugPolicies", "ManageReadingPolicies",
}; };
var missing = keys.Where(k => !k.CanTranslate()).ToList(); var missing = keys.Where(k => !k.CanTranslate()).ToList();
T.Check(missing.Count == 0, "strings missing from Keyed: " + string.Join(", ", missing)); T.Check(missing.Count == 0, "strings missing from Keyed: " + string.Join(", ", missing));
} }
[BlaxTest("ui: texts with a count read right for one; Assign by status asks first and names the count")]
public static void CountTextsForOne()
{
Caste c = Fixtures.NewCaste("Count of one");
OverlapMod mod = OverlapWarnings.Mods[0];
var texts = new List<string>
{
Dialog_ManageCastes.ApplyToAllConfirmText(c, 1),
Dialog_ManageCastes.AssignByStatusConfirmText(1),
"BlaxCastes_AssignByStatusTip".Translate(1),
"BlaxCastes_AssignByStatusDone".Translate(1),
OverlapWarnings.MessageText(new List<OverlapMod> { mod }),
"BlaxCastes_SettingFormerCasteDays".Translate(1),
};
foreach (string text in texts)
{
T.Check(!System.Text.RegularExpressions.Regex.IsMatch(text, @"\b1 (members|pawns|days)\b") && !text.Contains("all 1"), "reads wrong for one: " + text);
}
T.Check(!texts[4].Contains(mod.Name + " also set"), "the overlap message conjugates for many mods: " + texts[4]);
string confirm = Dialog_ManageCastes.AssignByStatusConfirmText(7);
T.Check(confirm.Contains("7"), "the Assign by status confirm does not name the count: " + confirm);
}
[BlaxTest("ui: a new game posts the first-load message once and stores that in the save")] [BlaxTest("ui: a new game posts the first-load message once and stores that in the save")]
public static void FirstLoadMessageOnNewGame() public static void FirstLoadMessageOnNewGame()
{ {

View File

@ -4,23 +4,33 @@ own save data folder, so your mod list, saves and settings stay untouched. Needs
the Harmony mod from the Workshop. Exit code: 0 all passed, 1 failures, 2 the run didn't finish. the Harmony mod from the Workshop. Exit code: 0 all passed, 1 failures, 2 the run didn't finish.
.\Tests\run-tests.ps1 Harmony, the installed DLCs, Blax Castes .\Tests\run-tests.ps1 Harmony, the installed DLCs, Blax Castes
.\Tests\run-tests.ps1 -Compat also Blax Slaves and the installed mods Castes overlaps with .\Tests\run-tests.ps1 -Compat also Blax Slaves (its own buy mode) and the installed mods Castes is tested next to:
Hospitality, Custom Prisoner Interactions, Prisoner Realism, Weapons Tab Reborn
.\Tests\run-tests.ps1 -Tasoc also Trade as Slave or Colonist; Blax Slaves' buy mode stands down for it
.\Tests\run-tests.ps1 -NoDlc core only, no DLC (slave and baby tests skip)
.\Tests\run-tests.ps1 -Dlc Royalty,Anomaly only these installed DLCs
.\Tests\run-tests.ps1 -NoBuild skip dotnet build .\Tests\run-tests.ps1 -NoBuild skip dotnet build
.\Tests\run-tests.ps1 -AllowWhileRunning run next to an open RimWorld (the test game runs at below-normal priority) .\Tests\run-tests.ps1 -AllowWhileRunning run next to an open RimWorld (the test game runs at below-normal priority)
Mods\BlaxCastes must be a directory junction to this repo; it is created if missing and left in place. Mods\BlaxCastes must be a directory junction to this repo; it is created if missing and left in place.
While the suite runs, the test mod is linked into the game's Mods folder; that link is removed afterwards. While the suite runs, the test mod is linked into the game's Mods folder; that link is removed afterwards.
Only one run at a time: a lock file in the data folder holds the running script's process id. Only one run at a time: a lock file in the data folder holds the running script's process id.
Every run starts from default mod settings: the Blax Castes and Blax Slaves settings files in the data folder are deleted.
#> #>
param( param(
[string]$RimWorldDir = 'E:\SteamLibrary\steamapps\common\RimWorld', [string]$RimWorldDir = 'E:\SteamLibrary\steamapps\common\RimWorld',
[string]$DataDir = (Join-Path $env:TEMP 'BlaxCastesTest'), [string]$DataDir = (Join-Path $env:TEMP 'BlaxCastesTest'),
[switch]$Compat, [switch]$Compat,
[switch]$Tasoc,
[switch]$NoDlc,
[string[]]$Dlc,
[switch]$NoBuild, [switch]$NoBuild,
[switch]$AllowWhileRunning, [switch]$AllowWhileRunning,
[int]$TimeoutSeconds = 900 [int]$TimeoutSeconds = 900
) )
$ErrorActionPreference = 'Stop' $ErrorActionPreference = 'Stop'
# A wrong path (for example a switch passed as a positional value) would put the Mods junction somewhere odd.
if (-not (Test-Path -LiteralPath (Join-Path $RimWorldDir 'Assembly-CSharp.dll'))) { throw "No RimWorld 1.7 install at '$RimWorldDir'." }
$repo = Split-Path -Parent $PSScriptRoot $repo = Split-Path -Parent $PSScriptRoot
$testMod = Join-Path $PSScriptRoot 'BlaxCastesTests' $testMod = Join-Path $PSScriptRoot 'BlaxCastesTests'
$modLink = Join-Path $RimWorldDir 'Mods\BlaxCastes' $modLink = Join-Path $RimWorldDir 'Mods\BlaxCastes'
@ -99,26 +109,39 @@ try {
[void]$list.Add($id) [void]$list.Add($id)
} }
# Load order: Harmony, core, DLCs, overlap mods, Blax Castes, Blax Slaves (Castes loads before Slaves), the tests. # Load order: Harmony, core, DLCs, the mods Castes is tested next to, Blax Castes, Blax Slaves (Castes loads before Slaves), the tests.
# Every installed DLC is listed as known, so the game does not switch on a left-out DLC as "new".
$installedDlcs = @(@('Royalty', 'Ideology', 'Biotech', 'Anomaly', 'Odyssey') | Where-Object { Test-Path (Join-Path $RimWorldDir "Data\$_") })
if ($NoDlc) { $loadDlcs = @() }
elseif ($Dlc) {
$wanted = @($Dlc | ForEach-Object { $_ -split ',' } | ForEach-Object { $_.Trim() } | Where-Object { $_ })
foreach ($w in $wanted) { if ($installedDlcs -notcontains $w) { Write-Warning "DLC not installed or unknown, skipped: $w" } }
$loadDlcs = @($installedDlcs | Where-Object { $wanted -contains $_ })
}
else { $loadDlcs = @($installedDlcs) }
$mods = New-Object System.Collections.ArrayList $mods = New-Object System.Collections.ArrayList
$expansions = @() $expansions = @($installedDlcs | ForEach-Object { 'ludeon.rimworld.' + $_.ToLower() })
[void]$mods.Add('brrainz.harmony') [void]$mods.Add('brrainz.harmony')
[void]$mods.Add('ludeon.rimworld') [void]$mods.Add('ludeon.rimworld')
foreach ($dlc in 'Royalty', 'Ideology', 'Biotech', 'Anomaly', 'Odyssey') { foreach ($d in $loadDlcs) { [void]$mods.Add('ludeon.rimworld.' + $d.ToLower()) }
if (Test-Path (Join-Path $RimWorldDir "Data\$dlc")) { $id = 'ludeon.rimworld.' + $dlc.ToLower(); [void]$mods.Add($id); $expansions += $id } Write-Host ("DLCs: " + $(if ($loadDlcs.Count) { $loadDlcs -join ', ' } else { 'none' }))
}
if ($Compat) { if ($Compat) {
foreach ($id in 'orion.hospitality', 'rhajiit.tradepurchasemode', 'mlie.customprisonerinteractions', 'legator.prisonerrealism') { # Trade as Slave or Colonist is left out, so Blax Slaves' own buy mode is the one tested; -Tasoc adds it.
foreach ($id in 'orion.hospitality', 'mlie.customprisonerinteractions', 'legator.prisonerrealism', 'papercrane1001.weaponstab') {
Add-WithDependencies $id $mods Add-WithDependencies $id $mods
} }
} }
if ($Tasoc) { Add-WithDependencies 'rhajiit.tradepurchasemode' $mods }
[void]$mods.Add('blax.castes') [void]$mods.Add('blax.castes')
if ($Compat) { Add-WithDependencies 'blax.slaves' $mods } if ($Compat) { Add-WithDependencies 'blax.slaves' $mods }
[void]$mods.Add('blax.castes.tests') [void]$mods.Add('blax.castes.tests')
# fresh test data folder: mod list only, no old save, results or mod settings # fresh test data folder: mod list only, no old save, results or mod settings (files are named Mod_<folder>_<class>.xml)
New-Item -ItemType Directory -Force (Join-Path $DataDir 'Config') | Out-Null New-Item -ItemType Directory -Force (Join-Path $DataDir 'Config') | Out-Null
Remove-Item -Force -ErrorAction SilentlyContinue (Join-Path $DataDir 'Saves\BlaxCastesTest.rws'), (Join-Path $DataDir 'BlaxCastesTestResults.txt'), (Join-Path $DataDir 'Config\Mod_blax.castes_*.xml') Remove-Item -Force -ErrorAction SilentlyContinue (Join-Path $DataDir 'Saves\BlaxCastesTest.rws'), (Join-Path $DataDir 'BlaxCastesTestResults.txt')
Get-ChildItem -LiteralPath (Join-Path $DataDir 'Config') -Filter 'Mod_*.xml' -ErrorAction SilentlyContinue |
Where-Object { $_.Name -like 'Mod_BlaxCastes_*' -or $_.Name -like 'Mod_BlaxSlaves_*' -or $_.Name -like 'Mod_blax.castes_*' } |
Remove-Item -Force -ErrorAction SilentlyContinue
$li = { param($ids) ($ids | ForEach-Object { " <li>$_</li>" }) -join "`n" } $li = { param($ids) ($ids | ForEach-Object { " <li>$_</li>" }) -join "`n" }
$modsConfig = "<?xml version=`"1.0`" encoding=`"utf-8`"?>`n<ModsConfigData>`n <version>1.7</version>`n <activeMods>`n" + $modsConfig = "<?xml version=`"1.0`" encoding=`"utf-8`"?>`n<ModsConfigData>`n <version>1.7</version>`n <activeMods>`n" +
(& $li $mods) + "`n </activeMods>`n <knownExpansions>`n" + (& $li $expansions) + "`n </knownExpansions>`n</ModsConfigData>`n" (& $li $mods) + "`n </activeMods>`n <knownExpansions>`n" + (& $li $expansions) + "`n </knownExpansions>`n</ModsConfigData>`n"

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 90 KiB

View File

@ -6,10 +6,10 @@ Every slave you buy needs its apparel, food, drug and reading policy set by hand
| Version | What players get | Replaces (subs) | Days | | 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.0 | Castes that set apparel, food, drug, reading, medical care, schedule, work priorities and weapon loadout in one click, with hand changes kept per pawn. Ready-made Colonist, Slave and Prisoner castes. Every status change (bought, enslaved, recruited, freed, arrested, captured) moves the pawn into the matching caste automatically, and a pawn that comes back gets its old caste. Warnings for clashing defaults mods. | Automatic Slave Outfit (16.7k), PrisonerDefaults (1.1k), Plug and Play Joiner work (1.5k), and the join, schedule and work defaults of Better Pawn Control (228k), BPC Forked (1.3k) and 1trickPwnyta's Defaults (75k) | 12 |
| 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.1 | A caste button on selected pawns, policy delete guard, ideo conflict warnings, new caste from a pawn | Food Restriction Eleven starting policies, partly (15.4k) | 2 |
| 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.2 | Castes also set 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) | 2 |
| 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.3 | A caste for every way a pawn joins, adult and child. 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) | 2 |
| 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.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 | | 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 | | Total | | | 23 |
@ -20,11 +20,11 @@ Effort: S = 0.5 days, M = 2, L = 5, summed per release and rounded up.
Change if you disagree. Change if you disagree.
- In 1.0 every join row starts at No caste, so nothing changes until you pick a caste. - Scope change 2026-11-29 (Fabian): 1.0 also sets schedule and weapon loadout, ships the starter castes wired to the join rows, moves pawns on every status change, returns pawns to their old caste and warns about overlapping mods. Reason: he does not want to set schedules, weapons and policies by hand every time a slave or colonist changes status, but still wants per-pawn hand changes. These items moved here from 1.1, 1.2 and 1.3; the details are in "1.0 additions" below.
- From 1.1, colonist rows use the Colonist caste. It copies your current default policies, so colonists see no change. - Colonist rows use the Colonist caste. It copies your current default policies, so in a new game colonists see no change. In an existing save "Assign by status" gives each pawn its caste's policies in place of its own, so it asks first.
- Starter Slave caste: Slave outfit, Simple food, No drugs. Reading and medical care stay vanilla. Starter Prisoner caste: Simple food. - 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. - Hand changes win. Editing a caste moves only members still on the old value. "Apply to all members" (1.0) forces it.
- In an existing save the starter castes appear, but nobody moves until you click "Assign by status". - In an existing save the starter castes appear, but nobody moves until you click "Assign by status" and confirm.
- The name stays Blax Castes, with the subtitle "policy bundles and join defaults", because three other Workshop mods already use "caste". - 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. - 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. - Not supported for now: multiplayer and animal castes.
@ -35,14 +35,14 @@ Change if you disagree.
- `Caste : Policy` with LoadKey "BlaxCaste". Ids, load IDs, rename (IRenameable) and duplicate (`CopyFrom`) work the vanilla way. - `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. - 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`). - Slots in 1.0: `ApparelPolicy`, `FoodPolicy`, `DrugPolicy` and `ReadingPolicy` (null = the caste leaves it alone), medCare as an int (-1 = leave alone, otherwise a `MedicalCareCategory`), the schedule as 24 `TimeAssignmentDef` names (null = leave alone), work priorities as work type defName to 0..4 (absent = leave alone) plus a "Start from nothing" flag, and the Weapons Tab Reborn loadout id (-1 = leave alone).
- 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. - Slots after the policies store defNames, labels or ints, never def references, and resolve with `GetNamedSilentFail`: schedule, work priorities and loadout id (1.0), area (label, per map), hostility, self-tend, carried medicine, fire at will, prisoner modes, DLC switches.
### Membership store ### Membership store
- One `GameComponent_BlaxCastes` holds all state: the caste list, `Dictionary<Pawn, CasteMembership>`, 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). - One `GameComponent_BlaxCastes` holds all state: the caste list, `Dictionary<Pawn, CasteMembership>`, the join rows (reason to No caste, Default caste or a caste), the join queue, former-caste records, the next id, a seeded flag, the overlap mods this save was warned about, and API hints and pre-picks (1.3). The pawns that left the player side since the last tick sit in an unsaved field of the component, so they go away with the game. No static field holds the game or its pawns; the `Instance` cache is weak.
- `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. - `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. - No ThingComp and no data on vanilla objects. The only vanilla data Castes writes is the pawn's own policy fields, medical care, timetable and work priorities, plus its Weapons Tab Reborn loadout through that mod's API.
- Overrides are not stored. A slot value that differs from the caste is an override. - Overrides are not stored. A slot value that differs from the caste is an override.
### Join classification and deferral ### Join classification and deferral
@ -52,29 +52,30 @@ Change if you disagree.
- 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. - 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. - 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. - `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. - Every hook body sits in try/catch with a one-time log, so a Castes bug can never break a trade. The log-once flags reset in `FinalizeInit`, so a failure in a later game is logged again.
### Save safety ### 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. - 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. - PostLoadInit checks every slot (`CasteManager.CheckSlots`): policies with `db.All*.Contains`, a missing one becomes unmanaged, with one warning per caste; a schedule hour whose `TimeAssignmentDef` is gone becomes Anything and a work type that is gone is dropped, each with one warning; a loadout id Weapons Tab Reborn no longer has becomes unmanaged with one warning (without the mod the id is kept). Apply checks the same before every write. The manager runs the same check every frame, and saving runs it too.
- Policy load IDs contain the label. That is safe, because the caste and the policy sit in the same save. - 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. - Former-caste records are keyed by ThingID string, not by reference, so a discarded pawn leaves no unresolved reference. The caste and the pawn's own policies in a record are stored by id; a policy deleted since is skipped on return.
- Removing the mod: pawns keep their last policies. The only trace is one "type not found" line for the component. - Former-caste records are pruned on save, after load and in the 2500-tick sweep when they are older than `formerCasteDays` or their caste is gone. Deleting a caste drops its records at once.
- Adding it mid-save: `Game.ExposeData` creates the component. From 1.1 the starter castes are seeded once on `LoadedGame`. - Removing the mod: pawns keep their last policies. The next load logs two red errors for the component: "Could not find class BlaxCastes.GameComponent_BlaxCastes" and "SaveableFromNode exception: Can't load abstract class Verse.GameComponent" (`ScribeExtractor.SaveableFromNode`). Both go away once the game is saved again.
- Adding it mid-save: `Game.ExposeData` creates the component. The starter castes are seeded once on `LoadedGame`.
## 1.0: castes and bought slaves (6 days) ## 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. 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. Reversed on 2026-11-29: starter castes, manager tools and overlap warnings are back in 1.0 (see "1.0 additions"); the delete guard and the gizmo stay in 1.1.
#### Castes #### 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. - **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:** - **How:**
- `CasteUtility.Apply(pawn, caste)` writes each managed slot through the vanilla setters: `CurrentApparelPolicy`, `CurrentFoodPolicy`, `CurrentPolicy` (drugs and reading), `playerSettings.medCare`. - `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. - Per-slot checks. Apparel, drug and reading need the tracker, `!IsQuestLodger()`, no prisoner and no `disablePolicies` mutant; apparel also skips `disableApparel` mutants. Food needs `foodRestriction.Configurable`, a non-baby and no `disablePolicies` mutant. 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. - 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). - 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). A slot that was unmanaged has no old value, so making it managed moves every member; unmanaging a slot moves nobody.
- Edits inside a policy, such as the Slave outfit's filter, reach members through the vanilla reference already. - 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. - 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. - **Settings:** `enabled` (on). Off: nothing is applied, castes stay in the save.
@ -89,13 +90,13 @@ Moved to 1.1 to keep 1.0 near a week: starter castes, overlap warnings, the poli
- **How:** - **How:**
- `Dialog_ManageCastes : Dialog_ManagePolicies<Caste>`. The base class already draws the list and handles duplicate, rename and the delete confirm. - `Dialog_ManageCastes : Dialog_ManagePolicies<Caste>`. 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`. - 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. - The default caste is what rows set to "Default caste" use. With no default set, those rows act as No caste. The base class gives "Make default" the vanilla tooltip about new colonists; after the base draws, `TooltipHandler.ClearTooltipsFrom` on that button's rect drops it and an own tip about Default caste rows replaces it. `TipKey` explains the default caste too.
- Delete: members become casteless and keep their current policies. Rows pointing at the caste fall back to No 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. - 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. - A first-load message points to Assign > Manage castes.
- **Settings:** none, covered by `enabled`. - **Settings:** none, covered by `enabled`.
- **Replaces:** none. - **Replaces:** none.
- **Effort:** S (0.5 days). Trimmed: member count, "Apply to all" and "Assign by status" move to 1.1. - **Effort:** S (0.5 days). Member count, "Apply to all" and "Assign by status" were trimmed to 1.1 and are back in 1.0 (2026-11-29).
- **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. - **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<T>` (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. - **Risks:** Generic methods over reference types share one JIT body, so another mod's patch on `Dialog_ManagePolicies<T>` (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.
@ -104,28 +105,31 @@ Moved to 1.1 to keep 1.0 near a week: starter castes, overlap warnings, the poli
- **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. - **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:** - **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. - 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. - Cell: `Widgets.Dropdown(..., paintable: true)`. The label is the caste name, "*" plus a tooltip naming overridden slots and their values, "(pending)" while a queued join will change the caste (the previous caste or the row gives one, or a No caste row takes a row-set caste away), or "Unchangeable" for quest lodgers.
- Painting runs the matching menu action on every GUI event over a cell, the start cell included. A pawn already in the painted caste (or already casteless when painting No caste) is skipped while `Widgets.Painting`, so painting never wipes its hand changes. A click still rewrites every managed slot.
- Menu: No caste (stored as casteless by choice), each caste, Reset to caste, Edit caste. - 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. - `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. - 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. - **Settings:** `showAssignColumn` (on). The column is removed from the table def at startup, so a change needs a restart. Since the 1.0 additions the setting covers the Caste column in all three tables (Assign, Schedule, Work); `CasteColumns.cs` handles them.
- **Replaces:** none. - **Replaces:** none.
- **Effort:** S (0.5 days). - **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. - **Tests:** At startup the Assign table def has `BlaxCastes_Caste` right before `HostilityResponse`, with and without the Ideology and Biotech columns (`run-tests.ps1 -NoDlc` runs the suite on the core game). The menu has No caste, one entry per caste and Reset, and invoking an entry assigns. Painting over a member of the same caste keeps its override. 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. - **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 #### 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. - **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:** - **How:**
- Each row is No caste, Default caste or a specific caste. Rows live in the save component. Layout follows `Dialog_MedicalDefaults`. - Each row is No caste, Default caste or a specific caste. Rows live in the save component. Layout follows `Dialog_MedicalDefaults`. Without Ideology the window hides the two slave rows. Castes in the picker are sorted by label, like the column menu.
- 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`. - 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. - 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. - 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. - A caste (or No caste) picked by hand between queue and apply beats the row. Each queued join remembers the membership object the pawn had when it was last queued; a different manual membership at apply time is a pick. After a load that reference is gone, and a manual membership set on or after the queueing tick counts instead.
- Selling: a "sold" scope on `Pawn.PreTraded` with PlayerSells keeps the slave-to-free step inside the sale (`SetGuestStatus(null)` before `SetFaction(null)`) from queueing a join.
- If the row is No caste and a join row had put the pawn in its caste (membership auto), it leaves the caste. With `revertOnLeave`, each managed slot where the pawn still has the caste's value returns to the database default; medical care runs `ResetMedicalCare` only if the caste manages it and the pawn still has the caste's value. Slots changed by hand stay. This is PrisonerDefaults' revert on recruit. A caste picked by hand is never removed by a No caste row. The schedule, work priorities and loadout have no database default and are not reverted. Since the 1.0 additions the same revert runs when a row moves a row-set member to another caste, for the slots the new caste leaves alone.
- Leaving the player faction, for example by being sold, ends the membership. - Leaving the player faction, for example by being sold, ends the membership.
- Babies and quest lodgers are skipped until 1.3. - Babies and quest lodgers are skipped until 1.3.
- **Settings:** `enableJoinDefaults` (on), `joinMessages` (on), `revertOnLeave` (on). - **Settings:** `enableJoinDefaults` (on), `joinMessages` (on), `revertOnLeave` (on; only governs the revert when a row takes a pawn out of a row-set caste).
- **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). - **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). - **Effort:** M (2 days).
- **Tests:** - **Tests:**
@ -137,14 +141,107 @@ Moved to 1.1 to keep 1.0 near a week: starter castes, overlap warnings, the poli
- `SetGuestStatus(null)` on an existing member does not re-queue it. - `SetGuestStatus(null)` on an existing member does not re-queue it.
- A pawn sold between queue and apply is dropped without errors. - A pawn sold between queue and apply is dropped without errors.
- An exception inside the scope leaves the stack empty. - 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. - -Compat with Blax Slaves (and without Trade as Slave or Colonist, so Blax Slaves' own buy mode runs): its slave or colonist choice lands in the right row. -Tasoc adds Trade as Slave or Colonist, and the same test drives that mod's choice.
- **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. - **Risks:** Better Pawn Control and its fork write policies in their own SetGuestStatus postfix. Castes applies a tick later and wins, and warns about it (1.0 additions). 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) ## 1.0 additions (scope change 2026-11-29)
#### Schedule slot
- **Players get:** A caste can carry a daily schedule. Slaves, colonists and anyone who changes status get their caste's schedule automatically. A schedule changed by hand on one pawn stays until "Reset to caste".
- **How:**
- Slot: 24 `TimeAssignmentDef` defNames (null = unmanaged), resolved with `GetNamedSilentFail`. Meditate becomes Anything without Royalty. Written with `Pawn_TimetableTracker.SetAssignment` only when `pawn.timetable` exists (prisoners have none and skip the slot; the schedule lands when they become slaves or colonists).
- Follow rule on the whole day: a member whose 24 hours equal the caste's old schedule moves to the new one; any other member keeps theirs. The override tooltip names "Schedule".
- Manager row: a 24-cell grid painted like the vanilla Schedule tab (the vanilla time assignment selector picks the brush), plus "Copy from pawn" (a float menu of colony pawns) and "Unmanaged".
- The caste column is also added to `PawnTableDef` Restrict (the Schedule tab), right after the timetable column (see Built).
- **Settings:** covered by `enabled`.
- **Replaces:** default schedules in 1trickPwnyta's Defaults (75k) and Better Pawn Control (228k).
- **Tests:** a caste with a night schedule sets all 24 hours on a colonist and a slave; a prisoner skips it without errors; Follow rule (A follows, B with one hour changed keeps its own); an unknown defName becomes Anything; the schedule survives save and reload.
- **Built (2026-11-29),** `ScheduleSlot.cs`:
- Checks: a timetable, not a quest lodger, not a prisoner (an arrested colonist keeps its timetable and is still skipped), not a mutant without policies, and not `IsSubhuman` (the vanilla Schedule tab leaves those out).
- Unknown names become Anything three times over: `SetSlot` stores Anything, Apply resolves an unknown stored name to Anything, and `CheckSlots` rewrites it after a load with one warning. Without Royalty the Meditate def does not exist, so it resolves the same way.
- Manager: the selector is vanilla's `TimeAssignmentSelector.DrawTimeAssignmentSelectorGrid`, so the brush is shared with the Schedule tab. Painting copies `PawnColumnWorker_Timetable` (mouse button held over a cell). "Unmanaged" is the "Leave alone" button, the word the other rows use. While unmanaged the cells show the game's starting schedule faded; painting one hour starts from it and, the slot having no old value, gives every member the whole day (the unmanaged tooltip and the manager hint say so, and "Copy from pawn" says the same). Each painted hour is one `SetSlot`, so followers follow hour by hour.
- The column goes right after the timetable (`CasteColumns.ApplyToSchedule`, Patches/BlaxCastes_ScheduleWork.xml). The Schedule tab has no extra top space, so its header starts at y 0, and `MainTabWindow_Schedule` draws the time assignment selector at (0, 0, 191, 65) after the table: one row of brushes 95.5 px wide at y 2 to 29.5, reaching x 476 with Royalty. The brushes draw on top of the header, and the header's buttons take the click first, so a column with header buttons anywhere left of x 476 steals the brush clicks. Everything left of the timetable is narrower than that (name 80 px or more, ideo, xenotype, copy and paste 36), and the timetable is at least 360 px, so right of it the column is always clear. The copy and paste buttons still sit next to the timetable.
- The brushes in the manager share the row's width (four, five with Royalty), 64 to 96 px each; at the window's starting size that is about 91 px, about what the Schedule tab gives them. At 64 px "Recreation" does not fit the Small font.
#### Work priorities slot
- **Players get:** A caste can set work priorities, only for the work types you pick. A Field slave caste sets Growing 1 and Plant cutting 2; every caste can set Firefighting 1, so new colonists and slaves no longer start with firefighting off or low. Work types the caste leaves out stay as they are. Pulled forward from 1.4 at Fabian's request (2026-11-29): he sets Firefighting to 1 by hand on every new pawn.
- **How:**
- Slot: work type defName to priority 0 to 4 (absent = leave alone), resolved with `GetNamedSilentFail`.
- Applied after the status is final (the one-tick deferral), because `SetFaction(player)` runs `EnableAndInitialize` and slaves ignore backstory disables. Work types where `Pawn.WorkTypeIsDisabled` is true are skipped, which avoids the `SetPriority` error. With manual priorities off (`Current.Game.playSettings.useWorkPriorities` false), any nonzero value means on. Castes stores the caste's own number anyway: `GetPriority` reads every stored nonzero value as 3 while manual priorities are off, so the game behaves the same, and when the player turns manual priorities on the member still has the caste's number. Storing 3 would detach every member at that moment, because nothing reacts to the switch.
- Follow rule per work type: a member whose priority equals the caste's old value for that type moves; others keep theirs. The override tooltip names the work types that differ.
- Manager row: a list of work types (all `WorkTypeDef`s in vanilla order) with a cycle button per type: leave alone, 1, 2, 3, 4, off. "Start from nothing" (per caste, off by default) turns every other work type off before writing, for castes that should do only their listed work.
- The caste column is also added to `PawnTableDef` Work, before the work columns.
- **Settings:** `manageWorkPriorities` (on). The row is greyed out with a note when Work Tab, Free Will, Work Manager, AutoPriorities or WorkRoles is active (packageIds checked before shipping), because they reset priorities all the time.
- **Replaces:** default work priorities in 1trickPwnyta's Defaults (75k) and Plug and Play Joiner (1.5k).
- **Tests:** a slave in a caste with Growing 1 and Firefighting 1 has both, other types unchanged; a disabled work type stays 0 with no log error; "Start from nothing" leaves only the caste's types, plus Patient and Bed rest as they were; with manual priorities off, nonzero becomes on and turning them on detaches nobody; clicking the cycle button through other values moves only the members that followed before the first click; Follow rule per type; survives save and reload.
- **Risks:** automatic work managers fight any fixed priorities, hence the detection.
- **Built (2026-11-29),** `WorkSlot.cs`:
- Colonists and slaves of the player with initialized work settings; prisoners and quest lodgers are skipped.
- The slot is managed while at least one work type is listed. "Start from nothing" needs a listed type, takes effect on the next assign, Reset to caste or Apply to all members, and moves nobody when ticked. The Follow rule never turns work off; only a full apply does.
- "Start from nothing" keeps the self-care work types (`WorkSlot.IsSelfCare`: `alwaysStartActive` and no work tags, which in the base game are Patient and Bed rest) as they are. A colonist or slave goes to bed for treatment or rest only through their work givers (`PatientGoToBedEmergencyTreatment`, `PatientGoToBedTreatment`, `PatientGoToBedRecuperate`); the `JobGiver_PatientGoToBed` think nodes cover prisoners, guests and crawling downed pawns only. Firefighting, Hauling and Cleaning are also `alwaysStartActive` but carry work tags, so they are turned off unless listed; the tooltip names the kept types and suggests listing Firefighting. Types are turned off one by one with `SetPriority(0)`, which also stops a job of that type.
- The cycle button works in runs (`Dialog_ManageCastes.WorkCycle`, one per window): the first click on a type takes its followers (`CasteManager.WorkFollowers`: members on the caste's value, or every member while the caste leaves the type alone), and every later click on the same type moves only them (`CasteManager.SetWorkPriority` with followers). Without that, each step would be a Follow rule step from the previous value: going 3, 4, off, leave alone, 1 picks up a pawn set to 4 by hand at the first step and every member at the leave-alone step. A click on another type or caste, a change to the type from anywhere else, "Apply to all members" or a new window starts a new run.
- Comparisons (Follow rule, overrides) use the priority as the game treats it: with manual priorities off, every nonzero value counts as on, so a caste value 1 and a pawn on 3 match. A work type the pawn cannot do never counts as an override.
- Greyed out means off: while `manageWorkPriorities` is off or a work manager is active, nothing is written and work never counts as an override. The caste keeps its values. The manager shows the reason; the settings page names the active work manager.
- The manager lists the visible work types in the Work tab's order (`WorkTypeDefsInPriorityOrder`), three columns, each with a cycle button (left click; the cycle wraps). The tooltip shows the work type's description.
- A work type that no longer exists is dropped from the caste with one warning (`CheckSlots`).
- The column goes right before `CopyPasteWorkPriorities`; the game adds the work columns after that column when it builds the table, so the Caste column ends up just left of them. In the Work table its header asks for the 25 px label and sort area plus one button (48 px) instead of 65, so the header stays at the work columns' 50 px and their label guide lines still end at the cells; only "Manage castes" sits above the label there (the join defaults are in the Assign and Schedule tabs and the mod settings). The column finds its table through `PawnTable`'s private `def` field (`AccessTools.FieldRefAccess`, with a fallback to the full header). The "Higher priority" and "Lower priority" hints `MainTabWindow_Work` draws at fixed x 370 and 630 stay where they are: they sit above the work columns with or without the Caste column and point at no column.
#### Weapon loadout slot (Weapons Tab Reborn)
- **Players get:** With [1001] Weapons Tab Reborn active, a caste can set the pawn's weapon loadout. A Guard caste hands out the rifle loadout, a Slave caste the unarmed one. Without the mod the row is hidden.
- **How:** Bound by reflection through the API Weapons Tab Reborn publishes for Better Pawn Control (`BPC_GetLoadoutId`, `BPC_SetLoadoutId`, `BPC_GetDefaultLoadoutId`, `BPC_GetLoadoutNamebyId`, the loadout database). The slot stores the loadout id; a missing id becomes unmanaged with one warning, like a missing policy. Detection by packageId `papercrane1001.weaponstab` (check the About.xml before shipping). Applied to colonists and slaves only. Follow rule as for policies. Any failure in the reflection disables the slot with one log line, never an exception.
- **Settings:** `manageWeaponLoadout` (on).
- **Replaces:** nothing; it removes the per-pawn loadout clicks.
- **Tests:** skip without Weapons Tab Reborn. With it (a -Compat run): a caste with a loadout sets it on a colonist; Follow rule; a deleted loadout becomes unmanaged without errors.
- **Risks:** Weapons Tab Reborn has no 1.7 build and loads its 1.6 assembly. If its API changes or fails, the slot turns itself off.
- **Built (2026-11-29),** `WeaponsTab.cs`:
- packageId `papercrane1001.WeaponsTab`, read from the installed Workshop copy's About.xml (2573988660); `Compat.IsActive` ignores case. The API sits in `WeaponsTabReborn.LoadoutDictionary`, read from its 1.6 assembly's metadata: `int BPC_GetLoadoutId(Pawn)`, `void BPC_SetLoadoutId(Pawn, int)`, `int BPC_GetDefaultLoadoutId()`, `string BPC_GetLoadoutNamebyId(int)`, `Dictionary<string, int> BPC_GetWeaponsLoadoutsDatabase()`. Bound once into typed delegates; a missing type or method turns the slot off for the session, a call that throws (anything but a missing id) turns it off until the next game is loaded. Each logs one warning.
- Quirks Castes works around: `BPC_SetLoadoutId` with an unknown id clears the pawn's loadout, so the id is checked first. `BPC_GetLoadoutNamebyId` throws `InvalidOperationException` for an unknown id; that is how existence is checked. The database dictionary is static and only grows (deleted and renamed loadouts stay, and a new loadout whose label is already a key is left out), so the manager's list checks every id by name and also probes the 16 ids above the highest one. Loadout ids are the highest id plus one, so deleting the newest loadout frees its id for the next one; a caste still holding that id then points at the new loadout.
- Colonists and slaves of the player only. Without the mod, `SetSlot` refuses a loadout and a stored id is kept (not checked, not applied) for when the mod comes back.
- Weapons Tab Reborn's own default loadout (Overlap warnings below) is explained in the setting's tooltip, not as an overlap warning: it is the mod this slot works with.
- Weapons Tab Reborn's job giver runs for every humanlike and logs "Non-colonist X tried to equip loadout." once for the first pawn of another faction that thinks. That is its own bug; the test harness lists it as a known foreign error (`KnownForeignErrors`), so it shows as a LOGERR line and does not fail the test that ticked the game.
#### Starter castes and Assign by status
- From 1.1 "Starter castes" and "Manager tools", unchanged in substance: Colonist, Slave and Prisoner castes seeded on a new game and once per existing save, rows wired (colonist rows to Colonist, slave rows to Slave, new prisoner to Prisoner), starting colonists assigned. In an existing save nobody moves until "Assign pawns without a caste by status"; the manager footer also gets the member count and "Apply to all members".
- Slave and Colonist schedules and loadouts start unmanaged: the player sets them once on the caste and every member follows.
- Built (2026-11-29), `StarterCastes.cs`:
- New game: `StartedNewGame` clears the join queue (joins queued while the colony was generated are not joins), seeds, then runs "Assign by status" on every player pawn. There is no separate starting-colonists row: the player cannot open the window before the game starts, so the new colonist row (Default caste, Colonist) places the starting colonists, and a starting slave goes to the new slave row.
- Existing save: `LoadedGame` seeds once, only if the save has no castes; a save that has castes is marked as seeded, so deleting them later never brings the starters back. With `seedStarterCastes` off nothing is seeded or marked. The one message replaces the first-load message.
- Seeding writes the component directly (raw slot writes, no members yet), so it works on a component that is not the game's, which is how the tests check the load path.
- A missed policy logs one line and its slot stays unmanaged. "Create Slave outfit" in the manager, shown while the caste's apparel is unmanaged and the game has no Slave outfit, makes one the way a new game does (apparel tagged for slaves, no deadman's apparel) and sets it on that caste. A caste with the Slave outfit warns about cold in the manager and in the column tooltip.
- "Assign by status" takes player colonists, slaves and prisoners (maps, caravans, transporters) that can join a caste, have no membership record, are not queued, and whose status row resolves to a caste. The button shows the count and only appears while there are such pawns. It asks first (`Dialog_MessageBox`, like "Apply to all members"): in an existing save the Colonist caste's default policies replace each colonist's own outfit, food, drug and reading policy, and nothing can undo that. A new game runs it without asking, since nothing is lost there.
- While the Caste column is off, the seeding message points to the mod settings (whose buttons open the same windows) instead of Assign > Manage castes. "Apply to all members" writes every managed slot to every live member after a `Dialog_MessageBox` confirm naming the caste and the count.
#### Status changes and the old caste
- Every transition between player colonist, player slave and player prisoner already goes through the status rows (new colonist, new slave, new prisoner). Freeing a slave lands in the new-colonist row, arresting a colonist in new prisoner, releasing back in new colonist.
- Previous caste from 1.3, pulled forward: when a member leaves the player side, is sold or becomes a prisoner, Castes writes a former-caste record (caste id, status class, tick), keyed by ThingID. If the pawn comes back within `formerCasteDays` (60) with the same status class (colonist or slave), it gets that caste back instead of the row's, and keeps its hand changes (see How). A pawn set to No caste comes back to No caste. An arrested colonist who is then enslaved goes to the slave row. Order at apply time: previous caste, then the row.
- **How (built 2026-11-29):**
- Arresting a colonist and imprisoning a slave both run `Pawn_GuestTracker.CapturedBy(Faction.OfPlayer)` (the arrest job). Imprisoning a slave sets the pawn back to its slave faction inside `SetGuestStatus`, so the nested `SetFaction` notes it as leaving and the outer call queues it as a new prisoner. Releasing an arrested colonist ends in `SetGuestStatus(null)`, and so does freeing a slave whose home is the colony (`SlaveRelease`); both land in new colonist. A freed slave from another faction walks off and leaves when it exits the map.
- The join hooks write the record when the status before the change was colonist or slave and the status after it is none or prisoner. Inside a sale nothing is written by the hooks; the `PreTraded` finalizer writes the record with the status the pawn had before the sale, once it is no longer player-side. A pawn set to No caste writes a No caste record; a pawn with no membership record writes none, so a status change moves it by its row.
- The record is taken in the hook prefixes (`JoinHooks.Before`, the `PreTraded` prefix), before the game resets medical care inside the change, and written by the postfix or finalizer. Besides the caste id it holds the pawn's own settings: policies by id, medical care, the 24 hours, every work type's priority (as the game reads it), the loadout id, and which of the caste's managed slots and decided work types the pawn followed then.
- Getting the caste back (`JoinDefaults.Restore`, `CasteUtility.Restore`) is not a full apply, because the game keeps policies, schedule and loadout through an arrest or a sale (it adds missing trackers and never removes them) and resets only medical care and, when the pawn joins the faction again, work priorities. A slot the caste manages gets the caste's current value if the pawn followed it when it left (so edits made while it was away reach it), else the pawn's own value from then. A slot the caste leaves alone is written only to undo the caste the pawn got while away: if that caste manages it and the pawn still has its value (the new-prisoner caste's food), the pawn gets its own value back. Values already in place are not written. A pawn that never left its caste (No caste rows) therefore gets nothing rewritten, and a pawn set to No caste goes back to No caste with its own food. Work goes type by type over the types either caste decides ("Start from nothing" decides every type but the self-care ones, at off).
- A row that moves a pawn from a row-set caste to another caste resets, with `revertOnLeave`, the policies the old caste manages and the new one leaves alone, where the pawn still has the old value, as a No caste row does. This covers the plain row path; the previous-caste path undoes with the pawn's own values instead of the database defaults.
- A record stores the caste id (not a reference), the status, the membership's auto flag and the tick. It is restored with that auto flag and the reason "previousCaste", and removed when used. A record whose status does not match stays until it is pruned, so a colonist arrested, enslaved and later freed within the window still comes back to its colonist caste.
- Order at apply time: a hand pick after queueing, then the previous caste, then the row.
- **Settings:** `returnToPreviousCaste` (on), `formerCasteDays` (60, 1 to 120). Records are written even while the setting is off, so turning it on later works.
- **Tests:** a Miner colonist arrested and released returns to Miner; a Miner slave sold and re-bought returns to Miner slave; an arrested colonist who is enslaved goes to the slave row; a record older than `formerCasteDays` is ignored and pruned; records survive save and reload, with the pawn's own settings. An arrested and released colonist keeps its hand-set outfit, drugs, medical care and schedule hour, and a followed slot gets the caste's new value; a pawn that never left its caste (No caste rows) gets nothing rewritten; a No caste pawn comes back to No caste with its own food; the prisoner caste's food is undone for a caste that leaves food alone; a row move from a row-set caste resets the old caste's food. Plus one test per transition the harness can drive: arrest, release, freeing a home slave, imprisoning a slave, enslaving after an arrest, selling and buying back; recruiting, enslaving and capturing are in the join tests.
#### Overlap warnings
- From 1.1 "Overlap warnings", unchanged, plus Weapons Tab Reborn's own default loadout: when the loadout slot is managed, Castes writes a tick after the join, so its choice wins; unmanaged, Weapons Tab Reborn keeps control.
- Built (2026-11-29), `OverlapWarnings.cs`: the settings page lists each active overlapping mod with what it sets; one message per save names the mods this save was not warned about yet (the component keeps the warned ids). Package ids, each read from the mod's About.xml in its public source repository (the repositories are listed in `Compat.cs`): Better Pawn Control `VouLT.BetterPawnControl`, Better Pawn Control Forked `KyleMHB.BetterPawnControlForked`, 1trickPwnyta's Defaults `defaults.1trickPwnyta`, Automatic Slave Outfit `ben.automaticslaveoutfit`, PrisonerDefaults `MSWS.PrisonerDefaults`. For the work slot: Work Tab `Fluffy.WorkTab`, Free Will `freemapa.freewill` (and `freemapa.freewill.unstable`), Work Manager `LordKuper.WorkManager`, AutoPriorities `LokiVKlokeNaAndoke.AutoPriorities`, WorkRoles `mnmr.workroles`. None is installed on the test machine; the test injects an id into the detection list.
## 1.1: ready out of the box (2 days)
Starter castes, manager tools, overlap warnings moved to 1.0 (2026-11-29).
#### Starter castes #### 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". - **Players get:** A new colony starts with Colonist, Slave and Prisoner castes, already wired to the join rows. In a new colony colonists see no change. In an existing save the castes appear, but nobody moves until you click "Assign by status" (it asks first, because it replaces the pawns' own policies).
- **How:** - **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. - 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. - 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.
@ -162,12 +259,12 @@ Moved to 1.1 to keep 1.0 near a week: starter castes, overlap warnings, the poli
#### Manager tools #### Manager tools
- **Players get:** The manager footer shows the member count, "Apply to all members" and "Assign pawns without a caste by status". - **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. - **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. It asks first too. Casteless-by-choice pawns are skipped.
- **Settings:** none, covered by `enabled`. - **Settings:** none, covered by `enabled`.
- **Replaces:** none. - **Replaces:** none.
- **Effort:** S (0.5 days). - **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. - **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. - **Risks:** "Apply to all" overwrites hand changes, and "Assign by status" overwrites the pawns' own policies in an existing save, hence the confirms.
#### Policy delete guard #### Policy delete guard
@ -309,7 +406,7 @@ Moved to 1.1 to keep 1.0 near a week: starter castes, overlap warnings, the poli
## 1.4: work and prisoners (4 days) ## 1.4: work and prisoners (4 days)
#### Work priorities per caste (optional) #### Work priorities per caste (moved to 1.0 on 2026-11-29; kept here for the shift-schedule notes below)
- **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. - **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. - **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.
@ -433,7 +530,7 @@ Moved to 1.1 to keep 1.0 near a week: starter castes, overlap warnings, the poli
- 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. - 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. - 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. - 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. -Compat adds the sibling mod and the installed mods Castes is tested next to (Weapons Tab Reborn among them), without Trade as Slave or Colonist; -Tasoc adds that mod; -NoDlc (or -Dlc with a list) leaves DLCs out. The overlap mods and work managers are not installed on the test machine, so their detection is tested with an injected id.
## Backlog ## Backlog
@ -447,7 +544,6 @@ Moved to 1.1 to keep 1.0 near a week: starter castes, overlap warnings, the poli
- Strict sync mode: it duplicates "Apply to all members", and as a ModSetting it would differ per client. - 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. - 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. - 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. - 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. - 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. - One patch per QuestPart: one `Quest.Notify_SignalReceived` scope covers all of them, modded parts included.