diff --git a/1.7/Assemblies/BlaxLaws.dll b/1.7/Assemblies/BlaxLaws.dll new file mode 100644 index 0000000..ef8fbef Binary files /dev/null and b/1.7/Assemblies/BlaxLaws.dll differ diff --git a/1.7/Assemblies/BlaxLaws.pdb b/1.7/Assemblies/BlaxLaws.pdb new file mode 100644 index 0000000..ad3cf0b Binary files /dev/null and b/1.7/Assemblies/BlaxLaws.pdb differ diff --git a/About/About.xml b/About/About.xml new file mode 100644 index 0000000..5ed05c1 --- /dev/null +++ b/About/About.xml @@ -0,0 +1,46 @@ + + + Blax Laws + Blax Gaming + blax.laws + 1.0.0 + +
  • 1.7
  • +
    + +
  • + brrainz.harmony + Harmony + steam://url/CommunityFilePage/2009463077 + https://github.com/pardeike/HarmonyRimWorld/releases/latest +
  • +
    + +
  • brrainz.harmony
  • +
  • blax.castes
  • +
  • blax.zones
  • +
  • blax.slaves
  • +
  • blax.defaults
  • +
    + Write a lawbook and the colony enforces it. Add "Drug binge, planning: subdue" and a warden goes for a binging colonist at once and beats it down; if it reaches a drug first, that dose counts as "did it". Add "Drug binge, did it: jail 5 days" and the one who already took some sits out five days in your prison and walks back to work. Works with any DLC combination, core only included. + +<color=#19C63C>Lawbook</color> +- A Laws tab in the bottom bar. The book starts empty, and until you add a law Blax Laws does nothing. +- A law's action comes from a searchable list built from the game's own defs: every mental break, everything that can be eaten or used, every social interaction, every act the game records and every bill, plus setting a fire, displaying a corpse and starting a social fight. DLC and modded content show up with their mod's name. +- "Starter lawbook" adds seven suggested laws in one click. +- The Cases tab lists who did what and when, the punishment and its status. + +<color=#19C63C>Punishments</color> +- Warn, guilty for N days, subdue (a short fistfight that ends a break: bruises on torso and limbs, never the head), jail for N days, and subdue then jail. +- A warden goes at once, but nobody is pulled off a rescue, a tending, a fire or a surgery, and nobody is sent while hostiles threaten the map. +- Jailed colonists sit out their sentence on "Maintain only", so no prison mod recruits or enslaves them, and walk back to work when it is served. Role holders and mechanitors wait for your "Arrest now". +- Laws only watches what the game already does: no new crime events, no new mental breaks. + +<color=#19C63C>Safe to add and remove</color> +- Add it to a running save. The lawbook and the cases live in Blax Laws' own save data, so after you unsubscribe the save still loads: jailed colonists stay prisoners you can release by hand, and the log shows two errors. + +Enforcement, the Laws tab, messages and letters can be switched off in the mod settings; with enforcement off, cases are still filed and listed. Multiplayer: not supported. + +<color=#19C63C>Made by Blax</color> +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 +
    diff --git a/About/ModIcon.png b/About/ModIcon.png new file mode 100644 index 0000000..b4a8fa8 Binary files /dev/null and b/About/ModIcon.png differ diff --git a/About/Preview.png b/About/Preview.png new file mode 100644 index 0000000..1a25c48 Binary files /dev/null and b/About/Preview.png differ diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..dfdaa7c --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,21 @@ +# Changelog + +## 1.0.0 + +- First release. "Laws" in the bottom bar opens the lawbook and the case log. The book starts empty, and until you add a law Blax Laws watches nothing. +- Laws: each row is Action, Stage, Severity, Punishment and Days, plus an On switch, and each dropdown offers only what fits the action and stage. A second row with the same action, drug and stage is refused, and the list jumps to the existing one. Severity sets the default days (1, 3, 5 or 10); days go from 1 to 50. +- Pick any act: "Add law" opens a searchable tree like a tailoring bill's filter, built from the game's own defs, so DLC and modded mental breaks, food, drugs, usables, social interactions, recorded acts, records and recipes show up with no patch, each labelled with its mod. Groups such as any drug binge, hard drugs, any meat, human meat, insult or slight and any surgery come first in each category. Special acts: set a fire, displayed a corpse ("on a table", "dug up from a grave") and started a social fight. +- Starter lawbook: one click adds seven laws. Drug binges, fire-starting sprees and corpse obsessions are subdued as they start, a binge whose drug was already taken is jailed for 5 days and a fire already set for 10, and starting a social fight or an insult gets a warning. Pressing it again adds only the missing ones. +- Planning and did it: planning is the moment a mental break starts; did it is the act the break is about, such as a dose during a binge, a fire, the displayed corpse or an insult. A break another pawn's psycast forces on a colonist is not the colonist's doing and opens no case, and a Berserk trance you order counts as a player order. A modded break built on one of these gets the same link. When two laws match, the most specific wins: "wake-up" over "hard drugs" over "any drug", "human meat" over "any meat". +- One case per incident: a binge is one case from start to end and counts the doses. Acts outside a break open at most one case per colonist and law a day (0 to 7 days in the settings), so a colony of meat eaters doesn't flood the log. +- Warn files the case with a message. Guilty for N days uses vanilla guilt: the arrest is always accepted, and executing or banishing the colonist costs the colony only the mildest thoughts. +- Subdue: a warden beats the offender down with fists to end its break. Bruises on torso and limbs only, never the head or a bionic part, no bleeding. Every part keeps at least half its health, and the bruises never add up to a deadly amount. The offender doesn't fight back and gets no catharsis from the break, and the warden isn't marked guilty. Children are never beaten. +- Jail for N days: the offender is arrested into a prisoner bed and set to "Maintain only", so no prison mod recruits or enslaves it. When the time is served a warden walks it out, and it goes back to work with its work priorities. "Subdue then jail" beats it down and carries it straight to the cell. +- If the binger reaches its drug before the warden reaches the binger, that dose counts as did it: the same warden arrests it instead of beating it. +- Enforcement: wardens first, then anyone able ("Wardens only" in the settings), nearest first. Nobody is pulled off a rescue, a patient, a fire or a surgery, and nobody is sent while hostiles threaten the map; a warden already on a case is called back when a raid arrives. A berserk colonist fights back, so its jail waits until the break ends or you down it. +- Role holders (Ideology) and mechanitors (Biotech) are never arrested on their own, since jail would take the role or shut the mechs down. Their case waits for "Arrest now" in the case log, and a letter says why. Once pressed, "Arrest now" stays in effect for that case, also after a save. Colony slaves are subdued during a break and warned otherwise. +- Cases: who, what, stage, when, punishment and status, newest first, with a jump to the pawn. Letters only when a colonist is jailed or you have to act: no prisoner bed, nobody to enforce, an arrest waiting for you. +- An arrest that fails gives the colonist its old bed back if it is still free. A jailed colonist that is recruited, released by you or another mod, escapes or dies closes its sentence; if no warden releases a colonist within a day of its release date, Laws releases it where it is. +- Settings: Enforce laws (off keeps the case log and carries out nothing), Show Laws tab, messages for cases, letters for jailings, wardens first or wardens only, subdued pawns lose their catharsis, player orders are exempt, days between cases and how long closed cases stay. +- Save-safe: the lawbook and the cases live in Blax Laws' own save data. Blax Laws can be added to a running save. After you remove it, a save loads with two errors in the log, and colonists it jailed stay prisoners you release by hand. +- Works with any DLC combination, core only included. diff --git a/Defs/BlaxLaws_Acts.xml b/Defs/BlaxLaws_Acts.xml new file mode 100644 index 0000000..e7718ae --- /dev/null +++ b/Defs/BlaxLaws_Acts.xml @@ -0,0 +1,27 @@ + + + + + + SetFire + + The pawn set something on fire. + + + + DisplayedCorpse + + The pawn hauled a corpse to a public place during a corpse obsession. + + + + StartedSocialFight + + The pawn answered an interaction with a social fight. The offender is the pawn who swings first. + + + diff --git a/Defs/BlaxLaws_BreakLinks.xml b/Defs/BlaxLaws_BreakLinks.xml new file mode 100644 index 0000000..4fea795 --- /dev/null +++ b/Defs/BlaxLaws_BreakLinks.xml @@ -0,0 +1,53 @@ + + + + + + BlaxLaws_Link_BingingDrug + + MentalState_BingingDrug + Ate/@anyDrug + true + + + + BlaxLaws_Link_BingingFood + + MentalState_Binging + Ate/@any + + + + BlaxLaws_Link_FireStartingSpree + + MentalState_FireStartingSpree + Special/SetFire + + + + BlaxLaws_Link_CorpseObsession + + MentalState_CorpseObsession + Special/DisplayedCorpse + + + + BlaxLaws_Link_InsultingSpree + + MentalState_InsultingSpree + Interaction/@insultOrSlight + + + + BlaxLaws_Link_Jailbreaker + + MentalState_Jailbreaker + Interaction/SparkJailbreak + + + diff --git a/Defs/BlaxLaws_Categories.xml b/Defs/BlaxLaws_Categories.xml new file mode 100644 index 0000000..911433e --- /dev/null +++ b/Defs/BlaxLaws_Categories.xml @@ -0,0 +1,83 @@ + + + + + + Break + + Every mental break a colonist can have. Planning: the break has started. Did it: the act linked to the break happened during it. + BlaxLaws.ActCategoryWorker_Break + 10 + +
  • MentalState_Berserk
  • +
  • MentalState_BerserkWarcall
  • +
    + +
  • Berserk
  • +
    +
    + + + Ate + + Everything that can be eaten or drunk: food, meals, raw food, corpses and drugs. Counts only when the pawn eats on its own. + BlaxLaws.ActCategoryWorker_Ate + 20 + + + + Used + + Everything that can be used: psytrainers, neurotrainers, mech serums and modded usables. + BlaxLaws.ActCategoryWorker_Used + 30 + + + + Interaction + + Every social interaction. The offender is the pawn who starts it. + BlaxLaws.ActCategoryWorker_Interaction + 40 + + + + RecordedAct + + Every act the game records with the pawn as the doer. Most recorded acts need Ideology. + BlaxLaws.ActCategoryWorker_RecordedAct + 50 + + + + Record + + Every record the game counts for a pawn, such as kills, bodies stripped or things hauled. A case opens when the record goes up. + BlaxLaws.ActCategoryWorker_Record + 60 + + + + Bill + + Every bill. A case opens when the pawn finishes one iteration. + BlaxLaws.ActCategoryWorker_Bill + 70 + + + + Special + + Acts the game records nowhere else: setting a fire, displaying a corpse and starting a social fight. + BlaxLaws.ActCategoryWorker_Special + 80 + + +
    diff --git a/Defs/BlaxLaws_Jobs.xml b/Defs/BlaxLaws_Jobs.xml new file mode 100644 index 0000000..57f830c --- /dev/null +++ b/Defs/BlaxLaws_Jobs.xml @@ -0,0 +1,18 @@ + + + + + + BlaxLaws_Subdue + BlaxLaws.JobDriver_Subdue + subduing TargetA. + false + false + false + + + diff --git a/Defs/BlaxLaws_MainButtons.xml b/Defs/BlaxLaws_MainButtons.xml new file mode 100644 index 0000000..2c95671 --- /dev/null +++ b/Defs/BlaxLaws_MainButtons.xml @@ -0,0 +1,18 @@ + + + + + + BlaxLaws_Laws + + Your colony's lawbook and its cases. + BlaxLaws.MainTabWindow_Laws + 105 + true + + + diff --git a/Defs/BlaxLaws_Punishments.xml b/Defs/BlaxLaws_Punishments.xml new file mode 100644 index 0000000..0701fca --- /dev/null +++ b/Defs/BlaxLaws_Punishments.xml @@ -0,0 +1,83 @@ + + + + + + Warn + + Files the case and posts a message, nothing more. + BlaxLaws.PunishmentWorker_Warn + 10 + true + +
  • BreakPlanning
  • +
  • BreakDidIt
  • +
  • HostileBreakPlanning
  • +
  • HostileBreakDidIt
  • +
  • Act
  • +
    +
    + + + Guilty + + Marks the pawn guilty the vanilla way for the days: its arrest is always accepted, and executing or banishing it costs the colony the mildest thoughts. + BlaxLaws.PunishmentWorker_Guilty + 20 + true + true + +
  • BreakDidIt
  • +
  • HostileBreakPlanning
  • +
  • HostileBreakDidIt
  • +
  • Act
  • +
    +
    + + + Subdue + + A warden beats the pawn down with fists to end its break: bruises on torso and limbs, never the head or a bionic part. After the break it warns instead. + BlaxLaws.PunishmentWorker_Subdue + 30 + +
  • BreakPlanning
  • +
  • BreakDidIt
  • +
    +
    + + + Jail + + A warden arrests the pawn. It sits out the days in a prisoner bed on "Maintain only" and walks back to work. + BlaxLaws.PunishmentWorker_Jail + 40 + true + +
  • BreakPlanning
  • +
  • BreakDidIt
  • +
  • HostileBreakPlanning
  • +
  • HostileBreakDidIt
  • +
  • Act
  • +
    +
    + + + SubdueThenJail + + A warden beats the pawn down and carries it to a prisoner bed. After the break it jails without the beating. + BlaxLaws.PunishmentWorker_SubdueThenJail + 50 + true + +
  • BreakDidIt
  • +
    +
    + +
    diff --git a/Languages/English/Keyed/BlaxLaws.xml b/Languages/English/Keyed/BlaxLaws.xml new file mode 100644 index 0000000..6bab1af --- /dev/null +++ b/Languages/English/Keyed/BlaxLaws.xml @@ -0,0 +1,64 @@ + + + + + + + Needs {0} + Missing: {0} + + + Planning + Did it + Minor + Moderate + Serious + Grave + Open + Enforcing + Jailed + Closed + Law repealed + Break ended + Not enforced + Offender gone + Warned + Guilty + Subdued + Sentence served + Released early + + + Any drug + Hard drugs + Social drugs + + + No laws yet. Add one or press Starter lawbook. + {0} broke a law: {1} ({2}). Punishment: {3}. + + + Enforce laws + Wardens carry out the punishments of your lawbook. Off: cases are still filed and listed, and nothing is carried out. + Show Laws tab + Shows the Laws button in the bottom bar. Off hides it; your laws stay and are still enforced. + Messages for cases + Posts a message whenever a case is filed or moves on. + Letters for jailings + Sends a letter when a colonist is jailed, and when you have to act: no prisoner bed, no enforcer, or a role holder waiting for "Arrest now". + Enforcers + Wardens first, then anyone able + The nearest colonist with Warden work goes first; when none can, the nearest colonist able to do the job. + Wardens only + Only colonists with Warden work enforce laws. When none can, the case waits. + Subdued pawns lose their catharsis + A colonist whose break ends because it was subdued doesn't get the catharsis that ending a break gives, so the beating doesn't reward the crime. + Player orders are exempt + An act done while drafted or on a job you ordered opens no case. + Days between cases for acts outside a break: {0} + A pawn who does the same act again while its last case under the same law is open, or within these days of that case, gets no new case; the count on that case goes up. 0 files every act. + Keep closed cases: {0} days + Closed cases older than this are removed from the case list when the game is saved. + Reset to defaults + + diff --git a/Languages/English/Keyed/BlaxLaws_Catalogue.xml b/Languages/English/Keyed/BlaxLaws_Catalogue.xml new file mode 100644 index 0000000..d7d354a --- /dev/null +++ b/Languages/English/Keyed/BlaxLaws_Catalogue.xml @@ -0,0 +1,30 @@ + + + + + Any mental break + Any drug binge + Any tantrum + Any insulting spree + Any aggressive break + + Anything eaten + Any drug + Hard drugs + Social drugs + Medical drugs + Any meat, meals with meat included + Raw meat or corpses + Human meat, as an ingredient too + Insect meat, as an ingredient too + Raw food + Any meal + + Insult or slight + + Any surgery + + + {0} ({1}) + + diff --git a/Languages/English/Keyed/BlaxLaws_Enforcement.xml b/Languages/English/Keyed/BlaxLaws_Enforcement.xml new file mode 100644 index 0000000..716fb1a --- /dev/null +++ b/Languages/English/Keyed/BlaxLaws_Enforcement.xml @@ -0,0 +1,50 @@ + + + + + + + waiting until the danger is over + nobody can enforce it + waiting for a free enforcer + waiting for a free prisoner bed + waiting while someone else handles the pawn + waiting until the break ends or the pawn is down + waiting for Arrest now + waiting until the pawn is back on a map + + + Not subdued + Escaped + Died in jail + Already a prisoner + + + {1} subdued {0}. + {1} stopped subduing {0}: the hits cause no pain. + {0} is a child and is warned instead of subdued. + {0}'s break is over, so {0} is warned instead of subdued. + {0} fights back in this break, so {0} is warned instead of subdued. + Slaves aren't jailed yet, so {0} is warned. + {0} is already a prisoner. Laws leaves {0} to you and closes the case. + {0} died while serving a sentence. + {0} escaped from jail. + {0} has served the sentence and is free again. + {0} is out of jail before the sentence ended. The case is closed. + {0} has served the sentence. A warden will release {0}. + No warden released {0} within a day of the sentence's end, so {0} is released where {0} is. + The law {0} was jailed under was repealed. A warden will release {0}. + + + Jailed: {0} + {0} was arrested for {2} and serves a sentence of {1} in a prisoner bed, on "Maintain only".\n\nThe sentence ends on {3}. Then a warden releases {0}, and {0} goes back to work with the same work priorities. + No prisoner bed: {0} + {0} is to be jailed for {1}, but there is no prisoner bed a warden can take {0} to.\n\nBuild a bed and set it for prisoners. The arrest follows within a few hours. + Nobody to enforce: {0} + Nobody can carry out the punishment of {0} for {1}.\n\nAn enforcer is an adult free colonist who can walk, and who can do violence for a subdue or carry people for an arrest. With "Wardens only" it also needs Warden work. The case waits until someone can. + Arrest waits: {0} + {0} is to be jailed for {1}. Laws doesn't arrest {0} on its own: {2}.\n\nPress "Arrest now" on the case in the Laws tab to jail {0} anyway. + an arrest takes away {0}'s ideoligion role + an arrest shuts down the mechs {0} controls + + diff --git a/Languages/English/Keyed/BlaxLaws_UI.xml b/Languages/English/Keyed/BlaxLaws_UI.xml new file mode 100644 index 0000000..fb89bbc --- /dev/null +++ b/Languages/English/Keyed/BlaxLaws_UI.xml @@ -0,0 +1,70 @@ + + + + + Lawbook + Cases + Add law + Pick an act from the catalogue of everything the game records and add a law for it. Then set its stage, severity and punishment. + Starter lawbook + Adds seven suggested laws: drug binges, fire-starting sprees, corpse obsession, starting a social fight and insults. Laws already in the book are skipped. + Laws added: {0}. + Every starter law is already in the book. + "Enforce laws" is off in the mod settings: cases are listed, nothing is carried out. + + + Action + Drug + Drug binges only: which drug counts as "did it". + Stage + Planning: a mental break has started and nothing is done yet. Did it: the act happened. Only mental breaks have Planning. + Severity + Sets the default days (Minor 1, Moderate 3, Serious 5, Grave 10) and orders the case log. + Punishment + Days + Days of guilt or of jail, 1 to 50. + On + Off: the law stays in the book and catches nothing. + - + + + {0}: {1} + Click to pick another act. + From: {0} + The book already has a law for {0} at stage {1}. + Delete this law + Delete the law "{0}"? Its open cases ({1}) close as "law repealed". + {0} of them sit in jail. They are set to "Release", and a warden lets them go. + This law can catch the same act as a law of another category, so one act may open a case under each:\n{0} + + + Pick an act + {0} ({1}) + Stages: {0} + A break hostile to the colony: the pawn fights back, so it can't be subdued. + Already in the lawbook. Adding it again adds a law for a stage that has none, or shows the existing law. + No act matches the search. + The act catalogue is empty. + + + Show closed cases + No cases yet. + Who + What + When + Status + {0} against {1} + {0} times + on a table + dug up from a grave + just now + {0} ago + {0} days + Jailed, release in {0} + Jailed, release due + Show + Select {0} and move the view there. + Arrest now + Laws doesn't make this arrest on its own: {0}. Press to arrest now. + + diff --git a/README.md b/README.md index 89ed0a9..6a060a1 100644 --- a/README.md +++ b/README.md @@ -1,93 +1,157 @@ +![Blax Laws](About/Preview.png) + # Blax Laws [![RimWorld 1.7](https://img.shields.io/badge/RimWorld-1.7-19C63C)](https://rimworldgame.com) [![Needs Harmony](https://img.shields.io/badge/needs-Harmony-050805)](https://steamcommunity.com/sharedfiles/filedetails/?id=2009463077) [![Any DLC combination](https://img.shields.io/badge/DLCs-any_combination-5a6b5d)](#dlc-support) -[![Status: design](https://img.shields.io/badge/status-design-CDCDCD)](docs/design.md) +[![Status: 1.0](https://img.shields.io/badge/status-1.0-CDCDCD)](CHANGELOG.md) -RimWorld mod (1.7) by Blax Gaming. Lawbook, crimes and punishments. Write your colony's laws, and colonists who break them get stopped, jailed and, later, tried in court. Add "Drug binge, wake-up, planning, subdue" and when a colonist starts a wake-up binge, a warden goes for it at once and beats it down; if it reaches a drug first, that dose counts as "did it" and the did-it law applies. Add "Drug binge, did it, jail 5 days" and the one who already took some sits out five days in your prison and walks back to work. Needs Harmony. Works with any DLC combination, core only included. - -Status: design. Nothing is built yet; below is what the first release, the quick first version, will do. What the whole mod covers and in which order: `docs/features.md`. The specs: `docs/design.md`. +RimWorld mod (1.7) by Blax Gaming. Lawbook, crimes and punishments. Write your colony's laws from every act the game knows, picked the way you pick what to tailor, and your wardens enforce them. Add "Drug binge, planning: subdue" and when a colonist starts a wake-up binge, a warden goes for it at once and beats it down; if it reaches a drug first, that dose counts as "did it". Add "Drug binge, did it: jail 5 days" and the one who already took some sits out five days in your prison and walks back to work. Needs Harmony. Works with any DLC combination, core only included. ## Features ### The lawbook -- ๐Ÿ“– **An empty lawbook.** A "Laws" tab in the bottom bar. Add a law as Action, Stage, Severity, Punishment and Days, each a dropdown that only offers what fits. Nothing is watched or punished until the first row exists. `Source/BlaxLaws/MainTabWindow_Laws.cs` -- ๐Ÿ”Ž **Pick any act.** The Action comes from a searchable list, like choosing what to tailor: every mental break, everything that can be eaten or used, every social interaction, every act the game records, every record and every bill. It's built from the game's own data when the game starts, so DLC and modded breaks, drugs and recipes show up with no patch, each labelled with its mod. `Source/BlaxLaws/Dialog_PickAct.cs` -- ๐Ÿ“ **Starter lawbook.** One click adds seven suggested laws: subdue drug binges, fire-starting sprees and corpse obsession before they start, jail for binges and fires already done, a warning for fights and insults. `Source/BlaxLaws/Lawbook.cs` -- ๐ŸŽฏ **One law per act.** Each action, option and stage appears once in the book, and when two laws fit an act the more specific one wins: "wake-up" over "hard drugs" over "any drug", "human meat" over "any meat". -- ๐ŸŽš๏ธ **Stages that mean something.** "Planning" is the moment a mental break starts and nothing is done yet; "Did it" is the act the break is about, such as the first dose of a binge. An entry only offers the stages the game can really tell apart. -- ๐Ÿ“‹ **Case log.** Who, what, when, which punishment and how it ended, newest first, with a jump to the pawn and "Arrest now" for cases that wait. +- ๐Ÿ“– **An empty lawbook.** A "Laws" button in the bottom bar with two tabs, Lawbook and Cases. A law is a row of Action, Stage, Severity, Punishment and Days, plus an On switch; each dropdown offers only what fits the action and stage. Nothing is watched or punished until the first row exists. `Source/BlaxLaws/UI/MainTabWindow_Laws.cs` +- ๐Ÿ”Ž **Pick any act.** "Add law" opens a searchable tree like a tailoring bill's filter: every mental break, everything that can be eaten or used, every social interaction, every act the game records, every record and every bill, plus the special acts. It's built from the loaded defs when the game starts, so DLC and modded breaks, drugs and recipes show up with no patch, each labelled with its mod. Typing filters every category at once; an entry already in the book shows a tick and jumps to its row. `Source/BlaxLaws/UI/Dialog_PickAct.cs`, `Source/BlaxLaws/Catalogue/ActCatalogue.cs` +- ๐Ÿ“ **Starter lawbook.** One click adds seven laws: any drug binge, planning: subdue (Moderate); any drug binge, did it: jail 5 days (Serious); fire-starting spree, planning: subdue (Serious); fire-starting spree, did it: jail 10 days (Grave); corpse obsession, planning: subdue (Moderate); started a social fight: warn (Minor); insult: warn (Minor). Pressing it again adds only the missing ones. Every starter law uses core content. `Source/BlaxLaws/Lawbook.cs` +- ๐ŸŽฏ **One law per act, the most specific wins.** Action, Option and Stage are a row's key; a second row with the same three is refused and the list jumps to the existing one. A drug binge row names which drug counts: any drug, hard drugs, social drugs or one drug. When two rows of a category match an act, a single def beats a group, a smaller group beats a larger one, and one drug beats hard or social drugs beats any drug: "wake-up" over "hard drugs" over "any drug", "human meat" over "any meat". +- ๐ŸŽš๏ธ **Stages that mean something.** "Planning" is the moment a mental break starts and nothing is done yet; the game picks the break type only then, so only breaks have it. "Did it" is the act the break is about, such as the first dose of a binge. An entry offers only the stages the game can tell apart. +- โš–๏ธ **Severity and days.** Minor, Moderate, Serious or Grave set the default days (1, 3, 5, 10) and order the case log. Days go from 1 to 50. Changing the severity moves the days along only while you haven't typed your own. +- ๐Ÿ“‹ **Case log.** Who, what, stage, when, punishment and status, newest first, with a jump to the pawn and "Arrest now" for cases that wait. Deleting a law with open cases asks first, names the count and closes them as "law repealed". +- ๐Ÿงฉ **Missing entries wait.** A row whose DLC or mod is gone stays in the book with its saved name, shows "Needs " or "Missing: ", isn't enforced and works again when the content comes back. ### Crimes -The catalogue holds hundreds of acts; these are the ones the starter lawbook and the examples use. +Laws adds no crime events and no mental breaks. It only watches what the game does anyway. `Source/BlaxLaws/Detection/`, `Source/BlaxLaws/CaseFiler.cs` -- ๐Ÿ’Š **Drug binge.** Any drug, hard or social drugs, or one chemical such as wake-up. Planning when the binge starts, did it with every dose. `Source/BlaxLaws/Detection/BreakHooks.cs` -- ๐Ÿ”ฅ **Fire-starting spree.** Planning when a pyromaniac's spree starts, did it with every fire set. -- โšฐ๏ธ **Corpse obsession.** Planning when the obsession starts, did it when the corpse is on display; the case notes "on a table" and whether the corpse was dug up from a grave, which it usually is. -- ๐Ÿ‘Š **Started a social fight.** The pawn who reacts and swings first, usually the insulted one. -- ๐Ÿ—ฏ๏ธ **Insult.** Every insult by the one who insults; slights are their own entry. Planning for insulting sprees. -- ๐Ÿ– **Ate.** Any food or drug by name, or a group: any meat (meals included), raw meat and corpses, human meat, insect meat, hard drugs. -- ๐Ÿงพ **Recorded acts, records and bills.** Cut a tree, butchered a human, harvested an organ (most need Ideology); kills, bodies stripped; made a human leather duster, any surgery. -- ๐Ÿ’ข **Tantrums and rages.** Planning when the break starts; a warden can subdue a tantrum or a murderous rage, since those pawns don't turn on it. A berserk colonist fights back, so its case takes a warning, guilt or jail, and the jail waits until the break is over or you down it. -- ๐Ÿงฎ **No flood.** Acts outside a break open at most one case per colonist and law a day; more acts only raise its count. +- ๐Ÿง  **Mental breaks.** Every break a colonist can have, berserk included; animal and baby states are left out. Groups: any drug binge, any tantrum, any insulting spree, any aggressive break, any break. +- ๐Ÿ– **Ate.** Every food, meal, raw food, corpse and drug, modded and DLC ones included. Groups: any drug, hard, social or medical drugs, any meat (meals with meat included), raw meat or corpses, human meat, insect meat, raw food, any meal. It counts only when the pawn eats on its own: a doctor's dose, a warden feeding a patient or a baby being fed doesn't. A drink at a gathering spot counts. +- ๐Ÿ’‰ **Used.** Psytrainers, neurotrainers, mech serums and modded usables, when the pawn uses one on its own. +- ๐Ÿ—ฏ๏ธ **Social interactions.** Every interaction: insults, slights, chitchat, romance attempts, breakups, jailbreak talk, modded ones. The pawn who starts it is the offender. Group: insult or slight. +- ๐Ÿงพ **Recorded acts.** Every act the game records with the pawn as its doer, such as cut a tree, butchered a human, harvested an organ or executed a prisoner. Most of them are recorded only with Ideology, and the category's tooltip says so. +- ๐Ÿ“Š **Records.** Every counted record, such as kills, animals slaughtered, bodies stripped or things hauled. A case opens when the record goes up. +- ๐Ÿงช **Bills.** Every recipe, such as made a human leather duster, cooked a fine meal or installed a bionic arm, when the pawn finishes one iteration. Group: any surgery. +- ๐Ÿ”ฅ **Special acts.** Set a fire (the pawn who ignites it, never a raider); displayed a corpse, where the case notes "on a table" and "dug up from a grave", which it nearly always is; started a social fight, filed on the pawn who swings first, usually the insulted one. +- ๐Ÿ”— **Breaks lead to their act.** A drug binge's "did it" is a dose of the drug the row names, a food binge's a meal, a fire-starting spree's a fire, a corpse obsession's the displayed corpse, an insulting spree's an insult or slight, a jailbreaker's jailbreak talk. Links go by mental state class, so a modded break built on one of these gets its link too, and another mod can add its own with a `BreakLinkDef` and no code. Every other break is Planning only for now. `Defs/BlaxLaws_BreakLinks.xml` +- ๐Ÿ“ **One case per incident.** A binge is one case from start to end; it moves from planning to did it, each row fires once per case, and the case counts the doses. An act that is the did-it of an open break case belongs to that case; when it also matches a row of its own, the row with the higher severity decides. +- ๐Ÿงฎ **No flood.** Acts outside a break open at most one case per offender and law a day (0 to 7 days in the settings). A further act in that window raises the count on that case and posts no message, so a meat-eating colony of 60 doesn't flood the log or the save. +- ๐Ÿ‘ฅ **Who is covered.** Free colonists, children included, and colony slaves. Never guests, Hospitality visitors, quest lodgers, prisoners or babies. Acts while drafted or on a job you ordered open no case (setting). ### Punishments -- โœ‹ **Warn.** A record and a message. -- โš–๏ธ **Guilty for N days.** Vanilla guilt: the arrest of a free colonist is always accepted, executing it costs the colony only the small "justified execution" mood hit plus its family's grief, and banishing it costs no colony-wide mood. -- ๐Ÿ›‘ **Subdue.** A warden beats the offender down with fists to stop the break: bruises on torso and limbs, never the head or a bionic part, no lost parts, no scars, and the beating doesn't hand out the break's catharsis. No warden is pulled off a rescue, a patient or a fire, and nobody is sent while raiders are on the map. `Source/BlaxLaws/JobDriver_Subdue.cs` -- ๐Ÿ”’ **Jail for N days.** Arrested into a prisoner bed, kept on "Maintain only" so no prison mod recruits or enslaves your colonist, released by a warden when the time is served, back to work with its priorities intact. `Source/BlaxLaws/Enforcement.cs` -- ๐Ÿ”— **Subdue, then jail.** Beaten down and carried straight to a cell before a doctor takes it to bed. +Which punishments a row offers depends on its entry and stage: a planning row offers warn, subdue and jail; a break's did-it row also guilty and subdue then jail; every other act warn, guilty and jail. `Defs/BlaxLaws_Punishments.xml` + +- โœ‹ **Warn.** The case is filed and a message posted, nothing more. +- โš–๏ธ **Guilty for N days.** Vanilla guilt: the guilty icon shows, the arrest of a free colonist is always accepted, executing it costs the colony only the -2 "justified execution of colonist" thought plus its family's grief, and banishing it costs no colony-wide thought. A longer guilt already on the pawn is never shortened. `Source/BlaxLaws/Enforcement/PunishmentWorker_Guilty.cs` +- ๐Ÿ›‘ **Subdue.** A warden beats the offender down with fists to end its break: capped blunt hits on torso, shoulders, arms and legs, never the head, never a bionic part, no lost parts, no scars, no bleeding. Every part keeps at least half its health, and the bruises never add up to a deadly amount. The offender doesn't fight back, and the enforcer isn't marked guilty. The beating stops at downed, or once three hits in a row add no pain (go-juice, painkillers). The subdued pawn loses the catharsis that ending its break would give (setting), so the beating doesn't reward the crime. Tantrums, murderous and sadistic rage can be subdued too; the warden is never the rage's named victim. After the break a subdue row warns instead. `Source/BlaxLaws/Enforcement/JobDriver_Subdue.cs` +- ๐Ÿ”’ **Jail for N days.** A warden arrests the offender into a prisoner bed; guilt for the sentence is renewed right before the arrest, so it is always accepted. Two ticks after the capture the prisoner is set to "Maintain only", after any default a prison mod or Blax Castes writes, so nothing recruits, enslaves or executes your colonist. `Source/BlaxLaws/Sentences/PunishmentWorker_Jail.cs` +- โ›“๏ธ **Subdue, then jail.** Beaten down, and in the same tick the warden's next job is the vanilla capture to a prisoner bed, ahead of a doctor's rescue. After the break it jails without the beating. +- ๐Ÿ‘ถ **Children are never beaten** (Biotech): a subdue on a child becomes jail when the row has days, a warning otherwise. +- ๐Ÿ˜ก **Berserk breaks fight back.** Their rows offer warn, guilty and jail, never subdue. The jail waits until the break ends or you down the pawn, then arrests or captures it. + +### Enforcement + +- ๐Ÿš‘ **One enforcer per case, safely.** The nearest awake colonist with Warden work goes, then anyone able (setting: wardens only). Never a slave, a child, the offender, a pawn in a break, on a player order or in a party or ritual, and never one rescuing, carrying or tending someone, fighting a fire, manning a turret, doing surgery or fleeing. `Source/BlaxLaws/Enforcement/Enforcers.cs` +- โš ๏ธ **Nobody is sent into danger.** While hostiles threaten the map, a berserk colonist included, cases wait and are enforced after the fight. A warden already on a case when a raid arrives is called back. +- ๐Ÿ” **Cases move on by themselves.** A planning case closes when the break ends with nothing done, a lost subdue starts again, and an arrest that waited for a bed, an enforcer, a doctor's reservation or the end of a fight happens as soon as it can. A did-it jail that arrives while the planning subdue still runs takes over from it. `Source/BlaxLaws/Enforcement/Enforcement.cs` +- ๐Ÿ“จ **Messages and letters.** A message for every case. A letter only when a colonist is jailed or you have to act: no prisoner bed, no enforcer, a role holder on hold. No second letter for a break, since the vanilla one already arrives. ### Sentences -- โณ **Served and released.** The colonist sits out its days on "Maintain only", a warden lets it out when the time is served, and another mod's early release closes the sentence instead of fighting it. -- โธ๏ธ **Role holders and mechanitors wait.** An arrest would take an ideoligion role and shut a mechanitor's mechs down, so their case waits with "Arrest now" and a letter says why. +- โณ **Served and released.** The colonist sits out its days on "Maintain only", keeping its work priorities, since prisoners have no disabled work types. When the time is served Laws sets "Release" and a warden walks it out; if nobody has after a day, Laws releases it in place. The release counts from the capture, not from the filing. `Source/BlaxLaws/Sentences/Sentences.cs` +- ๐Ÿ›๏ธ **The old bed.** The arrest job claims the prisoner bed before the arrest happens; if the arrest then fails, Laws gives the colonist its old bed back when it is still free. +- ๐Ÿšช **Another mod's early release wins.** A jailed colonist that is recruited, released by you or another mod, escapes or dies closes its sentence with that outcome and a message. +- โธ๏ธ **Role holders and mechanitors wait.** An arrest would take an ideoligion role (Ideology) and shut a mechanitor's mechs down (Biotech), so their case waits with "Arrest now" and a letter says why. Guilt is set anyway and renewed when you press it. +- ๐Ÿ”— **Slaves aren't jailed yet.** Releasing an imprisoned slave would send it back to its old faction, so a slave's jail row subdues it while it is in its break and warns otherwise, until "Jail for slaves" ships. ### Save and settings -- ๐Ÿ’พ **Save-safe.** One piece of game data holds the lawbook and the cases. Unsubscribing leaves a save that loads with two errors in the log; jailed colonists stay prisoners you can release by hand. `Source/BlaxLaws/GameComponent_BlaxLaws.cs` -- โš™๏ธ **Mod settings.** "Enforce laws", "Show Laws tab", messages and letters, who enforces, catharsis after subdue, player orders exempt, days between cases for acts outside a break, how long closed cases stay, "Reset to defaults". +- ๐Ÿ’พ **Save-safe.** One game component holds the lawbook and the cases, as names and numbers; nothing of Laws enters a vanilla save list, and the subdue job is hidden from the save. Blax Laws can be added to a running save. Unsubscribing leaves a save that loads with two errors in the log: jailed colonists stay vanilla prisoners you release by hand in the prisoner tab, and their guilt runs out on its own. `Source/BlaxLaws/GameComponent_BlaxLaws.cs` +- โš™๏ธ **Mod settings.** "Enforce laws" (off keeps the case log and carries out nothing), "Show Laws tab", "Messages for cases", "Letters for jailings", "Enforcers" (wardens first or wardens only), "Subdued pawns lose their catharsis", "Player orders are exempt", "Days between cases for acts outside a break", "Keep closed cases" (60 days), "Reset to defaults". `Source/BlaxLaws/BlaxLawsMod.cs` ## Planned -The whole plan, by area, with the order and the reasons: `docs/features.md`. Coming after the first release: +In build order. What each area covers and its steps are in `docs/features.md`, the specs in `docs/design.md`. -- ๐Ÿ”ช **Violence, next.** Assault, harming prisoners or slaves, manslaughter and murder, plus "did it" for tantrums, berserk, rages and the slaughterer break; drugs the pawn's drug policy doesn't allow. -- ๐Ÿ›๏ธ **Back to its own bed.** When the sentence is served the colonist gets back its bed, grave, throne, deathrest casket, ideoligion role, its mechs' work modes and the weapon the arrest made it drop, so role holders and mechanitors no longer wait. With it: pardon, early release and more days, a reprimand, and banish or execute after you confirm. -- ๐Ÿ›๏ธ **Court.** "Trial" as a punishment through Ideology's trial, then court sessions without any DLC: a judge, a prosecutor and spectators at a place you pick, a verdict that weighs evidence against Social skill, the sentence from your lawbook, "jail, then trial" for an offender you want locked up until the verdict, and if you want a court that sits on its own at a set hour. Then attorneys, witnesses and a guilty plea, trials over up to three days, courtrooms and appeals. -- ๐Ÿ—ณ๏ธ **Colony votes.** Colonists propose and repeal laws and vote by traits, beliefs, opinion and mood, and you back or veto the result; the colony elects its judge, with terms, by-elections and recalls; later a jury and pardon petitions. -- ๐Ÿ“ˆ **Repeat offenders.** A criminal record per colonist, harsher punishments for a repeat offence, and early release on probation. -- ๐Ÿง‘โ€โš–๏ธ **Your call.** Decide a case yourself instead of a fixed punishment, talk a colonist down instead of beating it, and laws for one group only: slaves, children, a caste, or a colonist above the law. -- ๐Ÿ“š **Lawbook templates.** Take your lawbook to the next colony. -- ๐Ÿšจ **Uprisings.** Your own convicts breaking out, and slave rebellions, as crimes. -- ๐Ÿ™ **Crimes against the faith.** One law for anything the colony's ideoligion forbids, and one for leaving it (Ideology). -- ๐ŸฅŠ **Subdue a pawn that fights back.** For a berserk colonist, you pick the fighter and Laws sends it. -- ๐Ÿค **With the other Blax mods.** Blax Castes keeps a convict's caste through any sentence, Blax Slaves' wardens calm slaves before Laws steps in, jailed slaves become slaves again, and a confinement sentence through a Blax Castes caste (the last two still Fabian's call). +- ๐Ÿ”ช **Violence, drugs and the rest of the punishments.** Assault, harming prisoners or slaves, manslaughter and murder, with "did it" for tantrums, berserk and the rages; the slaughterer break; drugs the pawn's drug policy doesn't allow. Reprimand, and banish or execute after you confirm. Release gives back the bed, grave, throne, deathrest casket, ideoligion role, mech work modes and the dropped weapon, so role holders and mechanitors no longer wait. Pardon, early release and more days. +- ๐Ÿ“ˆ **Repeat offenders.** A criminal record per colonist, then harsher punishments for a repeat offence and early release on probation. +- ๐Ÿ›๏ธ **Court.** "Trial" as a punishment through Ideology's trial, then court sessions on the core game: a judge, a prosecutor and spectators at a place you pick, a verdict that weighs evidence against Social skill, the sentence from your lawbook, "jail, then trial", and a court that sits on its own if you want. Then attorneys, witnesses and a guilty plea, trials over several days, courtrooms and appeals. +- ๐Ÿ—ณ๏ธ **Colony votes.** Colonists propose and repeal laws and vote by traits, beliefs, opinion and mood, and you back or veto the result; the colony elects its judge; later a jury and pardon petitions. +- ๐Ÿค **With the other Blax mods.** Blax Castes keeps a convict's caste through any sentence, Blax Slaves' wardens calm slaves before Laws steps in, a jailed slave becomes a slave again, and confinement as a sentence through a Blax Castes caste. +- ๐Ÿ’ฌ **Your call.** Decide a case yourself, talk a colonist down instead of beating it, laws for one group only (slaves, children, a caste, or a colonist above the law), lawbook templates for the next colony, your own convicts breaking out and slave rebellions as crimes, crimes against the faith (Ideology), and a fighter you pick to subdue a berserk colonist. ## DLC support -Blax Laws works with any combination of DLCs, core only included, and lists none as a dependency. Every category and punishment of the first release runs on the core game; later, the throne, deathrest casket, role and mech parts of the release give-back switch off without their DLC. The act list shows what your game has: a DLC's breaks, drugs and recipes appear when it's active. +Blax Laws works with any combination of DLCs, core only included, and lists none as a dependency. Every category and punishment of this release runs on the core game. The act list shows what your game has: a DLC's breaks, drugs, interactions, usables and recipes appear when it is active and are absent without it. -- **Ideology** adds slaves, who can be warned, marked guilty and subdued. An arrest takes a role holder's role, so its case waits for "Arrest now" until the give-back returns the role at the release. -- **Biotech** adds children, who are never beaten, and mechanitors, whose mechs shut down in jail; their case waits for "Arrest now" until the give-back returns the mechs to their work modes. -- **Ideology** also records most of the game's acts (cut a tree, butchered a human); without it the recorded acts category rarely fires. +- **Ideology** adds slaves, who get warn, guilty and subdue, and records most of the game's acts (cut a tree, butchered a human); without it the recorded acts category rarely fires. An arrest would take a role holder's role, so its case waits for "Arrest now". +- **Biotech** adds children, who are never beaten, and mechanitors, whose mechs would shut down in jail, so their case waits for "Arrest now". - **Royalty**, **Anomaly** and **Odyssey**: their acts appear in the list when active; Laws needs none of them. -- **A save made with a DLC** loads without it. +- **A save made with a DLC** loads without it. A law naming a DLC entry stays and shows "Needs "; a case whose offender was a slave keeps its name. ## Compatibility -- โœ”๏ธ Prison Labor, Prisoner Realism, Custom Prisoner Interactions and Hospitality: a jailed colonist is a vanilla prisoner, so their features apply; Laws only keeps its own prisoners on "Maintain only" and lets them go when the time is served. +- โœ”๏ธ Prison Labor, Prisoner Realism and Custom Prisoner Interactions: a jailed colonist is a vanilla prisoner, so their features apply. Laws only keeps its own convicts on "Maintain only" and lets them go when the time is served; Prison Labor's work toggle stays as that mod sets it. While that toggle is on, Prison Labor turns off the work types it bars prisoners from, and they stay off after the release; turn the toggle off on a jailed colonist to keep its work priorities. - โœ”๏ธ Prisoner Sentencing and Prison Expanded: if one of them releases a colonist Laws jailed, Laws closes its sentence instead of fighting it. -- โœ”๏ธ RimCourt: it judges civil disputes as the lord, Laws tries those who break your laws; both run side by side. -- โ™ป๏ธ Replaces Rimworld Law and Order, which has no 1.7 build, needs Ideology and adds its own crime events. +- โœ”๏ธ Hospitality: guests are never offenders. +- โœ”๏ธ Blax Zones: arrests use any prisoner bed, zone beds included. Blax Castes: a jailed colonist moves to its new-prisoner row and back to its old caste after the release; Laws writes only "Maintain only" and "Release" on colonists it jailed. +- โœ”๏ธ `Tests/run-tests.ps1 -Compat` runs the suite next to Prison Labor, Prisoner Realism, Custom Prisoner Interactions, Hospitality, Vanilla Social Interactions Expanded, Blax Castes, Blax Zones, Blax Slaves and Blax Defaults, and Humanoid Alien Races once it is installed. - โŒ Multiplayer: not supported. Load order: Harmony, Blax Castes, Blax Zones, Blax Slaves, Blax Laws. No Blax mod needs another. +## Development + +The repo is the mod folder. Link it into the game with a directory junction, run from the repo root (adjust the RimWorld path): + +```powershell +New-Item -ItemType Junction -Path "E:\SteamLibrary\steamapps\common\RimWorld\Mods\BlaxLaws" -Target (Get-Location).Path +``` + +Build (needs the .NET 10 SDK; output goes to `1.7/Assemblies/BlaxLaws.dll`). `RimWorldDir` and `HarmonyDir` in the csproj point at the Steam install and the Harmony mod; override them with `-p:RimWorldDir=...` elsewhere. + +```powershell +dotnet build Source\BlaxLaws\BlaxLaws.csproj -c Release +``` + +`Tests/run-tests.ps1` builds the mod and the test mod in `Tests/BlaxLawsTests`, starts RimWorld headless with its own save data folder in `%TEMP%\BlaxLawsTest`, runs the suite, saves and reloads, then loads the save with the mod's game component removed. Your mod list, saves and settings stay untouched. It needs Steam running. The script's header lists every switch. + +```powershell +.\Tests\run-tests.ps1 # every installed DLC +.\Tests\run-tests.ps1 -NoDlc # core only +.\Tests\run-tests.ps1 -Dlc Ideology # only the DLCs named +.\Tests\run-tests.ps1 -Compat # next to the mods listed under Compatibility +``` + +Design and roadmap: `docs/design.md` and `docs/features.md`. + +### Workshop upload + +`Tools/workshop-upload.ps1` creates and updates the Workshop item from the command line. A small tool (`Tools/WorkshopUpload`) uses the Steamworks.NET build and `steam_api64.dll` that ship with RimWorld and attaches to the running, logged-in Steam client as RimWorld, so it needs no password, no game window and no dev mode. + +```powershell +.\Tools\workshop-upload.ps1 # dry run: build, stage, check the Steam login and the item +.\Tools\workshop-upload.ps1 -Check # release check: every -Publish gate, then the list of problems +.\Tools\workshop-upload.ps1 -Publish -DescriptionFile docs\workshop-description.txt # upload and replace the description +``` + +The dry run and `-Check` upload nothing. The script stages only what players need (About, 1.7, Defs, Patches, Languages) in `%TEMP%`, sets the tags the game would (Mod plus the supported versions), the title from About.xml and the preview from `About/Preview.png`. The change note is every CHANGELOG.md entry newer than the version in `Tools/workshop-published.txt`. + +Blax Laws has no Workshop item yet. Without `About/PublishedFileId.txt` the first `-Publish` creates it, Public unless you pass `-Visibility private` (Steam's own default for a new item is Private), and writes its id to `About/PublishedFileId.txt` before the content upload, so a failed upload is retried as an update and never makes a second item. After a successful upload it writes `Tools/workshop-published.txt`. Commit both files. + +`-Publish` refuses unless: + +- the shipped files are committed and pushed, and the top CHANGELOG.md entry matches `modVersion` in About.xml; +- two `Tests/run-tests.ps1` runs passed after the last build, one with every installed DLC and one with `-NoDlc` (`BlaxLawsTestResults.all.txt` and `BlaxLawsTestResults.nodlc.txt` in `%TEMP%\BlaxLawsTest`); +- `About/Preview.png` is under 1 MB; +- the description fits Steam's 8000-byte limit, every forgejo.blax.at link in it opens without a login, and every `[img]` host sends an `Access-Control-Allow-Origin` header. Steam loads description images cross-origin and shows a broken image otherwise. Forgejo's raw URLs send no such header, so the images are served from `cdn.blax.at/blax-gaming/laws/`, which does. + +The Workshop page is `docs/workshop-description.txt` (Steam BBCode). Its art is rendered from `Source/Art` (see `Source/Art/README.md`), and `docs/workshop-media.md` lists the in-game clips worth recording. `-DescriptionOnly -DescriptionFile docs\workshop-description.txt` replaces just the text, with no build, no content upload and no change note. + +The in-game route still works: `Tools/workshop-stage.ps1` swaps the junction for a clean copy, upload from Mods > Blax Laws > Advanced... > Upload to Steam Workshop (dev mode), then `Tools/workshop-stage.ps1 -Done` copies `About/PublishedFileId.txt` back into the repo and restores the junction. + --- ## Made by Blax diff --git a/Source/Art/README.md b/Source/Art/README.md new file mode 100644 index 0000000..e29965d --- /dev/null +++ b/Source/Art/README.md @@ -0,0 +1,56 @@ +# 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 the art of the other Blax Gaming mods, so the mods read as one label: Blax black `#050805`, Blax green `#19C63C`, logo gray `#CDCDCD`, Geist for headings, Inter for body text, Rajdhani only for the "Blax Gaming" wordmark. Fonts are the woff2 files blax.at self-hosts (all SIL Open Font License); icons are lucide (ISC license). + +The preview has Slaves' layout: wordmark top left, "Blax Laws" with a green subtitle on the left, four feature rows on the right (write your own lawbook, any act can be a crime, subdue or jail, court and votes planned). "Laws" is short, so the feature column starts at 700 px instead of Zones' 760 and the longer row titles stay on one line. The icon is the Blax monogram with a green "scale" badge, so it stands apart from Slaves' plain monogram, Castes' "layers", Zones' "package" and Defaults' "sliders-horizontal" badges in the mod list. + +| File | Renders | +|---|---| +| `preview.html` | `About/Preview.png`, 1280x720 | +| `icon.html` + `icon.svg` | `About/ModIcon.png`, 256x256, transparent | +| `header.html` | the Workshop section headers in `docs/art/steam/`, 1270x150 | +| `oss-banner.html` | `docs/art/blax-oss-banner.png`, 1600x254, from `docs/art/blax-oss-banner.svg` | +| `blax-monogram.svg`, `monogram-centered.svg` | the Blax monogram, used by the pages above | +| `fonts/` | Geist, Inter, Rajdhani 700 | + +Render with Edge headless from this folder. The separate profile folder keeps the headless run away from an open Edge window, and `| Out-Null` waits for each screenshot. + +```powershell +$edge = 'C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe' +$here = (Get-Location).Path -replace '\\','/' +$edgeData = "$env:TEMP\blax-art-edge-laws" +& $edge --headless=new --disable-gpu --hide-scrollbars --user-data-dir="$edgeData" --virtual-time-budget=3000 --window-size=1280,720 --screenshot="$PWD\..\..\About\Preview.png" "file:///$here/preview.html" | Out-Null +& $edge --headless=new --disable-gpu --hide-scrollbars --user-data-dir="$edgeData" --virtual-time-budget=2000 --window-size=256,256 --default-background-color=00000000 --screenshot="$PWD\..\..\About\ModIcon.png" "file:///$here/icon.html" | Out-Null +``` + +`About/Preview.png` must stay under 1 MB for the Workshop; it is about 90 KB. + +## Workshop page art + +The Steam description (`docs/workshop-description.txt`) shows a section header from `docs/art/steam/` above each part and Blax Software's Open Source Initiative banner at the end. Steam shows no SVG, so the banner (`docs/art/blax-oss-banner.svg`, the same file as in the other Blax Gaming mods) is also rendered as a PNG; it is the same PNG as Zones' `docs/art/blax-oss-banner.png`. `header.html` takes the title (`t`), subtitle (`s`) and lucide icon name (`i`) as query parameters; the icon must be in its `icons` map. + +| File | t | s | i | +|---|---|---|---| +| `lawbook.png` | Lawbook | Write what is forbidden and see every case | book-open-text | +| `crimes.png` | Crimes | Any act can be one, DLC and modded content included | fingerprint | +| `punishments.png` | Punishments | Warn, guilty, subdue and jail | lock-keyhole | +| `planned.png` | Planned | Coming in later releases | milestone | +| `compatibility.png` | Compatibility | Other mods and where they overlap | puzzle | + +```powershell +& $edge --headless=new --disable-gpu --hide-scrollbars --user-data-dir="$edgeData" --virtual-time-budget=3000 --window-size=1600,254 --screenshot="$PWD\..\..\docs\art\blax-oss-banner.png" "file:///$here/oss-banner.html" | Out-Null +& $edge --headless=new --disable-gpu --hide-scrollbars --user-data-dir="$edgeData" --virtual-time-budget=3000 --window-size=1270,150 --screenshot="$PWD\..\..\docs\art\steam\lawbook.png" "file:///$here/header.html?t=Lawbook&s=Write%20what%20is%20forbidden%20and%20see%20every%20case&i=book-open-text" | Out-Null +& $edge --headless=new --disable-gpu --hide-scrollbars --user-data-dir="$edgeData" --virtual-time-budget=3000 --window-size=1270,150 --screenshot="$PWD\..\..\docs\art\steam\crimes.png" "file:///$here/header.html?t=Crimes&s=Any%20act%20can%20be%20one%2C%20DLC%20and%20modded%20content%20included&i=fingerprint" | Out-Null +& $edge --headless=new --disable-gpu --hide-scrollbars --user-data-dir="$edgeData" --virtual-time-budget=3000 --window-size=1270,150 --screenshot="$PWD\..\..\docs\art\steam\punishments.png" "file:///$here/header.html?t=Punishments&s=Warn%2C%20guilty%2C%20subdue%20and%20jail&i=lock-keyhole" | Out-Null +& $edge --headless=new --disable-gpu --hide-scrollbars --user-data-dir="$edgeData" --virtual-time-budget=3000 --window-size=1270,150 --screenshot="$PWD\..\..\docs\art\steam\planned.png" "file:///$here/header.html?t=Planned&s=Coming%20in%20later%20releases&i=milestone" | Out-Null +& $edge --headless=new --disable-gpu --hide-scrollbars --user-data-dir="$edgeData" --virtual-time-budget=3000 --window-size=1270,150 --screenshot="$PWD\..\..\docs\art\steam\compatibility.png" "file:///$here/header.html?t=Compatibility&s=Other%20mods%20and%20where%20they%20overlap&i=puzzle" | Out-Null +``` + +Check each result for its size before using it: + +```powershell +Add-Type -AssemblyName System.Drawing +Get-ChildItem ..\..\About\*.png, ..\..\docs\art\steam\*.png, ..\..\docs\art\*.png | ForEach-Object { $i = [System.Drawing.Image]::FromFile($_.FullName); '{0}: {1}x{2}, {3} bytes' -f $_.Name, $i.Width, $i.Height, $_.Length; $i.Dispose() } +``` + +The Steam page loads these images from the Blax CDN (`https://cdn.blax.at/blax-gaming/`), not from Forgejo: Steam requests description images cross-origin, and only the CDN answers with `Access-Control-Allow-Origin`. After re-rendering, copy the PNGs to `blax-gaming/laws/` on the CDN (`blax-gaming/laws/.png`; the banner is shared at `blax-gaming/blax-oss-banner.png` and is already there). The upload steps are in Blax's internal infrastructure docs. diff --git a/Source/Art/blax-monogram.svg b/Source/Art/blax-monogram.svg new file mode 100644 index 0000000..a628153 --- /dev/null +++ b/Source/Art/blax-monogram.svg @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/Source/Art/fonts/geist.woff2 b/Source/Art/fonts/geist.woff2 new file mode 100644 index 0000000..8f01e76 Binary files /dev/null and b/Source/Art/fonts/geist.woff2 differ diff --git a/Source/Art/fonts/inter.woff2 b/Source/Art/fonts/inter.woff2 new file mode 100644 index 0000000..41f6888 Binary files /dev/null and b/Source/Art/fonts/inter.woff2 differ diff --git a/Source/Art/fonts/rajdhani-700.woff2 b/Source/Art/fonts/rajdhani-700.woff2 new file mode 100644 index 0000000..59012d4 Binary files /dev/null and b/Source/Art/fonts/rajdhani-700.woff2 differ diff --git a/Source/Art/header.html b/Source/Art/header.html new file mode 100644 index 0000000..13c6af3 --- /dev/null +++ b/Source/Art/header.html @@ -0,0 +1,46 @@ + + + + + + + + + +

    + + + + diff --git a/Source/Art/icon.html b/Source/Art/icon.html new file mode 100644 index 0000000..f83e334 --- /dev/null +++ b/Source/Art/icon.html @@ -0,0 +1,6 @@ + + + diff --git a/Source/Art/icon.svg b/Source/Art/icon.svg new file mode 100644 index 0000000..8f2aedc --- /dev/null +++ b/Source/Art/icon.svg @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/Art/monogram-centered.svg b/Source/Art/monogram-centered.svg new file mode 100644 index 0000000..364c0b3 --- /dev/null +++ b/Source/Art/monogram-centered.svg @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/Source/Art/oss-banner.html b/Source/Art/oss-banner.html new file mode 100644 index 0000000..67202cb --- /dev/null +++ b/Source/Art/oss-banner.html @@ -0,0 +1,13 @@ + + + + + + + + + diff --git a/Source/Art/preview.html b/Source/Art/preview.html new file mode 100644 index 0000000..d049abc --- /dev/null +++ b/Source/Art/preview.html @@ -0,0 +1,76 @@ + + + + + + + +
    +
    + +
    Blax Gaming
    +
    +
    + +
    +

    Blax
    Laws

    +
    for RimWorld 1.7
    +

    Write your colony's laws.
    Wardens stop and jail whoever breaks them.

    +
    + + +
    +
    + +

    Write your own lawbook

    Empty until you add a law.

    +
    +
    + +

    Any act can be a crime

    Every break, drug, meal and bill.

    +
    +
    + +

    Subdue or jail

    A binge stopped before the first dose.

    +
    +
    + +

    Court and votes planned

    Trials, judges and laws put to a vote.

    +
    +
    + + diff --git a/Source/BlaxLaws/BlaxLaws.csproj b/Source/BlaxLaws/BlaxLaws.csproj new file mode 100644 index 0000000..d42b7a8 --- /dev/null +++ b/Source/BlaxLaws/BlaxLaws.csproj @@ -0,0 +1,46 @@ + + + + + net10.0 + BlaxLaws + BlaxLaws + latest + disable + disable + ..\..\1.7\Assemblies\ + false + false + false + false + portable + true + + false + + $(MSBuildProjectDirectory)=Source/BlaxLaws + + + + + E:\SteamLibrary\steamapps\common\RimWorld + E:\SteamLibrary\steamapps\workshop\content\294100\2009463077\1.7\Assemblies + + + + + $(RimWorldDir)\Assembly-CSharp.dll + false + + + $(RimWorldDir)\UnityStubs.dll + false + + + $(HarmonyDir)\0Harmony.dll + false + + + + diff --git a/Source/BlaxLaws/BlaxLawsDefOf.cs b/Source/BlaxLaws/BlaxLawsDefOf.cs new file mode 100644 index 0000000..dedcfd7 --- /dev/null +++ b/Source/BlaxLaws/BlaxLawsDefOf.cs @@ -0,0 +1,25 @@ +using RimWorld; +using Verse; + +namespace BlaxLaws +{ + /// Defs Laws ships. Act categories and special acts are read through ActCatalogue, not here. + [DefOf] + public static class BlaxLawsDefOf + { + public static PunishmentDef Warn; + public static PunishmentDef Guilty; + public static PunishmentDef Subdue; + public static PunishmentDef Jail; + public static PunishmentDef SubdueThenJail; + + public static JobDef BlaxLaws_Subdue; + + public static MainButtonDef BlaxLaws_Laws; + + static BlaxLawsDefOf() + { + DefOfHelper.EnsureInitializedInCtor(typeof(BlaxLawsDefOf)); + } + } +} diff --git a/Source/BlaxLaws/BlaxLawsMod.cs b/Source/BlaxLaws/BlaxLawsMod.cs new file mode 100644 index 0000000..3fcf287 --- /dev/null +++ b/Source/BlaxLaws/BlaxLawsMod.cs @@ -0,0 +1,211 @@ +using System; +using System.Collections.Generic; +using HarmonyLib; +using RimWorld; +using UnityEngine; +using Verse; + +namespace BlaxLaws +{ + /// Who enforces laws (setting "Enforcers"). + public enum EnforcerMode + { + /// Wardens (Warden work active) first, then anyone able. + WardensFirst, + /// Only wardens; without one the case waits. + WardensOnly, + } + + /// + /// Global settings (design: "Lawbook tab", settings page). The lawbook itself is per save and lives in + /// GameComponent_BlaxLaws, never here. + /// + public class BlaxLawsSettings : ModSettings + { + /// Wardens carry out punishments. Off: cases open and close, nothing is carried out. + public bool enforceLaws = true; + /// The Laws button shows in the bottom bar. Written live into MainButtonDef.buttonVisible. + public bool showLawsTab = true; + /// A message for every case (CaseMessages). + public bool caseMessages = true; + /// Letters when a colonist is jailed or the player has to act. + public bool jailLetters = true; + /// Who enforces. + public EnforcerMode enforcers = EnforcerMode.WardensFirst; + /// A subdued pawn loses the catharsis that ending its break gives. + public bool subdueRemovesCatharsis = true; + /// An act done while drafted or on a player-forced job opens no case. + public bool playerOrdersExempt = true; + /// Days between cases of one offender under one law for acts outside a break (0 to 7). + public int cooldownDays = DefaultCooldownDays; + /// Closed cases older than this are pruned on save (7 to 360). + public int keepClosedDays = DefaultKeepClosedDays; + + public const int DefaultCooldownDays = 1; + public const int MinCooldownDays = 0; + public const int MaxCooldownDays = 7; + public const int DefaultKeepClosedDays = 60; + public const int MinKeepClosedDays = 7; + public const int MaxKeepClosedDays = 360; + + public int CooldownDaysClamped => Mathf.Clamp(cooldownDays, MinCooldownDays, MaxCooldownDays); + + public int KeepClosedDaysClamped => Mathf.Clamp(keepClosedDays, MinKeepClosedDays, MaxKeepClosedDays); + + /// The cooldown window in ticks; 0 files every act. + public int CooldownTicks => CooldownDaysClamped * GenDate.TicksPerDay; + + public int KeepClosedTicks => KeepClosedDaysClamped * GenDate.TicksPerDay; + + public override void ExposeData() + { + base.ExposeData(); + Scribe_Values.Look(ref enforceLaws, "enforceLaws", true); + Scribe_Values.Look(ref showLawsTab, "showLawsTab", true); + Scribe_Values.Look(ref caseMessages, "caseMessages", true); + Scribe_Values.Look(ref jailLetters, "jailLetters", true); + Scribe_Values.Look(ref enforcers, "enforcers", EnforcerMode.WardensFirst); + Scribe_Values.Look(ref subdueRemovesCatharsis, "subdueRemovesCatharsis", true); + Scribe_Values.Look(ref playerOrdersExempt, "playerOrdersExempt", true); + Scribe_Values.Look(ref cooldownDays, "cooldownDays", DefaultCooldownDays); + Scribe_Values.Look(ref keepClosedDays, "keepClosedDays", DefaultKeepClosedDays); + if (Scribe.mode == LoadSaveMode.LoadingVars || Scribe.mode == LoadSaveMode.PostLoadInit) + { + cooldownDays = CooldownDaysClamped; + keepClosedDays = KeepClosedDaysClamped; + } + } + + public void Reset() + { + var d = new BlaxLawsSettings(); + enforceLaws = d.enforceLaws; + showLawsTab = d.showLawsTab; + caseMessages = d.caseMessages; + jailLetters = d.jailLetters; + enforcers = d.enforcers; + subdueRemovesCatharsis = d.subdueRemovesCatharsis; + playerOrdersExempt = d.playerOrdersExempt; + cooldownDays = d.cooldownDays; + keepClosedDays = d.keepClosedDays; + } + } + + public class BlaxLawsMod : Mod + { + public static BlaxLawsSettings Settings; + + /// The settings, or defaults before the mod class exists, so nothing reads null while loading. + public static BlaxLawsSettings S => Settings ?? (fallback ??= new BlaxLawsSettings()); + private static BlaxLawsSettings fallback; + + public BlaxLawsMod(ModContentPack content) : base(content) + { + Settings = GetSettings(); + } + + public override string SettingsCategory() => "Blax Laws"; + + /// + /// Writes "Show Laws tab" into the button def. The bottom bar counts buttonVisible for its width + /// (MainButtonsRoot.cs:15-27), so the change shows at once. Never throws. + /// + public static void ApplyTabVisibility() + { + try + { + MainButtonDef def = BlaxLawsDefOf.BlaxLaws_Laws ?? DefDatabase.GetNamedSilentFail("BlaxLaws_Laws"); + if (def != null) + def.buttonVisible = S.showLawsTab; + } + catch (Exception e) + { + LawsLog.Once("Show Laws tab", e); + } + } + + public override void DoSettingsWindowContents(Rect inRect) + { + BlaxLawsSettings s = Settings; + var l = new Listing_Standard(); + l.maxOneColumn = true; + l.Begin(inRect); + + l.CheckboxLabeled("BlaxLaws_SettingEnforceLaws".Translate(), ref s.enforceLaws, "BlaxLaws_SettingEnforceLawsTip".Translate()); + bool tab = s.showLawsTab; + l.CheckboxLabeled("BlaxLaws_SettingShowTab".Translate(), ref s.showLawsTab, "BlaxLaws_SettingShowTabTip".Translate()); + if (tab != s.showLawsTab) + ApplyTabVisibility(); + l.CheckboxLabeled("BlaxLaws_SettingCaseMessages".Translate(), ref s.caseMessages, "BlaxLaws_SettingCaseMessagesTip".Translate()); + l.CheckboxLabeled("BlaxLaws_SettingJailLetters".Translate(), ref s.jailLetters, "BlaxLaws_SettingJailLettersTip".Translate()); + l.GapLine(); + + l.Label("BlaxLaws_SettingEnforcers".Translate()); + if (l.RadioButton("BlaxLaws_EnforcersWardensFirst".Translate(), s.enforcers == EnforcerMode.WardensFirst, 12f, "BlaxLaws_EnforcersWardensFirstTip".Translate())) + s.enforcers = EnforcerMode.WardensFirst; + if (l.RadioButton("BlaxLaws_EnforcersWardensOnly".Translate(), s.enforcers == EnforcerMode.WardensOnly, 12f, "BlaxLaws_EnforcersWardensOnlyTip".Translate())) + s.enforcers = EnforcerMode.WardensOnly; + l.CheckboxLabeled("BlaxLaws_SettingSubdueCatharsis".Translate(), ref s.subdueRemovesCatharsis, "BlaxLaws_SettingSubdueCatharsisTip".Translate()); + l.CheckboxLabeled("BlaxLaws_SettingPlayerOrdersExempt".Translate(), ref s.playerOrdersExempt, "BlaxLaws_SettingPlayerOrdersExemptTip".Translate()); + l.GapLine(); + + s.cooldownDays = Mathf.RoundToInt(l.SliderLabeled("BlaxLaws_SettingCooldownDays".Translate(s.CooldownDaysClamped), + s.CooldownDaysClamped, BlaxLawsSettings.MinCooldownDays, BlaxLawsSettings.MaxCooldownDays, 0.6f, + "BlaxLaws_SettingCooldownDaysTip".Translate())); + s.cooldownDays = s.CooldownDaysClamped; + s.keepClosedDays = Mathf.RoundToInt(l.SliderLabeled("BlaxLaws_SettingKeepClosedDays".Translate(s.KeepClosedDaysClamped), + s.KeepClosedDaysClamped, BlaxLawsSettings.MinKeepClosedDays, BlaxLawsSettings.MaxKeepClosedDays, 0.6f, + "BlaxLaws_SettingKeepClosedDaysTip".Translate())); + s.keepClosedDays = s.KeepClosedDaysClamped; + + l.Gap(); + if (l.ButtonText("BlaxLaws_SettingsReset".Translate())) + { + s.Reset(); + ApplyTabVisibility(); + } + l.End(); + } + } + + /// + /// Applies the Harmony patches after every Mod class exists (so the Harmony mod has set up its 1.7 + /// backend), one class at a time so a single broken target can't take the rest down, and logs + /// "[Blax Laws] N patches applied". A patch class is any class in this assembly with [HarmonyPatch]. + /// + [StaticConstructorOnStartup] + public static class BlaxLawsStartup + { + public const string HarmonyId = "blax.laws"; + public static readonly Harmony Harmony = new Harmony(HarmonyId); + + /// Patch classes that failed to apply, by type name. Read by the smoke test. + public static readonly List FailedPatches = new List(); + + /// Patch classes applied at startup. + public static int Applied { get; private set; } + + static BlaxLawsStartup() + { + int ok = 0; + foreach (Type type in typeof(BlaxLawsStartup).Assembly.GetTypes()) + { + if (!type.IsDefined(typeof(HarmonyPatch), false)) + continue; + try + { + Harmony.CreateClassProcessor(type).Patch(); + ok++; + } + catch (Exception e) + { + FailedPatches.Add(type.Name); + Log.Error("[Blax Laws] Patch " + type.Name + " failed: " + e); + } + } + Applied = ok; + Log.Message("[Blax Laws] " + ok + " patches applied" + (FailedPatches.Count > 0 ? ", " + FailedPatches.Count + " failed" : "")); + BlaxLawsMod.ApplyTabVisibility(); + } + } +} diff --git a/Source/BlaxLaws/CaseFiler.cs b/Source/BlaxLaws/CaseFiler.cs new file mode 100644 index 0000000..343b877 --- /dev/null +++ b/Source/BlaxLaws/CaseFiler.cs @@ -0,0 +1,199 @@ +using System; +using Verse; +using Verse.AI; + +namespace BlaxLaws +{ + /// + /// Turns an act into a case (design: "Act catalogue and detection", How, and "Defaults I picked"). The one + /// entry point every detection hook calls; it never punishes, it queues: Enforcement starts the + /// punishment a tick later. + /// + /// - A break's start (category Break) opens a planning case when a planning row matches. + /// - An act that is the linked did-it of the offender's current break belongs to that break's case and + /// opens no other case. When the act also matches a row of its own category, the row with the higher + /// severity decides, the break's row on a tie. Each stage's punishment fires once per case; later acts + /// raise the count. + /// - Any other act: the most specific enabled row of its category decides. Within the cooldown + /// ("Days between cases") a further act of the same offender under the same row raises the count on + /// that case, open or closed, and files nothing new. + /// + public static class CaseFiler + { + /// + /// Files the act. Returns the case that took it (new or existing), or null when no row covers it, the + /// offender isn't covered, or the act is a player order. Safe to call from any hook; the hook still + /// wraps the call in its own try/catch. + /// + public static LawCase Report(ActEvent act) + { + if (LawsTestHooks.ReportThrows) + throw new InvalidOperationException("test: CaseFiler.Report throws"); + if (act?.offender == null || act.categoryId == null || !Watch.Any) + return null; + GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance; + if (comp == null || !Offenders.CountsAsOffender(act.offender)) + return null; + + if (act.categoryId == ActCategories.Break) + return ReportBreakStart(comp, act); + + Law own = Lawbook.BestRow(act, LawStage.DidIt); + LawCase linked = ReportLinkedAct(comp, act, own); + if (linked != null) + return linked; + return own == null ? null : ReportAct(comp, act, own); + } + + /// + /// Opens a case for a row, at a stage, without matching: for hooks that already know the row (a later + /// stage of a special flow) and for tests. Sets the stage's row, count, notes and ticks; queues nothing. + /// + public static LawCase Open(Law law, ActEvent act, LawStage stage) + { + GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance; + if (comp == null || law == null || act?.offender == null) + return null; + int now = Now; + var c = new LawCase + { + id = comp.TakeCaseId(), + actKey = law.actKey, + matchedDef = act.def?.defName, + stage = stage, + count = stage == LawStage.DidIt ? 1 : 0, + notes = act.notes, + openTick = now, + lastActTick = now, + status = CaseStatus.Open, + }; + c.SetOffender(act.offender); + c.SetVictim(act.victim); + c.SetLaw(stage, law); + comp.AddCase(c); + return c; + } + + /// The tick the pawn's break started, to within 30 ticks: now minus MentalState.Age. + public static int BreakStartTick(MentalState state) => state == null ? Now : Now - state.Age; + + /// Whether the case's break is still running on its offender. + public static bool StillInBreak(LawCase c) + { + if (c == null || !c.IsBreakCase || c.offender == null || c.offender.Dead) + return false; + MentalState state = c.offender.MentalState; + return state?.def != null && state.def.defName == c.breakState && + Math.Abs(BreakStartTick(state) - c.breakStartTick) <= GameComponent_BlaxLaws.BreakStartTolerance; + } + + private static int Now => Find.TickManager?.TicksGame ?? 0; + + // ---- the three paths ----------------------------------------------------------------- + + private static LawCase ReportBreakStart(GameComponent_BlaxLaws comp, ActEvent act) + { + if (!(act.def is MentalStateDef state)) + return null; + Law row = Lawbook.BestRow(act, LawStage.Planning); + if (row == null) + return null; + MentalState live = act.mentalState ?? act.offender.MentalState; + int start = BreakStartTick(live); + LawCase c = comp.BreakCaseOf(act.offender, state.defName, start); + if (c != null) + return c; + c = Open(row, act, LawStage.Planning); + c.breakState = state.defName; + c.breakStartTick = start; + Enforcement.Enqueue(c, LawStage.Planning); + return c; + } + + private static LawCase ReportLinkedAct(GameComponent_BlaxLaws comp, ActEvent act, Law own) + { + MentalState state = act.offender.MentalState; + if (state?.def == null) + return null; + BreakLinkDef link = BreakLinks.For(state.def); + if (link == null || !BreakLinks.Matches(link, act)) + return null; + + var breakAct = new ActEvent(ActCategories.Break, state.def, act.offender) + { + victim = act.victim, + thing = act.thing, + chemical = act.chemical, + drugCategory = act.drugCategory, + facts = act.facts, + notes = act.notes, + mentalState = state, + }; + Law breakRow = Lawbook.BestRow(breakAct, LawStage.DidIt); + int start = BreakStartTick(state); + LawCase c = comp.BreakCaseOf(act.offender, state.def.defName, start); + if (c == null && breakRow == null) + return null; // No law on this break: the act files as any other act. + + int now = Now; + if (c == null) + { + c = Open(breakRow, breakAct, LawStage.DidIt); + c.breakState = state.def.defName; + c.breakStartTick = start; + c.count = 0; + } + c.count++; + c.lastActTick = now; + c.notes |= act.notes; + c.matchedDef = act.def?.defName; + if (c.stage == LawStage.Planning) + c.stage = LawStage.DidIt; + if (c.victim == null && act.victim != null) + c.SetVictim(act.victim); + + if (c.didItLawId < 0 && !c.HasPunished(LawStage.DidIt)) + { + Law decider = breakRow; + if (own != null && (decider == null || own.severity > decider.severity)) + decider = own; + if (decider != null) + { + c.SetLaw(LawStage.DidIt, decider); + if (c.IsClosed) + { + // A planning case already closed (warned) while the break goes on: the did-it reopens it. + c.status = CaseStatus.Open; + c.outcome = null; + c.closeTick = -1; + } + Enforcement.Enqueue(c, LawStage.DidIt); + } + } + return c; + } + + private static LawCase ReportAct(GameComponent_BlaxLaws comp, ActEvent act, Law own) + { + int now = Now; + int window = BlaxLawsMod.S.CooldownTicks; + if (window > 0) + { + LawCase recent = comp.LatestActCaseOf(act.offender, own.id); + // An unresolved case takes every repeat, whatever its age (a held or waiting jail case gets no + // second case and no second letter). After it closes the window counts from its open tick, so + // frequent repeats can't push it out forever. + if (recent != null && (!recent.IsClosed || now - recent.openTick < window)) + { + recent.count++; + recent.lastActTick = now; + recent.notes |= act.notes; + return recent; + } + } + LawCase c = Open(own, act, LawStage.DidIt); + Enforcement.Enqueue(c, LawStage.DidIt); + return c; + } + } +} diff --git a/Source/BlaxLaws/Catalogue/ActCatalogue.cs b/Source/BlaxLaws/Catalogue/ActCatalogue.cs new file mode 100644 index 0000000..bb2ee31 --- /dev/null +++ b/Source/BlaxLaws/Catalogue/ActCatalogue.cs @@ -0,0 +1,266 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RimWorld; +using Verse; + +namespace BlaxLaws +{ + /// + /// Base class of the category workers (ActCategoryDef.workerClass). A worker walks its DefDatabase once + /// and returns the category's entries: one ActEntry.ForDef per def and one ActEntry.ForGroup per group, + /// groups in the order the picker shows them. It never reads the lawbook and keeps no state of a game. + /// + public class ActCategoryWorker + { + public ActCategoryDef def; + + /// Every entry of the category, def and group entries both. Default: none. + public virtual IEnumerable MakeEntries() + { + yield break; + } + + /// The category's tooltip in the picker. Default: the def's description. + public virtual string Tooltip => def?.description; + } + + /// + /// The act catalogue: every entry the loaded game has, by category (design: "The act catalogue is built + /// from the game's defs, saved as names"). Built once, on first use or at the first game start, from the + /// ActCategoryDefs' workers; never saved. The picker searches it; nothing else walks it. Lookups by key + /// are a dictionary read. + /// + public static class ActCatalogue + { + private static bool built; + private static bool building; + private static readonly List all = new List(); + private static readonly Dictionary byKey = new Dictionary(); + private static readonly Dictionary> byCategory = new Dictionary>(); + private static readonly List categories = new List(); + private static readonly List chemicalOptions = new List(); + private static readonly List Empty = new List(); + + /// Bumped on every build, for caches keyed on the catalogue. + public static int Version { get; private set; } + + public static bool Built => built; + + /// Every entry, category by category in picker order. + public static IReadOnlyList All + { + get + { + EnsureBuilt(); + return all; + } + } + + /// The categories in picker order. + public static IReadOnlyList Categories + { + get + { + EnsureBuilt(); + return categories; + } + } + + /// A category's entries: groups first, in the worker's order, then every def A to Z. + public static IReadOnlyList EntriesOf(string categoryId) + { + EnsureBuilt(); + return categoryId != null && byCategory.TryGetValue(categoryId, out List list) ? list : Empty; + } + + /// The entry for a key, or null when it is missing (a DLC or mod that isn't loaded, a typo). + public static ActEntry Get(string key) + { + if (key == null) + return null; + EnsureBuilt(); + byKey.TryGetValue(key, out ActEntry e); + return e; + } + + public static bool TryGet(string key, out ActEntry entry) + { + entry = Get(key); + return entry != null; + } + + /// The single-def entry of a def in a category, or null. + public static ActEntry EntryFor(string categoryId, Def def) => def == null ? null : Get(ActKey.Of(categoryId, def.defName)); + + /// The group behind a group key, or null. + public static ActGroup GroupOf(string key) => Get(key)?.group; + + /// + /// Drug options after Any, Hard and Social: the defName of every ChemicalDef a drug's + /// CompProperties_Drug names, A to Z by label. No other chemical is listed. + /// + public static IReadOnlyList ChemicalOptions + { + get + { + EnsureBuilt(); + return chemicalOptions; + } + } + + public static void EnsureBuilt() + { + if (!built && !building) + Build(); + } + + /// Builds the catalogue from the loaded defs. A worker that throws logs once and leaves its category empty. + public static void Build() + { + building = true; + try + { + all.Clear(); + byKey.Clear(); + byCategory.Clear(); + categories.Clear(); + chemicalOptions.Clear(); + BreakLinks.ClearCache(); + + categories.AddRange(DefDatabase.AllDefsListForReading.OrderBy(c => c.order).ThenBy(c => c.defName)); + foreach (ActCategoryDef cat in categories) + { + var list = new List(); + try + { + foreach (ActEntry e in cat.Worker.MakeEntries() ?? Enumerable.Empty()) + { + if (e == null || e.key.NullOrEmpty()) + continue; + if (e.categoryId != cat.defName) + { + LawsLog.WarningOnce("catalogue-category:" + e.key, "Catalogue entry " + e.key + " came from category " + cat.defName + "; skipped."); + continue; + } + if (byKey.ContainsKey(e.key)) + continue; + byKey[e.key] = e; + list.Add(e); + } + } + catch (Exception ex) + { + LawsLog.Once("Catalogue category " + cat.defName, ex); + } + Finish(cat, list); + byCategory[cat.defName] = list; + all.AddRange(list); + } + BuildChemicalOptions(); + Version++; + built = true; + } + finally + { + building = false; + } + } + + /// Drops the catalogue; the next read builds it again. Tests only. + public static void Reset() + { + built = false; + all.Clear(); + byKey.Clear(); + byCategory.Clear(); + categories.Clear(); + chemicalOptions.Clear(); + } + + /// Group sizes, the stage and break fields, and the picker order: groups first, defs A to Z. + private static void Finish(ActCategoryDef cat, List list) + { + List defs = list.Where(e => e.def != null).ToList(); + foreach (ActEntry g in list) + { + if (g.group == null) + continue; + g.group.size = g.group.IsAny ? defs.Count : defs.Count(d => SafeMatches(g.group, d.def)); + } + + bool breaks = cat.defName == ActCategories.Break; + foreach (ActEntry e in list) + { + if (!breaks) + { + e.hasPlanning = false; + e.hasDidIt = true; + continue; + } + e.hasPlanning = true; + e.links.Clear(); + if (e.def is MentalStateDef state) + { + BreakLinkDef link = BreakLinks.For(state); + if (link != null) + e.links.Add(link); + e.hostileBreak = BreakLinks.IsHostile(state); + } + else if (e.group != null) + { + bool anyMember = false, allHostile = true; + foreach (ActEntry d in defs) + { + if (!(d.def is MentalStateDef s) || !(e.group.IsAny || SafeMatches(e.group, s))) + continue; + anyMember = true; + if (!BreakLinks.IsHostile(s)) + allHostile = false; + BreakLinkDef link = BreakLinks.For(s); + if (link != null && !e.links.Contains(link)) + e.links.Add(link); + } + e.hostileBreak = anyMember && allHostile; + } + e.hasDidIt = e.links.Count > 0; + e.hasDrugOption = e.links.Any(l => l.usesDrugOption); + } + + List ordered = list.Where(e => e.group != null) + .Concat(list.Where(e => e.group == null).OrderBy(e => e.label, StringComparer.CurrentCultureIgnoreCase).ThenBy(e => e.key)) + .ToList(); + list.Clear(); + list.AddRange(ordered); + } + + private static bool SafeMatches(ActGroup g, Def def) + { + try + { + return g.MatchesDef(def); + } + catch (Exception ex) + { + LawsLog.Once("Catalogue group " + g.Key, ex); + return false; + } + } + + private static void BuildChemicalOptions() + { + var chems = new HashSet(); + foreach (ThingDef t in DefDatabase.AllDefsListForReading) + { + if (t.comps == null) + continue; + foreach (CompProperties c in t.comps) + { + if (c is CompProperties_Drug drug && drug.chemical != null) + chems.Add(drug.chemical); + } + } + chemicalOptions.AddRange(chems.OrderBy(c => c.label ?? c.defName, StringComparer.CurrentCultureIgnoreCase).Select(c => c.defName)); + } + } +} diff --git a/Source/BlaxLaws/Catalogue/ActEntry.cs b/Source/BlaxLaws/Catalogue/ActEntry.cs new file mode 100644 index 0000000..80cbd64 --- /dev/null +++ b/Source/BlaxLaws/Catalogue/ActEntry.cs @@ -0,0 +1,119 @@ +using System.Collections.Generic; +using Verse; + +namespace BlaxLaws +{ + /// + /// One entry of the act catalogue: a single def or a group. Built once per game start by ActCatalogue + /// from the category workers; never saved (rows save the key). The worker fills key, category, def or + /// group, label and source; ActCatalogue.Build fills the stage and break fields from the link table. + /// + public class ActEntry + { + /// "Ate/WakeUp" or "Ate/@hardDrugs". + public string key; + + public string categoryId; + + /// The def's defName, or the group id with its "@". + public string name; + + /// The def of a single entry; null for a group. + public Def def; + + /// The group of a group entry; null for a single def. + public ActGroup group; + + /// What the picker and the row show. + public string label; + + /// "Core", the DLC's name or the mod's name. + public string sourceMod; + + /// The source's package id, lower case. + public string sourcePackageId; + + /// Break entries: a planning stage (always, for a break). + public bool hasPlanning; + + /// A did-it stage: every entry outside the breaks, and a break with a link. + public bool hasDidIt = true; + + /// A break hostile to the colony (berserk): no Subdue. For a group: every member is hostile. + public bool hostileBreak; + + /// A drug binge entry: rows keep a drug option. + public bool hasDrugOption; + + /// Break entries: the links of the entry's breaks (one for a def, the distinct links of its members for a group). + public List links = new List(); + + public bool IsGroup => group != null; + + public bool IsBreak => categoryId == ActCategories.Break; + + /// Rank for "the most specific row wins": a single def 3, a group 2, the category's "any" 1. + public int Rank => def != null ? 3 : group != null && !group.IsAny ? 2 : 1; + + /// The stages the entry offers, planning first. + public IEnumerable Stages + { + get + { + if (hasPlanning) + yield return LawStage.Planning; + if (hasDidIt) + yield return LawStage.DidIt; + } + } + + public bool HasStage(LawStage stage) => stage == LawStage.Planning ? hasPlanning : hasDidIt; + + /// The stage a new row gets. + public LawStage FirstStage => hasPlanning ? LawStage.Planning : LawStage.DidIt; + + /// Whether the act is this entry's: the same def, or a member of the group. + public bool Matches(ActEvent act) + { + if (act == null || act.categoryId != categoryId) + return false; + if (group != null) + return group.Matches(act); + return act.def != null && (act.def == def || act.def.defName == name); + } + + // ---- builders for the category workers ------------------------------------------------- + + /// A single-def entry with the def's label and source mod. + public static ActEntry ForDef(string categoryId, Def def, string label = null) + { + return new ActEntry + { + key = ActKey.Of(categoryId, def.defName), + categoryId = categoryId, + name = def.defName, + def = def, + label = !label.NullOrEmpty() ? label : !def.label.NullOrEmpty() ? def.LabelCap.ToString() : def.defName, + sourceMod = DlcSupport.SourceName(def.modContentPack), + sourcePackageId = DlcSupport.SourcePackageId(def.modContentPack), + }; + } + + /// A group entry. Groups are Laws' own, so their source is Core. + public static ActEntry ForGroup(ActGroup group, string label = null) + { + return new ActEntry + { + key = group.Key, + categoryId = group.categoryId, + name = group.id, + group = group, + label = label.NullOrEmpty() ? group.Label : label, + sourceMod = DlcSupport.CoreName, + sourcePackageId = DlcSupport.CorePackageId, + }; + } + + public override string ToString() => key + " (" + label + ", " + sourceMod + ")"; + } +} diff --git a/Source/BlaxLaws/Catalogue/ActGroup.cs b/Source/BlaxLaws/Catalogue/ActGroup.cs new file mode 100644 index 0000000..bd19626 --- /dev/null +++ b/Source/BlaxLaws/Catalogue/ActGroup.cs @@ -0,0 +1,79 @@ +using System; +using Verse; + +namespace BlaxLaws +{ + /// + /// A group entry of a category ("Any drug binge", "Hard drugs", "Human meat", "Any surgery"). Groups are + /// predicates over defs, written once in code by the catalogue package; Watch expands a def-level group + /// into the set of defs it covers when the lawbook changes. A group that depends on the thing rather + /// than its def (a meal with human meat in it) sets DependsOnThing and overrides Matches(ActEvent); its + /// check then runs on every act of the category while the category is watched. + /// + public abstract class ActGroup + { + /// The category id. + public string categoryId; + + /// The group id with its "@" (ActGroups), unique within the category. + public string id; + + /// The Keyed key of the label ("BlaxLaws_Group_hardDrugs"). + public string labelKey; + + /// + /// Def entries of the category this group covers, set by ActCatalogue.Build. "The smaller group wins" + /// when two groups match one act. + /// + public int size; + + public string Key => ActKey.OfGroup(categoryId, id); + + /// The category's "any": every entry. The least specific row. + public bool IsAny => id == ActGroups.Any; + + /// The check needs the thing itself (ActEvent.facts or thing), not only the def. + public virtual bool DependsOnThing => false; + + public virtual string Label => labelKey.NullOrEmpty() ? id : labelKey.Translate().ToString(); + + /// + /// Whether a def of the category belongs to the group. For a DependsOnThing group: whether a thing of + /// this def could (a meal could hold meat); the act check decides. + /// + public abstract bool MatchesDef(Def def); + + /// Whether the act belongs to the group. Default: its def does. + public virtual bool Matches(ActEvent act) => IsAny || (act?.def != null && MatchesDef(act.def)); + } + + /// A group from two predicates, for the catalogue package's group lists. + public sealed class PredicateGroup : ActGroup + { + private readonly Func defPredicate; + private readonly Func actPredicate; + + /// Null for a def-level group; set for a group that reads the thing. + public PredicateGroup(string categoryId, string id, string labelKey, Func defPredicate, Func actPredicate = null) + { + this.categoryId = categoryId; + this.id = id.StartsWith(ActKey.GroupPrefix) ? id : ActKey.GroupPrefix + id; + this.labelKey = labelKey; + this.defPredicate = defPredicate ?? (_ => true); + this.actPredicate = actPredicate; + } + + public override bool DependsOnThing => actPredicate != null; + + public override bool MatchesDef(Def def) => def != null && defPredicate(def); + + public override bool Matches(ActEvent act) + { + if (IsAny) + return true; + if (act == null) + return false; + return actPredicate != null ? actPredicate(act) : act.def != null && defPredicate(act.def); + } + } +} diff --git a/Source/BlaxLaws/Catalogue/BlaxLawsActDefOf.cs b/Source/BlaxLaws/Catalogue/BlaxLawsActDefOf.cs new file mode 100644 index 0000000..1c6efed --- /dev/null +++ b/Source/BlaxLaws/Catalogue/BlaxLawsActDefOf.cs @@ -0,0 +1,18 @@ +using RimWorld; + +namespace BlaxLaws +{ + /// The special acts of the first release (Defs/BlaxLaws_Acts.xml), for the hooks that file them. + [DefOf] + public static class BlaxLawsActDefOf + { + public static ActDef SetFire; + public static ActDef DisplayedCorpse; + public static ActDef StartedSocialFight; + + static BlaxLawsActDefOf() + { + DefOfHelper.EnsureInitializedInCtor(typeof(BlaxLawsActDefOf)); + } + } +} diff --git a/Source/BlaxLaws/Catalogue/CatalogueDefs.cs b/Source/BlaxLaws/Catalogue/CatalogueDefs.cs new file mode 100644 index 0000000..1e79cc2 --- /dev/null +++ b/Source/BlaxLaws/Catalogue/CatalogueDefs.cs @@ -0,0 +1,230 @@ +using System; +using System.Collections.Generic; +using Verse; +using Verse.AI; + +namespace BlaxLaws +{ + /// + /// A category of the act catalogue (Defs/BlaxLaws_Categories.xml). The defName is the category id, the + /// first part of every act key, so it never changes. The worker reads the loaded defs once and returns + /// the category's entries. + /// + public class ActCategoryDef : Def + { + public Type workerClass = typeof(ActCategoryWorker); + + /// Picker order; lower first. + public int order; + + /// Def names the worker adds beyond its rule (Berserk for the breaks). + public List include = new List(); + + /// Def names the worker leaves out (animal and baby states, faction-level events). + public List exclude = new List(); + + /// + /// Break category only: mental state classes hostile to the colony, subclasses included (berserk). Their + /// entries never offer Subdue. Enforcement re-checks ForceHostileTo(Faction.OfPlayer) on the live + /// state, which wins over this list. + /// + public List hostileStateClasses = new List(); + + [Unsaved] + private ActCategoryWorker workerInt; + + public ActCategoryWorker Worker + { + get + { + if (workerInt == null) + { + workerInt = (ActCategoryWorker)Activator.CreateInstance(workerClass ?? typeof(ActCategoryWorker)); + workerInt.def = this; + } + return workerInt; + } + } + + public bool Includes(string defName) => include != null && include.Contains(defName); + + public bool Excludes(string defName) => exclude != null && exclude.Contains(defName); + + public override IEnumerable ConfigErrors() + { + foreach (string e in base.ConfigErrors()) + yield return e; + if (workerClass == null || !typeof(ActCategoryWorker).IsAssignableFrom(workerClass)) + yield return "workerClass must be an ActCategoryWorker"; + if (defName.IndexOf(ActKey.Separator) >= 0) + yield return "defName must not contain '" + ActKey.Separator + "': it is the first part of an act key"; + } + } + + /// + /// A special act with its own hook (Defs/BlaxLaws_Acts.xml): SetFire, DisplayedCorpse, StartedSocialFight in + /// the first release. The defName is the act's id in "Special/<defName>", so it never changes. Its + /// hook files it with an ActEvent whose def is this ActDef. + /// + public class ActDef : Def + { + public Type workerClass = typeof(ActWorker); + + /// Picker order inside "Special acts"; lower first, then A to Z. + public int order; + + [Unsaved] + private ActWorker workerInt; + + public ActWorker Worker + { + get + { + if (workerInt == null) + { + workerInt = (ActWorker)Activator.CreateInstance(workerClass ?? typeof(ActWorker)); + workerInt.def = this; + } + return workerInt; + } + } + + public string Key => ActKey.Of(ActCategories.Special, defName); + } + + /// + /// Behaviour of one special act beyond its hook. The first release needs none; the hook files the act. + /// Later acts (the violent ones, the uprisings) override what they need. + /// + public class ActWorker + { + public ActDef def; + + /// The tooltip the lawbook row shows, saying who counts as the offender. Default: the def's description. + public virtual string RowTooltip => def?.description; + } + + /// + /// A break's "Did it" (Defs/BlaxLaws_BreakLinks.xml): the act that counts, for a mental state class and its + /// subclasses. Another mod links its own break class with one of these and no code. + /// + public class BreakLinkDef : Def + { + /// The mental state class, subclasses included. + public Type stateClass; + + /// The linked act's key in another category: a single def ("Special/SetFire") or a group ("Ate/@anyDrug"). + public string act; + + /// The row's drug option filters the act (drug binges). + public bool usesDrugOption; + + public override IEnumerable ConfigErrors() + { + foreach (string e in base.ConfigErrors()) + yield return e; + if (stateClass == null || !typeof(MentalState).IsAssignableFrom(stateClass)) + yield return "stateClass must be a MentalState class"; + if (ActKey.CategoryOf(act) == null || ActKey.NameOf(act) == null) + yield return "act must be an act key such as Special/SetFire"; + if (ActKey.CategoryOf(act) == ActCategories.Break) + yield return "act must name an act outside the breaks"; + } + } + + /// Resolves the link of a mental state: the most derived linked class wins. + public static class BreakLinks + { + private static readonly Dictionary byClass = new Dictionary(); + private static readonly Dictionary hostileByClass = new Dictionary(); + + /// The link for a break, or null when its class has none (Planning only). + public static BreakLinkDef For(MentalStateDef state) => For(state?.stateClass); + + public static BreakLinkDef For(Type stateClass) + { + if (stateClass == null) + return null; + lock (byClass) + { + if (byClass.TryGetValue(stateClass, out BreakLinkDef cachedLink)) + return cachedLink; + } + BreakLinkDef best = null; + int bestDepth = -1; + foreach (BreakLinkDef link in DefDatabase.AllDefsListForReading) + { + if (link.stateClass == null || !link.stateClass.IsAssignableFrom(stateClass)) + continue; + int depth = Depth(link.stateClass); + if (depth > bestDepth) + { + best = link; + bestDepth = depth; + } + } + lock (byClass) byClass[stateClass] = best; + return best; + } + + /// + /// Whether the act is the link's act: same category and the link's def, or a member of the link's + /// group. The drug option is not checked here (Lawbook.BestRow checks it on the break row). + /// + public static bool Matches(BreakLinkDef link, ActEvent act) + { + if (link == null || act == null || act.def == null) + return false; + if (ActKey.CategoryOf(link.act) != act.categoryId) + return false; + string name = ActKey.NameOf(link.act); + if (!ActKey.IsGroup(link.act)) + return name == act.def.defName; + ActGroup group = ActCatalogue.GroupOf(link.act); + return group != null && group.Matches(act); + } + + /// A state hostile to the colony by its class (berserk), from the Break category's hostileStateClasses. + public static bool IsHostile(MentalStateDef state) + { + Type cls = state?.stateClass; + if (cls == null) + return false; + lock (hostileByClass) + { + if (hostileByClass.TryGetValue(cls, out bool h)) + return h; + } + bool hostile = false; + ActCategoryDef breaks = DefDatabase.GetNamedSilentFail(ActCategories.Break); + if (breaks?.hostileStateClasses != null) + { + foreach (Type t in breaks.hostileStateClasses) + { + if (t != null && t.IsAssignableFrom(cls)) + { + hostile = true; + break; + } + } + } + lock (hostileByClass) hostileByClass[cls] = hostile; + return hostile; + } + + /// Drops the caches (tests that add a link at runtime). + public static void ClearCache() + { + lock (byClass) byClass.Clear(); + lock (hostileByClass) hostileByClass.Clear(); + } + + private static int Depth(Type t) + { + int d = 0; + for (Type x = t; x != null; x = x.BaseType) + d++; + return d; + } + } +} diff --git a/Source/BlaxLaws/Catalogue/CatalogueGroups.cs b/Source/BlaxLaws/Catalogue/CatalogueGroups.cs new file mode 100644 index 0000000..29c8e57 --- /dev/null +++ b/Source/BlaxLaws/Catalogue/CatalogueGroups.cs @@ -0,0 +1,125 @@ +using System; +using System.Collections.Generic; +using RimWorld; +using Verse; +using Verse.AI; + +namespace BlaxLaws +{ + /// + /// The group entries of each category, in picker order (design: "Act catalogue and detection", the Groups + /// column). Labels are Keyed "BlaxLaws_Group_<id without @>"; the "any" group of a category is + /// "BlaxLaws_Group_any<Category>", since one id serves several categories. + /// + /// Def-level groups are expanded into Watch's set of watched defs. The meat groups that look into a meal's + /// ingredients read the thing (ActEvent.facts from hook C); their def check says which defs could match + /// (a meal could hold meat), which sets their size for "the smaller group wins". + /// + public static class CatalogueGroups + { + public static string LabelKey(string groupId) => "BlaxLaws_Group_" + (groupId.StartsWith(ActKey.GroupPrefix) ? groupId.Substring(1) : groupId); + + public static string AnyLabelKey(string categoryId) => "BlaxLaws_Group_any" + categoryId; + + /// Any break, any drug binge, any tantrum, any insulting spree, any aggressive break. + public static IEnumerable Break(string cat) + { + yield return new CatalogueAnyGroup(cat, AnyLabelKey(cat)); + yield return DefGroup(cat, ActGroups.AnyDrugBinge, d => StateIs(d, typeof(MentalState_BingingDrug))); + yield return DefGroup(cat, ActGroups.AnyTantrum, d => StateIs(d, typeof(MentalState_Tantrum))); + yield return DefGroup(cat, ActGroups.AnyInsultingSpree, d => StateIs(d, typeof(MentalState_InsultingSpree))); + yield return DefGroup(cat, ActGroups.AnyAggressive, d => d is MentalStateDef s && s.IsAggro); + } + + /// + /// Anything eaten (the food binge's link), the drug groups by ingestible.drugCategory, the meat groups, + /// raw food by preferability and any meal by the Meal food type. + /// + public static IEnumerable Ate(string cat) + { + yield return new CatalogueAnyGroup(cat, AnyLabelKey(cat)); + yield return DefGroup(cat, ActGroups.AnyDrug, d => d is ThingDef t && t.IsDrug); + yield return DefGroup(cat, ActGroups.HardDrugs, d => DrugInfo.CategoryOf(d as ThingDef) == DrugCategory.Hard); + yield return DefGroup(cat, ActGroups.SocialDrugs, d => DrugInfo.CategoryOf(d as ThingDef) == DrugCategory.Social); + yield return DefGroup(cat, ActGroups.MedicalDrugs, d => DrugInfo.CategoryOf(d as ThingDef) == DrugCategory.Medical); + yield return ThingGroup(cat, ActGroups.AnyMeat, ActFacts.Meat, + d => d is ThingDef t && (FoodUtility.GetFoodKind(t) == FoodKind.Meat || FoodFacts.HasIngredients(t))); + yield return DefGroup(cat, ActGroups.RawMeatOrCorpse, d => FoodFacts.IsRawMeatOrCorpse(d as ThingDef)); + yield return ThingGroup(cat, ActGroups.HumanMeat, ActFacts.HumanMeat, + d => d is ThingDef t && (FoodFacts.SourceIsHumanlike(t) || FoodFacts.HasIngredients(t))); + yield return ThingGroup(cat, ActGroups.InsectMeat, ActFacts.InsectMeat, + d => d is ThingDef t && (FoodFacts.SourceIsInsect(t) || FoodFacts.HasIngredients(t))); + yield return DefGroup(cat, ActGroups.RawFood, d => FoodFacts.IsRawFood(d as ThingDef)); + yield return DefGroup(cat, ActGroups.AnyMeal, d => FoodFacts.IsMeal(d as ThingDef)); + } + + /// Insult or slight: the two vanilla defs and any interaction whose worker is theirs or derives from it. + public static IEnumerable Interaction(string cat) + { + yield return DefGroup(cat, ActGroups.InsultOrSlight, IsInsultOrSlight); + } + + /// Any surgery (RecipeDef.IsSurgery, Verse/RecipeDef.cs:362). + public static IEnumerable Bill(string cat) + { + yield return DefGroup(cat, ActGroups.AnySurgery, d => d is RecipeDef r && r.IsSurgery); + } + + public static bool IsInsultOrSlight(Def d) + { + if (!(d is InteractionDef i)) + return false; + if (i == InteractionDefOf.Insult || i.defName == "Slight") + return true; + // workerClass is private; the worker is made once per def anyway (RimWorld/InteractionDef.cs:45-55). + InteractionWorker w = i.Worker; + return w is InteractionWorker_Insult || w is InteractionWorker_Slight; + } + + private static bool StateIs(Def d, Type stateClass) => + d is MentalStateDef s && s.stateClass != null && stateClass.IsAssignableFrom(s.stateClass); + + private static ActGroup DefGroup(string cat, string id, Func pred) => new PredicateGroup(cat, id, LabelKey(id), pred); + + private static ActGroup ThingGroup(string cat, string id, ActFacts fact, Func could) => + new PredicateGroup(cat, id, LabelKey(id), could, act => (FoodFacts.Of(act) & fact) != 0); + } + + /// + /// A category's "any": every def entry of the category, and nothing the catalogue left out (an "any + /// break" row never catches a social fight or a manhunter state). Rank 1, the least specific row. + /// Membership is a set of the category's defs, rebuilt when the catalogue is. + /// + public sealed class CatalogueAnyGroup : ActGroup + { + private HashSet members; + private int membersVersion = -1; + + public CatalogueAnyGroup(string categoryId, string labelKey) + { + this.categoryId = categoryId; + id = ActGroups.Any; + this.labelKey = labelKey; + } + + public override bool MatchesDef(Def def) + { + if (def == null) + return false; + if (members == null || membersVersion != ActCatalogue.Version) + { + var set = new HashSet(); + foreach (ActEntry e in ActCatalogue.EntriesOf(categoryId)) + { + if (e.def != null) + set.Add(e.def); + } + members = set; + membersVersion = ActCatalogue.Version; + } + return members.Contains(def); + } + + public override bool Matches(ActEvent act) => act?.def != null && (act.categoryId == null || act.categoryId == categoryId) && MatchesDef(act.def); + } +} diff --git a/Source/BlaxLaws/Catalogue/CatalogueRules.cs b/Source/BlaxLaws/Catalogue/CatalogueRules.cs new file mode 100644 index 0000000..5b18f5c --- /dev/null +++ b/Source/BlaxLaws/Catalogue/CatalogueRules.cs @@ -0,0 +1,210 @@ +using System; +using System.Collections.Generic; +using RimWorld; +using Verse; + +namespace BlaxLaws +{ + /// + /// The rules the category workers apply to the loaded defs (design: "Act catalogue and detection", How), + /// and the built-in include and exclude lists. The lists of an ActCategoryDef in XML add to the built-in + /// ones, so another mod can name its own states or events with no code. + /// + /// Checked against the 1.7 defs and decompiled code: + /// - Every MentalBreakDef names a colonist state (Core, Royalty, Ideology and Biotech + /// Defs/MentalStateDefs); animal, baby and mechanoid states come only from code (MentalStateDefOf.Manhunter, + /// Roaming, CocoonDisturbed, BerserkMechanoid; Biotech's baby fits). The exclude list guards against a + /// modded break naming one of them. Catatonic and RunWild name no state (MentalStates_Mood.xml), so no + /// hook ever sees them and they stay out. + /// - Time records never pass Increment or AddTo: they are added straight to the record map every 80 ticks + /// (RimWorld/Pawn_RecordsTracker.cs:60-70). + /// - Corpse defs carry an ingestible even for mechanoids (RimWorld/ThingDefGenerator_Corpses.cs:165-169), and + /// plants carry one for grazing animals; neither is anything a colonist eats. + /// + public static class CatalogueRules + { + /// + /// Break states colonists reach without a MentalBreakDef: berserk (pulsers, scaria, a refused arrest), the + /// trance berserk a pawn casts on itself, the warcall berserk, and states from hediffs. Hook A skips a state + /// another pawn's ability forced on the pawn (a psycast, Neuroquake), so those never file. A name that + /// isn't loaded (its DLC is off) is skipped. + /// + public static readonly string[] BreakInclude = + { + "Berserk", "BerserkPermanent", "BerserkWarcall", "BerserkTrance", "WanderConfused", "Wander_Psychotic_Short", + "CubeSculpting", "Terror", + }; + + /// + /// Animal, baby and mechanoid states, the panic flight of enemies (Verse.AI/MentalStateHandler.cs:207-214, + /// only for pawns outside the colony) and the social fight, which is the special act StartedSocialFight. + /// + public static readonly string[] BreakExclude = + { + "Manhunter", "ManhunterPermanent", "ManhunterBloodRain", "Roaming", "CocoonDisturbed", "BerserkMechanoid", + "Crying", "Giggling", "SocialFighting", "PanicFlee", + }; + + /// + /// Faction-level history events: goodwill, trade, quests, raids, charity and pollution reach a faction, + /// not a colonist (Core Defs/Goodwill, Ideology Precepts_Charity, Precepts_Raiders, Precepts_Relics, + /// Biotech HistoryEventDefs.xml). + /// + public static readonly string[] RecordedActExclude = + { + // Core Defs/Goodwill/GoodwillEvents_Diplomatic.xml + "GaveGift", "PeaceTalksBackfire", "PeaceTalksDisaster", "PeaceTalksSuccess", "PeaceTalksTriumph", "RequestedMilitaryAid", + "RequestedOrbitalTrader", "RequestedTrader", "Traded", + // GoodwillEvents_Misc.xml + "AttackedBuilding", "DebugGoodwill", "LaborersMissedShuttle", "ReachNaturalGoodwill", "RitualDone", "ShuttleDestroyed", + "UsedForbiddenThing", "UsedHarmfulAbility", + // GoodwillEvents_Pawns.xml + "AttackedMember", "FriendlyExitedMapTended", "GuiltyPrisonerDied", "InnocentPrisonerDied", "MemberCaptured", "MemberCrushed", + "MemberExitedMapHealthy", "MemberKilled", "MemberNeutrallyDied", "MemberSold", "MemberStripped", "PerformedHarmfulSurgery", + "PrisonerDied", "UsedHarmfulItem", "XenogermAbsorbed", + // GoodwillEvents_Quests.xml + "AcceptedDeserter", "FailedToKeepLodgersHappy", "MemberMissedShuttle", "MonumentConstructionExpired", + "MonumentConstructionMapRemoved", "MonumentDestroyed", "QuestGoodwillReward", "QuestPawnArrested", "QuestPawnLost", + "QuestPrisonerEnslaved", "QuestPrisonerRecruited", "ShuttleCommanderMissedShuttle", "ShuttleGuardsMissedShuttle", + // GoodwillEvents_World.xml + "AttackedCaravan", "AttackedSettlement", "DestroyedEnemyBase", "SettlementProximity", + // Core HistoryEventDefs.xml and Ideology Precepts_Charity.xml + "CharityRefused_ThreatReward_Joiner", "CharityFulfilled_Beggars", "CharityFulfilled_HospitalityRefugees", + "CharityFulfilled_IntroWimp", "CharityFulfilled_RefugeePodCrash", "CharityFulfilled_ShuttleCrashRescue", + "CharityFulfilled_ThreatReward_Joiner", "CharityFulfilled_WandererJoins", "CharityRefused_Beggars", "CharityRefused_Beggars_Betrayed", + "CharityRefused_HospitalityRefugees", "CharityRefused_IntroWimp", "CharityRefused_Pilgrims", "CharityRefused_Pilgrims_Betrayed", + "CharityRefused_RefugeePodCrash", "CharityRefused_ShuttleCrashRescue", "CharityRefused_WandererJoins", + // Ideology Precepts_Raiders.xml, Precepts_Proselytizing.xml, Precepts_Ranching.xml, Precepts_Relics.xml + "PlayerRaidedSomeone", "Raided", "Raided_BanditCamp", "Raided_WorkSite", "RelicHuntSuccess", "ReliquaryPilgrimsSuccess", + "HospitalitySuccess_Animals", "RelicDestroyed", "RelicLost", + // Biotech HistoryEventDefs.xml + "PollutedNearbySite", "PollutedBase", "ToxicWasteDumping", + }; + + private static readonly HashSet breakExclude = new HashSet(BreakExclude); + private static readonly HashSet recordedActExclude = new HashSet(RecordedActExclude); + + /// A def name the built-in list or the category's XML list leaves out. + public static bool Excluded(ActCategoryDef cat, string defName) + { + if (defName == null) + return true; + if (cat != null && cat.Excludes(defName)) + return true; + switch (cat?.defName) + { + case ActCategories.Break: return breakExclude.Contains(defName); + case ActCategories.RecordedAct: return recordedActExclude.Contains(defName); + default: return false; + } + } + + // ---- what each category holds --------------------------------------------------------- + + /// + /// Ate: anything with an ingestible a colonist can eat or drink. Plants (grazing) and the corpses of + /// races without flesh (mechanoids) are left out. + /// + public static bool IsEdible(ThingDef def) + { + if (def?.ingestible == null) + return false; + if (def.category == ThingCategory.Plant) + return false; + if (def.IsCorpse && def.ingestible.sourceDef?.race != null && !def.ingestible.sourceDef.race.IsFlesh) + return false; + return true; + } + + /// Used: a ThingDef whose comps hold a CompProperties_Usable (subclasses included). + public static bool IsUsable(ThingDef def) + { + if (def?.comps == null) + return false; + for (int i = 0; i < def.comps.Count; i++) + { + if (def.comps[i] is CompProperties_Usable) + return true; + } + return false; + } + + /// Records: Int and Float records count acts; Time records count time. + public static bool CountsActs(RecordDef def) => def != null && (def.type == RecordType.Int || def.type == RecordType.Float); + + // ---- building entries ---------------------------------------------------------------- + + /// + /// Single-def entries for the defs the rule found plus the include names, minus the exclude names, + /// each def once, with labels told apart (see Disambiguate). + /// + public static List EntriesFor(ActCategoryDef cat, IEnumerable byRule, IEnumerable builtInInclude = null) where T : Def + { + var defs = new List(); + var seen = new HashSet(); + void Take(T d) + { + if (d != null && !Excluded(cat, d.defName) && seen.Add(d)) + defs.Add(d); + } + + if (byRule != null) + { + foreach (T d in byRule) + Take(d); + } + if (builtInInclude != null) + { + foreach (string name in builtInInclude) + Take(DefDatabase.GetNamedSilentFail(name)); + } + if (cat?.include != null) + { + foreach (string name in cat.include) + Take(DefDatabase.GetNamedSilentFail(name)); + } + + var entries = new List(defs.Count); + foreach (T d in defs) + entries.Add(ActEntry.ForDef(cat.defName, d)); + Disambiguate(entries); + return entries; + } + + /// + /// Entries of one category that share a label (three states read "tantrum", two "binging on drug") + /// get the def's name in brackets, "Tantrum (Targeted Tantrum)". An entry whose def name reads as its + /// label keeps the plain label. The picker searches labels and def names, so both stay findable. + /// + public static void Disambiguate(List entries) + { + var byLabel = new Dictionary>(StringComparer.OrdinalIgnoreCase); + foreach (ActEntry e in entries) + { + if (e?.def == null || e.label == null) + continue; + if (!byLabel.TryGetValue(e.label, out List same)) + byLabel[e.label] = same = new List(); + same.Add(e); + } + foreach (List same in byLabel.Values) + { + if (same.Count < 2) + continue; + foreach (ActEntry e in same) + { + string readable = Readable(e.def.defName); + if (Squash(readable) == Squash(e.label)) + continue; + e.label = "BlaxLaws_CatalogueLabelWithName".Translate(e.label, readable); + } + } + } + + /// "Binging_DrugExtreme" to "Binging Drug Extreme". + public static string Readable(string defName) => + defName.NullOrEmpty() ? defName : GenText.SplitCamelCase(defName.Replace('_', ' ')).Replace(" ", " ").Trim(); + + private static string Squash(string s) => s == null ? "" : s.Replace(" ", "").Replace("-", "").ToLowerInvariant(); + } +} diff --git a/Source/BlaxLaws/Catalogue/FoodFacts.cs b/Source/BlaxLaws/Catalogue/FoodFacts.cs new file mode 100644 index 0000000..195d30d --- /dev/null +++ b/Source/BlaxLaws/Catalogue/FoodFacts.cs @@ -0,0 +1,178 @@ +using System; +using System.Collections.Generic; +using RimWorld; +using Verse; +using Verse.AI; + +namespace BlaxLaws +{ + /// + /// What a piece of food is, for the Ate groups that read the thing rather than its def (a meal with meat + /// in it, human meat as an ingredient). Hook C reads it in its prefix, before the stack can be destroyed, + /// and puts it into ActEvent.facts. Built on the game's own checks: + /// - meat: FoodUtility.GetFoodKind(Thing), which reads a meal's ingredients (RimWorld/FoodUtility.cs:1454-1486); + /// - human meat: FoodUtility.IsHumanlikeCorpseOrHumanlikeMeatOrIngredient (:1114-1129), as Thing.Ingested + /// uses it (Verse/Thing.cs:2033); + /// - insect meat: the meat's source race has insectoid flesh (FoodUtility.GetMeatSourceCategory, :1178-1197), + /// read for corpses and ingredients by FoodUtility.IsInsectCorpseOrInsectMeatIngredient (:1140-1159). + /// Meals carry the Meal food type (Core Defs/ThingDefs_Items/Items_Food.xml:36); the Processed food type + /// marks drugs and chocolate (Core Defs/Drugs), so "any meal" reads FoodTypeFlags.Meal, not IsProcessedFood. + /// + public static class FoodFacts + { + /// The facts of a real thing. Falls back to the def when the thing can't be read. + public static ActFacts Of(Thing food) + { + if (food?.def?.ingestible == null) + return ActFacts.None; + ThingDef def = food.def; + ActFacts f = OfDefOnly(def) & ~(ActFacts.Meat | ActFacts.HumanMeat | ActFacts.InsectMeat); + if (FoodUtility.GetFoodKind(food) == FoodKind.Meat) + f |= ActFacts.Meat; + if (FoodUtility.IsHumanlikeCorpseOrHumanlikeMeatOrIngredient(food)) + f |= ActFacts.HumanMeat; + if (FoodUtility.IsInsectCorpseOrInsectMeatIngredient(food)) + f |= ActFacts.InsectMeat; + return f; + } + + /// The facts a def alone gives: no ingredients, a corpse's race from its def. + public static ActFacts OfDefOnly(ThingDef def) + { + if (def?.ingestible == null) + return ActFacts.None; + ActFacts f = ActFacts.None; + if (FoodUtility.GetFoodKind(def) == FoodKind.Meat) + f |= ActFacts.Meat; + if (IsRawMeatOrCorpse(def)) + f |= ActFacts.RawMeatOrCorpse; + if (SourceIsHumanlike(def)) + f |= ActFacts.HumanMeat; + if (SourceIsInsect(def)) + f |= ActFacts.InsectMeat; + if (IsRawFood(def)) + f |= ActFacts.RawFood; + if (IsMeal(def)) + f |= ActFacts.Meal; + return f; + } + + /// + /// The facts of an act: the hook's, or read now from the thing (an act reported by other code), or + /// from the def. A thing that throws while read (a corpse already emptied) gives the def's facts. + /// + public static ActFacts Of(ActEvent act) + { + if (act == null) + return ActFacts.None; + if (act.facts != ActFacts.None) + return act.facts; + if (act.thing != null) + { + try + { + return Of(act.thing); + } + catch (Exception) + { + // A destroyed corpse has no inner pawn any more; the def still answers. + } + } + return OfDefOnly(act.def as ThingDef); + } + + public static bool IsRawMeatOrCorpse(ThingDef def) => def?.ingestible != null && !def.IsProcessedFood && (def.IsMeat || def.IsCorpse); + + public static bool IsRawFood(ThingDef def) => + def?.ingestible != null && (def.ingestible.preferability == FoodPreferability.RawBad || def.ingestible.preferability == FoodPreferability.RawTasty); + + public static bool IsMeal(ThingDef def) => def?.ingestible != null && (def.ingestible.foodType & FoodTypeFlags.Meal) != 0; + + /// The food can hold ingredients (meals, pemmican), so a thing of it may hold meat. + public static bool HasIngredients(ThingDef def) => def?.GetCompProperties() != null; + + /// Human meat or a humanlike corpse, by the def. + public static bool SourceIsHumanlike(ThingDef def) + { + if (def?.ingestible == null) + return false; + if (def.IsCorpse) + return def.ingestible.sourceDef?.race?.Humanlike ?? false; + return FoodUtility.GetMeatSourceCategory(def) == MeatSourceCategory.Humanlike; + } + + /// Insect meat or an insect corpse, by the def. + public static bool SourceIsInsect(ThingDef def) + { + if (def?.ingestible == null) + return false; + if (def.IsCorpse) + return def.ingestible.sourceDef?.race?.FleshType == FleshTypeDefOf.Insectoid; + return FoodUtility.GetMeatSourceCategory(def) == MeatSourceCategory.Insect; + } + } + + /// Drugs as the drug binge and its option see them. + public static class DrugInfo + { + private static Dictionary chemicalCategory; + + /// The chemical a drug def's CompProperties_Drug names, or null. + public static ChemicalDef ChemicalOf(ThingDef def) => def?.GetCompProperties()?.chemical; + + /// The drug category of a def; None for anything that isn't a drug. + public static DrugCategory CategoryOf(ThingDef def) => def?.ingestible?.drugCategory ?? DrugCategory.None; + + /// + /// The strongest category among the drugs carrying the chemical (wake-up: Hard; alcohol: Social), or + /// None when no loaded drug carries it. + /// + public static DrugCategory CategoryOfChemical(ChemicalDef chemical) + { + if (chemical == null) + return DrugCategory.None; + if (chemicalCategory == null) + { + var map = new Dictionary(); + foreach (ThingDef t in DefDatabase.AllDefsListForReading) + { + ChemicalDef c = ChemicalOf(t); + if (c == null) + continue; + DrugCategory cat = CategoryOf(t); + if (cat == DrugCategory.Any) + cat = DrugCategory.None; + if (!map.TryGetValue(c, out DrugCategory had) || Strength(cat) > Strength(had)) + map[c] = cat; + } + chemicalCategory = map; + } + return chemicalCategory.TryGetValue(chemical, out DrugCategory found) ? found : DrugCategory.None; + } + + /// + /// The category a binge's planning case counts under for the "hard" and "social" options. The state's + /// own category, unless vanilla set it to Any: an addict's binge, or one that found no drug of its + /// break's category (Verse.AI/MentalState_BingingDrug.cs:60-80). Then the chosen chemical decides. + /// + public static DrugCategory BingeCategory(MentalState_BingingDrug binge) + { + if (binge == null) + return DrugCategory.None; + if (binge.drugCategory == DrugCategory.Hard || binge.drugCategory == DrugCategory.Social || binge.drugCategory == DrugCategory.Medical) + return binge.drugCategory; + return CategoryOfChemical(binge.chemical); + } + + private static int Strength(DrugCategory c) + { + switch (c) + { + case DrugCategory.Hard: return 3; + case DrugCategory.Social: return 2; + case DrugCategory.Medical: return 1; + default: return 0; + } + } + } +} diff --git a/Source/BlaxLaws/Catalogue/Workers/ActCategoryWorkers.cs b/Source/BlaxLaws/Catalogue/Workers/ActCategoryWorkers.cs new file mode 100644 index 0000000..92a00b4 --- /dev/null +++ b/Source/BlaxLaws/Catalogue/Workers/ActCategoryWorkers.cs @@ -0,0 +1,97 @@ +using System.Collections.Generic; +using System.Linq; +using RimWorld; +using Verse; + +namespace BlaxLaws +{ + // The eight category workers (design: "Act catalogue and detection", How). Each walks its DefDatabase once + // per catalogue build and returns its group entries first, then one ActEntry.ForDef per def. ActCatalogue + // fills group sizes, stages, links and hostility, and sorts the defs A to Z. What each rule admits is in + // CatalogueRules, the groups in CatalogueGroups. + + /// + /// Mental breaks: every MentalStateDef a MentalBreakDef starts (mentalState), plus the built-in and XML + /// include lists (berserk and other states colonists reach without a break def), minus the exclude lists + /// (animal, baby and mechanoid states, the social fight). Groups: any break, any drug binge, any tantrum, + /// any insulting spree, any aggressive break. + /// + public class ActCategoryWorker_Break : ActCategoryWorker + { + public override IEnumerable MakeEntries() + { + var list = CatalogueGroups.Break(def.defName).Select(g => ActEntry.ForGroup(g)).ToList(); + IEnumerable fromBreaks = DefDatabase.AllDefsListForReading.Select(b => b.mentalState).Where(s => s != null); + list.AddRange(CatalogueRules.EntriesFor(def, fromBreaks, CatalogueRules.BreakInclude)); + return list; + } + } + + /// + /// Ate: every ThingDef with an ingestible a colonist can eat (CatalogueRules.IsEdible): food, meals, raw + /// food, corpses, drugs, modded and DLC ones. Groups: anything eaten, the drug groups, the meat groups, + /// raw food, any meal. + /// + public class ActCategoryWorker_Ate : ActCategoryWorker + { + public override IEnumerable MakeEntries() + { + var list = CatalogueGroups.Ate(def.defName).Select(g => ActEntry.ForGroup(g)).ToList(); + list.AddRange(CatalogueRules.EntriesFor(def, DefDatabase.AllDefsListForReading.Where(CatalogueRules.IsEdible))); + return list; + } + } + + /// Used: every ThingDef with a CompProperties_Usable (psytrainers, neurotrainers, mech serums, modded usables). No groups. + public class ActCategoryWorker_Used : ActCategoryWorker + { + public override IEnumerable MakeEntries() => + CatalogueRules.EntriesFor(def, DefDatabase.AllDefsListForReading.Where(CatalogueRules.IsUsable)); + } + + /// Social interactions: every InteractionDef. Group: insult or slight. + public class ActCategoryWorker_Interaction : ActCategoryWorker + { + public override IEnumerable MakeEntries() + { + var list = CatalogueGroups.Interaction(def.defName).Select(g => ActEntry.ForGroup(g)).ToList(); + list.AddRange(CatalogueRules.EntriesFor(def, DefDatabase.AllDefsListForReading)); + return list; + } + } + + /// + /// Recorded acts: every HistoryEventDef minus the faction-level ones (CatalogueRules.RecordedActExclude and + /// the XML list). No groups. Many are recorded only with Ideology active; the category tooltip says so. + /// + public class ActCategoryWorker_RecordedAct : ActCategoryWorker + { + public override IEnumerable MakeEntries() => + CatalogueRules.EntriesFor(def, DefDatabase.AllDefsListForReading); + } + + /// Records: every RecordDef with type Int or Float; Time records count time, not acts. No groups. + public class ActCategoryWorker_Record : ActCategoryWorker + { + public override IEnumerable MakeEntries() => + CatalogueRules.EntriesFor(def, DefDatabase.AllDefsListForReading.Where(CatalogueRules.CountsActs)); + } + + /// Bills: every RecipeDef. Group: any surgery. + public class ActCategoryWorker_Bill : ActCategoryWorker + { + public override IEnumerable MakeEntries() + { + var list = CatalogueGroups.Bill(def.defName).Select(g => ActEntry.ForGroup(g)).ToList(); + list.AddRange(CatalogueRules.EntriesFor(def, DefDatabase.AllDefsListForReading)); + return list; + } + } + + /// Special acts: every ActDef (Defs/BlaxLaws_Acts.xml), by order then A to Z. No groups. + public class ActCategoryWorker_Special : ActCategoryWorker + { + public override IEnumerable MakeEntries() => + CatalogueRules.EntriesFor(def, DefDatabase.AllDefsListForReading.OrderBy(a => a.order).ThenBy(a => a.label ?? a.defName)); + } +} diff --git a/Source/BlaxLaws/Compat.cs b/Source/BlaxLaws/Compat.cs new file mode 100644 index 0000000..f84d0d2 --- /dev/null +++ b/Source/BlaxLaws/Compat.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using Verse; + +namespace BlaxLaws +{ + /// + /// Shared mod detection. Laws has no hard dependency on any other mod. Sibling APIs (CastesApi, + /// SlavesApi) are bound by reflection into cached delegates at startup by the feature that needs them; + /// a missing sibling or member is a silent no-op. Package ids of mods a single feature reacts to live + /// in that feature's partial file of this class (Compat.PrisonLabor.cs and so on), each with the source + /// it was read from. + /// + /// Package ids of the Blax mods, from their own About/About.xml (2026-12-01). + /// + public static partial class Compat + { + public const string BlaxCastes = "blax.castes"; + public const string BlaxSlaves = "blax.slaves"; + public const string BlaxZones = "blax.zones"; + public const string BlaxDefaults = "blax.defaults"; + + /// + /// Package ids tests treat as active. Only tests write it; the runner clears it after every test. + /// + public static readonly HashSet SimulatedActive = new HashSet(StringComparer.OrdinalIgnoreCase); + + /// + /// Active by packageId, local or Steam copy, or simulated by a test. ModsConfig.IsActive misses a mod + /// that is installed both ways (the Steam copy gets a "_steam" postfix), so nothing in Blax Laws uses it. + /// + public static bool IsActive(string packageId) => + SimulatedActive.Contains(packageId) || ModLister.GetActiveModWithIdentifier(packageId, ignorePostfix: true) != null; + + public static bool CastesActive => IsActive(BlaxCastes); + + public static bool SlavesActive => IsActive(BlaxSlaves); + } +} diff --git a/Source/BlaxLaws/Detection/DetectionHooks.cs b/Source/BlaxLaws/Detection/DetectionHooks.cs new file mode 100644 index 0000000..946166e --- /dev/null +++ b/Source/BlaxLaws/Detection/DetectionHooks.cs @@ -0,0 +1,72 @@ +using System.Collections.Generic; +using RimWorld; +using Verse; +using Verse.AI; + +namespace BlaxLaws +{ + /// + /// The first release's detection hooks (design: "Detection: one postfix per act, quiet while the book is + /// empty"), one [HarmonyPatch] class per hook in this folder; BlaxLawsStartup applies them. Every hook reads + /// its Watch flag first, so an empty book costs one static field read per call; then Watch.MayMatch (one + /// set lookup); then it builds an ActEvent and calls CaseFiler.Report, all inside its own try/catch with + /// HookGuard.Fail. Hooks only record: CaseFiler queues, Enforcement punishes a tick later. + /// + /// | Hook | Target (decompiled 1.7) | Files | + /// |---|---|---| + /// | A | MentalStateHandler.TryStartMentalState, prefix and postfix (Verse.AI/MentalStateHandler.cs:91; undraft :141-144, PostStart :162, StopAll :165-172, return true :202) | Break, planning; skips states another pawn's ability caused | + /// | C | Thing.Ingested, prefix and postfix (Verse/Thing.cs:2005) | Ate, and a binge's dose | + /// | E | Pawn_InteractionsTracker.TryInteractWith, postfix (RimWorld/Pawn_InteractionsTracker.cs:176, true at :268) | Interaction | + /// | F | Pawn_InteractionsTracker.StartSocialFight, postfix (:373) | Special/StartedSocialFight | + /// | I | Verb_Ignite.TryCastShot, postfix (RimWorld/Verb_Ignite.cs:12) | Special/SetFire | + /// | J | MentalState_CorpseObsession.MentalStateTick, postfix (Verse.AI/MentalState_CorpseObsession.cs:18) | Special/DisplayedCorpse | + /// | U | CompUsable.UsedBy and every override, prefix, postfix and finalizer (RimWorld/CompUsable.cs:161) | Used | + /// | H | HistoryEventsManager.RecordEvent, postfix (RimWorld/HistoryEventsManager.cs:55) | RecordedAct | + /// | R | Pawn_RecordsTracker.Increment and AddTo, postfixes (RimWorld/Pawn_RecordsTracker.cs:72, 84) | Record | + /// | B | RecordsUtility.Notify_BillDone, postfix (RimWorld/RecordsUtility.cs:52) | Bill | + /// + /// None of the targets is a method of a few lines: A, C, E, H, U and B have loops, try blocks or dozens of + /// calls; F builds a message and starts two states; I and J are virtual overrides reached through a + /// virtual call; Increment and AddTo each build an error string on their failure path (about 80 bytes of + /// IL with five calls), above what the JIT inlines into a caller. + /// + public static class DetectionHooks + { + /// + /// The pawn acts on its own: one of the targets A, B or C of its current job is the thing. Vanilla + /// moves a job's target to the stack it carries (RimWorld/Toils_Ingest.cs:34; Verse.AI/Toils_Haul.cs:104) + /// and eats or uses the target (RimWorld/Toils_Ingest.cs:402, 428; RimWorld/JobDriver_UseItem.cs:95-96), + /// and a drink at a gathering spot is target C of the social relax job (RimWorld/JobDriver_SocialRelax.cs:75). + /// A doctor's dose, a warden or parent feeding someone and a doctor's serum run on the feeder's job + /// (RimWorld/Recipe_AdministerIngestible.cs:11, RimWorld/JobDriver_FoodFeedPatient.cs:78, + /// RimWorld/JobDriver_Feed.cs:47, RimWorld/Recipe_AdministerUsableItem.cs:15), so the eater's own job never + /// targets the thing. + /// + public static bool OnOwnJob(Pawn pawn, Thing thing) + { + if (thing == null) + return false; + Job job = pawn?.CurJob; + if (job == null) + return false; + return job.targetA.Thing == thing || job.targetB.Thing == thing || job.targetC.Thing == thing; + } + + /// A building whose def is a table (Verse/ThingDef.cs:1008) stands on the thing's cell. + public static bool OnTable(Thing thing) + { + if (thing == null || !thing.Spawned || thing.Map == null) + return false; + List here = thing.Position.GetThingList(thing.Map); + for (int i = 0; i < here.Count; i++) + { + if (here[i] != thing && here[i].def != null && here[i].def.IsTable) + return true; + } + return false; + } + + /// The corpse lies in a grave or sarcophagus (Verse.AI/CorpseObsessionMentalStateUtility.cs:46). + public static bool InGrave(Corpse corpse) => corpse?.ParentHolder is Building_Grave; + } +} diff --git a/Source/BlaxLaws/Detection/Hook_A_MentalState.cs b/Source/BlaxLaws/Detection/Hook_A_MentalState.cs new file mode 100644 index 0000000..549cb36 --- /dev/null +++ b/Source/BlaxLaws/Detection/Hook_A_MentalState.cs @@ -0,0 +1,99 @@ +using System; +using System.Runtime.CompilerServices; +using HarmonyLib; +using RimWorld; +using Verse; +using Verse.AI; + +namespace BlaxLaws +{ + /// + /// Hook A: a break starts (category Break, planning). Postfix on MentalStateHandler.TryStartMentalState + /// (Verse.AI/MentalStateHandler.cs:91), about 110 lines. The new state's PostStart has run at :162 before + /// `return true` at :202, so a drug binge has chosen its chemical (Verse.AI/MentalState_BingingDrug.cs:24-27) + /// and a corpse obsession its corpse (Verse.AI/MentalState_CorpseObsession.cs:41-45). The method undrafts + /// the pawn (:141-144) and, for most states, stops its job (:165-172) before the postfix runs. A state + /// another pawn's ability forced on the pawn files nothing, and a self-cast state is checked for the player + /// order in the prefix, before vanilla undrafts the pawn and stops its job. + /// + [HarmonyPatch(typeof(MentalStateHandler), nameof(MentalStateHandler.TryStartMentalState))] + public static class Patch_MentalStateHandler_TryStartMentalState + { + public const string Where = "hook A, MentalStateHandler.TryStartMentalState"; + + /// + /// A state the pawn starts on itself (a self-cast ability such as the Berserk trance: otherPawn is the pawn, + /// RimWorld/CompAbilityEffect_GiveMentalState.cs:59) is a player order when the pawn is drafted or on a + /// player-forced job. That has to be read here, before vanilla undrafts the pawn (Verse.AI/MentalStateHandler.cs:141-144) + /// and StopAll ends the cast job (:165-172). + /// + public static void Prefix(Pawn ___pawn, Pawn otherPawn, out bool __state) + { + __state = false; + if (!Watch.Break || otherPawn == null || otherPawn != ___pawn) + return; + __state = OrderedAtStart(___pawn); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static bool OrderedAtStart(Pawn pawn) + { + try + { + return Offenders.OnPlayerOrder(pawn); + } + catch (Exception e) + { + HookGuard.Fail(Where, e); + return false; + } + } + + public static void Postfix(MentalStateHandler __instance, Pawn ___pawn, MentalStateDef stateDef, Pawn otherPawn, bool __result, bool __state) + { + if (!Watch.Break || !__result) + return; + File(__instance, ___pawn, stateDef, otherPawn, __state); + } + + // The work, off the hot path: a method with a try block is never inlined, so the flag check above + // stays a static field read the patched method can inline. + [MethodImpl(MethodImplOptions.NoInlining)] + private static void File(MentalStateHandler __instance, Pawn ___pawn, MentalStateDef stateDef, Pawn otherPawn, bool orderedAtStart) + { + try + { + MentalState state = __instance.CurState; + // A state that ended inside its own start (no corpse to obsess over) files nothing. + if (state?.def == null || state.def != stateDef || !Watch.MayMatch(ActCategories.Break, state.def)) + return; + // Another pawn's ability forced the state on this one (a psycast, Neuroquake, a modded caster): the + // pawn did nothing. Only abilities and the social fight pass otherPawn, and the social fight is its own + // special act (hook F). + if (otherPawn != null && otherPawn != ___pawn) + return; + // A self-cast state on a player order (Berserk trance cast by the player) is exempt like any other order. + if (orderedAtStart && BlaxLawsMod.S.playerOrdersExempt) + return; + var act = new ActEvent(ActCategories.Break, state.def, ___pawn) { mentalState = state }; + if (state is MentalState_BingingDrug binge) + { + act.chemical = binge.chemical; + act.drugCategory = DrugInfo.BingeCategory(binge); + } + else if (state is MentalState_CorpseObsession obsession && DetectionHooks.InGrave(obsession.corpse)) + { + // Vanilla obsesses over buried corpses (Verse.AI/CorpseObsessionMentalStateUtility.cs:17-21), so + // the corpse is nearly always dug up; hook J keeps the note for the did-it. + act.notes |= CaseNotes.DugUp; + act.thing = obsession.corpse; + } + CaseFiler.Report(act); + } + catch (Exception e) + { + HookGuard.Fail(Where, e); + } + } + } +} diff --git a/Source/BlaxLaws/Detection/Hook_C_Ingested.cs b/Source/BlaxLaws/Detection/Hook_C_Ingested.cs new file mode 100644 index 0000000..8013356 --- /dev/null +++ b/Source/BlaxLaws/Detection/Hook_C_Ingested.cs @@ -0,0 +1,86 @@ +using System; +using System.Runtime.CompilerServices; +using HarmonyLib; +using RimWorld; +using Verse; + +namespace BlaxLaws +{ + /// + /// Hook C: a pawn eats or drinks (category Ate) and every dose of a drug binge, which reaches + /// CompDrug.PostIngested through this method (Verse/Thing.cs:2180; Verse/ThingWithComps.cs:767-774). Prefix + /// and postfix on Thing.Ingested (Verse/Thing.cs:2005). Toils_Ingest calls it once per meal with the job's + /// target as the eaten thing (RimWorld/Toils_Ingest.cs:402, 428). The prefix reads the facts while the + /// stack still exists (it may be destroyed at :2176-2179) and checks that the eater acts on its own job; + /// the postfix files, so an ingestion vanilla refuses (destroyed, not ingestible now, :2007-2016) files + /// nothing. + /// + [HarmonyPatch(typeof(Thing), nameof(Thing.Ingested))] + public static class Patch_Thing_Ingested + { + public const string Where = "hook C, Thing.Ingested"; + + /// What the prefix hands to the postfix. A struct: an empty book allocates nothing. + public struct State + { + public bool file; + public ActFacts facts; + public ChemicalDef chemical; + public DrugCategory drugCategory; + } + + public static void Prefix(Thing __instance, Pawn ingester, out State __state) + { + __state = default; + if (!Watch.Ate) + return; + __state = Read(__instance, ingester); + } + + // The work, off the hot path: a method with a try block is never inlined, so the flag check above + // stays a static field read the patched method can inline. + [MethodImpl(MethodImplOptions.NoInlining)] + private static State Read(Thing __instance, Pawn ingester) + { + State __state = default; + try + { + ThingDef def = __instance?.def; + if (def == null || ingester == null || __instance.Destroyed || !Watch.MayMatch(ActCategories.Ate, def)) + return default; + if (!Offenders.IsCovered(ingester) || !DetectionHooks.OnOwnJob(ingester, __instance)) + return default; + __state.facts = FoodFacts.Of(__instance); + __state.chemical = DrugInfo.ChemicalOf(def); + __state.drugCategory = DrugInfo.CategoryOf(def); + __state.file = true; + } + catch (Exception e) + { + __state = default; + HookGuard.Fail(Where, e); + } + return __state; + } + + public static void Postfix(Thing __instance, Pawn ingester, State __state) + { + if (!__state.file) + return; + try + { + CaseFiler.Report(new ActEvent(ActCategories.Ate, __instance.def, ingester) + { + thing = __instance, + facts = __state.facts, + chemical = __state.chemical, + drugCategory = __state.drugCategory, + }); + } + catch (Exception e) + { + HookGuard.Fail(Where, e); + } + } + } +} diff --git a/Source/BlaxLaws/Detection/Hook_EF_Interactions.cs b/Source/BlaxLaws/Detection/Hook_EF_Interactions.cs new file mode 100644 index 0000000..0bffab1 --- /dev/null +++ b/Source/BlaxLaws/Detection/Hook_EF_Interactions.cs @@ -0,0 +1,84 @@ +using System; +using System.Runtime.CompilerServices; +using HarmonyLib; +using RimWorld; +using Verse; + +namespace BlaxLaws +{ + /// + /// Hook E: a social interaction happens (category Interaction). Postfix on + /// Pawn_InteractionsTracker.TryInteractWith (RimWorld/Pawn_InteractionsTracker.cs:176), about 90 lines, + /// which returns true at :268 once the interaction took place. The offender is the initiator (the + /// tracker's pawn), the victim the recipient. Insults in a spree come through here (RimWorld/JobDriver_Insult.cs:34), + /// and so does the jailbreaker's talk: JobGiver_InducePrisonerToEscape gives a SparkJailbreak job + /// (RimWorld/JobGiver_InducePrisonerToEscape.cs:15-16) whose driver, JobDriver_SingleInteraction (Core + /// Defs/JobDefs/Jobs_Misc.xml:558-559), calls Toils_Interpersonal.Interact (RimWorld/Toils_Interpersonal.cs:292-301). + /// + [HarmonyPatch(typeof(Pawn_InteractionsTracker), nameof(Pawn_InteractionsTracker.TryInteractWith))] + public static class Patch_Pawn_InteractionsTracker_TryInteractWith + { + public const string Where = "hook E, Pawn_InteractionsTracker.TryInteractWith"; + + public static void Postfix(Pawn ___pawn, Pawn recipient, InteractionDef intDef, bool __result) + { + if (!Watch.Interaction || !__result) + return; + File(___pawn, recipient, intDef, __result); + } + + // The work, off the hot path: a method with a try block is never inlined, so the flag check above + // stays a static field read the patched method can inline. + [MethodImpl(MethodImplOptions.NoInlining)] + private static void File(Pawn ___pawn, Pawn recipient, InteractionDef intDef, bool __result) + { + try + { + if (intDef == null || !Watch.MayMatch(ActCategories.Interaction, intDef)) + return; + CaseFiler.Report(new ActEvent(ActCategories.Interaction, intDef, ___pawn) { victim = recipient }); + } + catch (Exception e) + { + HookGuard.Fail(Where, e); + } + } + } + + /// + /// Hook F: a social fight starts (Special/StartedSocialFight). Postfix on + /// Pawn_InteractionsTracker.StartSocialFight (RimWorld/Pawn_InteractionsTracker.cs:373): a message, two + /// TryStartMentalState calls and a tale. CheckSocialFightStart calls it on the recipient of an + /// interaction (:217, :355-371), so the offender is the tracker's pawn, the one who swings first, and the + /// provoker (otherPawn) is the victim. It files only when the fight really started for the offender. + /// + [HarmonyPatch(typeof(Pawn_InteractionsTracker), nameof(Pawn_InteractionsTracker.StartSocialFight))] + public static class Patch_Pawn_InteractionsTracker_StartSocialFight + { + public const string Where = "hook F, Pawn_InteractionsTracker.StartSocialFight"; + + public static void Postfix(Pawn ___pawn, Pawn otherPawn) + { + if (!Watch.StartedSocialFight) + return; + File(___pawn, otherPawn); + } + + // The work, off the hot path: a method with a try block is never inlined, so the flag check above + // stays a static field read the patched method can inline. + [MethodImpl(MethodImplOptions.NoInlining)] + private static void File(Pawn ___pawn, Pawn otherPawn) + { + try + { + if (___pawn == null || ___pawn.MentalStateDef != MentalStateDefOf.SocialFighting || BlaxLawsActDefOf.StartedSocialFight == null) + return; + CaseFiler.Report(new ActEvent(ActCategories.Special, BlaxLawsActDefOf.StartedSocialFight, ___pawn) { victim = otherPawn }); + } + catch (Exception e) + { + HookGuard.Fail(Where, e); + } + } + } +} diff --git a/Source/BlaxLaws/Detection/Hook_HRB_RecordsAndBills.cs b/Source/BlaxLaws/Detection/Hook_HRB_RecordsAndBills.cs new file mode 100644 index 0000000..5f89370 --- /dev/null +++ b/Source/BlaxLaws/Detection/Hook_HRB_RecordsAndBills.cs @@ -0,0 +1,171 @@ +using System; +using System.Runtime.CompilerServices; +using System.Collections.Generic; +using HarmonyLib; +using RimWorld; +using Verse; + +namespace BlaxLaws +{ + /// + /// Hook H: the game records an act with a doer (category RecordedAct). Postfix on + /// HistoryEventsManager.RecordEvent (RimWorld/HistoryEventsManager.cs:55-...), with a try block and two + /// record maps. The offender is the event's Doer argument; an event without a doer pawn files nothing. + /// Core records some events whatever DLC is on (ExecutedPrisoner, RimWorld/ThoughtUtility.cs:56; + /// IngestedDrug, RimWorld/CompDrug.cs:105; CutTree, RimWorld/Plant.cs:627; AteHumanMeat, Verse/Thing.cs:2041), + /// most others only behind ModsConfig.IdeologyActive. RecordEvent also runs for acts the player orders (an + /// execution); the player-order exemption reads the doer's job like every other hook. + /// + [HarmonyPatch(typeof(HistoryEventsManager), nameof(HistoryEventsManager.RecordEvent))] + public static class Patch_HistoryEventsManager_RecordEvent + { + public const string Where = "hook H, HistoryEventsManager.RecordEvent"; + + public static void Postfix(HistoryEvent historyEvent) + { + if (!Watch.RecordedAct) + return; + File(historyEvent); + } + + // The work, off the hot path: a method with a try block is never inlined, so the flag check above + // stays a static field read the patched method can inline. + [MethodImpl(MethodImplOptions.NoInlining)] + private static void File(HistoryEvent historyEvent) + { + try + { + HistoryEventDef def = historyEvent.def; + if (def == null || !Watch.MayMatch(ActCategories.RecordedAct, def)) + return; + if (!historyEvent.args.TryGetArg(HistoryEventArgsNames.Doer, out Pawn doer) || doer == null) + return; + historyEvent.args.TryGetArg(HistoryEventArgsNames.Victim, out Pawn victim); + CaseFiler.Report(new ActEvent(ActCategories.RecordedAct, def, doer) { victim = victim }); + } + catch (Exception e) + { + HookGuard.Fail(Where, e); + } + } + } + + /// + /// Hook R, first half: an Int record goes up by one (category Record). Postfix on + /// Pawn_RecordsTracker.Increment (RimWorld/Pawn_RecordsTracker.cs:72-82). The offender is the tracker's + /// pawn. Time records never come here: they are added to the record map directly (:60-70). + /// + [HarmonyPatch(typeof(Pawn_RecordsTracker), nameof(Pawn_RecordsTracker.Increment))] + public static class Patch_Pawn_RecordsTracker_Increment + { + public const string Where = "hook R, Pawn_RecordsTracker.Increment"; + + public static void Postfix(Pawn_RecordsTracker __instance, RecordDef def) + { + if (!Watch.Record) + return; + File(__instance, def); + } + + // The work, off the hot path: a method with a try block is never inlined, so the flag check above + // stays a static field read the patched method can inline. + [MethodImpl(MethodImplOptions.NoInlining)] + private static void File(Pawn_RecordsTracker __instance, RecordDef def) + { + try + { + // Increment changes only Int records (:74-81). + if (def == null || def.type != RecordType.Int || !Watch.MayMatch(ActCategories.Record, def)) + return; + CaseFiler.Report(new ActEvent(ActCategories.Record, def, __instance.pawn)); + } + catch (Exception e) + { + HookGuard.Fail(Where, e); + } + } + } + + /// + /// Hook R, second half: an Int or Float record goes up by a value (category Record). Postfix on + /// Pawn_RecordsTracker.AddTo (RimWorld/Pawn_RecordsTracker.cs:84-97). Files only when the record went up: + /// an Int record adds the rounded value (:88). + /// + [HarmonyPatch(typeof(Pawn_RecordsTracker), nameof(Pawn_RecordsTracker.AddTo))] + public static class Patch_Pawn_RecordsTracker_AddTo + { + public const string Where = "hook R, Pawn_RecordsTracker.AddTo"; + + public static void Postfix(Pawn_RecordsTracker __instance, RecordDef def, float value) + { + if (!Watch.Record) + return; + File(__instance, def, value); + } + + // The work, off the hot path: a method with a try block is never inlined, so the flag check above + // stays a static field read the patched method can inline. + [MethodImpl(MethodImplOptions.NoInlining)] + private static void File(Pawn_RecordsTracker __instance, RecordDef def, float value) + { + try + { + if (def == null || !Watch.MayMatch(ActCategories.Record, def)) + return; + bool up = def.type == RecordType.Int ? UnityEngine.Mathf.Round(value) >= 1f : def.type == RecordType.Float && value > 0f; + if (!up) + return; + CaseFiler.Report(new ActEvent(ActCategories.Record, def, __instance.pawn)); + } + catch (Exception e) + { + HookGuard.Fail(Where, e); + } + } + } + + /// + /// Hook B: a pawn finishes one iteration of a bill (category Bill). Postfix on RecordsUtility.Notify_BillDone + /// (RimWorld/RecordsUtility.cs:52-67), static, two nested loops. Toils_Recipe.FinishRecipeAndStartStoringProduct + /// calls it right after bill.Notify_IterationCompleted for every bill type, surgery and Biotech's mech + /// gestators included, always with the pawn that finished the bill (Verse.AI/Toils_Recipe.cs:197-200), and + /// nothing else calls it. The recipe is the doer's current job's (Verse.AI/Job.cs:197); a null files + /// nothing. A surgery names its patient as the victim. + /// + [HarmonyPatch(typeof(RecordsUtility), nameof(RecordsUtility.Notify_BillDone))] + public static class Patch_RecordsUtility_Notify_BillDone + { + public const string Where = "hook B, RecordsUtility.Notify_BillDone"; + + public static void Postfix(Pawn billDoer, List products) + { + if (!Watch.Bill) + return; + File(billDoer, products); + } + + // The work, off the hot path: a method with a try block is never inlined, so the flag check above + // stays a static field read the patched method can inline. + [MethodImpl(MethodImplOptions.NoInlining)] + private static void File(Pawn billDoer, List products) + { + try + { + RecipeDef recipe = billDoer?.CurJob?.RecipeDef; + if (recipe == null || !Watch.MayMatch(ActCategories.Bill, recipe)) + return; + var act = new ActEvent(ActCategories.Bill, recipe, billDoer); + // Bill_Medical.GiverPawn throws for a bill outside a pawn's bill stack (RimWorld/Bill_Medical.cs:72-85). + if (billDoer.CurJob.bill is Bill_Medical medical && medical.billStack?.billGiver is Pawn patient) + act.victim = patient; + if (products != null && products.Count > 0) + act.thing = products[0]; + CaseFiler.Report(act); + } + catch (Exception e) + { + HookGuard.Fail(Where, e); + } + } + } +} diff --git a/Source/BlaxLaws/Detection/Hook_IJ_FireAndCorpse.cs b/Source/BlaxLaws/Detection/Hook_IJ_FireAndCorpse.cs new file mode 100644 index 0000000..378877a --- /dev/null +++ b/Source/BlaxLaws/Detection/Hook_IJ_FireAndCorpse.cs @@ -0,0 +1,123 @@ +using System; +using System.Runtime.CompilerServices; +using HarmonyLib; +using RimWorld; +using Verse; +using Verse.AI; + +namespace BlaxLaws +{ + /// + /// Hook I: a pawn sets a fire (Special/SetFire). Postfix on Verb_Ignite.TryCastShot (RimWorld/Verb_Ignite.cs:12-22), + /// a protected override reached only through the virtual verb call (Verse/Verb.cs:462). The offender is + /// the caster, which FireUtility.TryStartFireIn gets as instigator (:16). Raiders ignite too + /// (RimWorld/TrashUtility.cs:97, 117); the offender filter in CaseFiler drops them. + /// + [HarmonyPatch(typeof(Verb_Ignite), "TryCastShot")] + public static class Patch_Verb_Ignite_TryCastShot + { + public const string Where = "hook I, Verb_Ignite.TryCastShot"; + + public static void Postfix(Verb_Ignite __instance, bool __result) + { + if (!Watch.SetFire || !__result) + return; + File(__instance, __result); + } + + // The work, off the hot path: a method with a try block is never inlined, so the flag check above + // stays a static field read the patched method can inline. + [MethodImpl(MethodImplOptions.NoInlining)] + private static void File(Verb_Ignite __instance, bool __result) + { + try + { + Pawn caster = __instance.CasterPawn; + if (caster == null || BlaxLawsActDefOf.SetFire == null) + return; + CaseFiler.Report(new ActEvent(ActCategories.Special, BlaxLawsActDefOf.SetFire, caster) { thing = __instance.CurrentTarget.Thing }); + } + catch (Exception e) + { + HookGuard.Fail(Where, e); + } + } + } + + /// + /// Hook J: a corpse obsession displays its corpse (Special/DisplayedCorpse). Postfix on + /// MentalState_CorpseObsession.MentalStateTick (Verse.AI/MentalState_CorpseObsession.cs:18-39), a virtual + /// override that runs only for obsessed pawns. The haul job's last, instant toil sets alreadyHauledCorpse + /// (RimWorld/JobDriver_HaulCorpseToPublicPlace.cs:82-95, the call at :90), so the hook sees the flag on + /// the obsession's next tick, after the haul job and its grave target are gone. + /// + /// The hook files when it saw the flag false and now sees it true. Vanilla saves the flag + /// (MentalState_CorpseObsession.cs:15), so after a load an obsession that already displayed its corpse is + /// never seen false and never files again; the "seen false" mark is unsaved and kept per live state. + /// While the flag is false it re-reads "dug up" for the current corpse on each tick, since vanilla may pick + /// another corpse (:26-28); a corpse carried out of its grave keeps the note. "On a table" is read from + /// the corpse's cell: 80% of drops go on a table (RimWorld/JobDriver_HaulCorpseToPublicPlace.cs:64, + /// TryFindTableCell :97-123). + /// + [HarmonyPatch(typeof(MentalState_CorpseObsession), nameof(MentalState_CorpseObsession.MentalStateTick))] + public static class Patch_MentalState_CorpseObsession_MentalStateTick + { + public const string Where = "hook J, MentalState_CorpseObsession.MentalStateTick"; + + private sealed class Seen + { + public bool unhauled; + public Corpse corpse; + public CaseNotes notes; + } + + private static readonly ConditionalWeakTable seen = new ConditionalWeakTable(); + + public static void Postfix(MentalState_CorpseObsession __instance) + { + if (!Watch.DisplayedCorpse) + return; + File(__instance); + } + + // The work, off the hot path: a method with a try block is never inlined, so the flag check above + // stays a static field read the patched method can inline. + [MethodImpl(MethodImplOptions.NoInlining)] + private static void File(MentalState_CorpseObsession __instance) + { + try + { + Pawn pawn = __instance.pawn; + // Recovered inside this tick: the state is gone from its pawn. + if (pawn == null || pawn.MentalState != __instance) + return; + Seen s = seen.GetValue(__instance, _ => new Seen()); + if (!__instance.alreadyHauledCorpse) + { + Corpse corpse = __instance.corpse; + if (corpse != s.corpse) + { + s.corpse = corpse; + s.notes = CaseNotes.None; + } + if (DetectionHooks.InGrave(corpse)) + s.notes |= CaseNotes.DugUp; + s.unhauled = true; + return; + } + if (!s.unhauled || BlaxLawsActDefOf.DisplayedCorpse == null) + return; + s.unhauled = false; + CaseNotes notes = s.notes; + Corpse shown = __instance.corpse; + if (DetectionHooks.OnTable(shown)) + notes |= CaseNotes.OnTable; + CaseFiler.Report(new ActEvent(ActCategories.Special, BlaxLawsActDefOf.DisplayedCorpse, pawn) { thing = shown, notes = notes }); + } + catch (Exception e) + { + HookGuard.Fail(Where, e); + } + } + } +} diff --git a/Source/BlaxLaws/Detection/Hook_U_UsedBy.cs b/Source/BlaxLaws/Detection/Hook_U_UsedBy.cs new file mode 100644 index 0000000..3baa790 --- /dev/null +++ b/Source/BlaxLaws/Detection/Hook_U_UsedBy.cs @@ -0,0 +1,101 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Runtime.CompilerServices; +using HarmonyLib; +using RimWorld; +using Verse; + +namespace BlaxLaws +{ + /// + /// Hook U: a pawn uses an item (category Used). Prefix, postfix and finalizer on CompUsable.UsedBy + /// (RimWorld/CompUsable.cs:161) and on every subclass that overrides it, found by reflection at startup + /// (in the game code only CompUseableDatacore, which calls base, RimWorld/CompUseableDatacore.cs:28-32). A + /// depth count makes an override that calls base file once. UsedBy returns with no effect when + /// CanBeUsedBy(p, false, true) refuses (:163-166), so the prefix asks the same question and files only + /// when it was accepted and the item is a target of the pawn's own job: JobDriver_UseItem uses its target + /// A (RimWorld/JobDriver_UseItem.cs:95-96) and IngestionOutcomeDoer_UseThing the ingested thing + /// (RimWorld/IngestionOutcomeDoer_UseThing.cs:10). A patient a doctor gives a healer mech serum + /// (RimWorld/Recipe_AdministerUsableItem.cs:15) lies in bed on its own job and files nothing. + /// + [HarmonyPatch] + public static class Patch_CompUsable_UsedBy + { + public const string Where = "hook U, CompUsable.UsedBy"; + + // __state: 0 the call isn't counted, 1 counted, 2 counted and files. + [ThreadStatic] + private static int depth; + + public static IEnumerable TargetMethods() + { + MethodInfo baseMethod = AccessTools.DeclaredMethod(typeof(CompUsable), nameof(CompUsable.UsedBy), new[] { typeof(Pawn) }); + if (baseMethod != null) + yield return baseMethod; + foreach (Type t in typeof(CompUsable).AllSubclasses()) + { + if (t.ContainsGenericParameters) + continue; + MethodInfo m = AccessTools.DeclaredMethod(t, nameof(CompUsable.UsedBy), new[] { typeof(Pawn) }); + if (m != null && !m.IsAbstract && m.GetMethodBody() != null) + yield return m; + } + } + + // The user is bound by position (__0): a modded override may name its parameter otherwise. + public static void Prefix(CompUsable __instance, Pawn __0, out int __state) + { + __state = 0; + if (!Watch.Used) + return; + depth++; + __state = 1; + if (depth == 1 && Files(__instance, __0)) + __state = 2; + } + + // The work, off the hot path: a method with a try block is never inlined, so the flag check above + // stays a static field read the patched method can inline. + [MethodImpl(MethodImplOptions.NoInlining)] + private static bool Files(CompUsable __instance, Pawn p) + { + try + { + ThingWithComps item = __instance?.parent; + if (p == null || item?.def == null || !Watch.MayMatch(ActCategories.Used, item.def)) + return false; + if (!Offenders.IsCovered(p) || !DetectionHooks.OnOwnJob(p, item)) + return false; + return __instance.CanBeUsedBy(p, forced: false, ignoreReserveAndReachable: true).Accepted; + } + catch (Exception e) + { + HookGuard.Fail(Where, e); + return false; + } + } + + public static void Postfix(CompUsable __instance, Pawn __0, int __state) + { + if (__state != 2) + return; + try + { + ThingWithComps item = __instance.parent; + CaseFiler.Report(new ActEvent(ActCategories.Used, item.def, __0) { thing = item }); + } + catch (Exception e) + { + HookGuard.Fail(Where, e); + } + } + + /// Balances the depth count even when UsedBy throws. Returns void, so other mods' stack traces stay whole. + public static void Finalizer(int __state) + { + if (__state != 0 && depth > 0) + depth--; + } + } +} diff --git a/Source/BlaxLaws/DlcSupport.cs b/Source/BlaxLaws/DlcSupport.cs new file mode 100644 index 0000000..ca9ec24 --- /dev/null +++ b/Source/BlaxLaws/DlcSupport.cs @@ -0,0 +1,117 @@ +using System; +using RimWorld; +using Verse; + +namespace BlaxLaws +{ + /// + /// Laws works with any DLC combination, core only included (design: "DLC support"). This class names + /// where a def comes from, says what a missing catalogue entry needs, and guards every read of DLC-only + /// pawn state behind ModsConfig.<DLC>Active. ModLister.Check<DLC> is an install check, not an + /// active check, and is never used. + /// + public static class DlcSupport + { + public const string CoreName = "Core"; + public const string CorePackageId = "ludeon.rimworld"; + private const string OfficialPrefix = "ludeon.rimworld."; + + /// The official DLCs by name, in release order. + public static readonly string[] DlcNames = { "Royalty", "Ideology", "Biotech", "Anomaly", "Odyssey" }; + + // ---- where a def comes from --------------------------------------------------------- + + /// "Core", the DLC's name ("Ideology") or the mod's name, as the catalogue shows it. + public static string SourceName(ModContentPack mod) + { + if (mod == null || mod.IsCoreMod) + return CoreName; + if (IsDlcPackageId(mod.PackageId)) + return DlcName(mod.PackageId); + return mod.Name.NullOrEmpty() ? mod.PackageIdPlayerFacing : mod.Name; + } + + /// The package id a catalogue entry saves with a row, lower case. Core for a def without a mod. + public static string SourcePackageId(ModContentPack mod) => mod?.PackageId ?? CorePackageId; + + /// True for "ludeon.rimworld.royalty" and the other official DLCs, false for Core and mods. + public static bool IsDlcPackageId(string packageId) => + !packageId.NullOrEmpty() && packageId.ToLowerInvariant().StartsWith(OfficialPrefix); + + /// "ludeon.rimworld.royalty" to "Royalty". + public static string DlcName(string packageId) + { + if (packageId.NullOrEmpty()) + return packageId; + string id = packageId.ToLowerInvariant(); + return (id.StartsWith(OfficialPrefix) ? id.Substring(OfficialPrefix.Length) : id).CapitalizeFirst(); + } + + /// + /// The official DLC a saved row's source names, by package id or by name ("Ideology"), or null for + /// Core and mods. + /// + public static string DlcOf(string savedMod, string savedPackageId) + { + if (IsDlcPackageId(savedPackageId)) + return DlcName(savedPackageId); + foreach (string dlc in DlcNames) + { + if (string.Equals(dlc, savedMod, StringComparison.OrdinalIgnoreCase)) + return dlc; + } + return null; + } + + /// Whether the official DLC of this name is active. False for an unknown name. + public static bool IsDlcActive(string dlcName) + { + switch (dlcName?.ToLowerInvariant()) + { + case "royalty": return ModsConfig.RoyaltyActive; + case "ideology": return ModsConfig.IdeologyActive; + case "biotech": return ModsConfig.BiotechActive; + case "anomaly": return ModsConfig.AnomalyActive; + case "odyssey": return ModsConfig.OdysseyActive; + default: return false; + } + } + + /// "Needs Ideology". + public static string NeedsText(string dlcName) => "BlaxLaws_NeedsDlc".Translate(dlcName); + + /// + /// What a row whose entry is missing shows: "Needs <DLC>" for a DLC source, else + /// "Missing: <mod>" (design: "A missing entry from a DLC shows Needs <DLC>"). + /// + public static string MissingText(string savedMod, string savedPackageId) + { + string dlc = DlcOf(savedMod, savedPackageId); + if (dlc != null) + return NeedsText(dlc); + string mod = !savedMod.NullOrEmpty() ? savedMod : !savedPackageId.NullOrEmpty() ? savedPackageId : CoreName; + return "BlaxLaws_MissingMod".Translate(mod); + } + + // ---- DLC-only pawn state, always behind the active check ------------------------------ + + /// A slave (Ideology). + public static bool IsSlave(Pawn p) => ModsConfig.IdeologyActive && p != null && p.IsSlave; + + /// A child, never beaten (Biotech). + public static bool IsChild(Pawn p) => ModsConfig.BiotechActive && p != null && p.DevelopmentalStage.Child(); + + /// Holds an ideoligion role, which an arrest takes (Ideology; Precept_Role.cs:582-585). + public static bool HoldsRole(Pawn p) => ModsConfig.IdeologyActive && p?.Ideo != null && p.Ideo.GetRole(p) != null; + + /// A mechanitor that controls mechs, which an arrest shuts down (Biotech; Pawn_GuestTracker.cs:536-539). + public static bool IsMechanitorWithMechs(Pawn p) => + ModsConfig.BiotechActive && p?.mechanitor != null && MechanitorUtility.IsMechanitor(p) && p.mechanitor.ControlledPawns.Count > 0; + + /// + /// Laws doesn't jail this pawn on its own while "Release gives back what jail took" isn't built or is + /// off: the case waits with "Arrest now" (design: "Jail for N days", hold). + /// + public static bool HeldForArrestNow(Pawn p) => HoldsRole(p) || IsMechanitorWithMechs(p); + } +} diff --git a/Source/BlaxLaws/Enforcement/CaseLetters.cs b/Source/BlaxLaws/Enforcement/CaseLetters.cs new file mode 100644 index 0000000..05ec48a --- /dev/null +++ b/Source/BlaxLaws/Enforcement/CaseLetters.cs @@ -0,0 +1,81 @@ +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using RimWorld; +using Verse; + +namespace BlaxLaws +{ + /// + /// Letters, only when a colonist is jailed or the player has to act: no prisoner bed, nobody to enforce, + /// a role holder or mechanitor waiting for "Arrest now" (setting "Letters for jailings"). Vanilla letter + /// defs only: Laws adds no Letter class and no LetterDef, so nothing of Laws enters the letter archive's + /// save (design: "Data model"). + /// + public static class CaseLetters + { + public const string KindNoEnforcer = "NoEnforcer"; + public const string KindNoBed = "NoBed"; + public const string KindHold = "Hold"; + + // Letters of each kind already sent per case in this session. Callers also send only when the + // case's saved wait reason changes, so a reload doesn't repeat a letter for the same wait. + private static readonly ConditionalWeakTable> sent = new ConditionalWeakTable>(); + + /// True the first time per case and kind in this session: one letter per wait, even when a case flips between waits. + public static bool Once(LawCase c, string kind) + { + if (c == null || kind == null) + return false; + return sent.GetOrCreateValue(c).Add(kind); + } + + /// Sends the letter when "Letters for jailings" is on. The keys take the args as {0}, {1}, ... + public static void Send(LawCase c, string labelKey, string textKey, LetterDef def, params NamedArgument[] args) + { + if (!BlaxLawsMod.S.jailLetters || Find.LetterStack == null) + return; + LookTargets targets = c?.offender != null && c.offender.Spawned ? new LookTargets(c.offender) : LookTargets.Invalid; + Find.LetterStack.ReceiveLetter(labelKey.Translate(args), textKey.Translate(args), def ?? LetterDefOf.NeutralEvent, targets); + } + + /// A letter when letters are on, else a case message (Messages for cases). + public static void SendOrPost(LawCase c, string labelKey, string textKey, LetterDef def, params NamedArgument[] args) + { + if (BlaxLawsMod.S.jailLetters) + Send(c, labelKey, textKey, def, args); + else + CaseMessages.Post(c, textKey.Translate(args)); + } + + /// + /// "Jailed: Bob" at the capture: the act, the sentence and the release day. A case message instead + /// while "Letters for jailings" is off. + /// + public static void Jailed(LawCase c) + { + if (c == null) + return; + int now = Find.TickManager?.TicksGame ?? 0; + int left = c.releaseTick >= 0 ? c.releaseTick - now : JailFlow.SentenceTicks(c); + SendOrPost(c, "BlaxLaws_LetterJailedLabel", "BlaxLaws_LetterJailedText", LetterDefOf.NeutralEvent, + c.OffenderLabel, left.ToStringTicksToPeriod(allowSeconds: false, shortForm: false, canUseDecimals: false), c.Label, Sentences.ReleaseDate(c)); + } + + /// The letter that the case waits because nobody can ever enforce it. + public static void NoEnforcer(LawCase c) => + Send(c, "BlaxLaws_LetterNoEnforcerLabel", "BlaxLaws_LetterNoEnforcerText", LetterDefOf.NegativeEvent, c.OffenderLabel, c.Label); + } + + /// Vanilla guilt (Pawn_GuiltTracker.cs:46-61), saved and counted down by the game. + public static class Guilt + { + /// Guilty for at least these ticks. A longer guilt already on the pawn is never shortened. + public static void AtLeast(Pawn p, int ticks) + { + if (p?.guilt == null || ticks <= 0) + return; + if (p.guilt.TicksUntilInnocent < ticks) + p.guilt.Notify_Guilty(ticks); + } + } +} diff --git a/Source/BlaxLaws/Enforcement/CaseMessages.cs b/Source/BlaxLaws/Enforcement/CaseMessages.cs new file mode 100644 index 0000000..93148a9 --- /dev/null +++ b/Source/BlaxLaws/Enforcement/CaseMessages.cs @@ -0,0 +1,31 @@ +using RimWorld; +using Verse; + +namespace BlaxLaws +{ + /// + /// Messages for cases (setting "Messages for cases"). Letters are the punishment workers' own, only when + /// a colonist is jailed or the player has to act (setting "Letters for jailings"); Laws never sends a + /// second letter for a break, since the vanilla break letter already arrives. + /// + public static class CaseMessages + { + /// One message when a stage's punishment is dispatched: "Bob broke a law: Wake-up (Did it). Punishment: jail." + public static void Filed(LawCase c, Law law, LawStage stage, PunishmentDef punishment) + { + if (c == null || law == null || !BlaxLawsMod.S.caseMessages) + return; + string text = "BlaxLaws_CaseFiled".Translate(c.OffenderLabel, law.Label, LawLabels.Stage(stage), punishment?.label ?? law.punishment); + Post(c, text); + } + + /// A message about the case, pointing at the offender while it is spawned. Does nothing with messages off. + public static void Post(LawCase c, string text, MessageTypeDef type = null) + { + if (!BlaxLawsMod.S.caseMessages || text.NullOrEmpty()) + return; + LookTargets target = c?.offender != null && c.offender.Spawned ? new LookTargets(c.offender) : LookTargets.Invalid; + Messages.Message(text, target, type ?? MessageTypeDefOf.NeutralEvent, historical: true); + } + } +} diff --git a/Source/BlaxLaws/Enforcement/Enforcement.cs b/Source/BlaxLaws/Enforcement/Enforcement.cs new file mode 100644 index 0000000..d5f637f --- /dev/null +++ b/Source/BlaxLaws/Enforcement/Enforcement.cs @@ -0,0 +1,269 @@ +using System; +using System.Collections.Generic; +using Verse; + +namespace BlaxLaws +{ + /// + /// The enforcement queue (design: "Enforcement runs a tick later"). CaseFiler queues (case, stage) + /// entries from inside hooks; GameComponent_BlaxLaws.GameComponentTick drains them on a later tick, so + /// nothing acts inside a status change, an ingestion or an interaction. Every 250 ticks a sweep walks + /// the open cases only; every 2500 ticks the jailed ones. Nothing scans all pawns. + /// + /// Not saved: entries refer to cases by id, and Refill rebuilds the queue from the cases after a load + /// (a stage with a row whose punishment never ran, a "Maintain only" write still owed). + /// + public static class Enforcement + { + public const int SweepInterval = 250; + public const int SentenceInterval = 2500; + + /// Ticks after the capture the "Maintain only" write lands (design: "Jail for N days"). + public const int MaintainOnlyDelay = 2; + + private struct Entry + { + public int caseId; + public CaseTask task; + public LawStage stage; + public int dueTick; + } + + private static readonly List queue = new List(); + private static readonly List due = new List(); + + /// Entries waiting. The component's tick returns at once while this is 0 and no case exists. + public static int Pending => queue.Count; + + /// Queues the stage's punishment for the next tick. + public static void Enqueue(LawCase c, LawStage stage) => Schedule(c, CaseTask.Punish, stage, 1); + + /// Queues a task for the case, delayTicks from now (at least 1). + public static void Schedule(LawCase c, CaseTask task, LawStage stage, int delayTicks) + { + if (c == null) + return; + int now = Find.TickManager?.TicksGame ?? 0; + queue.Add(new Entry { caseId = c.id, task = task, stage = stage, dueTick = now + Math.Max(1, delayTicks) }); + } + + /// Whether a task for the case is waiting. + public static bool IsQueued(LawCase c, CaseTask task) + { + if (c == null) + return false; + foreach (Entry e in queue) + { + if (e.caseId == c.id && e.task == task) + return true; + } + return false; + } + + /// Drops every entry: a new game or a load. Then Refill. + public static void Reset() => queue.Clear(); + + /// + /// After a load: queues each stage that has a row and never ran, and each "Maintain only" still owed + /// after a capture. Cases in Enforcing need nothing here; the 250-tick sweep re-issues their jobs. + /// + public static void Refill(GameComponent_BlaxLaws comp) + { + if (comp == null) + return; + foreach (LawCase c in comp.Cases) + { + if (c.IsClosed) + continue; + foreach (LawStage s in new[] { LawStage.Planning, LawStage.DidIt }) + { + if (c.LawIdFor(s) > 0 && !c.HasPunished(s)) + Enqueue(c, s); + } + if (c.status == CaseStatus.Jailed && c.captureTick >= 0 && !c.maintainOnlyDone) + Schedule(c, CaseTask.MaintainOnly, c.activeStage, 1); + } + } + + /// One game tick: due entries, then the sweeps. + internal static void Tick(GameComponent_BlaxLaws comp) + { + int now = Find.TickManager.TicksGame; + if (queue.Count > 0) + Drain(comp, now); + if (now % SweepInterval == 0) + Sweep(comp); + if (now % SentenceInterval == 0) + SentenceSweep(comp); + } + + private static void Drain(GameComponent_BlaxLaws comp, int now) + { + due.Clear(); + for (int i = 0; i < queue.Count; i++) + { + if (queue[i].dueTick <= now) + due.Add(queue[i]); + } + if (due.Count == 0) + return; + queue.RemoveAll(e => e.dueTick <= now); + foreach (Entry e in due) + { + LawCase c = comp.CaseById(e.caseId); + if (c == null) + continue; + try + { + switch (e.task) + { + case CaseTask.Punish: + Dispatch(comp, c, e.stage); + break; + case CaseTask.MaintainOnly: + Sentences.WriteMaintainOnly(c); + break; + } + } + catch (Exception ex) + { + HookGuard.Fail("Enforcement " + e.task, ex); + } + } + } + + /// + /// Dispatches the case's queued punish entries whose punishment passes the filter now instead of next + /// tick, so a case about to close still carries out a stage filed in the same tick (a did-it Guilty, + /// Warn or Subdue filed during the subdue). Returns whether one ran. + /// + internal static bool DispatchNow(LawCase c, Func filter) + { + GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance; + if (c == null || comp == null || queue.Count == 0) + return false; + List now = null; + for (int i = 0; i < queue.Count; i++) + { + Entry e = queue[i]; + if (e.caseId != c.id || e.task != CaseTask.Punish || c.HasPunished(e.stage)) + continue; + PunishmentDef p = c.LawFor(e.stage)?.PunishmentDef; + if (p != null && filter(p)) + (now ?? (now = new List())).Add(e); + } + if (now == null) + return false; + queue.RemoveAll(e => now.Contains(e)); + foreach (Entry e in now) + { + try + { + Dispatch(comp, c, e.stage); + } + catch (Exception ex) + { + HookGuard.Fail("Enforcement " + e.task, ex); + } + } + return true; + } + + /// Starts the stage's punishment: once per stage, with a message, handing over from an unfinished earlier one. + private static void Dispatch(GameComponent_BlaxLaws comp, LawCase c, LawStage stage) + { + if (c.IsClosed || c.HasPunished(stage)) + return; + Law law = c.LawFor(stage); + if (law == null) + return; + c.MarkPunished(stage); + PunishmentDef p = law.PunishmentDef; + CaseMessages.Filed(c, law, stage, p); + if (!BlaxLawsMod.S.enforceLaws) + { + // "Enforce laws" off: the case log runs, nothing is carried out. + if (c.activePunishment == null) + comp.CloseCase(c, CaseOutcomes.NotEnforced); + return; + } + if (p == null) + { + LawsLog.WarningOnce("punishment:" + law.punishment, "Law " + law.id + " names the punishment " + law.punishment + ", which isn't loaded; its cases are only listed."); + return; + } + if (!p.runsAlongside) + { + PunishmentDef active = ActiveOf(c); + if (active != null && active != p && !c.IsClosed) + active.Worker.Stop(c); + c.activePunishment = p.defName; + c.activeStage = stage; + } + p.Worker.Start(c, law, stage); + } + + /// The case's running punishment, or null. + public static PunishmentDef ActiveOf(LawCase c) => + c == null || c.activePunishment.NullOrEmpty() ? null : DefDatabase.GetNamedSilentFail(c.activePunishment); + + /// + /// Every 250 ticks: closes planning cases whose break ended with nothing done, closes cases whose + /// offender is gone, and lets each active punishment retry and re-issue. + /// + private static void Sweep(GameComponent_BlaxLaws comp) + { + if (!comp.AnyOpenCase) + return; + foreach (LawCase c in comp.OpenCases()) + { + try + { + if (c.offender == null || LawCase.IsGone(c.offender)) + { + if (c.status != CaseStatus.Jailed) + comp.CloseCase(c, CaseOutcomes.OffenderGone); + continue; + } + PunishmentDef active = ActiveOf(c); + if (active == null && c.status == CaseStatus.Open && c.IsBreakCase && c.stage == LawStage.Planning && + !IsQueued(c, CaseTask.Punish) && !CaseFiler.StillInBreak(c)) + { + comp.CloseCase(c, CaseOutcomes.BreakEnded); + continue; + } + if (active != null && c.status != CaseStatus.Jailed) + active.Worker.Sweep(c); + } + catch (Exception ex) + { + HookGuard.Fail("Enforcement sweep", ex); + } + } + } + + /// Every 2500 ticks: the sentence check of each jailed case. + private static void SentenceSweep(GameComponent_BlaxLaws comp) + { + if (!comp.AnyOpenCase) + return; + foreach (LawCase c in comp.OpenCases()) + { + if (c.status != CaseStatus.Jailed) + continue; + try + { + PunishmentDef active = ActiveOf(c); + if (active != null) + active.Worker.SentenceSweep(c); + else + Sentences.Check(c); + } + catch (Exception ex) + { + HookGuard.Fail("Sentence sweep", ex); + } + } + } + } +} diff --git a/Source/BlaxLaws/Enforcement/EnforcerJobs.cs b/Source/BlaxLaws/Enforcement/EnforcerJobs.cs new file mode 100644 index 0000000..d8c0951 --- /dev/null +++ b/Source/BlaxLaws/Enforcement/EnforcerJobs.cs @@ -0,0 +1,96 @@ +using RimWorld; +using Verse; +using Verse.AI; + +namespace BlaxLaws +{ + /// + /// Starting, finding and ending the enforcer's jobs. Laws starts its jobs at once, interrupting what the + /// enforcer does, with playerForced set (design: "Enforcement runs a tick later"), and never queues a + /// job of its own; the one job it queues is the vanilla Capture after a subdue. + /// + public static class EnforcerJobs + { + /// + /// Starts the job now: StartJob with InterruptForced and preToilReservationsCanFail, so a reservation + /// that fails ends the job quietly instead of logging (Pawn_JobTracker.cs:252, 373-375). Returns + /// whether the job runs. + /// + public static bool Start(Pawn enforcer, Job job) + { + if (enforcer?.jobs == null || job == null) + return false; + job.playerForced = true; + enforcer.jobs.StartJob(job, JobCondition.InterruptForced, null, resumeCurJobAfterwards: false, cancelBusyStances: true, + null, JobTag.Misc, fromQueue: false, canReturnCurJobToPool: false, keepCarryingThingOverride: null, continueSleeping: false, + addToJobsThisTick: true, preToilReservationsCanFail: true); + return enforcer.CurJob == job; + } + + /// A subdue, arrest or capture job on this offender. + public static bool IsEnforcementJob(Job job, Pawn offender) + { + if (job?.def == null || offender == null || job.targetA.Thing != offender) + return false; + return job.def == BlaxLawsDefOf.BlaxLaws_Subdue || job.def == JobDefOf.Arrest || job.def == JobDefOf.Capture; + } + + /// The pawn's current job is this def on this target. + public static bool Runs(Pawn pawn, JobDef def, Pawn target) + { + Job job = pawn?.CurJob; + return job != null && job.def == def && target != null && job.targetA.Thing == target; + } + + /// A job of this def on this target waits in the pawn's queue. + public static bool Queued(Pawn pawn, JobDef def, Pawn target) + { + JobQueue queue = pawn?.jobs?.jobQueue; + if (queue == null || target == null) + return false; + for (int i = 0; i < queue.Count; i++) + { + Job job = queue[i]?.job; + if (job != null && job.def == def && job.targetA.Thing == target) + return true; + } + return false; + } + + /// The pawn runs or has queued an Arrest or Capture of the target. + public static bool TakesToJail(Pawn pawn, Pawn target) => + pawn != null && target != null && !pawn.Dead && + (Runs(pawn, JobDefOf.Arrest, target) || Runs(pawn, JobDefOf.Capture, target) || + Queued(pawn, JobDefOf.Capture, target) || Queued(pawn, JobDefOf.Arrest, target)); + + /// + /// Ends the pawn's job of this def on this target, current or queued. Returns whether one ended. The pawn + /// starts no new job here: a hand-over (Enforcement.Dispatch stops the earlier punishment, then starts the + /// next) must find its enforcer free, and the think tree would hand it any job at once, Ingest, Reading + /// or ClearSnow among them, which aren't casually interruptible, so the pick would pass it over. A pawn + /// left without a job gets one from the think tree on its next job tick (Pawn_JobTracker.cs:195-202). + /// + public static bool End(Pawn pawn, JobDef def, Pawn target) + { + if (pawn?.jobs == null || def == null || target == null) + return false; + bool ended = false; + JobQueue queue = pawn.jobs.jobQueue; + for (int i = queue.Count - 1; i >= 0; i--) + { + Job job = queue[i]?.job; + if (job != null && job.def == def && job.targetA.Thing == target) + { + pawn.jobs.EndCurrentOrQueuedJob(job, JobCondition.InterruptForced); + ended = true; + } + } + if (Runs(pawn, def, target)) + { + pawn.jobs.EndCurrentJob(JobCondition.InterruptForced, startNewJob: false); + ended = true; + } + return ended; + } + } +} diff --git a/Source/BlaxLaws/Enforcement/Enforcers.cs b/Source/BlaxLaws/Enforcement/Enforcers.cs new file mode 100644 index 0000000..cc10cf2 --- /dev/null +++ b/Source/BlaxLaws/Enforcement/Enforcers.cs @@ -0,0 +1,208 @@ +using System.Collections.Generic; +using RimWorld; +using Verse; +using Verse.AI; +using Verse.AI.Group; + +namespace BlaxLaws +{ + /// What the enforcer must be able to do. + public enum EnforcerNeed + { + /// Violence (subdue). + Subdue, + /// Manipulation (arrest, capture). + Arrest, + /// Both: "Subdue then jail" beats the pawn down and carries it to the prisoner bed. + SubdueAndArrest, + } + + /// + /// Who enforces and when nobody may be sent (design: "Enforcement runs a tick later", enforcer pick and + /// danger). Runs only when a case is dispatched or swept, never per tick, and walks only the free + /// colonists of the offender's map. + /// + /// The pick: free non-slave adult colonists on the offender's map, awake, not downed, not in a mental + /// state, not drafted, no player-forced job, no lord (parties, rituals, caravans forming), not the + /// offender and not the victim a murderous rage names. Never pulled off a job that must not be dropped: + /// a job that isn't casually interruptible (in Core: Rescue, Capture, Arrest, TendPatient, BeatFire, + /// ExtinguishSelf, ManTurret, DeliverToBed, LayDown), carrying a pawn (PawnUtility.cs:115), fleeing + /// (Flee, FleeAndCower) or surgery (a DoBill whose recipe IsSurgery, RecipeDef.cs:362). Wardens first + /// (Warden work active), then anyone able unless the setting is "Wardens only"; nearest by straight + /// distance among those that can reach the offender. The case's own enforcer goes first when it is still + /// free, so a later stage hands over to the same pawn. + /// + public static class Enforcers + { + private struct Candidate + { + public Pawn pawn; + public bool warden; + public float distSq; + } + + private static readonly List tmp = new List(); + + /// The enforcer for the case, or null when nobody can go now (the case waits for the sweep). + public static Pawn Pick(LawCase c, EnforcerNeed need) => Pick(c, need, out _); + + /// The enforcer, or null with WaitReasons.NoEnforcer (nobody able at all) or Busy (nobody free now). + public static Pawn Pick(LawCase c, EnforcerNeed need, out string waitReason) + { + Pawn offender = c?.offender; + if (offender == null || !offender.Spawned || offender.Map == null) + { + waitReason = WaitReasons.Away; + return null; + } + return PickFrom(c, need, offender.Map.mapPawns.FreeColonistsSpawned, out waitReason); + } + + /// The pick over the given candidates (the map's free colonists in the game; a fixed list in tests). + public static Pawn PickFrom(LawCase c, EnforcerNeed need, IEnumerable candidates, out string waitReason) + { + waitReason = null; + Pawn offender = c?.offender; + if (offender == null || !offender.Spawned) + { + waitReason = WaitReasons.Away; + return null; + } + bool wardensOnly = BlaxLawsMod.S.enforcers == EnforcerMode.WardensOnly; + + // Hand-over: a later stage keeps the pawn that already acts for the case. + Pawn own = c.enforcer; + if (own != null && own.Spawned && own.Map == offender.Map && IsAble(own, offender, need, wardensOnly) && + IsFree(own, c) && own.CanReach(offender, PathEndMode.Touch, Danger.Deadly)) + return own; + + int able = 0; + tmp.Clear(); + try + { + foreach (Pawn p in candidates) + { + if (p == null || p.Map != offender.Map || !IsAble(p, offender, need, wardensOnly)) + continue; + able++; + if (!IsFree(p, c)) + continue; + tmp.Add(new Candidate { pawn = p, warden = IsWarden(p), distSq = (p.Position - offender.Position).LengthHorizontalSquared }); + } + tmp.Sort((a, b) => + { + if (a.warden != b.warden) + return a.warden ? -1 : 1; + return a.distSq.CompareTo(b.distSq); + }); + foreach (Candidate cand in tmp) + { + if (cand.pawn.CanReach(offender, PathEndMode.Touch, Danger.Deadly)) + return cand.pawn; + } + } + finally + { + tmp.Clear(); + } + waitReason = able == 0 ? WaitReasons.NoEnforcer : WaitReasons.Busy; + return null; + } + + /// + /// Could ever enforce this case, whatever it does right now: a free non-slave adult colonist other + /// than the offender, able to move and to do what the punishment needs; a warden in "Wardens only". + /// + public static bool IsAble(Pawn p, Pawn offender, EnforcerNeed need, bool wardensOnly) + { + if (p == null || p == offender || p.Dead || !p.RaceProps.Humanlike) + return false; + if (!p.IsFreeNonSlaveColonist || DlcSupport.IsSlave(p) || p.IsQuestLodger()) + return false; + // Children (Biotech) and babies never enforce; DevelopmentalStage reads Adult without Biotech. + if (!p.DevelopmentalStage.Adult()) + return false; + if (p.health?.capacities == null || !p.health.capacities.CapableOf(PawnCapacityDefOf.Moving)) + return false; + if ((need == EnforcerNeed.Subdue || need == EnforcerNeed.SubdueAndArrest) && p.WorkTagIsDisabled(WorkTags.Violent)) + return false; + if ((need == EnforcerNeed.Arrest || need == EnforcerNeed.SubdueAndArrest) && !p.health.capacities.CapableOf(PawnCapacityDefOf.Manipulation)) + return false; + if (wardensOnly && !IsWarden(p)) + return false; + return true; + } + + /// Free to be sent now (see the class summary). A job of this case's own enforcement counts as free. + public static bool IsFree(Pawn p, LawCase c) + { + if (p == null || !p.Spawned || p.Downed || p.Dead || !p.Awake() || p.InMentalState || p.Drafted) + return false; + if (p.GetLord() != null) + return false; + if (p.IsCarryingPawn()) + return false; + Pawn offender = c?.offender; + if (offender?.MentalState is MentalState_MurderousRage rage && rage.target == p) + return false; + Job job = p.CurJob; + if (job == null) + return true; + if (offender != null && EnforcerJobs.IsEnforcementJob(job, offender)) + return c.enforcer == p; + return !MustNotDrop(job); + } + + /// + /// A job Laws never pulls a pawn off: player-forced, not casually interruptible, fleeing, or surgery. + /// + public static bool MustNotDrop(Job job) + { + if (job?.def == null) + return false; + if (job.playerForced || !job.def.casualInterruptible) + return true; + if (job.def == JobDefOf.Flee || job.def == JobDefOf.FleeAndCower || job.def == JobDefOf.FleeAndCowerShort) + return true; + if (job.def == JobDefOf.DoBill && job.RecipeDef != null && job.RecipeDef.IsSurgery) + return true; + return false; + } + + /// Warden work is active for the pawn (and not disabled). + public static bool IsWarden(Pawn p) => + p?.workSettings != null && p.workSettings.EverWork && !p.WorkTypeIsDisabled(WorkTypeDefOf.Warden) && + p.workSettings.WorkIsActive(WorkTypeDefOf.Warden); + + /// + /// True while hostiles threaten the offender's map (GenHostility.cs:227) or are near the offender + /// (PawnUtility.cs:161): nobody is sent, the case waits. A berserk colonist counts: its state is + /// hostile to the player faction (MentalState_Berserk.cs:12-15, GenHostility.cs:128-133). + /// + public static bool DangerBlocks(Pawn offender) + { + if (offender == null || !offender.Spawned || offender.Map == null) + return false; + return GenHostility.AnyHostileActiveThreatToPlayer(offender.Map) || PawnUtility.EnemiesAreNearby(offender); + } + + /// + /// The offender's live break is hostile to the colony (berserk in vanilla). Wins over the catalogue's + /// hostileBreak (design: "Lawbook tab"): such a pawn fights back and vanilla refuses its arrest + /// (GenAI.cs:83). + /// + public static bool FightsBack(Pawn p) => p?.MentalState != null && p.MentalState.ForceHostileTo(Faction.OfPlayer); + + /// + /// The enforcer can take the offender to the bed now: neither is reserved by someone else. Checked + /// right before an Arrest or Capture starts, so StartJob never logs a reservation error + /// (ReservationUtility.cs:63; Pawn_JobTracker.cs:336, 373-380). + /// + public static bool CanTakeToBed(Pawn enforcer, Pawn offender, Building_Bed bed) + { + if (enforcer == null || offender == null || bed == null) + return false; + return enforcer.CanReserve(offender) && enforcer.CanReserve(bed, bed.SleepingSlotsCount, 0); + } + } +} diff --git a/Source/BlaxLaws/Enforcement/JobDriver_Subdue.cs b/Source/BlaxLaws/Enforcement/JobDriver_Subdue.cs new file mode 100644 index 0000000..7e94625 --- /dev/null +++ b/Source/BlaxLaws/Enforcement/JobDriver_Subdue.cs @@ -0,0 +1,168 @@ +using System; +using System.Collections.Generic; +using RimWorld; +using Verse; +using Verse.AI; + +namespace BlaxLaws +{ + /// + /// The subdue job's driver (JobDef BlaxLaws_Subdue, design: "Subdue"). One toil, + /// Toils_Combat.FollowAndMeleeAttack (Toils_Combat.cs:115-178): it follows the target, calls Hit while + /// adjacent and ends when the target is downed (:165-167) or unreachable (:132-134). The toil runs as a + /// tickIntervalAction, which Thing.DoTick calls every 1 to 15 ticks depending on the camera + /// (Thing.cs:726-735; GenTicks.cs:130-142), so hits are timed by game ticks, never by calls: one every 90 + /// ticks, also off screen. + /// + /// The job ends with a message once three hits in a row add no pain (a hit counts as painless when + /// PainTotal rises by less than a quarter of the new injury's own pain: go-juice's pain factor of 0.1, + /// painkillers, every allowed part at its cap, the pawn's injuries at the total cap of SubdueHits) or after + /// 40 hits. The beaten pawn loses the break's + /// recovery thought (Catharsis) that the downing gives through RecoverFromState (Pawn_HealthTracker.cs: + /// 850-853; MentalState.cs:92-95) while "Subdued pawns lose their catharsis" is on. + /// + /// Never saved: the JobDef isn't suspendable (an interrupt ends it instead of queueing it), the job + /// reserves nothing, and Patch_Pawn_JobTracker_ExposeData hides it from the save. So none of its fields + /// needs saving; after a load the sweep issues a new subdue. + /// + public class JobDriver_Subdue : JobDriver + { + public const int HitIntervalTicks = 90; + public const int MaxHits = 40; + public const int PainlessHitsToStop = 3; + + /// A hit is painful when PainTotal rises by at least this share of the injury's own pain. + public const float PainShare = 0.25f; + + private int lastHitTick = -1000000; + private int hits; + private int painlessHits; + private LawCase lawCase; + + private static readonly List memoriesBefore = new List(); + private static readonly List agesBefore = new List(); + + public Pawn Target => job?.GetTarget(TargetIndex.A).Thing as Pawn; + + /// Hits dealt so far. + public int Hits => hits; + + /// The job reserves nothing, so no reservation list ever refers to it. + public override bool TryMakePreToilReservations(bool errorOnFailed) => true; + + public override void Notify_Starting() + { + base.Notify_Starting(); + lawCase = SubdueFlow.CaseFor(pawn, Target); + } + + protected override IEnumerable MakeNewToils() + { + this.FailOnDespawnedOrNull(TargetIndex.A); + this.FailOn(() => Target == null || Target.Dead || lawCase == null || lawCase.IsClosed || lawCase.enforcer != pawn); + // No longer in the break the case recorded (it ended, or was cured some other way). + this.FailOn(() => Target != null && !Target.Downed && !SubdueFlow.InBreak(lawCase)); + yield return Toils_Combat.FollowAndMeleeAttack(TargetIndex.A, Hit); + } + + private void Hit() + { + try + { + Pawn target = Target; + if (target == null || lawCase == null || target.Dead) + return; + int now = Find.TickManager.TicksGame; + if (now - lastHitTick < HitIntervalTicks) + return; + lastHitTick = now; + hits++; + pawn.rotationTracker?.FaceTarget(target); + + ThoughtDef recovery = target.MentalStateDef?.moodRecoveryThought; + bool dropRecovery = recovery != null && BlaxLawsMod.S.subdueRemovesCatharsis; + if (dropRecovery) + RememberMemories(target, recovery); + float painBefore = target.health.hediffSet.PainTotal; + + float injuryPain = SubdueHits.Hit(pawn, target); + + if (target.Dead) + { + EndJobWith(JobCondition.Incompletable); + return; + } + if (target.Downed) + { + if (dropRecovery) + DropNewMemories(target, recovery); + SubdueFlow.OnDowned(lawCase, pawn); + ReadyForNextToil(); + return; + } + float gain = target.health.hediffSet.PainTotal - painBefore; + if (injuryPain <= 0f || gain < injuryPain * PainShare) + painlessHits++; + else + painlessHits = 0; + if (painlessHits >= PainlessHitsToStop || hits >= MaxHits) + { + SubdueFlow.OnGaveUp(lawCase, pawn); + EndJobWith(JobCondition.Incompletable); + } + } + catch (Exception e) + { + HookGuard.Fail("Subdue hit", e); + try + { + EndJobWith(JobCondition.Incompletable); + } + catch (Exception e2) + { + HookGuard.Fail("Subdue end after a failed hit", e2); + } + } + } + + /// The memories of the recovery thought the target has before the hit, with their ages. + private static void RememberMemories(Pawn target, ThoughtDef def) + { + memoriesBefore.Clear(); + agesBefore.Clear(); + List list = target.needs?.mood?.thoughts?.memories?.Memories; + if (list == null) + return; + foreach (Thought_Memory m in list) + { + if (m.def == def) + { + memoriesBefore.Add(m); + agesBefore.Add(m.age); + } + } + } + + /// Removes the recovery memory the downing gave, and puts back the age of one it only renewed. + private static void DropNewMemories(Pawn target, ThoughtDef def) + { + MemoryThoughtHandler handler = target.needs?.mood?.thoughts?.memories; + if (handler == null) + return; + List now = handler.Memories; + for (int i = now.Count - 1; i >= 0; i--) + { + Thought_Memory m = now[i]; + if (m.def != def) + continue; + int idx = memoriesBefore.IndexOf(m); + if (idx < 0) + handler.RemoveMemory(m); + else if (m.age < agesBefore[idx]) + m.age = agesBefore[idx]; + } + memoriesBefore.Clear(); + agesBefore.Clear(); + } + } +} diff --git a/Source/BlaxLaws/Enforcement/PunishmentDef.cs b/Source/BlaxLaws/Enforcement/PunishmentDef.cs new file mode 100644 index 0000000..1997b2f --- /dev/null +++ b/Source/BlaxLaws/Enforcement/PunishmentDef.cs @@ -0,0 +1,108 @@ +using System; +using System.Collections.Generic; +using Verse; + +namespace BlaxLaws +{ + /// + /// A punishment (Defs/BlaxLaws_Punishments.xml). The defName is what a row saves, so it never changes. + /// fits says which entry kinds and stages offer it; the worker carries it out. + /// + public class PunishmentDef : Def + { + public Type workerClass = typeof(PunishmentWorker); + + /// Dropdown order; lower first. + public int order; + + /// The row's Days field applies (Guilty, Jail, Subdue then jail). + public bool usesDays; + + /// + /// Never replaces or stops what a case already runs, and never becomes the case's active punishment + /// (Warn, Guilty: "Warn and Guilty run alongside"). + /// + public bool runsAlongside; + + public List fits = new List(); + + [Unsaved] + private PunishmentWorker workerInt; + + public PunishmentWorker Worker + { + get + { + if (workerInt == null) + { + workerInt = (PunishmentWorker)Activator.CreateInstance(workerClass ?? typeof(PunishmentWorker)); + workerInt.def = this; + } + return workerInt; + } + } + + /// The entry kind and stage a row has, as fits names them. + public static PunishmentFit FitOf(ActEntry entry, LawStage stage) + { + if (entry == null || !entry.IsBreak) + return PunishmentFit.Act; + if (entry.hostileBreak) + return stage == LawStage.Planning ? PunishmentFit.HostileBreakPlanning : PunishmentFit.HostileBreakDidIt; + return stage == LawStage.Planning ? PunishmentFit.BreakPlanning : PunishmentFit.BreakDidIt; + } + + public bool Fits(ActEntry entry, LawStage stage) => + entry != null && entry.HasStage(stage) && fits != null && fits.Contains(FitOf(entry, stage)); + + public override IEnumerable ConfigErrors() + { + foreach (string e in base.ConfigErrors()) + yield return e; + if (workerClass == null || !typeof(PunishmentWorker).IsAssignableFrom(workerClass)) + yield return "workerClass must be a PunishmentWorker"; + if (fits == null || fits.Count == 0) + yield return "fits names no entry kind"; + } + } + + /// + /// Carries out a punishment. Enforcement calls Start from the queue a tick after the act was filed, + /// never inside a hook, and never while "Enforce laws" is off. Every call is wrapped by Enforcement in + /// a HookGuard, so a throw logs once and the game goes on. + /// + /// One enforcement per case: when a case's active punishment is a different, unfinished one and the new + /// one doesn't run alongside, Enforcement calls the old worker's Stop first (it ends its job and keeps + /// LawCase.enforcer), then the new worker's Start, which takes over with the same enforcer. + /// + public class PunishmentWorker + { + public PunishmentDef def; + + /// + /// Starts the punishment for the stage. Set the case's status (Enforcing, Jailed, or close it with + /// GameComponent_BlaxLaws.CloseCase), its enforcer and waitReason as needed. Default: nothing. + /// + public virtual void Start(LawCase c, Law law, LawStage stage) + { + } + + /// + /// Every 250 ticks while this is the case's active punishment and the case isn't closed: retry a wait + /// (no bed, no enforcer, danger), re-issue a lost job, hand over to a capture, give an old bed back. + /// + public virtual void Sweep(LawCase c) + { + } + + /// Every 2500 ticks while the case is Jailed under this punishment: the sentence check. + public virtual void SentenceSweep(LawCase c) + { + } + + /// Ends this punishment's running job, because a later stage takes over or the law was deleted. Keeps LawCase.enforcer. + public virtual void Stop(LawCase c) + { + } + } +} diff --git a/Source/BlaxLaws/Enforcement/PunishmentWorker_Guilty.cs b/Source/BlaxLaws/Enforcement/PunishmentWorker_Guilty.cs new file mode 100644 index 0000000..4e1edb2 --- /dev/null +++ b/Source/BlaxLaws/Enforcement/PunishmentWorker_Guilty.cs @@ -0,0 +1,24 @@ +using Verse; + +namespace BlaxLaws +{ + /// + /// Guilty for N days: pawn.guilt.Notify_Guilty(days * 60000) (Pawn_GuiltTracker.cs:46-49), which vanilla + /// saves (:40-44) and counts down (:51-61); a longer guilt already on the pawn is never shortened. The + /// guilty icon shows, the arrest of a free colonist is always accepted (Pawn.cs:4087), and executing or + /// banishing it costs the colony the mildest thoughts (ThoughtUtility.cs:27-31; + /// PawnDiedOrDownedThoughtsUtility.cs:214-232). Runs alongside; closes the case as Guilty when nothing + /// else runs for it. Design: "Warn and guilty". + /// + public class PunishmentWorker_Guilty : PunishmentWorker + { + public override void Start(LawCase c, Law law, LawStage stage) + { + if (c?.offender == null || law == null) + return; + Guilt.AtLeast(c.offender, law.DaysTicks); + if (!c.IsClosed && c.activePunishment.NullOrEmpty()) + GameComponent_BlaxLaws.Instance?.CloseCase(c, CaseOutcomes.Guilty); + } + } +} diff --git a/Source/BlaxLaws/Enforcement/PunishmentWorker_Subdue.cs b/Source/BlaxLaws/Enforcement/PunishmentWorker_Subdue.cs new file mode 100644 index 0000000..67c48ca --- /dev/null +++ b/Source/BlaxLaws/Enforcement/PunishmentWorker_Subdue.cs @@ -0,0 +1,102 @@ +using Verse; + +namespace BlaxLaws +{ + /// + /// Subdue (design: "Subdue"): the BlaxLaws_Subdue job while the offender is still in its break. After the + /// break a did-it Subdue row warns and a planning one closes as "break ended". A child (Biotech) is never + /// beaten: it is warned (a Subdue row has no days). A break hostile to the colony (berserk, checked on + /// the live state) never gets it: the pawn fights back, so it is warned. A slave is subdued like a + /// colonist. A subdue that meets danger is called off; the sweep starts it again after the fight. + /// + public class PunishmentWorker_Subdue : PunishmentWorker + { + public override void Start(LawCase c, Law law, LawStage stage) + { + Pawn o = c?.offender; + if (o == null || c.IsClosed || o.Dead || SubdueFlow.Runs(c)) + return; + if (DlcSupport.IsChild(o)) + { + SubdueFlow.WarnInstead(c, "BlaxLaws_MsgWarnedChild"); + return; + } + if (o.Downed && c.status == CaseStatus.Enforcing) + { + // The earlier stage's subdue downed it: this stage's subdue is done too. + GameComponent_BlaxLaws.Instance?.CloseCase(c, CaseOutcomes.Subdued); + return; + } + if (o.Downed || !SubdueFlow.InBreak(c)) + { + SubdueFlow.BreakOver(c); + return; + } + if (Enforcers.FightsBack(o)) + { + SubdueFlow.WarnInstead(c, "BlaxLaws_MsgWarnedFightsBack"); + return; + } + SubdueFlow.TryIssue(c, EnforcerNeed.Subdue); + } + + public override void Sweep(LawCase c) + { + if (c == null || c.IsClosed) + return; + GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance; + if (!BlaxLawsMod.S.enforceLaws) + { + Stop(c); + comp?.CloseCase(c, CaseOutcomes.NotEnforced); + return; + } + Pawn o = c.offender; + if (o == null || o.Dead) + { + Stop(c); + comp?.CloseCase(c, CaseOutcomes.OffenderGone); + return; + } + if (SubdueFlow.Runs(c)) + { + // A raid or a berserk colonist since the start: the warden is called off and the case waits. + SubdueFlow.CallOffInDanger(c); + return; + } + // A did-it Warn, Guilty or Subdue queued for next tick runs now, before anything below closes the case. + SubdueFlow.RunQueuedAlongside(c, sameToo: true); + if (c.IsClosed || SubdueFlow.Runs(c)) + return; + // A later stage with another punishment dispatches next tick and takes over (as Enforcement.Sweep's + // break-ended close waits for it). + if (SubdueFlow.HandOverDue(c)) + return; + if (o.Downed && c.status == CaseStatus.Enforcing) + { + // Downed while the enforcer was on it, by a hit or anything else: the break is over. + comp?.CloseCase(c, CaseOutcomes.Subdued); + return; + } + if (o.Downed || !SubdueFlow.InBreak(c)) + { + SubdueFlow.BreakOver(c); + return; + } + if (Enforcers.FightsBack(o)) + { + SubdueFlow.WarnInstead(c, "BlaxLaws_MsgWarnedFightsBack"); + return; + } + // A lost subdue (the enforcer got hungry, drafted, downed, or the game was loaded) starts again. + SubdueFlow.TryIssue(c, EnforcerNeed.Subdue); + } + + public override void Stop(LawCase c) + { + SubdueFlow.End(c); + if (c != null && !c.IsClosed) + c.status = CaseStatus.Open; + } + } +} diff --git a/Source/BlaxLaws/Enforcement/PunishmentWorker_SubdueThenJail.cs b/Source/BlaxLaws/Enforcement/PunishmentWorker_SubdueThenJail.cs new file mode 100644 index 0000000..af19247 --- /dev/null +++ b/Source/BlaxLaws/Enforcement/PunishmentWorker_SubdueThenJail.cs @@ -0,0 +1,93 @@ +using Verse; + +namespace BlaxLaws +{ + /// + /// Subdue then jail (design: "Subdue"): the subdue job, and in the tick the hit downs the target, a + /// vanilla Capture to a prisoner bed at the front of the enforcer's queue (JailFlow.CaptureAfterSubdue). + /// From then on the case runs as Jail: activePunishment becomes "Jail" and PunishmentWorker_Jail sweeps + /// it. It jails without the beating when the break is over, when the pawn is already down, when its live + /// break fights back (the jail then waits), for a child (Biotech), and when the beating gives up. A slave + /// is never jailed in this release: subdued while in a break, else warned. + /// + public class PunishmentWorker_SubdueThenJail : PunishmentWorker + { + public override void Start(LawCase c, Law law, LawStage stage) + { + Pawn o = c?.offender; + if (o == null || c.IsClosed || o.Dead || c.status == CaseStatus.Jailed) + return; + if (SubdueFlow.Runs(c) || JailFlow.ArrestRuns(c)) + return; + if (DlcSupport.IsSlave(o)) + { + JailFlow.SlaveFallback(c); + return; + } + // Conviction: guilt for the sentence when the case is filed; renewed right before the capture. + Guilt.AtLeast(o, JailFlow.SentenceTicks(c)); + if (JailsWithoutBeating(c)) + { + JailFlow.Become(c); + JailFlow.TryArrest(c, ignoreHold: false); + return; + } + SubdueFlow.TryIssue(c, EnforcerNeed.SubdueAndArrest); + } + + public override void Sweep(LawCase c) + { + if (c == null || c.IsClosed) + return; + GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance; + if (!BlaxLawsMod.S.enforceLaws) + { + Stop(c); + comp?.CloseCase(c, CaseOutcomes.NotEnforced); + return; + } + Pawn o = c.offender; + if (o == null || o.Dead) + { + Stop(c); + comp?.CloseCase(c, CaseOutcomes.OffenderGone); + return; + } + if (SubdueFlow.Runs(c)) + { + // A raid or a berserk colonist since the start: the warden is called off and the case waits. + SubdueFlow.CallOffInDanger(c); + return; + } + if (DlcSupport.IsSlave(o)) + { + JailFlow.SlaveFallback(c); + return; + } + if (JailsWithoutBeating(c)) + { + JailFlow.Become(c); + JailFlow.TryArrest(c, ignoreHold: false); + return; + } + SubdueFlow.TryIssue(c, EnforcerNeed.SubdueAndArrest); + } + + public override void SentenceSweep(LawCase c) => Sentences.Check(c); + + public override void Stop(LawCase c) + { + SubdueFlow.End(c); + JailFlow.EndArrest(c); + if (c != null && !c.IsClosed && c.status != CaseStatus.Jailed) + c.status = CaseStatus.Open; + } + + /// Down already, the break over, a live break that fights back, or a child: jail without a beating. + private static bool JailsWithoutBeating(LawCase c) + { + Pawn o = c.offender; + return o.Downed || DlcSupport.IsChild(o) || Enforcers.FightsBack(o) || !SubdueFlow.InBreak(c); + } + } +} diff --git a/Source/BlaxLaws/Enforcement/PunishmentWorker_Warn.cs b/Source/BlaxLaws/Enforcement/PunishmentWorker_Warn.cs new file mode 100644 index 0000000..64eae3b --- /dev/null +++ b/Source/BlaxLaws/Enforcement/PunishmentWorker_Warn.cs @@ -0,0 +1,20 @@ +using Verse; + +namespace BlaxLaws +{ + /// + /// Warn: the case's message is the record (CaseMessages.Filed, posted by Enforcement at dispatch). Closes + /// the case as Warned once its stage is done, unless an earlier stage's punishment still runs beside it + /// ("Warn and Guilty run alongside"). A later did-it act reopens a closed break case (CaseFiler). + /// Design: "Warn and guilty". + /// + public class PunishmentWorker_Warn : PunishmentWorker + { + public override void Start(LawCase c, Law law, LawStage stage) + { + if (c == null || c.IsClosed || !c.activePunishment.NullOrEmpty()) + return; + GameComponent_BlaxLaws.Instance?.CloseCase(c, CaseOutcomes.Warned); + } + } +} diff --git a/Source/BlaxLaws/Enforcement/SubdueFlow.cs b/Source/BlaxLaws/Enforcement/SubdueFlow.cs new file mode 100644 index 0000000..77d31aa --- /dev/null +++ b/Source/BlaxLaws/Enforcement/SubdueFlow.cs @@ -0,0 +1,491 @@ +using System.Collections.Generic; +using RimWorld; +using UnityEngine; +using Verse; +using Verse.AI; +using Verse.Sound; + +namespace BlaxLaws +{ + /// + /// The subdue part of a case (design: "Subdue"): who is sent, what happens when the pawn goes down or the + /// beating gives up, and what a Subdue row does when the break is already over. The Subdue and "Subdue + /// then jail" workers and JobDriver_Subdue call in here. + /// + public static class SubdueFlow + { + /// + /// The offender is still in the break the case is about: the recorded break for a break case, any + /// break for a case outside one (a slave's jail row falls back to subdue only while it is in a break). + /// + public static bool InBreak(LawCase c) + { + Pawn o = c?.offender; + if (o == null || o.Dead) + return false; + return c.IsBreakCase ? CaseFiler.StillInBreak(c) : o.InMentalState; + } + + /// The case's enforcer runs the subdue job on the offender right now. + public static bool Runs(LawCase c) => + c?.enforcer != null && c.offender != null && EnforcerJobs.Runs(c.enforcer, BlaxLawsDefOf.BlaxLaws_Subdue, c.offender); + + /// The open case whose subdue this enforcer carries out on this target, or null. + public static LawCase CaseFor(Pawn enforcer, Pawn target) + { + GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance; + if (comp == null || enforcer == null || target == null) + return null; + IReadOnlyList list = comp.CasesOf(target); + for (int i = list.Count - 1; i >= 0; i--) + { + LawCase c = list[i]; + if (!c.IsClosed && c.enforcer == enforcer && IsSubduePunishment(c.activePunishment)) + return c; + } + return null; + } + + /// "Subdue" or "Subdue then jail". + public static bool IsSubduePunishment(string defName) => + defName != null && (defName == BlaxLawsDefOf.Subdue?.defName || defName == BlaxLawsDefOf.SubdueThenJail?.defName); + + /// + /// Sends an enforcer on the subdue job, or leaves the case waiting with its reason (danger, nobody + /// free, nobody able: a letter once). Returns whether the job runs. + /// + public static bool TryIssue(LawCase c, EnforcerNeed need) + { + Pawn o = c?.offender; + if (o == null || !o.Spawned) + { + WaitReasons.Set(c, WaitReasons.Away); + return false; + } + if (Enforcers.DangerBlocks(o)) + { + WaitReasons.Set(c, WaitReasons.Danger); + return false; + } + Pawn e = Enforcers.Pick(c, need, out string reason); + if (e == null) + { + if (WaitReasons.Set(c, reason) && reason == WaitReasons.NoEnforcer && CaseLetters.Once(c, CaseLetters.KindNoEnforcer)) + CaseLetters.NoEnforcer(c); + return false; + } + return TryStartWith(c, e); + } + + /// + /// Starts the subdue job with this enforcer, no pick and no danger check: the hook point for a subdue + /// the player starts ("Subdue a pawn that fights back", Enforcement step 3). Returns whether it runs. + /// Step 3 must also leave its offender out of CallOffInDanger. + /// + public static bool TryStartWith(LawCase c, Pawn enforcer) + { + if (c?.offender == null || enforcer == null || BlaxLawsDefOf.BlaxLaws_Subdue == null) + return false; + Job job = JobMaker.MakeJob(BlaxLawsDefOf.BlaxLaws_Subdue, c.offender); + c.enforcer = enforcer; + c.status = CaseStatus.Enforcing; + c.waitReason = null; + if (EnforcerJobs.Start(enforcer, job)) + return true; + WaitReasons.Set(c, WaitReasons.Busy); + return false; + } + + /// Ends the running subdue job of the case, if any. Keeps the enforcer for a hand-over. + public static void End(LawCase c) + { + if (c?.enforcer != null && c.offender != null) + EnforcerJobs.End(c.enforcer, BlaxLawsDefOf.BlaxLaws_Subdue, c.offender); + } + + /// + /// A running subdue meets danger (a raid lands, a colonist goes berserk): the job ends and the case waits + /// for Danger, so the sweep sends someone again after the fight. The job is player-forced, so vanilla + /// never pulls the enforcer off it when it is hit (Pawn_JobTracker.cs:982) and the hostility response + /// skips it (PawnUtility.cs:377-385). Returns whether it was called off. + /// + public static bool CallOffInDanger(LawCase c) + { + if (!Runs(c) || !Enforcers.DangerBlocks(c.offender)) + return false; + End(c); + WaitReasons.Set(c, WaitReasons.Danger); + return true; + } + + /// + /// A later stage of the case is queued and dispatches within a tick (a did-it act filed during the + /// subdue), and its punishment replaces the subdue (a Jail). The subdue then leaves the case open, so + /// Enforcement hands over to that stage's punishment (design: "One enforcement per case") instead of the + /// stage being dropped on a closed case. A queued Warn, Guilty or same subdue is no hand-over: + /// RunQueuedAlongside carries it out before the case closes. + /// + public static bool HandOverDue(LawCase c) + { + if (c == null || !BlaxLawsMod.S.enforceLaws || !Enforcement.IsQueued(c, CaseTask.Punish)) + return false; + foreach (LawStage s in new[] { LawStage.Planning, LawStage.DidIt }) + { + if (c.HasPunished(s)) + continue; + PunishmentDef p = c.LawFor(s)?.PunishmentDef; + if (p != null && !p.runsAlongside && p.defName != c.activePunishment) + return true; + } + return false; + } + + /// + /// Before the subdue closes its case: a queued stage that runs alongside (Warn, Guilty) runs now, and with + /// sameToo one with this same subdue punishment too, so it is carried out and logged instead of dropped + /// on the closed case. While the subdue job runs, a same-punishment stage starts nothing; from the sweep + /// its Start closes the downed offender's case as Subdued. A stage with another punishment (a Jail) + /// stays queued and HandOverDue keeps the case open for it. + /// + internal static void RunQueuedAlongside(LawCase c, bool sameToo) + { + if (c == null || c.IsClosed || !BlaxLawsMod.S.enforceLaws) + return; + string active = c.activePunishment; + Enforcement.DispatchNow(c, p => p.runsAlongside || (sameToo && p.defName == active)); + } + + /// Closes the case as Warned with a message saying why it wasn't a subdue. + public static void WarnInstead(LawCase c, string messageKey) + { + if (c == null || c.IsClosed) + return; + CaseMessages.Post(c, messageKey.Translate(c.OffenderLabel)); + GameComponent_BlaxLaws.Instance?.CloseCase(c, CaseOutcomes.Warned); + } + + /// + /// The break is over before a subdue could act: a planning case closes as "break ended" (nothing was + /// done), a did-it Subdue row warns (design: "Defaults I picked"). + /// + public static void BreakOver(LawCase c) + { + if (c == null || c.IsClosed) + return; + if (c.activeStage == LawStage.Planning) + GameComponent_BlaxLaws.Instance?.CloseCase(c, CaseOutcomes.BreakEnded); + else + WarnInstead(c, "BlaxLaws_MsgWarnedAfterBreak"); + } + + /// + /// The hit downed the offender. Subdue closes the case; "Subdue then jail" queues the vanilla Capture + /// at the front of the enforcer's queue (JailFlow.CaptureAfterSubdue). Called by the driver inside + /// its toil, so nothing here starts a job. A later stage already queued (HandOverDue) keeps the case open + /// for its hand-over. + /// + internal static void OnDowned(LawCase c, Pawn enforcer) + { + if (c == null || c.IsClosed) + return; + if (c.activePunishment == BlaxLawsDefOf.SubdueThenJail?.defName) + { + JailFlow.CaptureAfterSubdue(c, enforcer); + return; + } + CaseMessages.Post(c, "BlaxLaws_MsgSubdued".Translate(c.OffenderLabel, enforcer.LabelShort)); + RunQueuedAlongside(c, sameToo: Runs(c)); + if (c.IsClosed) + return; + if (HandOverDue(c)) + return; // The queued stage takes over next tick: a Jail captures the downed offender. + GameComponent_BlaxLaws.Instance?.CloseCase(c, CaseOutcomes.Subdued); + } + + /// + /// Three hits in a row caused no pain, or the ceiling was reached: one message. Subdue closes the case + /// as not subdued; "Subdue then jail" arrests instead, from the next sweep (the driver is still inside + /// its toil, so no job starts here). A later stage already queued (HandOverDue) keeps the case open for + /// its hand-over. + /// + internal static void OnGaveUp(LawCase c, Pawn enforcer) + { + if (c == null || c.IsClosed) + return; + CaseMessages.Post(c, "BlaxLaws_MsgSubdueGaveUp".Translate(c.OffenderLabel, enforcer.LabelShort)); + if (c.activePunishment == BlaxLawsDefOf.SubdueThenJail?.defName) + { + JailFlow.Become(c); + return; + } + // A queued same-punishment stage is no hand-over: it is done here while the job still runs (or dropped + // with the closed case), so it never starts a second beating of a pawn the subdue just gave up on. + RunQueuedAlongside(c, sameToo: Runs(c)); + if (c.IsClosed) + return; + if (HandOverDue(c)) + return; // The queued stage takes over next tick. + GameComponent_BlaxLaws.Instance?.CloseCase(c, EnforcementOutcomes.NotSubdued); + } + } + + /// + /// One hit of the subdue (design: "Subdue", the hit). Blunt damage on a random part of the torso or the + /// limbs: not missing, depth Outside, skin covered, not solid, not in the head or neck branch, not + /// carrying or below an added part (HediffSet.cs:1225; an injury there gives no pain, Hediff_Injury.cs: + /// 132-135). The injury is 4 to 8 points, capped so the part keeps at least half its HP and the pawn's + /// injuries, old scars included, stay at nine tenths of the sum that kills it: vanilla kills a pawn whose + /// injury severities add up to 150 times its health scale (Pawn_HealthTracker.cs:73, 705-719), and the + /// part caps alone add up to more (a human's torso and limbs to about 235). A normal adult goes down at + /// about 64 points of bruises, one with halved pain (Biotech's reduced pain gene) at about 128; one that isn't + /// down at the total cap gets the "no pain" ending. + /// + /// The caps hold whatever vanilla multiplies in on the way from the DamageInfo to the injury: the race's + /// damage multiplier, rounded to a whole number (Thing.cs:1487-1497), the genes' and hediffs' damage + /// factors (Pawn.cs:1919-1927), and IncomingDamageFactor, which applies even with armour ignored + /// (DamageWorker_AddInjury.cs:164-167; Tough is 0.5). The amount is divided by all of them; with + /// propagation off the injury's severity is exactly what is left (:181-183, 199-221). The part's HP is + /// counted unrounded: HediffSet.GetPartHealth rounds to a whole point (HediffSet.cs:581-605), which + /// would let a hit take a part with an odd maximum (a foot has 25) half a point below its share. A + /// rounding or another mod's damage factor that still takes the hit past a cap is healed back on the + /// hit's own bruise (Hediff_Injury.Heal, Hediff_Injury.cs:201-212). + /// + /// SetAllowDamagePropagation(false) makes AddInjury skip ApplySpecialEffectsToPart, so there is no inner + /// bone crack and no stun (DamageWorker_Blunt.cs:18-78): Blunt on a skin-covered, non-solid part is a + /// Bruise (HealthUtility.cs:519-531). instigatorGuilty false skips the guilt for harming a player pawn + /// (Pawn_HealthTracker.cs:323-329); TakeDamage sets no meleeThreat, so the target never turns on the + /// enforcer, and gives the target HarmedMe toward it (:379-382). + /// + public static class SubdueHits + { + public const float MinDamage = 4f; + public const float MaxDamage = 8f; + + /// A part keeps at least this share of its HP. + public const float KeepHealthShare = 0.5f; + + /// The pawn's injuries stay at or below this share of the injury sum that kills it. + public const float LethalShare = 0.9f; + + public const float MeleeXpPerHit = 40f; + + private static readonly List parts = new List(); + + /// + /// Hits once. Returns the pain the new injury carries before pain factors (its PainOffset), or 0 when + /// nothing could be hit: every allowed part at its cap, the pawn at the total cap, or a damage factor of 0. + /// + public static float Hit(Pawn enforcer, Pawn target) + { + if (enforcer == null || target == null || target.Dead || !target.Spawned) + return 0f; + BodyPartRecord part = PickPart(target, out float headroom); + if (part == null) + return 0f; + var dinfo = new DamageInfo(DamageDefOf.Blunt, 1f, armorPenetration: 0f, angle: -1f, instigator: enforcer, + hitPart: part, weapon: enforcer.def, category: DamageInfo.SourceCategory.ThingOrUnknown, intendedTarget: target, + instigatorGuilty: false); + dinfo.SetAllowDamagePropagation(false); + dinfo.SetIgnoreArmor(true); + float factor = DamageFactor(target, dinfo); + if (factor <= 0.001f) + return 0f; + float injury = Mathf.Min(Rand.Range(MinDamage, MaxDamage), headroom); + if (injury < 0.5f) + return 0f; + dinfo.SetAmount(injury / factor); + DamageWorker.DamageResult result = target.TakeDamage(dinfo); + KeepShare(target, part, result); + if (enforcer.Spawned) + enforcer.Drawer.Notify_MeleeAttackOn(target); + if (target.Spawned) + SoundDefOf.Pawn_Melee_Punch_HitPawn.PlayOneShot(new TargetInfo(target.Position, target.Map)); + enforcer.skills?.Learn(SkillDefOf.Melee, MeleeXpPerHit); + float pain = 0f; + if (result?.hediffs != null) + { + foreach (Hediff h in result.hediffs) + pain += h.PainOffset; + } + return pain; + } + + /// + /// What vanilla multiplies a damage amount by before it becomes the injury's severity, armour ignored: + /// the race's multiplier for the damage (Thing.cs:1487-1497, which also rounds the amount), the genes' + /// factor with Biotech and the hediffs' factor (Pawn.cs:1919-1927), and IncomingDamageFactor for + /// external violence (DamageWorker_AddInjury.cs:164-167). + /// + public static float DamageFactor(Pawn target, DamageInfo dinfo) + { + float factor = 1f; + List multipliers = target.def.damageMultipliers; + if (multipliers != null) + { + for (int i = 0; i < multipliers.Count; i++) + { + if (multipliers[i].damageDef == dinfo.Def) + factor *= multipliers[i].multiplier; + } + } + if (ModsConfig.BiotechActive && target.genes != null) + factor *= target.genes.FactorForDamage(dinfo); + factor *= target.health.FactorForDamage(dinfo); + if (dinfo.Def.ExternalViolenceFor(target)) + factor *= target.GetStatValue(StatDefOf.IncomingDamageFactor); + return factor; + } + + /// + /// After the hit: when the part ended below its share or the pawn past the total cap anyway (the race + /// multiplier's rounding, or a damage factor another mod adds), the hit's bruise there heals back the + /// difference. The bruise is the new injury, or the one it merged into (HediffSet.cs:325-331; + /// Hediff_Injury.cs:214-221). + /// + private static void KeepShare(Pawn target, BodyPartRecord part, DamageWorker.DamageResult result) + { + if (target.Dead) + return; + float deficit = Mathf.Max(Floor(target, part) - PartHealth(target, part), -RoomToLive(target)); + if (deficit <= 0f) + return; + List set = target.health.hediffSet.hediffs; + Hediff_Injury bruise = null; + HediffDef def = null; + if (result?.hediffs != null) + { + foreach (Hediff h in result.hediffs) + { + if (h is Hediff_Injury injury && injury.Part == part) + { + def = injury.def; + if (set.Contains(injury)) + bruise = injury; + } + } + } + for (int i = set.Count - 1; bruise == null && def != null && i >= 0; i--) + { + if (set[i] is Hediff_Injury merged && merged.Part == part && merged.def == def && !merged.IsPermanent() && !merged.IsTended()) + bruise = merged; + } + bruise?.Heal(Mathf.Min(deficit, bruise.Severity)); + } + + /// + /// A part the subdue may hit, weighted by coverage, and how much injury it can still take: its own + /// headroom, at most what the pawn has left below the total cap. Null when no part or no total is left. + /// + public static BodyPartRecord PickPart(Pawn target, out float headroom) + { + headroom = 0f; + HediffSet hs = target?.health?.hediffSet; + if (hs == null) + return null; + float room = RoomToLive(target); + if (room < 1f) + return null; + parts.Clear(); + try + { + foreach (BodyPartRecord part in hs.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Outside)) + { + if (Allowed(target, part) && Headroom(target, part) >= 1f) + parts.Add(part); + } + if (!parts.TryRandomElementByWeight(p => p.coverageAbs, out BodyPartRecord chosen)) + return null; + headroom = Mathf.Min(Headroom(target, chosen), room); + return chosen; + } + finally + { + parts.Clear(); + } + } + + /// A part of the torso or the limbs the subdue may ever hit (see the class summary). + public static bool Allowed(Pawn target, BodyPartRecord part) + { + HediffSet hs = target.health.hediffSet; + if (part == null || part.depth != BodyPartDepth.Outside || part.coverageAbs <= 0f) + return false; + if (hs.PartIsMissing(part) || part.def.IsSolid(part, hs.hediffs) || !part.def.IsSkinCovered(part, hs)) + return false; + if (hs.PartOrAnyAncestorHasDirectlyAddedParts(part)) + return false; + return !InHeadOrNeck(target, part); + } + + /// The part sits in the head: in the FullHead or UpperHead group, or in the brain's branch below the core part (the neck). + public static bool InHeadOrNeck(Pawn target, BodyPartRecord part) + { + for (BodyPartRecord p = part; p != null; p = p.parent) + { + if (p.IsInGroup(BodyPartGroupDefOf.FullHead) || p.IsInGroup(BodyPartGroupDefOf.UpperHead)) + return true; + } + BodyPartRecord branch = TopBranch(part); + if (branch.parent == null) + return false; + foreach (BodyPartRecord brain in target.RaceProps.body.GetPartsWithTag(BodyPartTagDefOf.ConsciousnessSource)) + { + if (TopBranch(brain) == branch) + return true; + } + return false; + } + + /// HP the part may still lose and keep its share: current HP minus half the maximum. + public static float Headroom(Pawn target, BodyPartRecord part) => PartHealth(target, part) - Floor(target, part); + + /// + /// Injury the pawn can still take before its injuries, old scars included, reach the total cap: the + /// share of the sum vanilla kills at (LethalDamageThreshold, Pawn_HealthTracker.cs:73, 705-719). + /// + public static float RoomToLive(Pawn target) + { + float sum = 0f; + List list = target.health.hediffSet.hediffs; + for (int i = 0; i < list.Count; i++) + { + if (list[i] is Hediff_Injury injury) + sum += injury.Severity; + } + return target.health.LethalDamageThreshold * LethalShare - sum; + } + + /// The HP the part always keeps: half its maximum (BodyPartDef.cs:138-141, scaled by the pawn's health scale). + public static float Floor(Pawn target, BodyPartRecord part) => part.def.GetMaxHealth(target) * KeepHealthShare; + + /// + /// The part's HP as HediffSet.GetPartHealth counts it, its maximum minus the injuries on it, 0 when it + /// is missing (HediffSet.cs:581-605), but not rounded to a whole point. + /// + public static float PartHealth(Pawn target, BodyPartRecord part) + { + float hp = part.def.GetMaxHealth(target); + List list = target.health.hediffSet.hediffs; + for (int i = 0; i < list.Count; i++) + { + Hediff h = list[i]; + if (h.Part != part) + continue; + if (h is Hediff_MissingPart) + return 0f; + if (h is Hediff_Injury injury) + hp = injury.destroysBodyParts ? hp - injury.Severity : Mathf.Max(hp - injury.Severity, 1f); + } + return Mathf.Max(hp, 0f); + } + + /// The part's ancestor right below the core part (the core part itself for the core). + private static BodyPartRecord TopBranch(BodyPartRecord part) + { + BodyPartRecord p = part; + while (p.parent != null && p.parent.parent != null) + p = p.parent; + return p; + } + } +} diff --git a/Source/BlaxLaws/Enforcement/SubdueSaveHook.cs b/Source/BlaxLaws/Enforcement/SubdueSaveHook.cs new file mode 100644 index 0000000..034576f --- /dev/null +++ b/Source/BlaxLaws/Enforcement/SubdueSaveHook.cs @@ -0,0 +1,104 @@ +using System; +using HarmonyLib; +using Verse; +using Verse.AI; + +namespace BlaxLaws +{ + /// + /// The subdue job never enters a save (design: "The subdue job never enters a save"). A saved job with a + /// missing JobDef would break the enforcer after removal: Job.ExposeData saves the def (Job.cs:505), and + /// Pawn_JobTracker.ExposeData (Pawn_JobTracker.cs:90-109, virtual, deep-saves curJob, curDriver and the + /// queue) would then end a job whose def is null. + /// + /// Prefix, only while Scribe.mode is Saving and only when the tracker holds a BlaxLaws_Subdue job: hides + /// curJob and curDriver from the scribe and swaps the queue for a copy without subdue entries (a + /// backstop: the JobDef isn't suspendable, so vanilla never queues it). The finalizer puts everything + /// back, also when saving throws. It returns void, so Harmony rethrows with the full stack trace. + /// + [HarmonyPatch(typeof(Pawn_JobTracker), nameof(Pawn_JobTracker.ExposeData))] + public static class Patch_Pawn_JobTracker_ExposeData + { + public sealed class Hidden + { + public bool hidCurrent; + public Job curJob; + public JobDriver curDriver; + public JobQueue queue; + } + + public static void Prefix(Pawn_JobTracker __instance, out Hidden __state) + { + __state = null; + try + { + if (Scribe.mode != LoadSaveMode.Saving || __instance == null) + return; + JobDef ours = BlaxLawsDefOf.BlaxLaws_Subdue; + if (ours == null) + return; + bool current = __instance.curJob?.def == ours; + bool queued = AnyQueued(__instance.jobQueue, ours); + if (!current && !queued) + return; + var hidden = new Hidden(); + if (current) + { + hidden.hidCurrent = true; + hidden.curJob = __instance.curJob; + hidden.curDriver = __instance.curDriver; + __instance.curJob = null; + __instance.curDriver = null; + } + if (queued) + { + hidden.queue = __instance.jobQueue; + var filtered = new JobQueue(); + foreach (QueuedJob q in hidden.queue) + { + if (q?.job != null && q.job.def != ours) + filtered.EnqueueLast(q.job, q.tag); + } + __instance.jobQueue = filtered; + } + __state = hidden; + } + catch (Exception e) + { + HookGuard.Fail("Hiding the subdue job from the save", e); + } + } + + public static void Finalizer(Pawn_JobTracker __instance, Hidden __state) + { + if (__state == null || __instance == null) + return; + try + { + if (__state.hidCurrent) + { + __instance.curJob = __state.curJob; + __instance.curDriver = __state.curDriver; + } + if (__state.queue != null) + __instance.jobQueue = __state.queue; + } + catch (Exception e) + { + HookGuard.Fail("Restoring the subdue job after the save", e); + } + } + + private static bool AnyQueued(JobQueue queue, JobDef def) + { + if (queue == null) + return false; + for (int i = 0; i < queue.Count; i++) + { + if (queue[i]?.job?.def == def) + return true; + } + return false; + } + } +} diff --git a/Source/BlaxLaws/Enforcement/WaitReasons.cs b/Source/BlaxLaws/Enforcement/WaitReasons.cs new file mode 100644 index 0000000..9f2ba20 --- /dev/null +++ b/Source/BlaxLaws/Enforcement/WaitReasons.cs @@ -0,0 +1,77 @@ +using Verse; + +namespace BlaxLaws +{ + /// + /// Why enforcement waits: the Keyed keys LawCase.waitReason holds and the Cases tab shows + /// (WaitReasons.Label). A case that waits is Open; the 250-tick sweep retries it, a case waiting for a + /// prisoner bed only every 2500 ticks (design: "Enforcement runs a tick later"). + /// + public static class WaitReasons + { + /// Hostiles threaten the offender's map (a raid, a berserk colonist): nobody is sent. + public const string Danger = "BlaxLaws_Wait_Danger"; + + /// Nobody on the map can ever enforce it (no warden in "Wardens only", nobody able): the player has to act. + public const string NoEnforcer = "BlaxLaws_Wait_NoEnforcer"; + + /// Enforcers exist but none is free now (asleep, on a rescue, in a ritual, out of reach). + public const string Busy = "BlaxLaws_Wait_Busy"; + + /// No prisoner bed the enforcer can take the offender to. + public const string NoBed = "BlaxLaws_Wait_NoBed"; + + /// Someone else holds the offender or the bed (a doctor's rescue): the arrest waits, no reservation error. + public const string Reserved = "BlaxLaws_Wait_Reserved"; + + /// The offender's break is hostile to the colony (berserk): the arrest waits until it ends or the pawn is down. + public const string HostileBreak = "BlaxLaws_Wait_HostileBreak"; + + /// A role holder or a mechanitor with mechs: Laws doesn't arrest it on its own; "Arrest now" does. + public const string Hold = "BlaxLaws_Wait_Hold"; + + /// The offender isn't on a map (carried, in a caravan). + public const string Away = "BlaxLaws_Wait_Away"; + + /// The reason's text, or "" for none. + public static string Label(string reason) + { + if (reason.NullOrEmpty()) + return ""; + return reason.CanTranslate() ? reason.Translate().ToString() : reason; + } + + /// + /// Puts the case back to Open with the reason. Returns true when the reason changed, so a letter goes + /// out once per wait and not on every sweep. + /// + public static bool Set(LawCase c, string reason) + { + if (c == null) + return false; + bool changed = c.waitReason != reason; + c.status = CaseStatus.Open; + c.waitReason = reason; + return changed; + } + } + + /// + /// Outcome keys of this package beside CaseOutcomes. Saved as strings; the label is + /// "BlaxLaws_Outcome_" + key (CaseOutcomes.Label), from BlaxLaws_Enforcement.xml. + /// + public static class EnforcementOutcomes + { + /// The subdue gave up: three hits in a row caused no pain (go-juice, painkillers, every part at its cap). + public const string NotSubdued = "NotSubdued"; + + /// A jailed pawn left the map before its sentence was served. + public const string Escaped = "Escaped"; + + /// A jailed pawn died. + public const string Died = "Died"; + + /// The offender became a prisoner some other way (arrested by hand, another mod): Laws never touches it. + public const string AlreadyPrisoner = "AlreadyPrisoner"; + } +} diff --git a/Source/BlaxLaws/GameComponent_BlaxLaws.cs b/Source/BlaxLaws/GameComponent_BlaxLaws.cs new file mode 100644 index 0000000..636f9d3 --- /dev/null +++ b/Source/BlaxLaws/GameComponent_BlaxLaws.cs @@ -0,0 +1,359 @@ +using System; +using System.Collections.Generic; +using Verse; + +namespace BlaxLaws +{ + /// + /// All Blax Laws state of one game: the lawbook rows and the cases (design: "Lawbook and cases in one + /// GameComponent"). Laws are colony policy across every map, caravan and world pawn, so this is a + /// GameComponent. Game.FillComponents adds it to a new game and after loading (Verse/Game.cs:345, + /// 443-446, 472-489), so a save made without Laws loads with an empty book. After a plain unsubscribe + /// the node loads as null with exactly 2 errors and FillComponents drops it (Verse/Game.cs:474). + /// + /// Read through the properties and lookups. Rows change only through Lawbook, cases only through + /// CaseFiler, Enforcement and the punishment workers (CloseCase). Nothing of Laws is stored on vanilla + /// objects, and no Laws def enters a vanilla save list. + /// + public class GameComponent_BlaxLaws : GameComponent + { + private List laws = new List(); + private int nextLawId = 1; + private List cases = new List(); + private int nextCaseId = 1; + + /// A random number per save, for ids Laws hands to other mods later. Never 0 after the first tick. + private int saveToken; + + // Not saved: cases by offender, rebuilt on load and kept on every add and prune. + private readonly Dictionary> byOffender = new Dictionary>(); + + // Weak, so the main menu never keeps the last game and its pawns alive. + private static readonly System.WeakReference cached = new System.WeakReference(null); + private static readonly System.WeakReference cachedGame = new System.WeakReference(null); + + private static readonly List EmptyCases = new List(); + + public GameComponent_BlaxLaws() + { + } + + /// Called by the game for a new game and for a loaded one, before anything of the save is read. + public GameComponent_BlaxLaws(Game game) : this() + { + // The hot-path flags and the queue belong to the last game: clear them before this one's hooks run. + Watch.Clear(); + Enforcement.Reset(); + saveToken = NewToken(); + if (game != null) + Remember(this, game); + } + + /// The component of the running game, or null when no game is loaded. + public static GameComponent_BlaxLaws Instance + { + get + { + Game game = Current.Game; + if (game == null) + return null; + if (cachedGame.TryGetTarget(out Game g) && g == game && cached.TryGetTarget(out GameComponent_BlaxLaws c) && c != null) + return c; + GameComponent_BlaxLaws found = game.GetComponent(); + if (found != null) + Remember(found, game); + return found; + } + } + + private static void Remember(GameComponent_BlaxLaws comp, Game game) + { + cached.SetTarget(comp); + cachedGame.SetTarget(game); + } + + private static int NewToken() => new Random(Environment.TickCount ^ Guid.NewGuid().GetHashCode()).Next(1, int.MaxValue); + + // ---- reads --------------------------------------------------------------------------- + + /// The lawbook rows in display order. Do not change the list; use Lawbook. + public IReadOnlyList Laws => laws; + + /// Every case, oldest first. Do not change the list. + public IReadOnlyList Cases => cases; + + public int NextLawId => nextLawId; + + public int NextCaseId => nextCaseId; + + public int SaveToken => saveToken; + + public Law LawById(int id) + { + if (id <= 0) + return null; + for (int i = 0; i < laws.Count; i++) + { + if (laws[i].id == id) + return laws[i]; + } + return null; + } + + public LawCase CaseById(int id) + { + if (id <= 0) + return null; + for (int i = cases.Count - 1; i >= 0; i--) + { + if (cases[i].id == id) + return cases[i]; + } + return null; + } + + /// The cases filed against this pawn, oldest first. Empty for null or a pawn without cases. + public IReadOnlyList CasesOf(Pawn pawn) + { + if (pawn != null && byOffender.TryGetValue(pawn, out List list)) + return list; + return EmptyCases; + } + + /// True while any case isn't closed. The tick's fast path reads it. + public bool AnyOpenCase + { + get + { + for (int i = cases.Count - 1; i >= 0; i--) + { + if (!cases[i].IsClosed) + return true; + } + return false; + } + } + + /// The cases that aren't closed, as a new list (safe to change cases while walking it). + public List OpenCases() + { + var result = new List(); + foreach (LawCase c in cases) + { + if (!c.IsClosed) + result.Add(c); + } + return result; + } + + /// Open cases a row runs for, for "deleting a law with open cases asks first and names the count". + public int OpenCaseCount(Law law) + { + if (law == null) + return 0; + int n = 0; + foreach (LawCase c in cases) + { + if (!c.IsClosed && (c.planningLawId == law.id || c.didItLawId == law.id)) + n++; + } + return n; + } + + /// + /// The pawn's newest case outside a break whose did-it row is this one, open or closed, or null. The + /// cooldown reads it. + /// + public LawCase LatestActCaseOf(Pawn pawn, int lawId) + { + IReadOnlyList list = CasesOf(pawn); + for (int i = list.Count - 1; i >= 0; i--) + { + LawCase c = list[i]; + if (!c.IsBreakCase && c.didItLawId == lawId) + return c; + } + return null; + } + + /// Ticks two break start ticks may differ by and still name the same break (MentalState.age moves in steps of 30). + public const int BreakStartTolerance = 120; + + /// The pawn's case for this break (same state def, started at the same tick), open or closed, or null. + public LawCase BreakCaseOf(Pawn pawn, string stateDefName, int breakStartTick) + { + if (stateDefName.NullOrEmpty()) + return null; + IReadOnlyList list = CasesOf(pawn); + for (int i = list.Count - 1; i >= 0; i--) + { + LawCase c = list[i]; + if (c.breakState == stateDefName && Math.Abs(c.breakStartTick - breakStartTick) <= BreakStartTolerance) + return c; + } + return null; + } + + // ---- writes, for Lawbook, CaseFiler and Enforcement ---------------------------------------- + + internal int TakeLawId() + { + foreach (Law l in laws) + { + if (l.id >= nextLawId) + nextLawId = l.id + 1; + } + return nextLawId++; + } + + internal int TakeCaseId() + { + if (cases.Count > 0 && cases[cases.Count - 1].id >= nextCaseId) + nextCaseId = cases[cases.Count - 1].id + 1; + return nextCaseId++; + } + + internal void AddLaw(Law law) => laws.Add(law); + + internal bool RemoveLaw(Law law) => laws.Remove(law); + + internal void MoveLaw(Law law, int index) + { + if (!laws.Remove(law)) + return; + laws.Insert(Math.Max(0, Math.Min(index, laws.Count)), law); + } + + internal void AddCase(LawCase c) + { + cases.Add(c); + Index(c); + } + + /// Closes the case with a CaseOutcomes key. A closed case is pruned after "Keep closed cases". + public void CloseCase(LawCase c, string outcome) + { + if (c == null) + return; + c.status = CaseStatus.Closed; + c.outcome = outcome; + c.closeTick = Find.TickManager?.TicksGame ?? 0; + c.activePunishment = null; + c.waitReason = null; + } + + /// + /// Removes closed cases that closed more than the given ticks ago. Returns the number removed. + /// Runs on every save with "Keep closed cases". + /// + public int PruneClosedCases(int olderThanTicks) + { + int now = Find.TickManager?.TicksGame ?? 0; + int removed = cases.RemoveAll(c => c == null || (c.IsClosed && c.closeTick >= 0 && now - c.closeTick > olderThanTicks)); + if (removed > 0) + RebuildIndex(); + return removed; + } + + private void Index(LawCase c) + { + if (c?.offender == null) + return; + if (!byOffender.TryGetValue(c.offender, out List list)) + byOffender[c.offender] = list = new List(); + list.Add(c); + } + + private void RebuildIndex() + { + byOffender.Clear(); + foreach (LawCase c in cases) + Index(c); + } + + // ---- game hooks ---------------------------------------------------------------------- + + public override void GameComponentTick() + { + // The empty book costs one count and one field read per tick. + if (cases.Count == 0 && Enforcement.Pending == 0) + return; + try + { + Enforcement.Tick(this); + } + catch (Exception e) + { + HookGuard.Fail("Enforcement tick", e); + } + } + + public override void FinalizeInit() + { + Remember(this, Current.Game); + // Log-once flags count per game, so a failure in a later game is not silent. + LawsLog.ResetOnce(); + try + { + ActCatalogue.EnsureBuilt(); + Watch.Rebuild(); + Enforcement.Reset(); + Enforcement.Refill(this); + } + catch (Exception e) + { + HookGuard.Fail("Game start", e); + } + } + + // ---- save ---------------------------------------------------------------------------- + + public override void ExposeData() + { + if (Scribe.mode == LoadSaveMode.Saving) + { + try + { + PruneClosedCases(BlaxLawsMod.S.KeepClosedTicks); + } + catch (Exception e) + { + HookGuard.Fail("Pruning closed cases", e); + } + } + + Scribe_Values.Look(ref saveToken, "saveToken"); + Scribe_Values.Look(ref nextLawId, "nextLawId", 1); + Scribe_Collections.Look(ref laws, "laws", LookMode.Deep); + Scribe_Values.Look(ref nextCaseId, "nextCaseId", 1); + Scribe_Collections.Look(ref cases, "cases", LookMode.Deep); + + if (Scribe.mode == LoadSaveMode.LoadingVars) + Remember(this, Current.Game); + if (Scribe.mode == LoadSaveMode.PostLoadInit) + EnsureState(); + } + + /// Missing lists, null entries and ids that would repeat. + private void EnsureState() + { + laws ??= new List(); + laws.RemoveAll(l => l == null || l.actKey.NullOrEmpty()); + cases ??= new List(); + cases.RemoveAll(c => c == null); + if (saveToken == 0) + saveToken = NewToken(); + foreach (Law l in laws) + { + if (l.id >= nextLawId) + nextLawId = l.id + 1; + } + foreach (LawCase c in cases) + { + if (c.id >= nextCaseId) + nextCaseId = c.id + 1; + } + RebuildIndex(); + } + } +} diff --git a/Source/BlaxLaws/HookGuard.cs b/Source/BlaxLaws/HookGuard.cs new file mode 100644 index 0000000..81d0ba5 --- /dev/null +++ b/Source/BlaxLaws/HookGuard.cs @@ -0,0 +1,50 @@ +using System; + +namespace BlaxLaws +{ + /// + /// Every Harmony hook catches its own exceptions, so the vanilla method and every other mod's patch + /// always run (design: "Rules every feature follows"). The pattern, in every prefix, postfix and + /// finalizer body: + /// + /// try { ... } + /// catch (Exception e) { HookGuard.Fail("hook C, Thing.Ingested", e); } + /// + /// Hot hooks write the try/catch themselves; Run allocates a closure per call and is for cold paths + /// only (startup, UI, a sweep). A finalizer always returns void: one that returns an Exception makes + /// Harmony "throw ex" and cuts every other mod's stack trace. A prefix that must not skip vanilla + /// returns void too; a bool prefix returns true from its catch. + /// + public static class HookGuard + { + /// Logs the failure once per game under this key and swallows it. + public static void Fail(string where, Exception e) => LawsLog.Once(where, e); + + /// Runs the body; a throw is logged once and swallowed. + public static void Run(string where, Action body) + { + try + { + body(); + } + catch (Exception e) + { + Fail(where, e); + } + } + + /// Runs the body and returns its value; a throw is logged once and gives the fallback. + public static T Run(string where, Func body, T fallback) + { + try + { + return body(); + } + catch (Exception e) + { + Fail(where, e); + return fallback; + } + } + } +} diff --git a/Source/BlaxLaws/Lawbook.cs b/Source/BlaxLaws/Lawbook.cs new file mode 100644 index 0000000..e24c8d6 --- /dev/null +++ b/Source/BlaxLaws/Lawbook.cs @@ -0,0 +1,399 @@ +using System.Collections.Generic; +using System.Linq; +using Verse; + +namespace BlaxLaws +{ + /// + /// Every write to the lawbook goes through here (design: "Lawbook tab", How), and so does the "most + /// specific row wins" match. Each write rebuilds Watch. Action, Option and Stage are a row's key: a write + /// that would make a second row with the same key is refused and names the existing row. + /// + public static class Lawbook + { + public const int MinDays = 1; + public const int MaxDays = 50; + + private static readonly List NoLaws = new List(); + + /// The running game's rows, or an empty list without a game. + public static IReadOnlyList Laws => GameComponent_BlaxLaws.Instance?.Laws ?? NoLaws; + + /// The default days of a severity: Minor 1, Moderate 3, Serious 5, Grave 10. + public static int DefaultDays(LawSeverity severity) + { + switch (severity) + { + case LawSeverity.Minor: return 1; + case LawSeverity.Moderate: return 3; + case LawSeverity.Serious: return 5; + default: return 10; + } + } + + public static int ClampDays(int days) => days < MinDays ? MinDays : days > MaxDays ? MaxDays : days; + + /// Null, "" and "@any" read as the same option (no option for a non-binge row, any drug for a binge row). + public static string NormalizeOption(string option) => option.NullOrEmpty() || option == DrugOptions.Any ? null : option; + + // ---- lookups ------------------------------------------------------------------------- + + /// The row with this key, or null. + public static Law Find(string actKey, string option, LawStage stage) + { + foreach (Law l in Laws) + { + if (l.HasKey(actKey, option, stage)) + return l; + } + return null; + } + + /// The stages an entry offers (planning only for breaks; did it for linked breaks and every other entry). + public static IEnumerable StagesOf(ActEntry entry) => entry?.Stages ?? Enumerable.Empty(); + + /// Whether the punishment fits the entry and stage (PunishmentDef.fits). + public static bool Fits(PunishmentDef punishment, ActEntry entry, LawStage stage) => + punishment != null && entry != null && punishment.Fits(entry, stage); + + /// The punishments a row of this entry and stage offers, in order. + public static IEnumerable PunishmentsFor(ActEntry entry, LawStage stage) => + DefDatabase.AllDefsListForReading.Where(p => Fits(p, entry, stage)).OrderBy(p => p.order); + + /// "Needs Ideology" or "Missing: Core" for a row whose entry is missing, else null. + public static string MissingText(Law law) => law?.MissingText; + + // ---- writes -------------------------------------------------------------------------- + + /// + /// A new row for the entry, not added yet: the entry's first stage, Moderate, Warn, 3 days and On; a + /// drug binge row gets the Any option. A missing entry gives a did-it row. + /// + public static Law NewRow(string actKey) + { + ActEntry entry = ActCatalogue.Get(actKey); + var law = new Law + { + actKey = actKey, + stage = entry?.FirstStage ?? LawStage.DidIt, + severity = LawSeverity.Moderate, + punishment = BlaxLawsDefOf.Warn?.defName ?? "Warn", + days = DefaultDays(LawSeverity.Moderate), + enabled = true, + option = entry != null && entry.hasDrugOption ? DrugOptions.Any : null, + }; + Remember(law, entry); + return law; + } + + /// + /// Adds a prepared row (from NewRow, the starter list or a test). Gives it an id and, when its entry + /// resolves, the entry's label and source. Refuses a row whose key exists: then existing is that row. + /// + public static bool TryAdd(Law law, out Law existing) + { + existing = null; + GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance; + if (comp == null || law == null || law.actKey.NullOrEmpty()) + return false; + existing = Find(law.actKey, law.option, law.stage); + if (existing != null) + return false; + if (law.id <= 0 || comp.LawById(law.id) != null) + law.id = comp.TakeLawId(); + law.days = ClampDays(law.days); + Remember(law, ActCatalogue.Get(law.actKey)); + comp.AddLaw(law); + Changed(); + return true; + } + + /// Adds NewRow(actKey). Returns the new row, or null when a row with that key exists (Find gives it). + public static Law Add(string actKey) + { + Law law = NewRow(actKey); + return TryAdd(law, out _) ? law : null; + } + + /// + /// Changes the row's action. The stage moves to the entry's first stage if the entry lacks it, a + /// punishment that no longer fits resets to Warn, and the option follows the entry. Refused when the + /// new key exists: then existing is that row. + /// + public static bool SetAction(Law law, string actKey, out Law existing) + { + existing = null; + if (law == null || actKey.NullOrEmpty()) + return false; + ActEntry entry = ActCatalogue.Get(actKey); + LawStage stage = entry == null || entry.HasStage(law.stage) ? law.stage : entry.FirstStage; + string option = entry != null && entry.hasDrugOption ? law.option ?? DrugOptions.Any : null; + existing = FindOther(law, actKey, option, stage); + if (existing != null) + return false; + law.actKey = actKey; + law.stage = stage; + law.option = option; + Remember(law, entry); + ResetPunishmentIfUnfit(law, entry); + Changed(); + return true; + } + + /// Changes a drug binge row's option. Refused when the key exists. + public static bool SetOption(Law law, string option, out Law existing) + { + existing = null; + if (law == null) + return false; + existing = FindOther(law, law.actKey, option, law.stage); + if (existing != null) + return false; + law.option = option; + Changed(); + return true; + } + + /// Changes the row's stage; a punishment that no longer fits resets to Warn. Refused when the key exists. + public static bool SetStage(Law law, LawStage stage, out Law existing) + { + existing = null; + if (law == null) + return false; + ActEntry entry = law.Entry; + if (entry != null && !entry.HasStage(stage)) + return false; + existing = FindOther(law, law.actKey, law.option, stage); + if (existing != null) + return false; + law.stage = stage; + ResetPunishmentIfUnfit(law, entry); + Changed(); + return true; + } + + /// Changes the severity. Days move to the new default only while they still equal the old default. + public static void SetSeverity(Law law, LawSeverity severity) + { + if (law == null || law.severity == severity) + return; + if (law.days == DefaultDays(law.severity)) + law.days = DefaultDays(severity); + law.severity = severity; + Changed(); + } + + /// Changes the punishment. Refused (false) when it doesn't fit the row's entry and stage. + public static bool SetPunishment(Law law, PunishmentDef punishment) + { + if (law == null || punishment == null) + return false; + ActEntry entry = law.Entry; + if (entry != null && !punishment.Fits(entry, law.stage)) + return false; + law.punishment = punishment.defName; + Changed(); + return true; + } + + public static void SetDays(Law law, int days) + { + if (law == null) + return; + law.days = ClampDays(days); + Changed(); + } + + public static void SetEnabled(Law law, bool enabled) + { + if (law == null || law.enabled == enabled) + return; + law.enabled = enabled; + Changed(); + } + + /// Moves the row to a new place in the list. + public static void Move(Law law, int index) + { + GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance; + if (comp == null || law == null) + return; + comp.MoveLaw(law, index); + Changed(); + } + + /// The open cases a delete would close; the UI names the count and asks first. + public static int OpenCaseCount(Law law) => GameComponent_BlaxLaws.Instance?.OpenCaseCount(law) ?? 0; + + /// Deletes the row. Its open cases close as "law repealed". Returns how many closed. + public static int Delete(Law law) + { + GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance; + if (comp == null || law == null || !comp.RemoveLaw(law)) + return 0; + int closed = 0; + foreach (LawCase c in comp.OpenCases()) + { + if (c.planningLawId != law.id && c.didItLawId != law.id) + continue; + PunishmentDef active = c.activePunishment.NullOrEmpty() ? null : DefDatabase.GetNamedSilentFail(c.activePunishment); + if (active != null) + HookGuard.Run("Stopping " + active.defName, () => active.Worker.Stop(c)); + comp.CloseCase(c, CaseOutcomes.Repealed); + closed++; + } + Changed(); + return closed; + } + + // ---- starter lawbook ----------------------------------------------------------------- + + /// One suggested row. + public readonly struct StarterRow + { + public readonly string actKey; + public readonly string option; + public readonly LawStage stage; + public readonly LawSeverity severity; + public readonly string punishment; + public readonly int days; + + public StarterRow(string actKey, string option, LawStage stage, LawSeverity severity, string punishment, int days) + { + this.actKey = actKey; + this.option = option; + this.stage = stage; + this.severity = severity; + this.punishment = punishment; + this.days = days; + } + } + + /// + /// The seven suggested rows (design: "Defaults I picked"), Core entries only. "Ate: any meat" is left + /// out, since most colonies eat meat. + /// + public static readonly StarterRow[] StarterRows = + { + new StarterRow(ActKey.OfGroup(ActCategories.Break, ActGroups.AnyDrugBinge), DrugOptions.Any, LawStage.Planning, LawSeverity.Moderate, "Subdue", 3), + new StarterRow(ActKey.OfGroup(ActCategories.Break, ActGroups.AnyDrugBinge), DrugOptions.Any, LawStage.DidIt, LawSeverity.Serious, "Jail", 5), + new StarterRow(ActKey.Of(ActCategories.Break, "FireStartingSpree"), null, LawStage.Planning, LawSeverity.Serious, "Subdue", 5), + new StarterRow(ActKey.Of(ActCategories.Break, "FireStartingSpree"), null, LawStage.DidIt, LawSeverity.Grave, "Jail", 10), + new StarterRow(ActKey.Of(ActCategories.Break, "CorpseObsession"), null, LawStage.Planning, LawSeverity.Moderate, "Subdue", 3), + new StarterRow(ActKey.Of(ActCategories.Special, SpecialActs.StartedSocialFight), null, LawStage.DidIt, LawSeverity.Minor, "Warn", 1), + new StarterRow(ActKey.Of(ActCategories.Interaction, "Insult"), null, LawStage.DidIt, LawSeverity.Minor, "Warn", 1), + }; + + /// Adds the starter rows that are missing. Returns how many were added (0 when pressed again). + public static int AddStarter() + { + int added = 0; + foreach (StarterRow s in StarterRows) + { + if (Find(s.actKey, s.option, s.stage) != null) + continue; + var law = new Law + { + actKey = s.actKey, + option = s.option, + stage = s.stage, + severity = s.severity, + punishment = s.punishment, + days = s.days, + enabled = true, + // Every starter entry is Core's; this is what a missing entry shows until the catalogue knows it. + savedLabel = ActKey.NameOf(s.actKey), + savedMod = DlcSupport.CoreName, + savedPackageId = DlcSupport.CorePackageId, + }; + if (TryAdd(law, out _)) + added++; + } + return added; + } + + // ---- matching ------------------------------------------------------------------------ + + /// + /// The most specific enabled row of the act's category for the stage whose entry matches the act, or + /// null. Specificity: a single def over a group (the smaller group first) over the category's "any"; + /// then, for drug binge rows, one chemical over hard or social over any drug; then the older row. + /// Rows whose entry is missing never match. + /// + public static Law BestRow(ActEvent act, LawStage stage) + { + if (act == null || act.categoryId == null) + return null; + IReadOnlyList rows = Watch.LawsOf(act.categoryId); + Law best = null; + ActEntry bestEntry = null; + for (int i = 0; i < rows.Count; i++) + { + Law law = rows[i]; + if (!law.enabled || law.stage != stage) + continue; + ActEntry entry = ActCatalogue.Get(law.actKey); + if (entry == null || !entry.Matches(act)) + continue; + if (entry.hasDrugOption && !DrugOptions.Matches(law.option, act)) + continue; + if (best == null || MoreSpecific(entry, law, bestEntry, best)) + { + best = law; + bestEntry = entry; + } + } + return best; + } + + /// Whether row a (entry ea) is more specific than row b (entry eb). + public static bool MoreSpecific(ActEntry ea, Law a, ActEntry eb, Law b) + { + if (ea.Rank != eb.Rank) + return ea.Rank > eb.Rank; + if (ea.Rank == 2) + { + int sa = ea.group?.size ?? int.MaxValue, sb = eb.group?.size ?? int.MaxValue; + if (sa != sb) + return sa < sb; + } + int oa = ea.hasDrugOption ? DrugOptions.Rank(a.option) : 0; + int ob = eb.hasDrugOption ? DrugOptions.Rank(b.option) : 0; + if (oa != ob) + return oa > ob; + return a.id < b.id; + } + + // ---- helpers ------------------------------------------------------------------------- + + private static Law FindOther(Law self, string actKey, string option, LawStage stage) + { + foreach (Law l in Laws) + { + if (l != self && l.HasKey(actKey, option, stage)) + return l; + } + return null; + } + + /// Stores the entry's label and source on the row, so a missing entry still shows them. + private static void Remember(Law law, ActEntry entry) + { + if (entry == null) + return; + law.savedLabel = entry.label; + law.savedMod = entry.sourceMod; + law.savedPackageId = entry.sourcePackageId; + } + + private static void ResetPunishmentIfUnfit(Law law, ActEntry entry) + { + PunishmentDef p = law.PunishmentDef; + if (entry != null && (p == null || !p.Fits(entry, law.stage))) + law.punishment = BlaxLawsDefOf.Warn?.defName ?? "Warn"; + } + + /// After every write: the hot-path cache follows the book. + private static void Changed() => Watch.Rebuild(); + } +} diff --git a/Source/BlaxLaws/LawsLog.cs b/Source/BlaxLaws/LawsLog.cs new file mode 100644 index 0000000..81d8ed0 --- /dev/null +++ b/Source/BlaxLaws/LawsLog.cs @@ -0,0 +1,88 @@ +using System; +using System.Collections.Generic; +using Verse; + +namespace BlaxLaws +{ + /// + /// One-time logging. Every hook sits in try/catch and logs through HookGuard, which logs here, so a + /// broken hook logs once per game instead of every call. The flags reset in + /// GameComponent_BlaxLaws.FinalizeInit, so a failure in a later game logs again. + /// + public static class LawsLog + { + private static readonly HashSet logged = new HashSet(); + + /// Logs "[Blax Laws] where failed" with the exception, once per key until the next reset. + public static void Once(string where, Exception e) + { + try + { + lock (logged) + { + if (!logged.Add(where)) + return; + } + Log.Error("[Blax Laws] " + where + " failed (logged once per game): " + e); + } + catch + { + // Logging must never throw into a hook. + } + } + + /// A one-time message (stand-downs, hints), not an error. + public static void MessageOnce(string key, string text) + { + try + { + lock (logged) + { + if (!logged.Add("msg:" + key)) + return; + } + Log.Message("[Blax Laws] " + text); + } + catch + { + } + } + + /// A one-time warning, for data the game hands over that Laws can't use (a broken def, a saved name it can't read). + public static void WarningOnce(string key, string text) + { + try + { + lock (logged) + { + if (!logged.Add("warn:" + key)) + return; + } + Log.Warning("[Blax Laws] " + text); + } + catch + { + } + } + + public static void ResetOnce() + { + lock (logged) logged.Clear(); + } + } + + /// + /// Switches the test mod flips to force failure paths. Not game state: nothing here is saved and the + /// test runner resets every field after each test. + /// + public static class LawsTestHooks + { + /// CaseFiler.Report throws, to test that a hook's HookGuard keeps vanilla running. + public static bool ReportThrows; + + public static void Reset() + { + ReportThrows = false; + } + } +} diff --git a/Source/BlaxLaws/Model/ActEvent.cs b/Source/BlaxLaws/Model/ActEvent.cs new file mode 100644 index 0000000..97cb499 --- /dev/null +++ b/Source/BlaxLaws/Model/ActEvent.cs @@ -0,0 +1,61 @@ +using RimWorld; +using Verse; +using Verse.AI; + +namespace BlaxLaws +{ + /// + /// One act as a hook saw it, handed to CaseFiler.Report. Hooks build it only after their Watch flag and + /// Watch.MayMatch passed, so an empty lawbook allocates nothing. Never saved. + /// + /// What each category puts in def: Break the MentalStateDef, Ate the eaten ThingDef, Used the used + /// ThingDef, Interaction the InteractionDef, RecordedAct the HistoryEventDef, Record the RecordDef, Bill + /// the RecipeDef, Special the ActDef. + /// + public sealed class ActEvent + { + /// The category id (ActCategories). + public string categoryId; + + /// The def the act is about; see the class summary. + public Def def; + + /// Who did it. Filtered by Offenders.IsCovered inside Report. + public Pawn offender; + + /// Who it was done to, when there is someone (the insulted pawn, the provoker of a fight). + public Pawn victim; + + /// The thing involved (the eaten stack, the used item, the corpse), when there is one. May be destroyed by now. + public Thing thing; + + /// The drug's chemical (a dose), or the binge's chosen chemical (hook A on a drug binge). + public ChemicalDef chemical; + + /// The drug's category (a dose), or the binge's (MentalState_BingingDrug.drugCategory). + public DrugCategory drugCategory; + + /// What the hook read from the thing for thing-level groups (hook C's prefix). + public ActFacts facts; + + /// Notes the case takes over (on a table, dug up). + public CaseNotes notes; + + /// The live mental state: the new one for a Break report, else null (Report reads the offender's). + public MentalState mentalState; + + public ActEvent() + { + } + + public ActEvent(string categoryId, Def def, Pawn offender) + { + this.categoryId = categoryId; + this.def = def; + this.offender = offender; + } + + public override string ToString() => + categoryId + "/" + (def?.defName ?? "null") + " by " + (offender?.LabelShort ?? "nobody") + (victim != null ? " on " + victim.LabelShort : ""); + } +} diff --git a/Source/BlaxLaws/Model/ActKey.cs b/Source/BlaxLaws/Model/ActKey.cs new file mode 100644 index 0000000..4ddfc4d --- /dev/null +++ b/Source/BlaxLaws/Model/ActKey.cs @@ -0,0 +1,164 @@ +using System; +using RimWorld; +using Verse; + +namespace BlaxLaws +{ + /// + /// Act keys: how the save names a catalogue entry. "Category/defName" for a single def + /// ("Ate/WakeUp", "Break/FireStartingSpree", "Special/SetFire"), "Category/@group" for a group + /// ("Ate/@humanMeat", "Break/@anyDrugBinge"). The category is an ActCategoryDef's defName, the group + /// id an ActGroup's id. Keys are only ever added, never renamed: a saved row names its entry by key. + /// + public static class ActKey + { + public const char Separator = '/'; + public const string GroupPrefix = "@"; + + public static string Of(string categoryId, string name) => categoryId + Separator + name; + + public static string Of(string categoryId, Def def) => Of(categoryId, def.defName); + + /// A group key; the id may come with or without its "@". + public static string OfGroup(string categoryId, string groupId) => + Of(categoryId, groupId.StartsWith(GroupPrefix) ? groupId : GroupPrefix + groupId); + + /// "Ate" for "Ate/WakeUp", null for a key without a separator. + public static string CategoryOf(string key) + { + if (key.NullOrEmpty()) + return null; + int i = key.IndexOf(Separator); + return i <= 0 ? null : key.Substring(0, i); + } + + /// "WakeUp" for "Ate/WakeUp", "@humanMeat" for "Ate/@humanMeat", null for a key without a separator. + public static string NameOf(string key) + { + if (key.NullOrEmpty()) + return null; + int i = key.IndexOf(Separator); + return i < 0 || i == key.Length - 1 ? null : key.Substring(i + 1); + } + + public static bool IsGroup(string key) => NameOf(key)?.StartsWith(GroupPrefix) ?? false; + + public static bool TryParse(string key, out string categoryId, out string name) + { + categoryId = CategoryOf(key); + name = NameOf(key); + return categoryId != null && name != null; + } + } + + /// The categories' ids: the defNames of the ActCategoryDefs in Defs/BlaxLaws_Categories.xml. + public static class ActCategories + { + public const string Break = "Break"; + public const string Ate = "Ate"; + public const string Used = "Used"; + public const string Interaction = "Interaction"; + public const string RecordedAct = "RecordedAct"; + public const string Record = "Record"; + public const string Bill = "Bill"; + public const string Special = "Special"; + + public static readonly string[] All = { Break, Ate, Used, Interaction, RecordedAct, Record, Bill, Special }; + } + + /// The special acts' ids: the defNames of the ActDefs in Defs/BlaxLaws_Acts.xml. + public static class SpecialActs + { + public const string SetFire = "SetFire"; + public const string DisplayedCorpse = "DisplayedCorpse"; + public const string StartedSocialFight = "StartedSocialFight"; + } + + /// + /// Group ids the catalogue package registers (design: "Act catalogue and detection", the Groups column). + /// Each is unique within its category; the key is ActKey.OfGroup(category, id). + /// + public static class ActGroups + { + /// The category's "any": every entry of it. The least specific row. + public const string Any = "@any"; + + // Mental breaks + public const string AnyDrugBinge = "@anyDrugBinge"; + public const string AnyTantrum = "@anyTantrum"; + public const string AnyInsultingSpree = "@anyInsultingSpree"; + public const string AnyAggressive = "@anyAggressive"; + + // Ate + public const string AnyDrug = "@anyDrug"; + public const string HardDrugs = "@hardDrugs"; + public const string SocialDrugs = "@socialDrugs"; + public const string MedicalDrugs = "@medicalDrugs"; + public const string AnyMeat = "@anyMeat"; + public const string RawMeatOrCorpse = "@rawMeatOrCorpse"; + public const string HumanMeat = "@humanMeat"; + public const string InsectMeat = "@insectMeat"; + public const string RawFood = "@rawFood"; + public const string AnyMeal = "@anyMeal"; + + // Social interactions + public const string InsultOrSlight = "@insultOrSlight"; + + // Bills + public const string AnySurgery = "@anySurgery"; + } + + /// + /// The option of a drug binge row: which drug counts. "@any", "@hard", "@social", or a ChemicalDef's + /// defName. Rows of other entries keep a null option. + /// + public static class DrugOptions + { + public const string Any = "@any"; + public const string Hard = "@hard"; + public const string Social = "@social"; + + /// Null and "" read as Any. + public static string Normalize(string option) => option.NullOrEmpty() ? Any : option; + + /// + /// The option's rank for "the most specific row wins": one chemical 3, hard or social 2, any 1. + /// + public static int Rank(string option) + { + string o = Normalize(option); + if (o == Any) + return 1; + return o == Hard || o == Social ? 2 : 3; + } + + /// Whether the dose (or the binge's chosen chemical) in the act counts under the option. + public static bool Matches(string option, ActEvent act) + { + string o = Normalize(option); + if (o == Any) + return true; + if (act == null) + return false; + if (o == Hard) + return act.drugCategory == DrugCategory.Hard; + if (o == Social) + return act.drugCategory == DrugCategory.Social; + return act.chemical != null && act.chemical.defName == o; + } + + /// The option's label: "Any drug", "Hard drugs", "Social drugs" or the chemical's label. + public static string Label(string option) + { + string o = Normalize(option); + if (o == Any) + return "BlaxLaws_DrugOption_Any".Translate(); + if (o == Hard) + return "BlaxLaws_DrugOption_Hard".Translate(); + if (o == Social) + return "BlaxLaws_DrugOption_Social".Translate(); + ChemicalDef chem = DefDatabase.GetNamedSilentFail(o); + return chem != null ? chem.LabelCap.ToString() : o; + } + } +} diff --git a/Source/BlaxLaws/Model/Enums.cs b/Source/BlaxLaws/Model/Enums.cs new file mode 100644 index 0000000..7dcf5c1 --- /dev/null +++ b/Source/BlaxLaws/Model/Enums.cs @@ -0,0 +1,139 @@ +using System; +using Verse; + +namespace BlaxLaws +{ + /// + /// A law's stage. Planning: a break has started and nothing is done yet (break entries only). Did it: + /// the act happened. Saved by name, so the names never change. + /// + public enum LawStage + { + Planning, + DidIt, + } + + /// A law's severity. Sets the default days (1, 3, 5, 10) and orders the case log. Saved by name. + public enum LawSeverity + { + Minor, + Moderate, + Serious, + Grave, + } + + /// Where a case stands. Saved by name. + public enum CaseStatus + { + /// Filed; nothing runs yet, or it waits (no bed, no enforcer, danger, a hold). + Open, + /// An enforcer is on it (a subdue, an arrest or a capture job). + Enforcing, + /// The offender serves a sentence in Laws' custody. + Jailed, + /// Done; LawCase.outcome says how. + Closed, + } + + /// Notes a case keeps about the act ("on a table", "dug up from a grave"). Saved by name. + [Flags] + public enum CaseNotes + { + None = 0, + OnTable = 1, + DugUp = 2, + } + + /// + /// What a hook read from the thing itself, before it could be destroyed (hook C's prefix), for groups + /// that depend on the thing rather than its def: a meal with meat in it, human meat. Not saved. + /// + [Flags] + public enum ActFacts + { + None = 0, + /// Any meat, meals with meat included (FoodUtility.GetFoodKind). + Meat = 1, + /// Raw meat or a corpse, unprocessed. + RawMeatOrCorpse = 2, + /// Human meat, a humanlike corpse or an ingredient of either. + HumanMeat = 4, + /// Insect meat. + InsectMeat = 8, + /// Raw food (ingestible preferability). + RawFood = 16, + /// A meal (processed food). + Meal = 32, + } + + /// Which stages of a case have had their punishment dispatched. Saved by name. + [Flags] + public enum StageMask + { + None = 0, + Planning = 1, + DidIt = 2, + } + + /// + /// The entry kind and stage a punishment fits (design: "Lawbook tab", punishments per entry and stage). + /// Read from PunishmentDef.fits in XML. + /// + public enum PunishmentFit + { + /// A break that isn't hostile to the colony, at planning. + BreakPlanning, + /// A break that isn't hostile to the colony, at did it. + BreakDidIt, + /// A break hostile to the colony (berserk), at planning. + HostileBreakPlanning, + /// A break hostile to the colony (berserk), at did it. + HostileBreakDidIt, + /// Every entry outside the breaks: ate, used, interactions, recorded acts, records, bills, special acts. + Act, + } + + /// What an Enforcement queue entry does when it comes due. + public enum CaseTask + { + /// Start the punishment of the case's law for the entry's stage (PunishmentWorker.Start). + Punish, + /// Write "Maintain only" on a pawn Laws just jailed (Sentences.WriteMaintainOnly). + MaintainOnly, + } + + /// Outcome keys of closed cases. The label is "BlaxLaws_Outcome_" + key. Saved as strings. + public static class CaseOutcomes + { + public const string Repealed = "Repealed"; + public const string BreakEnded = "BreakEnded"; + public const string NotEnforced = "NotEnforced"; + public const string OffenderGone = "OffenderGone"; + public const string Warned = "Warned"; + public const string Guilty = "Guilty"; + public const string Subdued = "Subdued"; + public const string Served = "Served"; + public const string ReleasedEarly = "ReleasedEarly"; + + /// The outcome's label, or the key itself when no string exists (an outcome a later release added). + public static string Label(string key) + { + if (key.NullOrEmpty()) + return ""; + string k = "BlaxLaws_Outcome_" + key; + return k.CanTranslate() ? k.Translate().ToString() : key; + } + } + + /// Labels for the enums, from Keyed. + public static class LawLabels + { + public static string Stage(LawStage stage) => ("BlaxLaws_Stage_" + stage).Translate(); + + public static string Severity(LawSeverity severity) => ("BlaxLaws_Severity_" + severity).Translate(); + + public static string Status(CaseStatus status) => ("BlaxLaws_Status_" + status).Translate(); + + public static StageMask Mask(LawStage stage) => stage == LawStage.Planning ? StageMask.Planning : StageMask.DidIt; + } +} diff --git a/Source/BlaxLaws/Model/Law.cs b/Source/BlaxLaws/Model/Law.cs new file mode 100644 index 0000000..b3c4496 --- /dev/null +++ b/Source/BlaxLaws/Model/Law.cs @@ -0,0 +1,89 @@ +using RimWorld; +using Verse; + +namespace BlaxLaws +{ + /// + /// One row of the lawbook. Holds only names and numbers, so a row whose entry is gone (a DLC drug + /// without its DLC, a removed mod's interaction) stays, shows "Needs <DLC>" or "Missing: <mod>" + /// and works again when the mod comes back (design: "Lawbook and cases in one GameComponent"). + /// + /// Read the fields freely; change a row only through Lawbook, which keeps the key unique and rebuilds + /// the Watch cache. Action (actKey), Option and Stage are the row's key. + /// + public class Law : IExposable + { + /// Unique in the save, never reused. 0 until Lawbook adds the row. + public int id; + + /// The catalogue entry: "Ate/WakeUp", "Break/@anyDrugBinge" (ActKey). + public string actKey; + + /// The entry's label when the row was written, shown while the entry is missing. + public string savedLabel; + + /// The entry's source when the row was written: "Core", "Ideology" or a mod's name. + public string savedMod; + + /// The entry's source package id when the row was written ("ludeon.rimworld.ideology"). + public string savedPackageId; + + /// Drug binge rows only: DrugOptions ("@any", "@hard", "@social" or a ChemicalDef defName). Null otherwise. + public string option; + + public LawStage stage = LawStage.DidIt; + + public LawSeverity severity = LawSeverity.Moderate; + + /// The PunishmentDef's defName ("Warn", "Jail"). + public string punishment = "Warn"; + + /// 1 to 50; used by punishments with usesDays. + public int days = 3; + + public bool enabled = true; + + /// The category id, the first part of the act key. + public string CategoryId => ActKey.CategoryOf(actKey); + + /// The catalogue entry, or null while it is missing. + public ActEntry Entry => ActCatalogue.Get(actKey); + + public bool Resolves => Entry != null; + + /// The punishment's def, or null when a later release's punishment was saved and is gone. + public PunishmentDef PunishmentDef => punishment.NullOrEmpty() ? null : DefDatabase.GetNamedSilentFail(punishment); + + /// The label the lawbook shows: the entry's, the saved one while missing, else the key. + public string Label => Entry?.label ?? (savedLabel.NullOrEmpty() ? actKey : savedLabel); + + /// "Needs Ideology" or "Missing: Core" while the entry is missing, else null. + public string MissingText => Resolves ? null : DlcSupport.MissingText(savedMod, savedPackageId); + + /// The sentence or guilt length in ticks. + public int DaysTicks => days * GenDate.TicksPerDay; + + /// Whether this row has the given key (option compared as DrugOptions only for rows that keep one). + public bool HasKey(string key, string opt, LawStage stg) => + actKey == key && stage == stg && Lawbook.NormalizeOption(option) == Lawbook.NormalizeOption(opt); + + public void ExposeData() + { + Scribe_Values.Look(ref id, "id"); + Scribe_Values.Look(ref actKey, "actKey"); + Scribe_Values.Look(ref savedLabel, "savedLabel"); + Scribe_Values.Look(ref savedMod, "savedMod"); + Scribe_Values.Look(ref savedPackageId, "savedPackageId"); + Scribe_Values.Look(ref option, "option"); + Scribe_Values.Look(ref stage, "stage", LawStage.DidIt); + Scribe_Values.Look(ref severity, "severity", LawSeverity.Moderate); + Scribe_Values.Look(ref punishment, "punishment", "Warn"); + Scribe_Values.Look(ref days, "days", 3); + Scribe_Values.Look(ref enabled, "enabled", true); + } + + public override string ToString() => + "Law " + id + " " + actKey + (option != null ? " [" + option + "]" : "") + " " + stage + " " + severity + " " + punishment + + (enabled ? "" : " (off)"); + } +} diff --git a/Source/BlaxLaws/Model/LawCase.cs b/Source/BlaxLaws/Model/LawCase.cs new file mode 100644 index 0000000..5576b14 --- /dev/null +++ b/Source/BlaxLaws/Model/LawCase.cs @@ -0,0 +1,237 @@ +using RimWorld; +using RimWorld.Planet; +using Verse; + +namespace BlaxLaws +{ + /// + /// One incident: a break from its start to its end, or one act outside a break (plus the repeats the + /// cooldown folds into it). Saved deep in GameComponent_BlaxLaws as names, numbers and pawn references; + /// a reference to a pawn that is gone becomes null on save and after load, and the case keeps the name + /// (design: "Lawbook and cases in one GameComponent"). + /// + /// CaseFiler opens cases; Enforcement and the punishment workers move them on. Write the fields from + /// those places only; close a case with GameComponent_BlaxLaws.CloseCase. + /// + public class LawCase : IExposable + { + public int id; + + // ---- who ------------------------------------------------------------------------------ + + public Pawn offender; + /// The offender's short name when the case was filed, kept after the pawn is gone. + public string offenderName; + public string offenderId; + + public Pawn victim; + public string victimName; + public string victimId; + + // ---- what ----------------------------------------------------------------------------- + + /// The act key of the row that opened the case. + public string actKey; + + /// The defName that matched (which drug, which recipe, which break). Updated by a later act of the case. + public string matchedDef; + + /// Break cases: the MentalStateDef's defName. Null for acts outside a break. + public string breakState; + + /// Break cases: the tick the break started (TicksGame minus MentalState.Age, to within 30 ticks). + public int breakStartTick = -1; + + /// The row whose punishment the planning stage runs, or -1. + public int planningLawId = -1; + + /// The row whose punishment the did-it stage runs, or -1. Set once per case. + public int didItLawId = -1; + + /// The highest severity of the case's rows, kept for the log after a row is deleted. + public LawSeverity severity; + + /// The stage reached. + public LawStage stage; + + /// Did-it acts in this case: doses during a binge, repeats inside the cooldown. 0 at planning. + public int count; + + public CaseNotes notes; + + // ---- when and how far ----------------------------------------------------------------- + + public int openTick; + public int lastActTick; + public int closeTick = -1; + public CaseStatus status = CaseStatus.Open; + + /// CaseOutcomes key once closed, else null. + public string outcome; + + /// Which stages' punishments were dispatched (each row fires once per case). + public StageMask punishedStages; + + /// The PunishmentDef defName running for this case (Enforcement calls its Sweep), or null. + public string activePunishment; + + /// The stage activePunishment runs for. + public LawStage activeStage; + + /// The pawn carrying it out, one enforcement at a time. + public Pawn enforcer; + + /// Why enforcement waits, as a Keyed key the Cases tab shows, or null. Set by the punishment workers. + public string waitReason; + + // ---- jail ----------------------------------------------------------------------------- + + /// The tick the offender became Laws' prisoner (hook K), or -1. + public int captureTick = -1; + + /// "Maintain only" was written two ticks after the capture. + public bool maintainOnlyDone; + + /// Capture tick plus the sentence, or -1. + public int releaseTick = -1; + + /// The bed the offender owned right before the arrest job took it, given back when the arrest fails. + public Building_Bed oldBed; + + /// "Arrest now" lifted the hold for this case: from here on it arrests a role holder or mechanitor like anyone. + public bool holdLifted; + + // ---- reads ---------------------------------------------------------------------------- + + public bool IsClosed => status == CaseStatus.Closed; + + public bool IsBreakCase => !breakState.NullOrEmpty(); + + public MentalStateDef BreakStateDef => breakState.NullOrEmpty() ? null : DefDatabase.GetNamedSilentFail(breakState); + + public int LawIdFor(LawStage s) => s == LawStage.Planning ? planningLawId : didItLawId; + + /// The row the stage runs, or null (none, or deleted). + public Law LawFor(LawStage s) => GameComponent_BlaxLaws.Instance?.LawById(LawIdFor(s)); + + /// The row the case shows: did it, else planning, else null. + public Law CurrentLaw => LawFor(LawStage.DidIt) ?? LawFor(LawStage.Planning); + + public bool HasPunished(LawStage s) => (punishedStages & LawLabels.Mask(s)) != 0; + + public void MarkPunished(LawStage s) => punishedStages |= LawLabels.Mask(s); + + /// The offender's name, live while the pawn exists. + public string OffenderLabel => offender != null ? offender.LabelShort : offenderName ?? "?"; + + public string VictimLabel => victim != null ? victim.LabelShort : victimName; + + /// What the case is about: the current row's label, else the act key. + public string Label => CurrentLaw?.Label ?? actKey; + + // ---- writes for CaseFiler, Enforcement and the punishment workers ----------------------- + + public void SetOffender(Pawn p) + { + offender = p; + offenderName = p?.LabelShort; + offenderId = p?.ThingID; + } + + public void SetVictim(Pawn p) + { + victim = p; + victimName = p?.LabelShort; + victimId = p?.ThingID; + } + + /// Sets the row a stage runs and raises the case's severity to it. + public void SetLaw(LawStage s, Law law) + { + if (law == null) + return; + if (s == LawStage.Planning) + planningLawId = law.id; + else + didItLawId = law.id; + if (law.severity > severity) + severity = law.severity; + } + + /// Nulls references to pawns and things that are gone, so the save holds no reference it can't load. Names stay. + public void DropGoneReferences() + { + if (IsGone(offender)) + offender = null; + if (IsGone(victim)) + victim = null; + if (IsGone(enforcer)) + enforcer = null; + if (oldBed != null && (oldBed.Destroyed || oldBed.Discarded)) + oldBed = null; + } + + /// + /// Null, discarded, or destroyed without being dead. A dead pawn stays while its corpse or the world + /// still holds it, so its reference resolves on load (the Castes rule). + /// + public static bool IsGone(Pawn pawn) + { + if (pawn == null || pawn.Discarded) + return true; + if (!pawn.Destroyed) + return false; + if (!pawn.Dead) + return true; + return pawn.Corpse == null && !pawn.IsWorldPawn(); + } + + public void ExposeData() + { + if (Scribe.mode == LoadSaveMode.Saving) + DropGoneReferences(); + + Scribe_Values.Look(ref id, "id"); + Scribe_References.Look(ref offender, "offender", saveDestroyedThings: true); + Scribe_Values.Look(ref offenderName, "offenderName"); + Scribe_Values.Look(ref offenderId, "offenderId"); + Scribe_References.Look(ref victim, "victim", saveDestroyedThings: true); + Scribe_Values.Look(ref victimName, "victimName"); + Scribe_Values.Look(ref victimId, "victimId"); + + Scribe_Values.Look(ref actKey, "actKey"); + Scribe_Values.Look(ref matchedDef, "matchedDef"); + Scribe_Values.Look(ref breakState, "breakState"); + Scribe_Values.Look(ref breakStartTick, "breakStartTick", -1); + Scribe_Values.Look(ref planningLawId, "planningLawId", -1); + Scribe_Values.Look(ref didItLawId, "didItLawId", -1); + Scribe_Values.Look(ref severity, "severity", LawSeverity.Minor); + Scribe_Values.Look(ref stage, "stage", LawStage.Planning); + Scribe_Values.Look(ref count, "count"); + Scribe_Values.Look(ref notes, "notes", CaseNotes.None); + + Scribe_Values.Look(ref openTick, "openTick"); + Scribe_Values.Look(ref lastActTick, "lastActTick"); + Scribe_Values.Look(ref closeTick, "closeTick", -1); + Scribe_Values.Look(ref status, "status", CaseStatus.Open); + Scribe_Values.Look(ref outcome, "outcome"); + Scribe_Values.Look(ref punishedStages, "punishedStages", StageMask.None); + Scribe_Values.Look(ref activePunishment, "activePunishment"); + Scribe_Values.Look(ref activeStage, "activeStage", LawStage.Planning); + Scribe_References.Look(ref enforcer, "enforcer", saveDestroyedThings: true); + Scribe_Values.Look(ref waitReason, "waitReason"); + + Scribe_Values.Look(ref captureTick, "captureTick", -1); + Scribe_Values.Look(ref maintainOnlyDone, "maintainOnlyDone"); + Scribe_Values.Look(ref releaseTick, "releaseTick", -1); + Scribe_References.Look(ref oldBed, "oldBed"); + Scribe_Values.Look(ref holdLifted, "holdLifted"); + + if (Scribe.mode == LoadSaveMode.PostLoadInit) + DropGoneReferences(); + } + + public override string ToString() => + "Case " + id + " " + OffenderLabel + " " + actKey + " " + stage + " x" + count + " " + status + (outcome != null ? " (" + outcome + ")" : ""); + } +} diff --git a/Source/BlaxLaws/Offenders.cs b/Source/BlaxLaws/Offenders.cs new file mode 100644 index 0000000..c11c2d9 --- /dev/null +++ b/Source/BlaxLaws/Offenders.cs @@ -0,0 +1,47 @@ +using RimWorld; +using Verse; + +namespace BlaxLaws +{ + /// + /// Who the laws cover (design: "Detection", offender filter, shared by every hook): free colonists, + /// children included, and colony slaves, spawned on a map. Never guests, Hospitality visitors, quest + /// lodgers, prisoners, babies or subhumans. Caravan acts are skipped. + /// + public static class Offenders + { + /// The pawn can be an offender. + public static bool IsCovered(Pawn p) + { + if (p == null || !p.Spawned || p.Map == null || p.Dead) + return false; + if (p.RaceProps == null || !p.RaceProps.Humanlike) + return false; + if (p.Faction == null || !p.Faction.IsPlayer) + return false; + // A slave in a break isn't IsColonist (Pawn.cs:518-527), so slaves are checked on their own. + if (!p.IsFreeColonist && !p.IsSlaveOfColony) + return false; + if (p.IsPrisoner) + return false; + if (p.IsQuestLodger()) + return false; + if (p.DevelopmentalStage.Baby()) + return false; + // Mutants exist only with Anomaly; without it IsSubhuman reads a null field and is false. + if (p.IsSubhuman) + return false; + return true; + } + + /// + /// The act is a player order: the pawn is drafted or its current job is player-forced (Job.cs:37). + /// Exempt while "Player orders are exempt" is on. + /// + public static bool OnPlayerOrder(Pawn p) => p != null && (p.Drafted || (p.CurJob?.playerForced ?? false)); + + /// IsCovered and, while the setting is on, not on a player order. + public static bool CountsAsOffender(Pawn p) => + IsCovered(p) && !(BlaxLawsMod.S.playerOrdersExempt && OnPlayerOrder(p)); + } +} diff --git a/Source/BlaxLaws/Sentences/CaptureHook.cs b/Source/BlaxLaws/Sentences/CaptureHook.cs new file mode 100644 index 0000000..efe3f38 --- /dev/null +++ b/Source/BlaxLaws/Sentences/CaptureHook.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using HarmonyLib; +using RimWorld; +using Verse; + +namespace BlaxLaws +{ + /// + /// Hook K (design: "Enforcement runs a tick later"): a postfix on Pawn_GuestTracker.CapturedBy + /// (RimWorld/Pawn_GuestTracker.cs:561-576, 16 lines with calls, not inlinable), which the arrest and + /// capture jobs call when the enforcer picks the pawn up (JobDriver_TakeToBed.cs:164-178). It returns at + /// once unless the pawn has a case in Enforcing whose own enforcer made the capture for a jail + /// punishment; then the sentence starts (Sentences.OnCaptured). Nothing else of the capture changes. + /// + /// Hook point for later steps: "Release gives back what jail took" adds a prefix here that notes the + /// weapon the pawn holds before SetGuestStatus drops it (:564; :461), and "Castes keeps the caste" sends + /// Castes the blax.laws.jailed hint from that prefix. + /// + [HarmonyPatch(typeof(Pawn_GuestTracker), nameof(Pawn_GuestTracker.CapturedBy))] + public static class Patch_Pawn_GuestTracker_CapturedBy + { + public static void Postfix(Pawn ___pawn, Faction by, Pawn byPawn) + { + try + { + if (byPawn == null || ___pawn == null || by == null || !by.IsPlayer) + return; + GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance; + if (comp == null) + return; + IReadOnlyList list = comp.CasesOf(___pawn); + if (list.Count == 0 || !___pawn.IsPrisonerOfColony) + return; + for (int i = list.Count - 1; i >= 0; i--) + { + LawCase c = list[i]; + if (Sentences.IsOurCapture(c, byPawn)) + { + Sentences.OnCaptured(c); + return; + } + } + } + catch (Exception e) + { + HookGuard.Fail("hook K, Pawn_GuestTracker.CapturedBy", e); + } + } + } +} diff --git a/Source/BlaxLaws/Sentences/JailFlow.cs b/Source/BlaxLaws/Sentences/JailFlow.cs new file mode 100644 index 0000000..6f1bb0e --- /dev/null +++ b/Source/BlaxLaws/Sentences/JailFlow.cs @@ -0,0 +1,285 @@ +using RimWorld; +using Verse; +using Verse.AI; + +namespace BlaxLaws +{ + /// + /// The arrest of a jail case (design: "Jail for N days"): the hold for role holders and mechanitors, the + /// waits (hostile break, danger, no enforcer, no prisoner bed, a reservation someone else holds), guilt + /// renewed right before the job, the old bed noted before the job's first toil takes it and given back + /// when the arrest fails, and the Arrest or Capture job itself. PunishmentWorker_Jail, "Subdue then + /// jail" and "Arrest now" call in here; the sentence itself is Sentences. + /// + public static class JailFlow + { + /// The sentence: the days of the row the case runs, in ticks. + public static int SentenceTicks(LawCase c) + { + Law law = c?.LawFor(c.activeStage) ?? c?.CurrentLaw; + if (law != null) + return Lawbook.ClampDays(law.days) * GenDate.TicksPerDay; + return Lawbook.DefaultDays(c?.severity ?? LawSeverity.Moderate) * GenDate.TicksPerDay; + } + + /// + /// Guilt right before an Arrest or Capture: the sentence plus one day for the release fallback, so the + /// arrest of a free colonist is accepted (Pawn.cs:4087) and a downed one can be captured + /// (GenAI.cs:39-67) however late the arrest comes. + /// + public static int RenewalTicks(LawCase c) => SentenceTicks(c) + Sentences.FallbackTicks; + + /// + /// The case now runs as Jail (from "Subdue then jail", or a fallback). Clears the wait reason the subdue + /// left. + /// + public static void Become(LawCase c) + { + if (c == null || c.IsClosed) + return; + c.activePunishment = BlaxLawsDefOf.Jail?.defName ?? "Jail"; + if (c.status != CaseStatus.Jailed) + c.status = CaseStatus.Open; + c.waitReason = null; + } + + /// The case's enforcer runs or has queued an Arrest or Capture of the offender. + public static bool ArrestRuns(LawCase c) => c?.enforcer != null && EnforcerJobs.TakesToJail(c.enforcer, c.offender); + + /// Ends the case's Arrest or Capture job, current or queued, and gives the old bed back. + public static void EndArrest(LawCase c) + { + if (c?.enforcer == null || c.offender == null) + return; + bool ended = EnforcerJobs.End(c.enforcer, JobDefOf.Arrest, c.offender); + ended |= EnforcerJobs.End(c.enforcer, JobDefOf.Capture, c.offender); + if (ended) + GiveOldBedBack(c); + } + + /// + /// A running or queued Arrest or Capture meets danger: the job ends, the old bed goes back and the case + /// waits for Danger; the sweep arrests after the fight. An enforcer already carrying the offender + /// finishes, since the carry makes it a prisoner (JobDriver_TakeToBed.cs:121-129). Returns whether it + /// was called off. + /// + public static bool CallOffInDanger(LawCase c) + { + Pawn o = c?.offender; + if (o == null || c.enforcer == null || c.enforcer.IsCarryingPawn(o) || !Enforcers.DangerBlocks(o)) + return false; + EndArrest(c); + WaitReasons.Set(c, WaitReasons.Danger); + return true; + } + + /// Whether "Arrest now" lifted the hold for this case. Saved on the case. + public static bool HoldLifted(LawCase c) => c != null && c.holdLifted; + + /// "Arrest now": from here on the case arrests a role holder or mechanitor like anyone. + public static void LiftHold(LawCase c) + { + if (c == null) + return; + c.holdLifted = true; + } + + /// + /// Starts the Arrest (or the Capture of a downed offender) now, or leaves the case waiting with its + /// reason; a letter goes out once when the player has to act (hold, no bed, nobody to enforce). + /// Returns whether the job runs. + /// + public static bool TryArrest(LawCase c, bool ignoreHold) + { + Pawn o = c?.offender; + if (o == null || c.IsClosed || o.Dead || c.status == CaseStatus.Jailed) + return false; + if (o.IsPrisonerOfColony) + { + AlreadyPrisoner(c); + return false; + } + // First: a role holder or mechanitor waits for "Arrest now" whatever else its case waited for before. + if (!ignoreHold && DlcSupport.HeldForArrestNow(o) && !HoldLifted(c)) + { + if (WaitReasons.Set(c, WaitReasons.Hold) && CaseLetters.Once(c, CaseLetters.KindHold)) + HoldLetter(c); + return false; + } + if (!o.Spawned) + { + WaitReasons.Set(c, WaitReasons.Away); + return false; + } + // Vanilla refuses the arrest of a pawn whose break is hostile to the arrester (GenAI.cs:83): wait + // until it ends or the pawn is down, then arrest or capture it. + if (!o.Downed && Enforcers.FightsBack(o)) + { + WaitReasons.Set(c, WaitReasons.HostileBreak); + return false; + } + if (Enforcers.DangerBlocks(o)) + { + WaitReasons.Set(c, WaitReasons.Danger); + return false; + } + Pawn e = Enforcers.Pick(c, EnforcerNeed.Arrest, out string reason); + if (e == null) + { + if (WaitReasons.Set(c, reason) && reason == WaitReasons.NoEnforcer && CaseLetters.Once(c, CaseLetters.KindNoEnforcer)) + CaseLetters.NoEnforcer(c); + return false; + } + Building_Bed bed = FindPrisonerBed(o, e); + if (bed == null) + { + if (WaitReasons.Set(c, WaitReasons.NoBed) && CaseLetters.Once(c, CaseLetters.KindNoBed)) + NoBedLetter(c); + return false; + } + if (!Enforcers.CanTakeToBed(e, o, bed)) + { + WaitReasons.Set(c, WaitReasons.Reserved); + return false; + } + Guilt.AtLeast(o, RenewalTicks(c)); + NoteOldBed(c, o); + // The float menu offers Arrest only to drafted pawns (FloatMenuOptionProvider_Arrest.cs:27-30), so + // Laws builds the job as it does (:52-54). + Job job = JobMaker.MakeJob(o.Downed ? JobDefOf.Capture : JobDefOf.Arrest, o, bed); + job.count = 1; + c.enforcer = e; + c.status = CaseStatus.Enforcing; + c.waitReason = null; + if (EnforcerJobs.Start(e, job)) + return true; + WaitReasons.Set(c, WaitReasons.Reserved); + return false; + } + + /// + /// "Subdue then jail", in the tick the hit downed the offender: renews guilt and puts a vanilla Capture + /// to a prisoner bed at the front of the enforcer's queue (JobQueue.cs:40), so it is the enforcer's + /// next job, ahead of a doctor's rescue. A queued job fails its reservations silently + /// (Pawn_JobTracker.cs:336, 373-375), and a queued vanilla Capture is safe in a save. The case runs as + /// Jail from here; no bed or a hold leaves it waiting. + /// + public static void CaptureAfterSubdue(LawCase c, Pawn enforcer) + { + Become(c); + Pawn o = c?.offender; + if (o == null || enforcer?.jobs == null || c.IsClosed) + return; + if (DlcSupport.HeldForArrestNow(o) && !HoldLifted(c)) + { + if (WaitReasons.Set(c, WaitReasons.Hold) && CaseLetters.Once(c, CaseLetters.KindHold)) + HoldLetter(c); + return; + } + Building_Bed bed = FindPrisonerBed(o, enforcer); + if (bed == null) + { + if (WaitReasons.Set(c, WaitReasons.NoBed) && CaseLetters.Once(c, CaseLetters.KindNoBed)) + NoBedLetter(c); + return; + } + Guilt.AtLeast(o, RenewalTicks(c)); + NoteOldBed(c, o); + Job job = JobMaker.MakeJob(JobDefOf.Capture, o, bed); + job.count = 1; + job.playerForced = true; + enforcer.jobs.jobQueue.EnqueueFirst(job, JobTag.Misc); + c.enforcer = enforcer; + c.status = CaseStatus.Enforcing; + c.waitReason = null; + } + + /// + /// A prisoner bed the enforcer can take the offender to, as the arrest float menu searches + /// (FloatMenuOptionProvider_Arrest.cs:41-49): first respecting other reservations, then ignoring + /// them. The caller checks the reservations before it starts a job. + /// + public static Building_Bed FindPrisonerBed(Pawn offender, Pawn enforcer) + { + if (offender == null || enforcer == null) + return null; + return RestUtility.FindBedFor(offender, enforcer, checkSocialProperness: false, ignoreOtherReservations: false, GuestStatus.Prisoner) + ?? RestUtility.FindBedFor(offender, enforcer, checkSocialProperness: false, ignoreOtherReservations: true, GuestStatus.Prisoner); + } + + /// + /// The bed the offender owns, right before the job: the arrest's first toil claims the prisoner bed, + /// which unclaims the colonist's own (JobDriver_TakeToBed.cs:73; Pawn_Ownership.cs:125-138), and a + /// failed job gives up only the prisoner bed (JobDriver_TakeToBed.cs:74-80). + /// + public static void NoteOldBed(LawCase c, Pawn o) + { + Building_Bed owned = o?.ownership?.OwnedBed; + if (owned != null && !owned.ForPrisoners && !owned.Medical) + c.oldBed = owned; + } + + /// + /// After an Arrest or Capture that ended without a prisoner: reclaims the old bed if it is still free. + /// A bed someone else claimed meanwhile stays theirs (ClaimBedIfNonMedical would evict them). + /// + public static void GiveOldBedBack(LawCase c) + { + Pawn o = c?.offender; + Building_Bed bed = c?.oldBed; + if (o?.ownership == null || bed == null || o.Dead || o.IsPrisonerOfColony) + return; + if (!bed.Spawned || bed.Destroyed || bed.ForPrisoners || bed.Medical) + return; + Building_Bed owned = o.ownership.OwnedBed; + if (owned == bed || (owned != null && !owned.ForPrisoners)) + return; + if (!bed.AnyUnownedSleepingSlot) + return; + o.ownership.ClaimBedIfNonMedical(bed); + } + + /// + /// A slave's jail row in this release (no "Jail for slaves" yet: releasing an imprisoned slave sends it + /// back to its old faction, GenGuest.cs:14-19): subdue while it is in a break, else warn. + /// + public static void SlaveFallback(LawCase c) + { + Pawn o = c?.offender; + if (o == null || c.IsClosed) + return; + if (!o.Downed && SubdueFlow.InBreak(c) && !Enforcers.FightsBack(o) && !DlcSupport.IsChild(o)) + { + c.activePunishment = BlaxLawsDefOf.Subdue?.defName ?? "Subdue"; + c.waitReason = null; + SubdueFlow.TryIssue(c, EnforcerNeed.Subdue); + return; + } + SubdueFlow.WarnInstead(c, "BlaxLaws_MsgWarnedSlave"); + } + + /// The offender became a prisoner without Laws (by hand, another mod): Laws never touches it and closes the case. + public static void AlreadyPrisoner(LawCase c) + { + if (c == null || c.IsClosed || c.status == CaseStatus.Jailed) + return; + CaseMessages.Post(c, "BlaxLaws_MsgAlreadyPrisoner".Translate(c.OffenderLabel)); + GameComponent_BlaxLaws.Instance?.CloseCase(c, EnforcementOutcomes.AlreadyPrisoner); + } + + /// Why Laws holds the arrest of this pawn: its ideoligion role or the mechs it controls. For the hold letter and the "Arrest now" tooltip. + public static string HoldReason(Pawn p) + { + string name = p?.LabelShort ?? "?"; + return DlcSupport.HoldsRole(p) + ? "BlaxLaws_HoldRole".Translate(name).Resolve() + : "BlaxLaws_HoldMechs".Translate(name).Resolve(); + } + + private static void HoldLetter(LawCase c) => + CaseLetters.Send(c, "BlaxLaws_LetterHoldLabel", "BlaxLaws_LetterHoldText", LetterDefOf.NegativeEvent, c.OffenderLabel, c.Label, HoldReason(c.offender)); + + private static void NoBedLetter(LawCase c) => + CaseLetters.Send(c, "BlaxLaws_LetterNoBedLabel", "BlaxLaws_LetterNoBedText", LetterDefOf.NegativeEvent, c.OffenderLabel, c.Label); + } +} diff --git a/Source/BlaxLaws/Sentences/PunishmentWorker_Jail.cs b/Source/BlaxLaws/Sentences/PunishmentWorker_Jail.cs new file mode 100644 index 0000000..5aebe13 --- /dev/null +++ b/Source/BlaxLaws/Sentences/PunishmentWorker_Jail.cs @@ -0,0 +1,94 @@ +using Verse; + +namespace BlaxLaws +{ + /// + /// Jail for N days (design: "Jail for N days"). Start convicts (guilt for the sentence) and arrests + /// through JailFlow: guilt renewed right before the job, a prisoner bed, the old bed noted, Arrest or + /// Capture with reservation checks. A break hostile to the colony waits until it ends or the pawn is + /// down; a role holder or mechanitor waits for "Arrest now"; a slave falls back to subdue in a break, + /// else warn. The sweep retries waits (a missing bed every 2500 ticks) and gives the old bed back when an + /// arrest ended without a prisoner; Sentences takes over at the capture. An arrest or capture not yet + /// carrying the offender is called off when danger comes. + /// + public class PunishmentWorker_Jail : PunishmentWorker + { + public override void Start(LawCase c, Law law, LawStage stage) + { + Pawn o = c?.offender; + if (o == null || c.IsClosed || o.Dead || c.status == CaseStatus.Jailed || JailFlow.ArrestRuns(c)) + return; + if (DlcSupport.IsSlave(o)) + { + JailFlow.SlaveFallback(c); + return; + } + // Conviction: guilt for the sentence when the case is filed. The arrest may come days later; it + // renews the guilt right before the job, and the sentence counts from the capture. + Guilt.AtLeast(o, JailFlow.SentenceTicks(c)); + JailFlow.Become(c); + JailFlow.TryArrest(c, ignoreHold: false); + } + + public override void Sweep(LawCase c) + { + if (c == null || c.IsClosed || c.status == CaseStatus.Jailed) + return; + GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance; + if (!BlaxLawsMod.S.enforceLaws) + { + Stop(c); + comp?.CloseCase(c, CaseOutcomes.NotEnforced); + return; + } + Pawn o = c.offender; + if (o == null || o.Dead) + { + Stop(c); + comp?.CloseCase(c, CaseOutcomes.OffenderGone); + return; + } + if (c.status == CaseStatus.Enforcing) + { + if (JailFlow.ArrestRuns(c)) + { + // Danger since the start: the arrest or the queued capture is called off and the case waits. + JailFlow.CallOffInDanger(c); + return; + } + if (o.IsPrisonerOfColony) + { + JailFlow.AlreadyPrisoner(c); + return; + } + // The Arrest or Capture ended without a prisoner (interrupted, refused, reservations lost). + JailFlow.GiveOldBedBack(c); + c.status = CaseStatus.Open; + c.waitReason = null; + } + if (c.waitReason == WaitReasons.NoBed && (Find.TickManager.TicksGame % Enforcement.SentenceInterval) != 0) + return; + JailFlow.TryArrest(c, ignoreHold: false); + } + + public override void SentenceSweep(LawCase c) => Sentences.Check(c); + + /// + /// Ends an unfinished arrest and gives the old bed back (a later stage takes over). A jailed case is + /// stopped only when its law is repealed: the pawn Laws jailed gets "Release". + /// + public override void Stop(LawCase c) + { + if (c == null) + return; + if (c.status == CaseStatus.Jailed) + { + Sentences.ReleaseOnRepeal(c); + return; + } + JailFlow.EndArrest(c); + if (!c.IsClosed) + c.status = CaseStatus.Open; + } + } +} diff --git a/Source/BlaxLaws/Sentences/Sentences.cs b/Source/BlaxLaws/Sentences/Sentences.cs new file mode 100644 index 0000000..a9ee2db --- /dev/null +++ b/Source/BlaxLaws/Sentences/Sentences.cs @@ -0,0 +1,173 @@ +using System; +using RimWorld; +using UnityEngine; +using Verse; + +namespace BlaxLaws +{ + /// + /// Serving the sentence (design: "Jail for N days"). Hook K (Patch_Pawn_GuestTracker_CapturedBy) moves a + /// case to Jailed at the capture and starts the sentence there, not at filing; "Maintain only" lands two + /// ticks later, after any next-tick default from Blax Castes or a prison mod. Every 2500 ticks Check sets + /// "Release" once the sentence is served, releases in place a day later if no warden did, and closes the + /// case when the pawn is out (served, released early, escaped, dead). Laws writes the prisoner + /// interaction mode only on pawns it jailed itself. + /// + public static class Sentences + { + /// A day after the release tick without a release, Laws releases the pawn in place. + public const int FallbackTicks = GenDate.TicksPerDay; + + private static int Now => Find.TickManager?.TicksGame ?? 0; + + /// + /// Writes "Maintain only" on a pawn Laws jailed, two ticks after the capture + /// (Pawn_GuestTracker.cs:304), and sets maintainOnlyDone. Two ticks win over Castes' next-tick default + /// and Prison Labor's default in any component order (GameComponentUtility.cs:24-31; Game.cs:472-489). + /// + public static void WriteMaintainOnly(LawCase c) + { + if (c == null || c.IsClosed || c.status != CaseStatus.Jailed || c.maintainOnlyDone) + return; + Pawn p = c.offender; + if (p?.guest == null || !p.IsPrisonerOfColony) + return; + p.guest.SetExclusiveInteraction(PrisonerInteractionModeDefOf.MaintainOnly); + c.maintainOnlyDone = true; + } + + /// + /// Every 2500 ticks for a jailed case: the early end, the "Maintain only" backstop, "Release" at the + /// release tick (wardens take it through WorkGiver_Warden_ReleasePrisoner, which calls + /// GenGuest.PrisonerRelease: WasImprisoned, unclaim, free again, GenGuest.cs:8-21), and the fallback. + /// + public static void Check(LawCase c) + { + if (c == null || c.IsClosed || c.status != CaseStatus.Jailed) + return; + GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance; + if (comp == null) + return; + Pawn p = c.offender; + int now = Now; + if (p == null || LawCase.IsGone(p)) + { + comp.CloseCase(c, CaseOutcomes.OffenderGone); + return; + } + if (p.Dead) + { + CaseMessages.Post(c, "BlaxLaws_MsgDiedInJail".Translate(c.OffenderLabel)); + comp.CloseCase(c, EnforcementOutcomes.Died); + return; + } + if (c.releaseTick < 0) + c.releaseTick = (c.captureTick >= 0 ? c.captureTick : now) + JailFlow.SentenceTicks(c); + bool served = now >= c.releaseTick; + if (!p.IsPrisonerOfColony) + { + // Out of Laws' custody: released by a warden after the sentence, or early (recruited, + // released by hand or by another mod), or escaped off the map. + if (!p.Spawned && !served) + { + CaseMessages.Post(c, "BlaxLaws_MsgEscaped".Translate(c.OffenderLabel)); + comp.CloseCase(c, EnforcementOutcomes.Escaped); + } + else if (served) + { + CaseMessages.Post(c, "BlaxLaws_MsgBackAtWork".Translate(c.OffenderLabel)); + comp.CloseCase(c, CaseOutcomes.Served); + } + else + { + CaseMessages.Post(c, "BlaxLaws_MsgReleasedEarly".Translate(c.OffenderLabel)); + comp.CloseCase(c, CaseOutcomes.ReleasedEarly); + } + return; + } + if (!c.maintainOnlyDone && !Enforcement.IsQueued(c, CaseTask.MaintainOnly)) + WriteMaintainOnly(c); + if (!served) + return; + if (p.guest.ExclusiveInteractionMode != PrisonerInteractionModeDefOf.Release) + { + p.guest.SetExclusiveInteraction(PrisonerInteractionModeDefOf.Release); + CaseMessages.Post(c, "BlaxLaws_MsgSentenceServed".Translate(c.OffenderLabel)); + } + if (now >= c.releaseTick + FallbackTicks && p.Spawned) + { + // Nobody released it (no warden, unreachable, a break): Laws releases it where it is. + GenGuest.PrisonerRelease(p); + CaseMessages.Post(c, "BlaxLaws_MsgReleasedInPlace".Translate(c.OffenderLabel)); + comp.CloseCase(c, CaseOutcomes.Served); + } + } + + /// The Cases tab's "Arrest now" applies: a jail case held for a role holder or mechanitor. + public static bool CanArrestNow(LawCase c) => + c?.offender != null && !c.IsClosed && c.status == CaseStatus.Open && c.waitReason == WaitReasons.Hold; + + /// "Arrest now" on a held case: lifts the hold, renews guilt and starts the arrest (or leaves it waiting for a bed or an enforcer). + public static void ArrestNow(LawCase c) + { + if (!CanArrestNow(c)) + return; + JailFlow.LiftHold(c); + JailFlow.Become(c); + JailFlow.TryArrest(c, ignoreHold: true); + } + + /// Ticks of the sentence left for a jailed case, or -1. The Cases tab counts down with it. + public static int TicksLeft(LawCase c) => + c != null && c.status == CaseStatus.Jailed && c.releaseTick >= 0 ? Math.Max(0, c.releaseTick - Now) : -1; + + /// This capture is the one Laws sent: the case's own enforcer took the offender for a jail case. + public static bool IsOurCapture(LawCase c, Pawn byPawn) + { + if (c == null || c.IsClosed || c.status != CaseStatus.Enforcing || byPawn == null || c.enforcer != byPawn) + return false; + string p = c.activePunishment; + return p != null && (p == BlaxLawsDefOf.Jail?.defName || p == BlaxLawsDefOf.SubdueThenJail?.defName); + } + + /// + /// Hook K's postfix: the sentence starts at the capture. Records the capture and release ticks, queues + /// "Maintain only" two ticks on, and sends the jail letter. + /// + internal static void OnCaptured(LawCase c) + { + int now = Now; + c.activePunishment = BlaxLawsDefOf.Jail?.defName ?? "Jail"; + c.status = CaseStatus.Jailed; + c.waitReason = null; + c.captureTick = now; + c.releaseTick = now + JailFlow.SentenceTicks(c); + c.maintainOnlyDone = false; + Enforcement.Schedule(c, CaseTask.MaintainOnly, c.activeStage, Enforcement.MaintainOnlyDelay); + CaseLetters.Jailed(c); + } + + /// + /// The law of a jailed case was repealed (Lawbook.Delete stops the case): Laws sets "Release" on the + /// pawn it jailed, so a warden lets it go. + /// + internal static void ReleaseOnRepeal(LawCase c) + { + Pawn p = c?.offender; + if (p?.guest == null || !p.IsPrisonerOfColony) + return; + p.guest.SetExclusiveInteraction(PrisonerInteractionModeDefOf.Release); + CaseMessages.Post(c, "BlaxLaws_MsgRepealedRelease".Translate(c.OffenderLabel)); + } + + /// The release day as a date at the offender's map. + public static string ReleaseDate(LawCase c) + { + if (c == null || c.releaseTick < 0) + return ""; + Map map = c.offender?.MapHeld; + Vector2 at = map != null ? Find.WorldGrid.LongLatOf(map.Tile) : Vector2.zero; + return GenDate.DateFullStringAt(GenDate.TickGameToAbs(c.releaseTick), at); + } + } +} diff --git a/Source/BlaxLaws/UI/ActIcons.cs b/Source/BlaxLaws/UI/ActIcons.cs new file mode 100644 index 0000000..43de3ff --- /dev/null +++ b/Source/BlaxLaws/UI/ActIcons.cs @@ -0,0 +1,97 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using HarmonyLib; +using RimWorld; +using UnityEngine; +using Verse; + +namespace BlaxLaws +{ + /// Textures the Laws tab uses, all vanilla. + [StaticConstructorOnStartup] + internal static class LawsTex + { + /// The overlap icon: vanilla's warning sign, or the info button when a texture pack lacks it. + public static readonly Texture2D Overlap = ContentFinder.Get("UI/Widgets/Warning", false) ?? TexButton.Info; + + public static readonly Texture2D InBook = Widgets.CheckboxOnTex; + } + + /// + /// The icon of a catalogue entry (design: "Act picker"): the thing's icon for ate, used and bills, the + /// interaction symbol for interactions, nothing otherwise (the label carries it). Never throws into the + /// GUI: a broken modded icon logs once and draws nothing. + /// + public static class ActIcons + { + private static readonly Dictionary symbols = new Dictionary(); + + // InteractionDef.symbol is private; reading the path first keeps ContentFinder from logging an error + // for a modded interaction without one. + private static readonly FieldInfo SymbolPath = AccessTools.Field(typeof(InteractionDef), "symbol"); + + /// Whether the entry draws an icon. + public static bool HasIcon(ActEntry e) + { + switch (e?.def) + { + case ThingDef _: + return true; + case RecipeDef r: + return r.UIIconThing != null || r.UIIcon != null; + case InteractionDef i: + return Symbol(i) != null; + default: + return false; + } + } + + public static void Draw(Rect rect, ActEntry e) + { + if (e?.def == null) + return; + try + { + switch (e.def) + { + case ThingDef t: + Widgets.DefIcon(rect, t); + break; + case RecipeDef r when r.UIIconThing != null || r.UIIcon != null: + Widgets.DefIcon(rect, r); + break; + case InteractionDef i: + Texture2D tex = Symbol(i); + if (tex != null) + GUI.DrawTexture(rect, tex); + break; + } + } + catch (Exception ex) + { + LawsLog.Once("Icon of " + e.key, ex); + } + } + + private static Texture2D Symbol(InteractionDef def) + { + if (symbols.TryGetValue(def, out Texture2D tex)) + return tex; + tex = null; + try + { + // Ideoligion and faction symbols depend on the initiator; the picker shows the def's own symbol only. + string path = SymbolPath?.GetValue(def) as string; + if (!path.NullOrEmpty() && def.symbolSource == InteractionSymbolSource.Def) + tex = def.GetSymbol(); + } + catch (Exception ex) + { + LawsLog.Once("Symbol of " + def.defName, ex); + } + symbols[def] = tex; + return tex; + } + } +} diff --git a/Source/BlaxLaws/UI/ActOverlaps.cs b/Source/BlaxLaws/UI/ActOverlaps.cs new file mode 100644 index 0000000..ebcee61 --- /dev/null +++ b/Source/BlaxLaws/UI/ActOverlaps.cs @@ -0,0 +1,279 @@ +using System; +using System.Collections.Generic; +using RimWorld; +using Verse; + +namespace BlaxLaws +{ + /// + /// The overlap icon of the lawbook (design: "Lawbook tab", row spec, and "One act, one case"): a row + /// that can catch the same act as a row of another category. Outside a break each category files its + /// own case, so a dose can open an "Ate" case and a "Recorded acts" case at once; the icon says so. + /// + /// Only did-it rows outside the breaks take part: inside a break the break case owns the act. Rows that + /// are off or whose entry is missing catch nothing and are left out. The pairs come from what one game + /// act records in each category, read from the game code: + /// + /// - Ate and Recorded acts: Thing.Ingested records the eating events (Verse/Thing.cs:2031-2129) and + /// CompDrug.PostIngested the drug events (RimWorld/CompDrug.cs:105-113) for the eater as doer. + /// - Ate and Records: the ingest toil adds the nutrition eaten (RimWorld/Toils_Ingest.cs:432). + /// - Bills and Records: a finished bill counts meals cooked or things crafted + /// (RimWorld/RecordsUtility.cs:52-75), a surgery the operations performed (RimWorld/Bill_Medical.cs:138). + /// + /// Cached per lawbook write (Watch.Version) and catalogue build; the tab reads it every frame. + /// + public static class ActOverlaps + { + private static readonly List None = new List(); + private static readonly Dictionary> byLaw = new Dictionary>(); + private static readonly Dictionary pairCache = new Dictionary(); + private static int cachedWatch = -1; + private static int cachedCatalogue = -1; + private static int cachedCount = -1; + // The game the cache belongs to, by identity hash, so the cache never keeps a finished game alive. + private static int cachedComp; + + /// The rows of other categories that can catch the same act as this row. Empty when none. + public static IReadOnlyList Of(Law law) + { + if (law == null) + return None; + Refresh(); + return byLaw.TryGetValue(law, out List list) ? list : None; + } + + /// Whether the row takes part in overlaps at all: on, resolving, did it, outside the breaks. + public static bool Counts(Law law) + { + if (law == null || !law.enabled || law.stage != LawStage.DidIt) + return false; + ActEntry e = law.Entry; + return e != null && !e.IsBreak && e.HasStage(LawStage.DidIt); + } + + /// Whether one game act can be caught by both entries (different categories only). + public static bool Overlap(ActEntry a, ActEntry b) + { + if (a == null || b == null || a.categoryId == b.categoryId) + return false; + string key = string.CompareOrdinal(a.key, b.key) < 0 ? a.key + "|" + b.key : b.key + "|" + a.key; + if (pairCache.TryGetValue(key, out bool known)) + return known; + bool result = HookGuard.Run("Overlap " + key, () => Compute(a, b), false); + pairCache[key] = result; + return result; + } + + /// Drops the cache. The next read builds it again. + public static void Reset() + { + byLaw.Clear(); + pairCache.Clear(); + cachedWatch = -1; + } + + private static void Refresh() + { + IReadOnlyList laws = Lawbook.Laws; + GameComponent_BlaxLaws instance = GameComponent_BlaxLaws.Instance; + int comp = instance == null ? 0 : System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(instance); + if (cachedWatch == Watch.Version && cachedCatalogue == ActCatalogue.Version && cachedCount == laws.Count && cachedComp == comp) + return; + cachedWatch = Watch.Version; + cachedCount = laws.Count; + cachedComp = comp; + if (cachedCatalogue != ActCatalogue.Version) + { + pairCache.Clear(); + cachedCatalogue = ActCatalogue.Version; + } + byLaw.Clear(); + for (int i = 0; i < laws.Count; i++) + { + Law a = laws[i]; + if (!Counts(a)) + continue; + for (int j = i + 1; j < laws.Count; j++) + { + Law b = laws[j]; + if (!Counts(b) || !Overlap(a.Entry, b.Entry)) + continue; + Add(a, b); + Add(b, a); + } + } + } + + private static void Add(Law of, Law other) + { + if (!byLaw.TryGetValue(of, out List list)) + byLaw[of] = list = new List(); + list.Add(other); + } + + private static bool Compute(ActEntry a, ActEntry b) + { + if (Is(a, b, ActCategories.Ate, ActCategories.RecordedAct, out ActEntry ate, out ActEntry rec)) + return Any(ate, rec, (t, e) => t is ThingDef td && e is HistoryEventDef ev && IngestionRecords(td, ev)); + if (Is(a, b, ActCategories.Ate, ActCategories.Record, out ate, out rec)) + return Any(ate, rec, (t, r) => t is ThingDef td && r is RecordDef rd && rd == RecordDefOf.NutritionEaten && td.IsNutritionGivingIngestible); + if (Is(a, b, ActCategories.Bill, ActCategories.Record, out ActEntry bill, out rec)) + return Any(bill, rec, (x, r) => x is RecipeDef recipe && r is RecordDef rd && BillCounts(recipe, rd)); + return false; + } + + private static bool Is(ActEntry a, ActEntry b, string catA, string catB, out ActEntry first, out ActEntry second) + { + if (a.categoryId == catA && b.categoryId == catB) + { + first = a; + second = b; + return true; + } + if (b.categoryId == catA && a.categoryId == catB) + { + first = b; + second = a; + return true; + } + first = second = null; + return false; + } + + /// True when some member def of a and some member def of b make the pair. + private static bool Any(ActEntry a, ActEntry b, Func pair) + { + List mb = Members(b); + if (mb.Count == 0) + return false; + foreach (Def da in Members(a)) + { + for (int i = 0; i < mb.Count; i++) + { + if (pair(da, mb[i])) + return true; + } + } + return false; + } + + /// The defs an entry covers: its def, or every def entry of its category the group matches. + public static List Members(ActEntry e) + { + var result = new List(); + if (e == null) + return result; + if (e.def != null) + { + result.Add(e.def); + return result; + } + ActGroup g = e.group; + if (g == null) + return result; + foreach (ActEntry d in ActCatalogue.EntriesOf(e.categoryId)) + { + if (d.def == null) + continue; + bool member; + try + { + member = g.IsAny || g.MatchesDef(d.def); + } + catch (Exception ex) + { + HookGuard.Fail("Overlap group " + g.Key, ex); + member = false; + } + if (member) + result.Add(d.def); + } + return result; + } + + /// + /// Whether eating a thing of this def can record the event with the eater as doer. Def-level, so it + /// says "can": a meal records human meat only when one of its ingredients is. + /// + public static bool IngestionRecords(ThingDef t, HistoryEventDef ev) + { + if (t?.ingestible == null || ev == null) + return false; + if (t.ingestible.ateEvent == ev) + return true; + bool drug = t.GetCompProperties() != null; + bool ingredients = t.HasComp(typeof(CompIngredients)); + bool humanMeat = HumanlikeMeatOrCorpse(t); + bool rawPlant = t.thingCategories != null && t.thingCategories.Contains(ThingCategoryDefOf.PlantFoodRaw); + bool meat = t.IsMeat || t.IsCorpse; + switch (ev.defName) + { + // RimWorld/CompDrug.cs:105-113 + case "IngestedDrug": + return drug; + case "IngestedHardDrug": + return drug && t.ingestible.drugCategory == DrugCategory.Hard; + case "IngestedRecreationalDrug": + return drug && t.IsNonMedicalDrug; + // Verse/Thing.cs:2031-2045, 2089-2104 + case "AteHumanMeat": + return humanMeat || ingredients; + case "AteHumanMeatDirect": + return humanMeat; + case "AteHumanMeatAsIngredient": + case "AteInsectMeatAsIngredient": + case "AteFungusAsIngredient": + case "AteNonFungusMealWithPlants": + return ingredients; + // Verse/Thing.cs:2046-2049 + case "AteNonCannibalFood": + return t.IsNutritionGivingIngestible && !humanMeat; + // Verse/Thing.cs:2055-2071 + case "AteMeat": + return meat && !t.IsProcessedFood && !humanMeat; + case "AteNonMeat": + return !meat && !t.IsProcessedFood && !t.IsDrug && t.IsNutritionGivingIngestible; + // Verse/Thing.cs:2072-2086 + case "AteVeneratedAnimalMeat": + return meat || ingredients; + case "AteFungus": + case "AteNonFungusPlant": + return rawPlant; + default: + return false; + } + } + + private static bool HumanlikeMeatOrCorpse(ThingDef t) + { + if (t.IsCorpse) + return t.ingestible?.sourceDef?.race?.Humanlike ?? false; + return FoodUtility.GetMeatSourceCategory(t) == MeatSourceCategory.Humanlike; + } + + /// Whether finishing one iteration of the recipe raises the record for the doer. + public static bool BillCounts(RecipeDef recipe, RecordDef record) + { + if (recipe == null || record == null) + return false; + if (record == RecordDefOf.OperationsPerformed) + return recipe.IsSurgery; + if (recipe.products == null) + return false; + foreach (ThingDefCountClass p in recipe.products) + { + ThingDef d = p?.thingDef; + if (d == null) + continue; + // RimWorld/RecordsUtility.cs:58-65 and ShouldIncrementThingsCrafted :69-75 + bool meal = d.IsNutritionGivingIngestible && (int)d.ingestible.preferability >= 7; + if (meal && record == RecordDefOf.MealsCooked) + return true; + if (!meal && record == RecordDefOf.ThingsCrafted && + (d.IsApparel || d.IsWeapon || d.HasComp(typeof(CompArt)) || d.HasComp(typeof(CompQuality)))) + return true; + } + return false; + } + } +} diff --git a/Source/BlaxLaws/UI/ActPickerTree.cs b/Source/BlaxLaws/UI/ActPickerTree.cs new file mode 100644 index 0000000..39e9001 --- /dev/null +++ b/Source/BlaxLaws/UI/ActPickerTree.cs @@ -0,0 +1,154 @@ +using System.Collections.Generic; +using RimWorld; +using Verse; + +namespace BlaxLaws +{ + /// One visible line of the act picker: a category header or an entry. + public sealed class ActPickerRow + { + public ActCategoryDef category; + + /// Null for a category header. + public ActEntry entry; + + /// Header: the category is open. + public bool open; + + /// Header: entries that pass the search (all of them without a search). + public int count; + + /// Entry: the lawbook has a row for this act key (the tick). + public bool inBook; + + public bool IsHeader => entry == null; + + public override string ToString() => IsHeader ? "[" + category?.defName + " " + count + (open ? " open" : "") + "]" : entry.key + (inBook ? " (in book)" : ""); + } + + /// + /// The act picker's tree (design: "Act picker"): the catalogue's categories as collapsible headers, each + /// with its groups first and then every entry A to Z (ActCatalogue's order). The search matches each + /// entry's label and defName; typing filters every category at once, opens those with hits and hides + /// those without. The visible lines are rebuilt only when the search, an open state, the catalogue or the + /// lawbook changes, so the window draws only the lines in view, even with hundreds of bills. + /// + public sealed class ActPickerTree + { + public readonly QuickSearchFilter filter = new QuickSearchFilter(); + + private readonly HashSet open = new HashSet(); + private readonly List rows = new List(); + private readonly HashSet inBook = new HashSet(); + private string builtText; + private int builtCatalogue = -1; + private int builtWatch = -1; + private int builtLaws = -1; + private bool dirty = true; + + /// The lines to draw, top to bottom. + public IReadOnlyList Rows + { + get + { + Refresh(); + return rows; + } + } + + /// Entries the search leaves, over every category. + public int Hits { get; private set; } + + public string SearchText + { + get => filter.Text; + set + { + if (filter.Text == value) + return; + filter.Text = value ?? ""; + dirty = true; + } + } + + /// Whether the category's entries show. While searching, a category with hits is always open. + public bool IsOpen(string categoryId) => filter.Active || open.Contains(categoryId); + + /// Opens or closes a category (no effect while searching, when hits decide). + public void Toggle(string categoryId) + { + if (filter.Active || categoryId == null) + return; + if (!open.Remove(categoryId)) + open.Add(categoryId); + dirty = true; + } + + public void SetOpen(string categoryId, bool isOpen) + { + if (categoryId == null) + return; + if (isOpen ? open.Add(categoryId) : open.Remove(categoryId)) + dirty = true; + } + + /// Whether the entry passes the search: its label or its defName (a group's id) contains the text. + public bool Matches(ActEntry e) + { + if (e == null) + return false; + if (!filter.Active) + return true; + return filter.Matches(e.label) || filter.Matches(e.name) || (e.def != null && filter.Matches(e.def.defName)); + } + + /// The entry rows of a category that pass the search, in picker order. + public List EntriesShown(string categoryId) + { + var list = new List(); + foreach (ActEntry e in ActCatalogue.EntriesOf(categoryId)) + { + if (Matches(e)) + list.Add(e); + } + return list; + } + + public void MarkDirty() => dirty = true; + + private void Refresh() + { + int laws = Lawbook.Laws.Count; + if (!dirty && builtText == filter.Text && builtCatalogue == ActCatalogue.Version && builtWatch == Watch.Version && builtLaws == laws) + return; + dirty = false; + builtText = filter.Text; + builtCatalogue = ActCatalogue.Version; + builtWatch = Watch.Version; + builtLaws = laws; + + inBook.Clear(); + foreach (Law l in Lawbook.Laws) + { + if (!l.actKey.NullOrEmpty()) + inBook.Add(l.actKey); + } + + rows.Clear(); + Hits = 0; + foreach (ActCategoryDef cat in ActCatalogue.Categories) + { + List shown = EntriesShown(cat.defName); + Hits += shown.Count; + if (filter.Active && shown.Count == 0) + continue; + bool isOpen = IsOpen(cat.defName); + rows.Add(new ActPickerRow { category = cat, open = isOpen, count = shown.Count }); + if (!isOpen) + continue; + foreach (ActEntry e in shown) + rows.Add(new ActPickerRow { category = cat, entry = e, inBook = inBook.Contains(e.key) }); + } + } + } +} diff --git a/Source/BlaxLaws/UI/CaseLog.cs b/Source/BlaxLaws/UI/CaseLog.cs new file mode 100644 index 0000000..36a2596 --- /dev/null +++ b/Source/BlaxLaws/UI/CaseLog.cs @@ -0,0 +1,201 @@ +using System.Collections.Generic; +using RimWorld; +using RimWorld.Planet; +using Verse; + +namespace BlaxLaws +{ + /// + /// The logic behind the Cases tab (design: "Lawbook tab", Cases): cases newest first with who, what, + /// stage, when, punishment and status, the jump to the pawn, and "Arrest now" for a held case. Reads + /// the component only; "Arrest now" goes through Sentences. + /// + public static class CaseLog + { + /// Cases newest first, as a new list (see FillRows). Closed ones only when asked. + public static List Rows(bool includeClosed) + { + var rows = new List(); + FillRows(rows, includeClosed); + return rows; + } + + /// + /// Fills the list with the cases newest first; among cases of one tick the higher severity first, then the + /// higher id. Closed ones only when asked. The Cases tab calls it on every GUI event with a list it keeps, + /// so it allocates nothing and sorts nothing it doesn't have to: cases are added in the order they open, so + /// walking them backwards is already in order, and the insertion sort only moves cases of one tick. + /// + public static void FillRows(List into, bool includeClosed) + { + if (into == null) + return; + into.Clear(); + GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance; + if (comp == null) + return; + IReadOnlyList all = comp.Cases; + for (int i = all.Count - 1; i >= 0; i--) + { + LawCase c = all[i]; + if (c == null || (!includeClosed && c.IsClosed)) + continue; + int j = into.Count - 1; + into.Add(c); + while (j >= 0 && ShowsBefore(c, into[j])) + { + into[j + 1] = into[j]; + j--; + } + into[j + 1] = c; + } + } + + private static bool ShowsBefore(LawCase a, LawCase b) + { + if (a.openTick != b.openTick) + return a.openTick > b.openTick; + if (a.severity != b.severity) + return a.severity > b.severity; + return a.id > b.id; + } + + /// The offender's name, with the victim when the case has one. + public static string Who(LawCase c) + { + if (c == null) + return ""; + string victim = c.VictimLabel; + return victim.NullOrEmpty() ? c.OffenderLabel : "BlaxLaws_CaseWhoVictim".Translate(c.OffenderLabel, victim).ToString(); + } + + /// The row's action, the def that matched when it differs, the count and the notes. + public static string What(LawCase c) + { + if (c == null) + return ""; + Law law = c.CurrentLaw; + string text = law != null ? LawbookUi.ActionLabel(law) : LawbookUi.CategoryLabel(ActKey.CategoryOf(c.actKey)) + ": " + (ActKey.NameOf(c.actKey) ?? c.actKey); + string matched = MatchedLabel(c); + if (!matched.NullOrEmpty() && (law == null || !string.Equals(matched, law.Label, System.StringComparison.OrdinalIgnoreCase))) + text += " (" + matched + ")"; + if (c.count > 1) + text += ", " + "BlaxLaws_CaseCount".Translate(c.count); + if ((c.notes & CaseNotes.OnTable) != 0) + text += ", " + "BlaxLaws_Note_OnTable".Translate(); + if ((c.notes & CaseNotes.DugUp) != 0) + text += ", " + "BlaxLaws_Note_DugUp".Translate(); + return text; + } + + /// The label of the def that matched (which drug, which recipe, which break), or null. + public static string MatchedLabel(LawCase c) + { + string name = c?.matchedDef ?? c?.breakState; + if (name.NullOrEmpty()) + return null; + string category = ActKey.CategoryOf(c.actKey); + ActEntry e = ActCatalogue.Get(ActKey.Of(category ?? "", name)); + if (e != null) + return e.label; + // A dose during a binge matched an Ate def, not a Break def. + foreach (ActCategoryDef cat in ActCatalogue.Categories) + { + e = ActCatalogue.Get(ActKey.Of(cat.defName, name)); + if (e != null) + return e.label; + } + return name; + } + + public static string Stage(LawCase c) => c == null ? "" : LawLabels.Stage(c.stage); + + /// "3 days ago", from the last act of the case. + public static string When(LawCase c) + { + if (c == null || Find.TickManager == null) + return ""; + int ago = Find.TickManager.TicksGame - c.lastActTick; + if (ago < GenDate.TicksPerHour) + return "BlaxLaws_JustNow".Translate(); + return "BlaxLaws_Ago".Translate(ago.ToStringTicksToPeriod(allowSeconds: false, shortForm: false, canUseDecimals: false)); + } + + /// The punishment the case runs or ran, with its days. + public static string Punishment(LawCase c) + { + if (c == null) + return ""; + PunishmentDef active = Enforcement.ActiveOf(c); + Law law = c.LawFor(c.activeStage) ?? c.CurrentLaw; + PunishmentDef p = active ?? law?.PunishmentDef; + if (p == null) + return law?.punishment ?? ""; + string text = p.LabelCap; + if (p.usesDays && law != null) + text += ", " + "BlaxLaws_DaysCount".Translate(law.days); + return text; + } + + /// The status, with the outcome of a closed case, the countdown of a jailed one or why it waits. + public static string Status(LawCase c) + { + if (c == null) + return ""; + string status = LawLabels.Status(c.status); + if (c.IsClosed) + return c.outcome.NullOrEmpty() ? status : CaseOutcomes.Label(c.outcome); + if (c.status == CaseStatus.Jailed && c.releaseTick >= 0 && Find.TickManager != null) + { + int left = c.releaseTick - Find.TickManager.TicksGame; + return left > 0 + ? "BlaxLaws_ReleaseIn".Translate(left.ToStringTicksToPeriod(allowSeconds: false, shortForm: false, canUseDecimals: false)).ToString() + : "BlaxLaws_ReleaseDue".Translate().ToString(); + } + string wait = WaitReasons.Label(c.waitReason); + return wait.NullOrEmpty() ? status : status + ": " + wait; + } + + /// + /// "Arrest now" shows for a case that waits on the hold: the jail of a role holder or a mechanitor with + /// mechs, which Laws doesn't arrest on its own (design: "Jail for N days", hold). + /// + public static bool CanArrestNow(LawCase c) => + c != null && c.offender != null && !LawCase.IsGone(c.offender) && Sentences.CanArrestNow(c); + + /// Why the case is held, for the button's tooltip. + public static string HoldReason(Pawn p) => JailFlow.HoldReason(p); + + /// The "Arrest now" button: renews guilt and starts the arrest (Sentences.ArrestNow). + public static void ArrestNow(LawCase c) + { + if (!CanArrestNow(c)) + return; + HookGuard.Run("Arrest now", () => Sentences.ArrestNow(c)); + } + + /// Whether the jump button can show the offender: alive or dead, on a map, carried, in a caravan. + public static bool CanJump(LawCase c) + { + Pawn p = c?.offender; + if (p == null || LawCase.IsGone(p)) + return false; + return CameraJumper.CanJump(Target(p)); + } + + /// The jump button: selects the offender (its corpse when dead) the vanilla way. + public static void JumpTo(LawCase c) + { + if (!CanJump(c)) + return; + HookGuard.Run("Jump to offender", () => CameraJumper.TryJumpAndSelect(Target(c.offender))); + } + + private static GlobalTargetInfo Target(Pawn p) + { + if (p.Dead && p.Corpse != null) + return p.Corpse; + return p; + } + } +} diff --git a/Source/BlaxLaws/UI/Dialog_PickAct.cs b/Source/BlaxLaws/UI/Dialog_PickAct.cs new file mode 100644 index 0000000..bbbc549 --- /dev/null +++ b/Source/BlaxLaws/UI/Dialog_PickAct.cs @@ -0,0 +1,194 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RimWorld; +using UnityEngine; +using Verse; +using Verse.Sound; + +namespace BlaxLaws +{ + /// + /// The act picker (design: "Lawbook tab", Act picker), a window like the ingredient filter of a tailoring + /// bill: the vanilla QuickSearchWidget on top, below it the catalogue's categories as a collapsible tree + /// (ActPickerTree), groups first, then every entry A to Z with its icon and its source mod in grey. An + /// entry already in the book shows a tick. One click picks an entry and closes the window. Only the lines + /// in view are drawn. + /// + public class Dialog_PickAct : Window + { + private const float RowHeight = 26f; + private const float IconSize = 24f; + private const float Indent = 22f; + private const float TitleHeight = 36f; + private const float Gap = 6f; + + private readonly Action onPick; + private readonly QuickSearchWidget search = new QuickSearchWidget(); + private readonly ActPickerTree tree = new ActPickerTree(); + private Vector2 scroll; + private bool focusSearch = true; + + /// The tree the window draws, for tests and callers that preset the search. + public ActPickerTree Tree => tree; + + /// Called with the picked act key. + public Dialog_PickAct(Action onPick) + { + this.onPick = onPick; + doCloseX = true; + closeOnClickedOutside = true; + absorbInputAroundWindow = true; + forcePause = false; + onlyOneOfTypeAllowed = true; + } + + /// "Add law": a pick adds a row (LawbookUi.AddFromPicker), or shows the existing one. + public static Dialog_PickAct ForNewRow() => new Dialog_PickAct(key => LawbookUi.AddFromPicker(key, out _)); + + /// A click on a row's Action: a pick changes the row's action (LawbookUi.ChangeAction). + public static Dialog_PickAct ForRow(Law law) + { + var d = new Dialog_PickAct(key => LawbookUi.ChangeAction(law, key)); + string cat = law?.CategoryId; + if (cat != null) + d.tree.SetOpen(cat, true); + return d; + } + + public override Vector2 InitialSize => new Vector2(560f, 680f); + + public override void DoWindowContents(Rect inRect) + { + Rect title = new Rect(inRect.x, inRect.y, inRect.width, TitleHeight); + using (new TextBlock(GameFont.Medium)) + Widgets.Label(title, "BlaxLaws_PickerTitle".Translate()); + + Rect searchRect = new Rect(inRect.x, title.yMax, inRect.width, QuickSearchWidget.WidgetHeight); + search.noResultsMatched = tree.filter.Active && tree.Hits == 0; + search.OnGUI(searchRect, () => tree.SearchText = search.filter.Text); + if (focusSearch) + { + search.Focus(); + focusSearch = false; + } + if (tree.SearchText != search.filter.Text) + tree.SearchText = search.filter.Text; + + Rect outRect = new Rect(inRect.x, searchRect.yMax + Gap, inRect.width, inRect.yMax - searchRect.yMax - Gap); + IReadOnlyList rows = tree.Rows; + if (rows.Count == 0) + { + using (new TextBlock(GameFont.Small, TextAnchor.UpperLeft, ColoredText.SubtleGrayColor)) + Widgets.Label(outRect, tree.filter.Active ? "BlaxLaws_PickerNoMatch".Translate() : "BlaxLaws_PickerEmpty".Translate()); + return; + } + + Rect viewRect = new Rect(0f, 0f, outRect.width - 16f, rows.Count * RowHeight); + Widgets.BeginScrollView(outRect, ref scroll, viewRect); + try + { + int first = Mathf.Max(0, Mathf.FloorToInt(scroll.y / RowHeight)); + int last = Mathf.Min(rows.Count - 1, Mathf.CeilToInt((scroll.y + outRect.height) / RowHeight)); + for (int i = first; i <= last; i++) + { + Rect r = new Rect(0f, i * RowHeight, viewRect.width, RowHeight); + try + { + if (rows[i].IsHeader) + DrawHeader(r, rows[i]); + else if (DrawEntry(r, rows[i], i)) + break; + } + catch (Exception e) + { + LawsLog.Once("Act picker row", e); + } + } + } + finally + { + Widgets.EndScrollView(); + } + } + + private void DrawHeader(Rect r, ActPickerRow row) + { + Widgets.DrawHighlightIfMouseover(r); + Rect icon = new Rect(r.x, r.y + (r.height - 18f) / 2f, 18f, 18f); + GUI.DrawTexture(icon, row.open ? TexButton.Collapse : TexButton.Reveal); + Rect label = new Rect(icon.xMax + 6f, r.y, r.width - icon.width - 6f, r.height); + using (new TextBlock(GameFont.Small, TextAnchor.MiddleLeft)) + Widgets.Label(label, "BlaxLaws_PickerCategory".Translate(row.category.LabelCap, row.count)); + string tip = HookGuard.Run("Category tooltip", () => row.category.Worker.Tooltip, null); + if (!tip.NullOrEmpty()) + TooltipHandler.TipRegion(r, tip); + if (Widgets.ButtonInvisible(r)) + { + tree.Toggle(row.category.defName); + (row.open ? SoundDefOf.TabClose : SoundDefOf.TabOpen).PlayOneShotOnCamera(); + } + } + + /// True when the click picked the entry and the window closed. + private bool DrawEntry(Rect r, ActPickerRow row, int index) + { + ActEntry e = row.entry; + if (index % 2 == 1) + Widgets.DrawLightHighlight(r); + Widgets.DrawHighlightIfMouseover(r); + float x = r.x + Indent; + if (ActIcons.HasIcon(e)) + { + ActIcons.Draw(new Rect(x, r.y + (r.height - IconSize) / 2f, IconSize, IconSize), e); + x += IconSize + 4f; + } + Rect tick = new Rect(r.xMax - 22f, r.y + (r.height - 18f) / 2f, 18f, 18f); + float sourceWidth = Mathf.Min(150f, r.width * 0.3f); + Rect source = new Rect(tick.x - sourceWidth - 4f, r.y, sourceWidth, r.height); + Rect label = new Rect(x, r.y, source.x - x - 4f, r.height); + using (new TextBlock(GameFont.Small, TextAnchor.MiddleLeft)) + { + Widgets.Label(label, e.label.Truncate(label.width)); + GUI.color = ColoredText.SubtleGrayColor; + Text.Anchor = TextAnchor.MiddleRight; + Widgets.Label(source, (e.sourceMod ?? "").Truncate(source.width)); + GUI.color = Color.white; + } + if (row.inBook) + GUI.DrawTexture(tick, LawsTex.InBook); + TooltipHandler.TipRegion(r, () => EntryTooltip(e, row.inBook), e.key.GetHashCode()); + if (!Widgets.ButtonInvisible(r)) + return false; + SoundDefOf.Click.PlayOneShotOnCamera(); + Pick(e.key); + return true; + } + + /// The entry's tooltip: label, source, stages, what the act is and whether the book has it. + public static string EntryTooltip(ActEntry e, bool inBook) + { + if (e == null) + return null; + var parts = new List { e.label, "BlaxLaws_SourceMod".Translate(e.sourceMod ?? DlcSupport.CoreName) }; + string stages = string.Join(", ", Lawbook.StagesOf(e).Select(LawLabels.Stage)); + if (!stages.NullOrEmpty()) + parts.Add("BlaxLaws_PickerStages".Translate(stages)); + if (e.IsBreak && e.hostileBreak) + parts.Add("BlaxLaws_PickerHostile".Translate()); + string what = LawbookUi.EntryDescription(e); + if (!what.NullOrEmpty()) + parts.Add(what); + if (inBook) + parts.Add("BlaxLaws_PickerInBook".Translate()); + return string.Join("\n\n", parts); + } + + /// Returns the key to the caller and closes. + protected void Pick(string actKey) + { + Close(); + HookGuard.Run("Picking an act", () => onPick?.Invoke(actKey)); + } + } +} diff --git a/Source/BlaxLaws/UI/LawbookUi.cs b/Source/BlaxLaws/UI/LawbookUi.cs new file mode 100644 index 0000000..7ab6d8d --- /dev/null +++ b/Source/BlaxLaws/UI/LawbookUi.cs @@ -0,0 +1,361 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RimWorld; +using UnityEngine; +using Verse; + +namespace BlaxLaws +{ + /// One entry of a lawbook column's dropdown. A null action is a disabled entry; reason says why. + public sealed class RowChoice + { + public string label; + + /// The value the entry sets: a drug option, a LawStage, a LawSeverity or a PunishmentDef. + public object payload; + + /// Writes the choice through Lawbook. Null for a disabled entry. + public Action action; + + /// Why the entry is disabled ("Needs Ideology"), or null. + public string reason; + + /// The row has this value now. + public bool selected; + + public override string ToString() => label + (selected ? " (selected)" : "") + (action == null ? " (disabled: " + reason + ")" : ""); + } + + /// + /// The logic behind the Lawbook tab (design: "Lawbook tab"), kept apart from the drawing so the + /// headless tests drive it: what each column offers, what a pick from the act picker does, the starter + /// button and the delete confirmation. Every write goes through Lawbook. A write Lawbook refuses because + /// the key exists shows the existing row instead (Focus). + /// + public static class LawbookUi + { + /// Seconds the tab highlights a row it jumped to. + public const float FocusSeconds = 2.5f; + + /// The row the tab scrolls to and highlights, or 0. + public static int FocusLawId { get; private set; } + + /// Real time until which the focused row is highlighted. + public static float FocusUntil { get; private set; } + + /// Set when Focus asks the tab to scroll; the tab clears it once it scrolled. + public static bool ScrollPending { get; set; } + + /// Shows the row: the Lawbook tab scrolls to it and highlights it. + public static void Focus(Law law) + { + if (law == null) + return; + FocusLawId = law.id; + FocusUntil = Time.realtimeSinceStartup + FocusSeconds; + ScrollPending = true; + } + + public static void ClearFocus() + { + FocusLawId = 0; + ScrollPending = false; + } + + // ---- labels ------------------------------------------------------------------------ + + /// "Ate: Wake-up". A row whose entry is missing shows its saved label. + public static string ActionLabel(Law law) + { + if (law == null) + return ""; + return "BlaxLaws_ActionLabel".Translate(CategoryLabel(law.CategoryId), law.Label); + } + + /// The category's label ("Ate"), or its id while the category is unknown. + public static string CategoryLabel(string categoryId) + { + if (categoryId.NullOrEmpty()) + return "?"; + ActCategoryDef cat = DefDatabase.GetNamedSilentFail(categoryId); + return cat != null && !cat.label.NullOrEmpty() ? cat.LabelCap.ToString() : categoryId; + } + + /// The Action cell's tooltip: source mod, what counts, a missing entry's reason. + public static string ActionTooltip(Law law) + { + if (law == null) + return null; + var parts = new List(); + ActEntry e = law.Entry; + parts.Add(ActionLabel(law)); + string missing = law.MissingText; + if (missing != null) + parts.Add(missing); + string source = e?.sourceMod ?? law.savedMod; + if (!source.NullOrEmpty()) + parts.Add("BlaxLaws_SourceMod".Translate(source)); + string what = EntryDescription(e); + if (!what.NullOrEmpty()) + parts.Add(what); + parts.Add("BlaxLaws_ActionTip".Translate()); + return string.Join("\n\n", parts); + } + + /// What the entry's act is, for tooltips: a special act's row tooltip, else the category's tooltip. + public static string EntryDescription(ActEntry e) + { + if (e == null) + return null; + return HookGuard.Run("Entry tooltip " + e.key, () => + { + if (e.def is ActDef act) + return act.Worker.RowTooltip; + ActCategoryDef cat = DefDatabase.GetNamedSilentFail(e.categoryId); + return cat?.Worker.Tooltip; + }, null); + } + + /// The Days cell: the number when the punishment uses days, else "-". + public static bool UsesDays(Law law) => law?.PunishmentDef?.usesDays ?? false; + + public static string PunishmentLabel(Law law) + { + if (law == null) + return ""; + PunishmentDef p = law.PunishmentDef; + return p != null ? p.LabelCap.ToString() : law.punishment ?? ""; + } + + // ---- column choices ---------------------------------------------------------------- + + /// Whether the row has an Option column value: drug binges only. + public static bool HasOption(Law law) => law?.Entry?.hasDrugOption ?? (law?.option != null); + + /// Any drug, hard drugs, social drugs, then every drug's chemical A to Z. + public static List OptionChoices(Law law) + { + var list = new List(); + if (law == null || !HasOption(law)) + return list; + var options = new List { DrugOptions.Any, DrugOptions.Hard, DrugOptions.Social }; + options.AddRange(ActCatalogue.ChemicalOptions); + string current = DrugOptions.Normalize(law.option); + foreach (string o in options) + { + string option = o; + list.Add(new RowChoice + { + label = DrugOptions.Label(option), + payload = option, + selected = option == current, + action = () => ChangeOption(law, option), + }); + } + return list; + } + + /// The stages the entry offers; a missing entry keeps the row's stage only. + public static List StageChoices(Law law) + { + var list = new List(); + if (law == null) + return list; + ActEntry e = law.Entry; + IEnumerable stages = e != null ? Lawbook.StagesOf(e) : new[] { law.stage }; + foreach (LawStage s in stages) + { + LawStage stage = s; + list.Add(new RowChoice + { + label = LawLabels.Stage(stage), + payload = stage, + selected = stage == law.stage, + action = e == null ? (Action)null : () => ChangeStage(law, stage), + reason = e == null ? law.MissingText : null, + }); + } + return list; + } + + public static List SeverityChoices(Law law) + { + var list = new List(); + if (law == null) + return list; + foreach (LawSeverity s in Enum.GetValues(typeof(LawSeverity))) + { + LawSeverity severity = s; + list.Add(new RowChoice + { + label = LawLabels.Severity(severity), + payload = severity, + selected = severity == law.severity, + action = () => Lawbook.SetSeverity(law, severity), + }); + } + return list; + } + + /// + /// The punishments that fit the row's entry and stage, in order (Lawbook.PunishmentsFor). A row whose + /// entry is missing keeps its punishment and offers nothing else. + /// + public static List PunishmentChoices(Law law) + { + var list = new List(); + if (law == null) + return list; + ActEntry e = law.Entry; + if (e == null) + { + PunishmentDef p = law.PunishmentDef; + list.Add(new RowChoice { label = PunishmentLabel(law), payload = p, selected = true, reason = law.MissingText }); + return list; + } + foreach (PunishmentDef p in Lawbook.PunishmentsFor(e, law.stage)) + { + PunishmentDef punishment = p; + list.Add(new RowChoice + { + label = punishment.LabelCap, + payload = punishment, + selected = punishment.defName == law.punishment, + action = () => Lawbook.SetPunishment(law, punishment), + }); + } + return list; + } + + // ---- writes that may be refused ---------------------------------------------------- + + /// Sets the option; a refusal shows the row that has the key. + public static bool ChangeOption(Law law, string option) + { + if (Lawbook.SetOption(law, option, out Law existing)) + return true; + Refused(existing); + return false; + } + + /// Sets the stage; a punishment that no longer fits resets to Warn. A refusal shows the existing row. + public static bool ChangeStage(Law law, LawStage stage) + { + if (Lawbook.SetStage(law, stage, out Law existing)) + return true; + Refused(existing); + return false; + } + + /// The act picker's pick for an existing row: SetAction, or the existing row with that key. + public static bool ChangeAction(Law law, string actKey) + { + if (Lawbook.SetAction(law, actKey, out Law existing)) + { + Focus(law); + return true; + } + Refused(existing); + return false; + } + + /// + /// The act picker's pick for "Add law". Adds a row for the entry's first stage that has no row yet + /// (a drug binge with the Any option), so an entry with planning and did it can get both. When every + /// stage has a row, nothing is added and existing is the first stage's row, which the tab shows. + /// Returns the new row, or null. + /// + public static Law AddFromPicker(string actKey, out Law existing) + { + existing = null; + if (actKey.NullOrEmpty()) + return null; + Law row = Lawbook.NewRow(actKey); + ActEntry entry = ActCatalogue.Get(actKey); + IEnumerable stages = entry != null ? Lawbook.StagesOf(entry) : new[] { row.stage }; + foreach (LawStage s in stages) + { + Law found = Lawbook.Find(actKey, row.option, s); + if (found != null) + { + existing ??= found; + continue; + } + row.stage = s; + if (!Lawbook.TryAdd(row, out Law refused)) + { + existing = refused; + break; + } + existing = null; + Focus(row); + return row; + } + Refused(existing); + return null; + } + + /// Rows already in the book for this act key, any option and stage. + public static List RowsOf(string actKey) => Lawbook.Laws.Where(l => l.actKey == actKey).ToList(); + + /// "Starter lawbook": adds the missing starter rows and says how many. + public static int PressStarter() + { + int added = Lawbook.AddStarter(); + string text = added > 0 ? "BlaxLaws_StarterAdded".Translate(added) : "BlaxLaws_StarterNone".Translate(); + Messages.Message(text, MessageTypeDefOf.SilentInput, historical: false); + return added; + } + + /// The confirmation a delete asks first, naming the open cases it closes; null when it has none. + public static string DeleteConfirmText(Law law) + { + int open = Lawbook.OpenCaseCount(law); + if (open <= 0) + return null; + string text = "BlaxLaws_DeleteConfirm".Translate(ActionLabel(law), open); + int jailed = JailedCount(law); + if (jailed > 0) + text += "\n\n" + "BlaxLaws_DeleteConfirmJailed".Translate(jailed); + return text; + } + + /// Open cases of the row whose offender serves its sentence: a repeal sets them to Release (PunishmentWorker_Jail.Stop). + public static int JailedCount(Law law) + { + GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance; + if (comp == null || law == null) + return 0; + int n = 0; + foreach (LawCase c in comp.Cases) + { + if (!c.IsClosed && c.status == CaseStatus.Jailed && (c.planningLawId == law.id || c.didItLawId == law.id)) + n++; + } + return n; + } + + /// Deletes the row, asking first when it has open cases (design: "Bulk changes ask first and name the count"). + public static void RequestDelete(Law law) + { + if (law == null) + return; + string confirm = DeleteConfirmText(law); + if (confirm == null) + { + Lawbook.Delete(law); + return; + } + Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation(confirm, () => Lawbook.Delete(law), destructive: true)); + } + + private static void Refused(Law existing) + { + if (existing == null) + return; + Focus(existing); + Messages.Message("BlaxLaws_RowExists".Translate(ActionLabel(existing), LawLabels.Stage(existing.stage)), MessageTypeDefOf.RejectInput, historical: false); + } + } +} diff --git a/Source/BlaxLaws/UI/MainTabWindow_Laws.cs b/Source/BlaxLaws/UI/MainTabWindow_Laws.cs new file mode 100644 index 0000000..29dbefa --- /dev/null +++ b/Source/BlaxLaws/UI/MainTabWindow_Laws.cs @@ -0,0 +1,470 @@ +using System; +using System.Collections.Generic; +using RimWorld; +using UnityEngine; +using Verse; + +namespace BlaxLaws +{ + /// + /// The Laws tab (MainButtonDef BlaxLaws_Laws; design: "Lawbook tab"). Two tabs: + /// - Lawbook: one line per row with Action (icon, category and label; a click opens the act picker), + /// Option (drug binges only), Stage, Severity, Punishment, Days, On, the overlap icon and delete. + /// Each dropdown offers only what fits the row's action and stage. "Add law" opens the act picker, + /// "Starter lawbook" adds the suggested rows. An empty book shows one line. + /// - Cases: newest first, who, what, stage, when, punishment and status, a button to jump to the pawn + /// and, for a held case, "Arrest now". + /// The logic lives in LawbookUi and CaseLog; every write goes through Lawbook. Only the lines in view + /// are drawn. + /// + public class MainTabWindow_Laws : MainTabWindow + { + private enum Page + { + Lawbook, + Cases, + } + + private const float RowHeight = 30f; + private const float HeaderHeight = 26f; + private const float ButtonHeight = 32f; + private const float Gap = 6f; + private const float IconSize = 24f; + private const float ScrollBar = 16f; + + // Lawbook columns; Action takes what is left. + private const float OptionWidth = 130f; + private const float StageWidth = 90f; + private const float SeverityWidth = 100f; + private const float PunishmentWidth = 150f; + private const float DaysWidth = 56f; + private const float OnWidth = 36f; + private const float SmallIcon = 24f; + + // Cases columns; What takes what is left. + private const float WhoWidth = 150f; + private const float CaseStageWidth = 80f; + private const float WhenWidth = 110f; + private const float CasePunishmentWidth = 140f; + private const float StatusWidth = 190f; + private const float CaseButtonsWidth = 180f; + + private static Page page = Page.Lawbook; + private static bool showClosed = true; + private static readonly Color SeriousColor = new Color(1f, 0.82f, 0.45f); + + private Vector2 lawScroll; + private Vector2 caseScroll; + // The Cases tab's rows, refilled in place on every GUI event (CaseLog.FillRows). + private readonly List caseRows = new List(); + private struct DaysBuffer + { + public int value; + public string text; + } + + private readonly Dictionary dayBuffers = new Dictionary(); + private readonly List tabs = new List(); + + public override Vector2 RequestedTabSize => new Vector2(1010f, 640f); + + public override void PreOpen() + { + base.PreOpen(); + dayBuffers.Clear(); + } + + public override void DoWindowContents(Rect inRect) + { + Rect body = inRect; + body.yMin += TabDrawer.TabHeight; + tabs.Clear(); + tabs.Add(new TabRecord("BlaxLaws_TabLawbook".Translate(), () => page = Page.Lawbook, page == Page.Lawbook)); + tabs.Add(new TabRecord("BlaxLaws_TabCases".Translate(), () => page = Page.Cases, page == Page.Cases)); + Widgets.DrawMenuSection(body); + TabDrawer.DrawTabs(body, tabs); + body = body.ContractedBy(10f); + try + { + if (page == Page.Lawbook) + DoLawbook(body); + else + DoCases(body); + } + catch (Exception e) + { + LawsLog.Once("Laws tab", e); + } + finally + { + Text.Anchor = TextAnchor.UpperLeft; + Text.Font = GameFont.Small; + GUI.color = Color.white; + } + } + + // ---- Lawbook --------------------------------------------------------------------------- + + private void DoLawbook(Rect rect) + { + Rect buttons = new Rect(rect.x, rect.y, rect.width, ButtonHeight); + Rect add = new Rect(buttons.x, buttons.y, 160f, ButtonHeight); + if (Widgets.ButtonText(add, "BlaxLaws_AddLaw".Translate())) + Find.WindowStack.Add(Dialog_PickAct.ForNewRow()); + TooltipHandler.TipRegion(add, "BlaxLaws_AddLawTip".Translate()); + Rect starter = new Rect(add.xMax + Gap, buttons.y, 180f, ButtonHeight); + if (Widgets.ButtonText(starter, "BlaxLaws_StarterLawbook".Translate())) + LawbookUi.PressStarter(); + TooltipHandler.TipRegion(starter, "BlaxLaws_StarterLawbookTip".Translate()); + if (!BlaxLawsMod.S.enforceLaws) + { + Rect off = new Rect(starter.xMax + Gap * 2, buttons.y, buttons.xMax - starter.xMax - Gap * 2, ButtonHeight); + using (new TextBlock(GameFont.Small, TextAnchor.MiddleRight, ColorLibrary.RedReadable)) + Widgets.Label(off, "BlaxLaws_EnforceOff".Translate()); + } + + IReadOnlyList laws = Lawbook.Laws; + Rect list = new Rect(rect.x, buttons.yMax + Gap, rect.width, rect.yMax - buttons.yMax - Gap); + if (laws.Count == 0) + { + using (new TextBlock(GameFont.Small, TextAnchor.UpperLeft, ColoredText.SubtleGrayColor)) + Widgets.Label(list, "BlaxLaws_EmptyBook".Translate()); + return; + } + + Rect header = new Rect(list.x, list.y, list.width - ScrollBar, HeaderHeight); + DrawLawHeader(header); + Rect outRect = new Rect(list.x, header.yMax, list.width, list.yMax - header.yMax); + Rect viewRect = new Rect(0f, 0f, outRect.width - ScrollBar, laws.Count * RowHeight); + ScrollToFocus(laws, outRect.height); + Widgets.BeginScrollView(outRect, ref lawScroll, viewRect); + try + { + int first = Mathf.Max(0, Mathf.FloorToInt(lawScroll.y / RowHeight)); + int last = Mathf.Min(laws.Count - 1, Mathf.CeilToInt((lawScroll.y + outRect.height) / RowHeight)); + for (int i = first; i <= last && i < laws.Count; i++) + { + Rect r = new Rect(0f, i * RowHeight, viewRect.width, RowHeight); + try + { + DrawLaw(r, laws[i], i); + } + catch (Exception e) + { + LawsLog.Once("Lawbook row", e); + } + } + } + finally + { + Widgets.EndScrollView(); + } + } + + private void ScrollToFocus(IReadOnlyList laws, float height) + { + if (!LawbookUi.ScrollPending) + return; + LawbookUi.ScrollPending = false; + page = Page.Lawbook; + for (int i = 0; i < laws.Count; i++) + { + if (laws[i].id != LawbookUi.FocusLawId) + continue; + float top = i * RowHeight; + if (top < lawScroll.y || top + RowHeight > lawScroll.y + height) + lawScroll.y = Mathf.Max(0f, top - height / 2f); + return; + } + } + + private static void Columns(Rect r, out Rect action, out Rect option, out Rect stage, out Rect severity, out Rect punishment, + out Rect days, out Rect on, out Rect overlap, out Rect delete) + { + float x = r.xMax; + delete = new Rect(x - SmallIcon, r.y, SmallIcon, r.height); + x = delete.x - Gap; + overlap = new Rect(x - SmallIcon, r.y, SmallIcon, r.height); + x = overlap.x - Gap; + on = new Rect(x - OnWidth, r.y, OnWidth, r.height); + x = on.x - Gap; + days = new Rect(x - DaysWidth, r.y, DaysWidth, r.height); + x = days.x - Gap; + punishment = new Rect(x - PunishmentWidth, r.y, PunishmentWidth, r.height); + x = punishment.x - Gap; + severity = new Rect(x - SeverityWidth, r.y, SeverityWidth, r.height); + x = severity.x - Gap; + stage = new Rect(x - StageWidth, r.y, StageWidth, r.height); + x = stage.x - Gap; + option = new Rect(x - OptionWidth, r.y, OptionWidth, r.height); + x = option.x - Gap; + action = new Rect(r.x, r.y, x - r.x, r.height); + } + + private static void DrawLawHeader(Rect r) + { + Columns(r, out Rect action, out Rect option, out Rect stage, out Rect severity, out Rect punishment, out Rect days, out Rect on, out _, out _); + using (new TextBlock(GameFont.Small, TextAnchor.LowerLeft, ColoredText.SubtleGrayColor)) + { + HeaderLabel(action, "BlaxLaws_ColAction", null); + HeaderLabel(option, "BlaxLaws_ColOption", "BlaxLaws_ColOptionTip"); + HeaderLabel(stage, "BlaxLaws_ColStage", "BlaxLaws_ColStageTip"); + HeaderLabel(severity, "BlaxLaws_ColSeverity", "BlaxLaws_ColSeverityTip"); + HeaderLabel(punishment, "BlaxLaws_ColPunishment", null); + HeaderLabel(days, "BlaxLaws_ColDays", "BlaxLaws_ColDaysTip"); + HeaderLabel(on, "BlaxLaws_ColOn", "BlaxLaws_ColOnTip"); + } + Widgets.DrawLineHorizontal(r.x, r.yMax - 1f, r.width); + } + + private static void HeaderLabel(Rect r, string key, string tipKey) + { + Widgets.Label(r, key.Translate()); + if (tipKey != null) + TooltipHandler.TipRegion(r, tipKey.Translate()); + } + + private void DrawLaw(Rect r, Law law, int index) + { + if (index % 2 == 1) + Widgets.DrawLightHighlight(r); + if (law.id == LawbookUi.FocusLawId && Time.realtimeSinceStartup < LawbookUi.FocusUntil) + Widgets.DrawHighlightSelected(r); + Columns(r, out Rect action, out Rect option, out Rect stage, out Rect severity, out Rect punishment, out Rect days, out Rect on, + out Rect overlap, out Rect delete); + ActEntry entry = law.Entry; + Color rowColor = law.enabled ? Color.white : Color.gray; + + // Action: icon, category and label; a click opens the picker. + Widgets.DrawHighlightIfMouseover(action); + float x = action.x + 2f; + if (entry != null && ActIcons.HasIcon(entry)) + { + ActIcons.Draw(new Rect(x, action.y + (action.height - IconSize) / 2f, IconSize, IconSize), entry); + x += IconSize + 4f; + } + Rect label = new Rect(x, action.y, action.xMax - x, action.height); + string text = LawbookUi.ActionLabel(law); + string missing = law.MissingText; + using (new TextBlock(GameFont.Small, TextAnchor.MiddleLeft, missing != null ? ColoredText.SubtleGrayColor : rowColor)) + Widgets.Label(label, (missing != null ? text + " (" + missing + ")" : text).Truncate(label.width)); + TooltipHandler.TipRegion(action, () => LawbookUi.ActionTooltip(law), law.id * 31 + 1); + if (Widgets.ButtonInvisible(action)) + Find.WindowStack.Add(Dialog_PickAct.ForRow(law)); + + // Option, drug binges only. + if (LawbookUi.HasOption(law)) + Dropdown(option, law, LawbookUi.OptionChoices, DrugOptions.Label(law.option)); + + Dropdown(stage, law, LawbookUi.StageChoices, LawLabels.Stage(law.stage)); + Dropdown(severity, law, LawbookUi.SeverityChoices, LawLabels.Severity(law.severity)); + Dropdown(punishment, law, LawbookUi.PunishmentChoices, LawbookUi.PunishmentLabel(law)); + + // Days: a 1 to 50 field for punishments with days, "-" otherwise. + if (LawbookUi.UsesDays(law)) + { + // The buffer belongs to the value it was typed for; a change from elsewhere (Severity moving + // untouched days) starts a fresh one, so stale text never writes the old number back. + string buffer = null; + if (dayBuffers.TryGetValue(law.id, out DaysBuffer kept) && kept.value == law.days) + buffer = kept.text; + int value = law.days; + Rect field = days.ContractedBy(0f, 3f); + Widgets.TextFieldNumeric(field, ref value, ref buffer, Lawbook.MinDays, Lawbook.MaxDays); + if (value != law.days && value >= Lawbook.MinDays && value <= Lawbook.MaxDays) + Lawbook.SetDays(law, value); + dayBuffers[law.id] = new DaysBuffer { value = law.days, text = buffer }; + } + else + { + using (new TextBlock(GameFont.Small, TextAnchor.MiddleCenter, ColoredText.SubtleGrayColor)) + Widgets.Label(days, "BlaxLaws_NoDays".Translate()); + } + + // On. + bool enabled = law.enabled; + Widgets.Checkbox(new Vector2(on.x + (on.width - 24f) / 2f, on.y + (on.height - 24f) / 2f), ref enabled); + if (enabled != law.enabled) + Lawbook.SetEnabled(law, enabled); + TooltipHandler.TipRegion(on, "BlaxLaws_ColOnTip".Translate()); + + // Overlap icon. + IReadOnlyList overlaps = ActOverlaps.Of(law); + if (overlaps.Count > 0) + { + Rect icon = new Rect(overlap.x, overlap.y + (overlap.height - SmallIcon) / 2f, SmallIcon, SmallIcon); + GUI.DrawTexture(icon, LawsTex.Overlap); + TooltipHandler.TipRegion(icon, () => OverlapTip(overlaps), law.id * 31 + 2); + } + + // Delete, asking first when the row has open cases. + Rect del = new Rect(delete.x, delete.y + (delete.height - SmallIcon) / 2f, SmallIcon, SmallIcon); + if (Widgets.ButtonImage(del, TexButton.Delete, Color.white, GenUI.SubtleMouseoverColor, true, "BlaxLaws_DeleteLaw".Translate())) + LawbookUi.RequestDelete(law); + } + + private static string OverlapTip(IReadOnlyList overlaps) + { + var lines = new List(); + foreach (Law o in overlaps) + lines.Add(" - " + LawbookUi.ActionLabel(o) + " (" + LawLabels.Stage(o.stage) + ")"); + return "BlaxLaws_OverlapTip".Translate(string.Join("\n", lines)); + } + + private static void Dropdown(Rect rect, Law law, Func> choices, string label) + { + Rect button = rect.ContractedBy(0f, 2f); + Widgets.Dropdown(button, law, l => (object)null, l => Elements(choices(l)), label.Truncate(button.width - 16f)); + } + + private static IEnumerable> Elements(List choices) + { + foreach (RowChoice c in choices) + { + string label = c.action == null && !c.reason.NullOrEmpty() ? c.label + " (" + c.reason + ")" : c.label; + yield return new Widgets.DropdownMenuElement + { + option = new FloatMenuOption(label, c.action), + payload = c.payload, + }; + } + } + + // ---- Cases ----------------------------------------------------------------------------- + + private void DoCases(Rect rect) + { + Rect top = new Rect(rect.x, rect.y, rect.width, ButtonHeight); + Rect closed = new Rect(top.x, top.y + 4f, 240f, 24f); + Widgets.CheckboxLabeled(closed, "BlaxLaws_ShowClosed".Translate(), ref showClosed); + + CaseLog.FillRows(caseRows, showClosed); + List cases = caseRows; + Rect list = new Rect(rect.x, top.yMax + Gap, rect.width, rect.yMax - top.yMax - Gap); + if (cases.Count == 0) + { + using (new TextBlock(GameFont.Small, TextAnchor.UpperLeft, ColoredText.SubtleGrayColor)) + Widgets.Label(list, "BlaxLaws_NoCases".Translate()); + return; + } + + Rect header = new Rect(list.x, list.y, list.width - ScrollBar, HeaderHeight); + CaseColumns(header, out Rect who, out Rect what, out Rect stage, out Rect when, out Rect punishment, out Rect status, out _); + using (new TextBlock(GameFont.Small, TextAnchor.LowerLeft, ColoredText.SubtleGrayColor)) + { + Widgets.Label(who, "BlaxLaws_ColWho".Translate()); + Widgets.Label(what, "BlaxLaws_ColWhat".Translate()); + Widgets.Label(stage, "BlaxLaws_ColStage".Translate()); + Widgets.Label(when, "BlaxLaws_ColWhen".Translate()); + Widgets.Label(punishment, "BlaxLaws_ColPunishment".Translate()); + Widgets.Label(status, "BlaxLaws_ColStatus".Translate()); + } + Widgets.DrawLineHorizontal(header.x, header.yMax - 1f, header.width); + + Rect outRect = new Rect(list.x, header.yMax, list.width, list.yMax - header.yMax); + Rect viewRect = new Rect(0f, 0f, outRect.width - ScrollBar, cases.Count * RowHeight); + Widgets.BeginScrollView(outRect, ref caseScroll, viewRect); + try + { + int first = Mathf.Max(0, Mathf.FloorToInt(caseScroll.y / RowHeight)); + int last = Mathf.Min(cases.Count - 1, Mathf.CeilToInt((caseScroll.y + outRect.height) / RowHeight)); + for (int i = first; i <= last; i++) + { + try + { + DrawCase(new Rect(0f, i * RowHeight, viewRect.width, RowHeight), cases[i], i); + } + catch (Exception e) + { + LawsLog.Once("Cases row", e); + } + } + } + finally + { + Widgets.EndScrollView(); + } + } + + private static void CaseColumns(Rect r, out Rect who, out Rect what, out Rect stage, out Rect when, out Rect punishment, out Rect status, out Rect buttons) + { + float x = r.xMax; + buttons = new Rect(x - CaseButtonsWidth, r.y, CaseButtonsWidth, r.height); + x = buttons.x - Gap; + status = new Rect(x - StatusWidth, r.y, StatusWidth, r.height); + x = status.x - Gap; + punishment = new Rect(x - CasePunishmentWidth, r.y, CasePunishmentWidth, r.height); + x = punishment.x - Gap; + when = new Rect(x - WhenWidth, r.y, WhenWidth, r.height); + x = when.x - Gap; + stage = new Rect(x - CaseStageWidth, r.y, CaseStageWidth, r.height); + x = stage.x - Gap; + who = new Rect(r.x, r.y, WhoWidth, r.height); + what = new Rect(who.xMax + Gap, r.y, x - who.xMax - Gap, r.height); + } + + private static void DrawCase(Rect r, LawCase c, int index) + { + if (index % 2 == 1) + Widgets.DrawLightHighlight(r); + Widgets.DrawHighlightIfMouseover(r); + CaseColumns(r, out Rect who, out Rect what, out Rect stage, out Rect when, out Rect punishment, out Rect status, out Rect buttons); + Color color = c.IsClosed ? ColoredText.SubtleGrayColor : SeverityColor(c.severity); + using (new TextBlock(GameFont.Small, TextAnchor.MiddleLeft, color)) + { + Cell(who, CaseLog.Who(c)); + Cell(what, CaseLog.What(c)); + Cell(stage, CaseLog.Stage(c)); + Cell(when, CaseLog.When(c)); + Cell(punishment, CaseLog.Punishment(c)); + Cell(status, CaseLog.Status(c)); + } + TooltipHandler.TipRegion(new Rect(r.x, r.y, buttons.x - r.x, r.height), () => CaseTip(c), c.id * 31 + 3); + + float bx = buttons.xMax; + if (CaseLog.CanJump(c)) + { + Rect jump = new Rect(bx - 70f, r.y + 3f, 70f, r.height - 6f); + if (Widgets.ButtonText(jump, "BlaxLaws_JumpTo".Translate())) + CaseLog.JumpTo(c); + TooltipHandler.TipRegion(jump, "BlaxLaws_JumpToTip".Translate(c.OffenderLabel)); + bx = jump.x - Gap; + } + if (CaseLog.CanArrestNow(c)) + { + Rect arrest = new Rect(bx - 100f, r.y + 3f, 100f, r.height - 6f); + if (Widgets.ButtonText(arrest, "BlaxLaws_ArrestNow".Translate())) + CaseLog.ArrestNow(c); + TooltipHandler.TipRegion(arrest, () => "BlaxLaws_ArrestNowTip".Translate(CaseLog.HoldReason(c.offender)), c.id * 31 + 4); + } + } + + private static void Cell(Rect r, string text) + { + Widgets.Label(r, (text ?? "").Truncate(r.width)); + } + + private static string CaseTip(LawCase c) + { + var lines = new List + { + CaseLog.Who(c), + CaseLog.What(c), + LawLabels.Severity(c.severity) + ", " + CaseLog.Stage(c), + CaseLog.Punishment(c), + CaseLog.Status(c), + }; + return string.Join("\n", lines); + } + + private static Color SeverityColor(LawSeverity s) + { + switch (s) + { + case LawSeverity.Grave: return ColorLibrary.RedReadable; + case LawSeverity.Serious: return SeriousColor; + default: return Color.white; + } + } + } +} diff --git a/Source/BlaxLaws/Watch.cs b/Source/BlaxLaws/Watch.cs new file mode 100644 index 0000000..d155ef7 --- /dev/null +++ b/Source/BlaxLaws/Watch.cs @@ -0,0 +1,210 @@ +using System.Collections.Generic; +using Verse; + +namespace BlaxLaws +{ + /// + /// The hot-path cache of the current game's lawbook (design: "Detection: one postfix per act, quiet while + /// the book is empty"). One static flag per category and per special act, plus per category the set of + /// watched defs (groups expanded) and the enabled rows whose entry resolves. Rebuilt on every lawbook + /// write and in GameComponent_BlaxLaws.FinalizeInit, cleared when a game starts or loads. Not game state: + /// nothing here is saved. + /// + /// Every hook reads its flag first, so while the book is empty a hook costs one static field read: + /// + /// if (!Watch.Ate) return; // empty book: done + /// if (!Watch.MayMatch(ActCategories.Ate, def)) return; // one set lookup + /// CaseFiler.Report(new ActEvent(ActCategories.Ate, def, pawn) { ... }); + /// + /// A break row with a linked did-it also watches the linked act (a drug binge row watches every drug, + /// a fire-starting spree row the SetFire special act), so a dose during a binge reaches CaseFiler. + /// + public static class Watch + { + /// Any category or special act is watched. False for an empty book. + public static bool Any; + + // One flag per category: some enabled row (or a break row's link) uses it. + public static bool Break; + public static bool Ate; + public static bool Used; + public static bool Interaction; + public static bool RecordedAct; + public static bool Record; + public static bool Bill; + public static bool Special; + + // One flag per special act of the first release. + public static bool SetFire; + public static bool DisplayedCorpse; + public static bool StartedSocialFight; + + /// Bumped on every rebuild. + public static int Version { get; private set; } + + private sealed class CategoryWatch + { + public readonly HashSet defs = new HashSet(); + /// A row or link on the category's "any". + public bool all; + /// A watched group reads the thing, so every act of the category must be checked. + public bool thingGroups; + /// Enabled rows of this category whose entry resolves, in lawbook order. + public readonly List laws = new List(); + } + + private static readonly Dictionary byCategory = new Dictionary(); + private static readonly HashSet specials = new HashSet(); + private static readonly List NoLaws = new List(); + + /// Whether any enabled row (or break link) uses the category. + public static bool Category(string categoryId) => categoryId != null && byCategory.ContainsKey(categoryId); + + /// Whether a row (or break link) watches this special act ("SetFire"). + public static bool SpecialAct(string actId) => actId != null && specials.Contains(actId); + + /// The def is in the category's watched set, or the category watches everything. + public static bool IsWatched(string categoryId, Def def) + { + if (categoryId == null || !byCategory.TryGetValue(categoryId, out CategoryWatch w)) + return false; + return w.all || (def != null && w.defs.Contains(def)); + } + + /// A watched group of the category reads the thing, so a hook must report every act of it. + public static bool ThingGroups(string categoryId) => + categoryId != null && byCategory.TryGetValue(categoryId, out CategoryWatch w) && w.thingGroups; + + /// + /// The act may match a row or a link: the def is watched, or a thing-level group needs the act. A + /// hook builds its ActEvent and calls CaseFiler.Report only when this is true. + /// + public static bool MayMatch(string categoryId, Def def) + { + if (categoryId == null || !byCategory.TryGetValue(categoryId, out CategoryWatch w)) + return false; + return w.all || w.thingGroups || (def != null && w.defs.Contains(def)); + } + + /// Enabled rows of the category whose entry resolves. Empty when none. Do not change the list. + public static IReadOnlyList LawsOf(string categoryId) + { + if (categoryId != null && byCategory.TryGetValue(categoryId, out CategoryWatch w)) + return w.laws; + return NoLaws; + } + + /// Everything off: an empty book. + public static void Clear() + { + byCategory.Clear(); + specials.Clear(); + SetFlags(); + Version++; + } + + /// + /// Rebuilds from the running game's lawbook. Disabled rows and rows whose entry is missing watch + /// nothing. Never throws. + /// + public static void Rebuild() + { + try + { + byCategory.Clear(); + specials.Clear(); + GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance; + if (comp != null) + { + foreach (Law law in comp.Laws) + { + if (law == null || !law.enabled) + continue; + ActEntry entry = ActCatalogue.Get(law.actKey); + if (entry == null || !entry.HasStage(law.stage)) + continue; + Of(entry.categoryId).laws.Add(law); + AddEntry(entry); + if (entry.IsBreak) + { + foreach (BreakLinkDef link in entry.links) + { + ActEntry linked = ActCatalogue.Get(link.act); + if (linked != null) + AddEntry(linked); + } + } + } + } + } + catch (System.Exception e) + { + HookGuard.Fail("Rebuilding the watched acts", e); + } + SetFlags(); + Version++; + } + + private static CategoryWatch Of(string categoryId) + { + if (!byCategory.TryGetValue(categoryId, out CategoryWatch w)) + byCategory[categoryId] = w = new CategoryWatch(); + return w; + } + + private static void AddEntry(ActEntry entry) + { + CategoryWatch w = Of(entry.categoryId); + if (entry.categoryId == ActCategories.Special) + specials.Add(entry.name); + if (entry.def != null) + { + w.defs.Add(entry.def); + return; + } + ActGroup g = entry.group; + if (g == null) + return; + if (g.IsAny) + { + w.all = true; + if (entry.categoryId == ActCategories.Special) + { + foreach (ActEntry e in ActCatalogue.EntriesOf(ActCategories.Special)) + { + if (e.def != null) + specials.Add(e.name); + } + } + return; + } + if (g.DependsOnThing) + w.thingGroups = true; + foreach (ActEntry e in ActCatalogue.EntriesOf(entry.categoryId)) + { + if (e.def != null && g.MatchesDef(e.def)) + { + w.defs.Add(e.def); + if (entry.categoryId == ActCategories.Special) + specials.Add(e.name); + } + } + } + + private static void SetFlags() + { + Break = Category(ActCategories.Break); + Ate = Category(ActCategories.Ate); + Used = Category(ActCategories.Used); + Interaction = Category(ActCategories.Interaction); + RecordedAct = Category(ActCategories.RecordedAct); + Record = Category(ActCategories.Record); + Bill = Category(ActCategories.Bill); + Special = Category(ActCategories.Special); + SetFire = SpecialAct(SpecialActs.SetFire); + DisplayedCorpse = SpecialAct(SpecialActs.DisplayedCorpse); + StartedSocialFight = SpecialAct(SpecialActs.StartedSocialFight); + Any = byCategory.Count > 0; + } + } +} diff --git a/Tests/BlaxLawsTests/About/About.xml b/Tests/BlaxLawsTests/About/About.xml new file mode 100644 index 0000000..86c4c43 --- /dev/null +++ b/Tests/BlaxLawsTests/About/About.xml @@ -0,0 +1,19 @@ + + + Blax Laws Tests + Blax Gaming + blax.laws.tests + +
  • 1.7
  • +
    + + +
  • blax.castes
  • +
  • blax.zones
  • +
  • blax.slaves
  • +
  • blax.defaults
  • +
  • blax.laws
  • +
    + In-game test suite for Blax Laws. Does nothing unless the game is started with -blaxlawstests (see Tests/run-tests.ps1). Not for players. +
    diff --git a/Tests/BlaxLawsTests/Defs/BlaxLawsTests_Catalogue.xml b/Tests/BlaxLawsTests/Defs/BlaxLawsTests_Catalogue.xml new file mode 100644 index 0000000..c3bd74b --- /dev/null +++ b/Tests/BlaxLawsTests/Defs/BlaxLawsTests_Catalogue.xml @@ -0,0 +1,73 @@ + + + + + + BlaxLawsTest_Drug + + A drug that exists only in the Blax Laws test suite. + + Things/Item/Drug/WakeUp + Graphic_StackCount + + false + None + + 1 + 0.005 + + + Social + + +
  • + 9999 +
  • +
    +
    + + + BlaxLawsTest_Interaction + + InteractionWorker + + +
  • r_logentry->[INITIATOR_nameDef] tested [RECIPIENT_nameDef].
  • +
    +
    +
    + + + BlaxLawsTest_Recipe + + A recipe that exists only in the Blax Laws test suite. + Making a test thing. + 100 + + + + BlaxLawsTest_FireBreak + BlaxLawsTest_FireSpree + 0 + Minor + + + + BlaxLawsTest_FireSpree + MentalState_FireStartingSpree + + Malicious + true + false + 6000 + 10000 + 0.033 + Mental state: Test fire spree + + +
    diff --git a/Tests/BlaxLawsTests/Source/BlaxLawsTests.csproj b/Tests/BlaxLawsTests/Source/BlaxLawsTests.csproj new file mode 100644 index 0000000..de18ce9 --- /dev/null +++ b/Tests/BlaxLawsTests/Source/BlaxLawsTests.csproj @@ -0,0 +1,45 @@ + + + + + net10.0 + BlaxLawsTests + BlaxLawsTests + latest + disable + disable + ..\1.7\Assemblies\ + false + false + false + false + portable + $(MSBuildProjectDirectory)=Tests/BlaxLawsTests/Source + + + + E:\SteamLibrary\steamapps\common\RimWorld + E:\SteamLibrary\steamapps\workshop\content\294100\2009463077\1.7\Assemblies + $(MSBuildProjectDirectory)\..\..\..\1.7\Assemblies + + + + + $(RimWorldDir)\Assembly-CSharp.dll + false + + + $(RimWorldDir)\UnityStubs.dll + false + + + $(HarmonyDir)\0Harmony.dll + false + + + $(BlaxLawsDir)\BlaxLaws.dll + false + + + + diff --git a/Tests/BlaxLawsTests/Source/CatalogueTests.cs b/Tests/BlaxLawsTests/Source/CatalogueTests.cs new file mode 100644 index 0000000..aa0c176 --- /dev/null +++ b/Tests/BlaxLawsTests/Source/CatalogueTests.cs @@ -0,0 +1,390 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using BlaxLaws; +using RimWorld; +using Verse; +using Verse.AI; + +namespace BlaxLawsTests +{ + /// + /// The act catalogue (design: "Act catalogue and detection", Tests, Catalogue; "Lawbook tab", Tests, the + /// parts the catalogue answers): every def of the loaded game has its entry, the groups cover what their + /// rules say, breaks carry their stages and links, labels can be found and told apart, DLC entries appear + /// only with their DLC, and the watched sets follow the lawbook. + /// + public static class CatalogueTests + { + private const string TestModPackageId = "blax.laws.tests"; + + private static ActEntry Entry(string key) + { + ActEntry e = ActCatalogue.Get(key); + T.NotNull(e, "catalogue entry " + key); + return e; + } + + private static string Key(string category, Def def) => ActKey.Of(category, def.defName); + + [BlaxTest("catalogue: every break state, edible thing, usable, interaction, recorded act, counting record, recipe and special act has an entry; no Time record, plant or excluded state has one")] + public static void EveryDefHasAnEntry() + { + var sw = Stopwatch.StartNew(); + ActCatalogue.Build(); + sw.Stop(); + Watch.Rebuild(); + T.Info("catalogue built in " + sw.ElapsedMilliseconds + " ms: " + string.Join(", ", + ActCatalogue.Categories.Select(c => c.defName + " " + ActCatalogue.EntriesOf(c.defName).Count)) + ", " + ActCatalogue.All.Count + " in all"); + + var missing = new List(); + void Need(string category, Def def) + { + if (def != null && ActCatalogue.Get(Key(category, def)) == null) + missing.Add(Key(category, def)); + } + + ActCategoryDef breaks = DefDatabase.GetNamed(ActCategories.Break); + foreach (MentalBreakDef b in DefDatabase.AllDefsListForReading) + { + if (b.mentalState != null && !CatalogueRules.Excluded(breaks, b.mentalState.defName)) + Need(ActCategories.Break, b.mentalState); + } + foreach (string name in CatalogueRules.BreakInclude) + Need(ActCategories.Break, DefDatabase.GetNamedSilentFail(name)); + foreach (ThingDef t in DefDatabase.AllDefsListForReading) + { + if (CatalogueRules.IsEdible(t)) + Need(ActCategories.Ate, t); + if (CatalogueRules.IsUsable(t)) + Need(ActCategories.Used, t); + } + foreach (InteractionDef i in DefDatabase.AllDefsListForReading) + Need(ActCategories.Interaction, i); + ActCategoryDef recorded = DefDatabase.GetNamed(ActCategories.RecordedAct); + foreach (HistoryEventDef h in DefDatabase.AllDefsListForReading) + { + if (!CatalogueRules.Excluded(recorded, h.defName)) + Need(ActCategories.RecordedAct, h); + } + foreach (RecordDef r in DefDatabase.AllDefsListForReading) + { + if (r.type != RecordType.Time) + Need(ActCategories.Record, r); + } + foreach (RecipeDef r in DefDatabase.AllDefsListForReading) + Need(ActCategories.Bill, r); + foreach (ActDef a in DefDatabase.AllDefsListForReading) + Need(ActCategories.Special, a); + T.Check(missing.Count == 0, missing.Count + " def(s) without an entry, first: " + string.Join(", ", missing.Take(8))); + + var wrong = new List(); + foreach (RecordDef r in DefDatabase.AllDefsListForReading.Where(r => r.type == RecordType.Time)) + { + if (ActCatalogue.Get(Key(ActCategories.Record, r)) != null) + wrong.Add("Time record " + r.defName); + } + foreach (string name in CatalogueRules.BreakExclude) + { + if (ActCatalogue.Get(ActKey.Of(ActCategories.Break, name)) != null) + wrong.Add("excluded state " + name); + } + foreach (ThingDef plant in DefDatabase.AllDefsListForReading.Where(t => t.category == ThingCategory.Plant && t.ingestible != null).Take(20)) + { + if (ActCatalogue.Get(Key(ActCategories.Ate, plant)) != null) + wrong.Add("plant " + plant.defName); + } + if (ActCatalogue.Get(ActKey.Of(ActCategories.RecordedAct, "Traded")) != null) + wrong.Add("faction-level event Traded"); + T.Check(wrong.Count == 0, "entries that must not exist: " + string.Join(", ", wrong.Take(8))); + + // The examples of the design, all Core. + Entry("Break/Binging_DrugExtreme"); + Entry("Break/FireStartingSpree"); + Entry("Break/CorpseObsession"); + Entry("Break/Berserk"); + Entry("Ate/WakeUp"); + Entry("Used/MechSerumHealer"); + Entry("Interaction/Insult"); + Entry("Interaction/SparkJailbreak"); + Entry("RecordedAct/ExecutedPrisoner"); + Entry("Record/BodiesStripped"); + Entry("Bill/" + RecipeDefOf.RemoveBodyPart.defName); + Entry("Special/SetFire"); + Entry("Special/DisplayedCorpse"); + Entry("Special/StartedSocialFight"); + } + + [BlaxTest("catalogue: every group of the design exists with its label, comes before the defs and covers what its rule says")] + public static void Groups() + { + var groups = new (string category, string id)[] + { + (ActCategories.Break, ActGroups.Any), (ActCategories.Break, ActGroups.AnyDrugBinge), (ActCategories.Break, ActGroups.AnyTantrum), + (ActCategories.Break, ActGroups.AnyInsultingSpree), (ActCategories.Break, ActGroups.AnyAggressive), + (ActCategories.Ate, ActGroups.Any), (ActCategories.Ate, ActGroups.AnyDrug), (ActCategories.Ate, ActGroups.HardDrugs), + (ActCategories.Ate, ActGroups.SocialDrugs), (ActCategories.Ate, ActGroups.MedicalDrugs), (ActCategories.Ate, ActGroups.AnyMeat), + (ActCategories.Ate, ActGroups.RawMeatOrCorpse), (ActCategories.Ate, ActGroups.HumanMeat), (ActCategories.Ate, ActGroups.InsectMeat), + (ActCategories.Ate, ActGroups.RawFood), (ActCategories.Ate, ActGroups.AnyMeal), + (ActCategories.Interaction, ActGroups.InsultOrSlight), (ActCategories.Bill, ActGroups.AnySurgery), + }; + foreach (var (category, id) in groups) + { + ActEntry e = Entry(ActKey.OfGroup(category, id)); + T.Check(e.IsGroup && e.def == null, e.key + " is not a group entry"); + T.Check(e.group.labelKey.CanTranslate(), e.key + ": label " + e.group.labelKey + " missing from Keyed"); + T.Check(e.label == e.group.labelKey.Translate().ToString(), e.key + " reads '" + e.label + "', not its Keyed label"); + T.Equal(DlcSupport.CoreName, e.sourceMod, e.key + " source"); + T.Check(e.group.size > 0, e.key + " covers no def of the loaded game"); + } + foreach (ActCategoryDef cat in ActCatalogue.Categories) + { + IReadOnlyList list = ActCatalogue.EntriesOf(cat.defName); + int firstDef = list.Count; + for (int i = 0; i < list.Count; i++) + { + if (list[i].def != null) + { + firstDef = i; + break; + } + } + T.Check(list.Skip(firstDef).All(e => e.def != null), cat.defName + ": a group comes after a def entry"); + } + + ActGroup G(string key) => Entry(key).group; + void In(string key, Def def, bool expected) + { + T.NotNull(def, "def for " + key); + T.Check(G(key).MatchesDef(def) == expected, key + (expected ? " misses " : " takes in ") + def.defName); + } + MentalStateDef State(string name) => DefDatabase.GetNamed(name); + + In("Break/@anyDrugBinge", State("Binging_DrugExtreme"), true); + In("Break/@anyDrugBinge", State("Binging_DrugMajor"), true); + In("Break/@anyDrugBinge", State("Binging_Food"), false); + In("Break/@anyTantrum", State("Tantrum"), true); + In("Break/@anyTantrum", State("TargetedTantrum"), true); + In("Break/@anyTantrum", State("BedroomTantrum"), true); + In("Break/@anyTantrum", State("MurderousRage"), false); + In("Break/@anyInsultingSpree", State("InsultingSpree"), true); + In("Break/@anyInsultingSpree", State("TargetedInsultingSpree"), true); + In("Break/@anyAggressive", State("Berserk"), true); + In("Break/@anyAggressive", State("Wander_Sad"), false); + In("Break/@any", State("Wander_Sad"), true); + In("Break/@any", MentalStateDefOf.SocialFighting, false); + In("Break/@any", MentalStateDefOf.Manhunter, false); + + ThingDef cowMeat = ThingDefOf.Cow.race.meatDef; + ThingDef insect = DefDatabase.GetNamed("Megaspider"); + In("Ate/@any", ThingDefOf.MealSimple, true); + In("Ate/@anyDrug", ThingDefOf.Beer, true); + In("Ate/@anyDrug", ThingDefOf.MealSimple, false); + In("Ate/@hardDrugs", ThingDefOf.WakeUp, true); + In("Ate/@hardDrugs", ThingDefOf.Yayo, true); + In("Ate/@hardDrugs", ThingDefOf.Beer, false); + In("Ate/@socialDrugs", ThingDefOf.Beer, true); + In("Ate/@socialDrugs", ThingDefOf.SmokeleafJoint, true); + In("Ate/@medicalDrugs", ThingDefOf.Penoxycyline, true); + In("Ate/@rawMeatOrCorpse", cowMeat, true); + In("Ate/@rawMeatOrCorpse", ThingDefOf.Human.race.corpseDef, true); + In("Ate/@rawMeatOrCorpse", ThingDefOf.MealSimple, false); + In("Ate/@humanMeat", ThingDefOf.Meat_Human, true); + In("Ate/@humanMeat", ThingDefOf.Human.race.corpseDef, true); + In("Ate/@humanMeat", cowMeat, false); + In("Ate/@insectMeat", insect.race.meatDef, true); + In("Ate/@insectMeat", insect.race.corpseDef, true); + In("Ate/@insectMeat", cowMeat, false); + In("Ate/@anyMeat", cowMeat, true); + In("Ate/@rawFood", ThingDefOf.RawPotatoes, true); + In("Ate/@rawFood", ThingDefOf.MealSimple, false); + In("Ate/@anyMeal", ThingDefOf.MealSimple, true); + In("Ate/@anyMeal", ThingDefOf.MealSurvivalPack, true); + In("Ate/@anyMeal", ThingDefOf.Beer, false); + In("Ate/@anyMeal", ThingDefOf.Chocolate, false); + In("Interaction/@insultOrSlight", InteractionDefOf.Insult, true); + In("Interaction/@insultOrSlight", DefDatabase.GetNamed("Slight"), true); + In("Interaction/@insultOrSlight", InteractionDefOf.Chitchat, false); + In("Bill/@anySurgery", RecipeDefOf.RemoveBodyPart, true); + In("Bill/@anySurgery", DefDatabase.GetNamed("CookMealSimple"), false); + + // The thing decides for meals: a simple meal is human meat only with human meat in it. + Thing mealHuman = ThingMaker.MakeThing(ThingDefOf.MealSimple); + mealHuman.TryGetComp().RegisterIngredient(ThingDefOf.Meat_Human); + Thing mealVeg = ThingMaker.MakeThing(ThingDefOf.MealSimple); + mealVeg.TryGetComp().RegisterIngredient(ThingDefOf.RawPotatoes); + ActEvent Ate(Thing food) => new ActEvent(ActCategories.Ate, food.def, null) { thing = food, facts = FoodFacts.Of(food) }; + T.Check(G("Ate/@humanMeat").Matches(Ate(mealHuman)), "a simple meal with human meat isn't human meat"); + T.Check(G("Ate/@anyMeat").Matches(Ate(mealHuman)), "a simple meal with human meat isn't meat"); + T.Check(!G("Ate/@humanMeat").Matches(Ate(mealVeg)), "a simple meal of potatoes is human meat"); + T.Check(!G("Ate/@anyMeat").Matches(Ate(mealVeg)), "a simple meal of potatoes is meat"); + T.Check(!G("Ate/@rawMeatOrCorpse").Matches(Ate(mealHuman)), "a simple meal is raw meat"); + + // The smaller group wins: sizes must order the nested groups. + T.Check(G("Ate/@hardDrugs").size < G("Ate/@anyDrug").size, "hard drugs aren't smaller than any drug"); + T.Check(G("Ate/@humanMeat").size < G("Ate/@anyMeat").size, "human meat isn't smaller than any meat"); + T.Check(G("Break/@anyDrugBinge").size < G("Break/@any").size, "any drug binge isn't smaller than any break"); + } + + [BlaxTest("catalogue: breaks get Planning, a Did it through their link, hostility and the drug option; other entries are Did it only")] + public static void BreakStagesAndLinks() + { + ActEntry fire = Entry("Break/FireStartingSpree"); + T.Check(fire.hasPlanning && fire.hasDidIt, "fire-starting spree stages: planning " + fire.hasPlanning + ", did it " + fire.hasDidIt); + T.Check(fire.links.Any(l => l.act == "Special/SetFire"), "fire-starting spree isn't linked to Special/SetFire"); + ActEntry sad = Entry("Break/Wander_Sad"); + T.Check(sad.hasPlanning && !sad.hasDidIt, "sad wandering offers Did it without a link"); + T.Check(Entry("Break/CorpseObsession").links.Any(l => l.act == "Special/DisplayedCorpse"), "corpse obsession isn't linked to DisplayedCorpse"); + T.Check(Entry("Break/Jailbreaker").links.Any(l => l.act == "Interaction/SparkJailbreak"), "jailbreaker isn't linked to SparkJailbreak"); + T.Check(Entry("Break/TargetedInsultingSpree").links.Any(l => l.act == "Interaction/@insultOrSlight"), "targeted insulting spree isn't linked to insult or slight"); + ActEntry extreme = Entry("Break/Binging_DrugExtreme"); + T.Check(extreme.links.Count == 1 && extreme.links[0].act == "Ate/@anyDrug" && extreme.hasDrugOption, + "a drug binge takes the drug link (most derived class) with the option, has: " + string.Join(", ", extreme.links.Select(l => l.act))); + ActEntry food = Entry("Break/Binging_Food"); + T.Check(food.links.Count == 1 && food.links[0].act == "Ate/@any" && !food.hasDrugOption, "food binge link: " + string.Join(", ", food.links.Select(l => l.act))); + ActEntry anyBinge = Entry("Break/@anyDrugBinge"); + T.Check(anyBinge.hasPlanning && anyBinge.hasDidIt && anyBinge.hasDrugOption, "any drug binge: planning, did it and the drug option expected"); + T.Check(Entry("Break/Berserk").hostileBreak, "berserk isn't hostile to the colony"); + T.Check(!Entry("Break/Tantrum").hostileBreak && !Entry("Break/MurderousRage").hostileBreak, "a tantrum or murderous rage is marked hostile"); + T.Check(!Entry("Break/@anyAggressive").hostileBreak, "any aggressive break is marked hostile, but holds tantrums"); + + foreach (BreakLinkDef link in DefDatabase.AllDefsListForReading) + T.NotNull(ActCatalogue.Get(link.act), "the act of " + link.defName + " (" + link.act + ")"); + + foreach (ActEntry e in ActCatalogue.All.Where(x => !x.IsBreak)) + T.Check(!e.hasPlanning && e.hasDidIt, e.key + " should be Did it only"); + } + + [BlaxTest("catalogue: a Berserk row offers Warn, Guilty and Jail, never Subdue; a Tantrum or MurderousRage row also offers Subdue; a Planning row never offers Guilty")] + public static void PunishmentsByEntry() + { + string Names(string key, LawStage stage) => string.Join(",", Lawbook.PunishmentsFor(Entry(key), stage).Select(p => p.defName)); + T.Equal("Warn,Guilty,Jail", Names("Break/Berserk", LawStage.Planning), "Berserk planning"); + T.Equal("Warn,Subdue,Jail", Names("Break/Tantrum", LawStage.Planning), "Tantrum planning"); + T.Equal("Warn,Subdue,Jail", Names("Break/MurderousRage", LawStage.Planning), "MurderousRage planning"); + T.Check(Names("Break/FireStartingSpree", LawStage.DidIt).Contains("Subdue"), "a linked break's did-it lacks Subdue"); + T.Check(!Names("Interaction/Insult", LawStage.DidIt).Contains("Subdue"), "an interaction offers Subdue"); + } + + [BlaxTest("catalogue: the drug option list holds WakeUp, every option is a drug's chemical, and no other chemical")] + public static void ChemicalOptions() + { + IReadOnlyList options = ActCatalogue.ChemicalOptions; + T.Check(options.Contains("WakeUp"), "WakeUp missing from the drug options: " + string.Join(", ", options)); + var drugChemicals = new HashSet(DefDatabase.AllDefsListForReading.Select(DrugInfo.ChemicalOf).Where(c => c != null).Select(c => c.defName)); + T.Check(options.All(drugChemicals.Contains), "a drug option no drug carries: " + string.Join(", ", options.Where(o => !drugChemicals.Contains(o)))); + T.Equal(DrugCategory.Hard, DrugInfo.CategoryOfChemical(DefDatabase.GetNamed("WakeUp")), "category of the wake-up chemical"); + T.Equal(DrugCategory.Social, DrugInfo.CategoryOfChemical(DefDatabase.GetNamed("Alcohol")), "category of the alcohol chemical"); + } + + [BlaxTest("catalogue: searching 'wake' finds Wake-up under Ate and the make wake-up bill; 'insult' finds Insult and the insulting sprees; equal labels are told apart")] + public static void LabelsAndSearch() + { + // The picker matches the label and the def name (design: "Act picker"). + List Search(string text) => ActCatalogue.All.Where(e => + (e.label ?? "").IndexOf(text, StringComparison.OrdinalIgnoreCase) >= 0 || + (e.def?.defName ?? "").IndexOf(text, StringComparison.OrdinalIgnoreCase) >= 0).ToList(); + + List wake = Search("wake"); + T.Check(wake.Any(e => e.categoryId == ActCategories.Ate && e.def == ThingDefOf.WakeUp), "'wake' doesn't find Ate: wake-up"); + ActEntry makeWake = wake.FirstOrDefault(e => e.categoryId == ActCategories.Bill && (e.def as RecipeDef)?.ProducedThingDef == ThingDefOf.WakeUp); + T.NotNull(makeWake, "'wake' finding the bill that makes wake-up"); + T.Check(makeWake.label.IndexOf("wake-up", StringComparison.OrdinalIgnoreCase) >= 0, "the wake-up bill reads '" + makeWake.label + "'"); + + List insult = Search("insult"); + T.Check(insult.Any(e => e.key == "Interaction/Insult"), "'insult' doesn't find Interaction: insult"); + T.Check(insult.Any(e => e.key == "Break/InsultingSpree") && insult.Any(e => e.key == "Break/TargetedInsultingSpree"), + "'insult' doesn't find both insulting sprees under breaks"); + + string extreme = Entry("Break/Binging_DrugExtreme").label, major = Entry("Break/Binging_DrugMajor").label; + T.Check(extreme != major, "both drug binges read '" + extreme + "'"); + T.Equal("Tantrum", Entry("Break/Tantrum").label, "the plain tantrum's label"); + T.Check(Entry("Break/TargetedTantrum").label != "Tantrum", "the targeted tantrum reads like the plain one"); + // Strict for the official content; a mod list may hold two defs whose names read alike, noted only. + foreach (ActCategoryDef cat in ActCatalogue.Categories) + { + var shared = ActCatalogue.EntriesOf(cat.defName).Where(e => e.def != null) + .GroupBy(e => e.label, StringComparer.OrdinalIgnoreCase).Where(g => g.Count() > 1).ToList(); + var official = shared.Where(g => g.All(e => e.sourcePackageId == DlcSupport.CorePackageId || DlcSupport.IsDlcPackageId(e.sourcePackageId))) + .Select(g => g.Key).ToList(); + T.Check(official.Count == 0, cat.defName + ": labels still shared: " + string.Join(", ", official.Take(5))); + if (shared.Count > official.Count) + T.Info(cat.defName + ": " + (shared.Count - official.Count) + " label(s) shared by modded entries, first: " + shared.First(g => !official.Contains(g.Key)).Key); + } + T.Equal(DlcSupport.CoreName, Entry("Ate/WakeUp").sourceMod, "source of Ate: wake-up"); + } + + [BlaxTest("catalogue: the test mod's drug, interaction, recipe and break appear with the test mod as source; the test break offers Did it through its class's link")] + public static void TestModDefs() + { + string[] keys = { "Ate/BlaxLawsTest_Drug", "Interaction/BlaxLawsTest_Interaction", "Bill/BlaxLawsTest_Recipe", "Break/BlaxLawsTest_FireSpree" }; + if (DefDatabase.GetNamedSilentFail("BlaxLawsTest_FireSpree") == null) + T.Fail("the test mod's catalogue defs aren't loaded: Tests/BlaxLawsTests/Defs/BlaxLawsTests_Catalogue.xml is missing"); + foreach (string key in keys) + { + ActEntry e = Entry(key); + T.Equal(TestModPackageId, e.sourcePackageId, key + " source package"); + T.Check(e.sourceMod != DlcSupport.CoreName && !e.sourceMod.NullOrEmpty(), key + " source reads '" + e.sourceMod + "'"); + } + ActEntry spree = Entry("Break/BlaxLawsTest_FireSpree"); + T.Check(spree.hasPlanning && spree.hasDidIt && spree.links.Any(l => l.act == "Special/SetFire"), + "the test break reusing MentalState_FireStartingSpree lacks the SetFire link"); + T.Check(Entry("Ate/@anyDrug").group.MatchesDef(DefDatabase.GetNamed("BlaxLawsTest_Drug")), "the test drug isn't in any drug"); + } + + [BlaxTest("catalogue: no entry of an inactive DLC appears, each active DLC's entries name it, and every starter row resolves")] + public static void DlcEntries() + { + var bySource = ActCatalogue.All.GroupBy(e => e.sourceMod).Select(g => g.Key + " " + g.Count()); + T.Info("entries by source: " + string.Join(", ", bySource)); + var stray = ActCatalogue.All.Where(e => DlcSupport.IsDlcPackageId(e.sourcePackageId) && !DlcSupport.IsDlcActive(DlcSupport.DlcName(e.sourcePackageId))).ToList(); + T.Check(stray.Count == 0, "entries of an inactive DLC: " + string.Join(", ", stray.Take(5))); + if (ModsConfig.IdeologyActive) + T.Equal("Ideology", Entry("Break/IdeoChange").sourceMod, "source of the Ideology break IdeoChange"); + else + T.Check(ActCatalogue.Get("Break/IdeoChange") == null, "Ideology's IdeoChange break is listed without Ideology"); + if (ModsConfig.BiotechActive) + T.Equal("Biotech", Entry("Break/PanicFleeFire").sourceMod, "source of the Biotech break PanicFleeFire"); + foreach (Lawbook.StarterRow s in Lawbook.StarterRows) + { + ActEntry e = Entry(s.actKey); + T.Check(e.HasStage(s.stage), "starter row " + s.actKey + " has no " + s.stage + " stage"); + T.Check(!DlcSupport.IsDlcPackageId(e.sourcePackageId), "starter row " + s.actKey + " comes from " + e.sourceMod); + } + } + + [BlaxTest("watch: an any-drug-binge row watches both binge states and every drug through its link; deleting it clears them; a meal group watches every meal")] + public static void WatchFollowsRows() + { + MentalStateDef extreme = DefDatabase.GetNamed("Binging_DrugExtreme"); + MentalStateDef major = DefDatabase.GetNamed("Binging_DrugMajor"); + MentalStateDef sad = DefDatabase.GetNamed("Wander_Sad"); + T.Check(!Watch.Break && !Watch.Ate, "the book isn't empty at the start"); + Law binge = Fixtures.LawRow("Break/@anyDrugBinge", DrugOptions.Any, LawStage.Planning, LawSeverity.Moderate, "Warn", 3); + T.Check(Watch.Any && Watch.Break, "the Break flag is off with a binge row"); + T.Check(Watch.IsWatched(ActCategories.Break, extreme) && Watch.IsWatched(ActCategories.Break, major), "a binge state isn't watched"); + T.Check(!Watch.IsWatched(ActCategories.Break, sad), "sad wandering is watched by a binge row"); + T.Check(Watch.Ate && Watch.IsWatched(ActCategories.Ate, ThingDefOf.WakeUp) && Watch.IsWatched(ActCategories.Ate, ThingDefOf.Beer), + "the binge's link doesn't watch the drugs"); + T.Check(!Watch.MayMatch(ActCategories.Ate, ThingDefOf.MealSimple), "a binge row watches simple meals"); + T.Check(!Watch.Interaction && !Watch.Special, "a binge row turned an unrelated flag on"); + Lawbook.Delete(binge); + T.Check(!Watch.Any && !Watch.Break && !Watch.Ate, "deleting the binge row left a flag on"); + T.Check(!Watch.IsWatched(ActCategories.Break, extreme), "deleting the binge row left the state watched"); + + Law fire = Fixtures.LawRow("Break/FireStartingSpree", null, LawStage.Planning, LawSeverity.Moderate, "Warn", 3); + T.Check(Watch.SetFire && Watch.Special && !Watch.DisplayedCorpse, "a fire spree row must watch SetFire only among the special acts"); + Lawbook.SetEnabled(fire, false); + T.Check(!Watch.Any, "a disabled row still watches"); + Lawbook.SetEnabled(fire, true); + + Fixtures.LawRow("Ate/@anyMeal", null, LawStage.DidIt, LawSeverity.Minor, "Warn", 1); + T.Check(Watch.IsWatched(ActCategories.Ate, ThingDefOf.MealSimple) && Watch.IsWatched(ActCategories.Ate, ThingDefOf.MealFine), "any meal doesn't watch the meals"); + T.Check(!Watch.IsWatched(ActCategories.Ate, ThingDefOf.RawPotatoes), "any meal watches raw potatoes"); + Fixtures.LawRow("Ate/@humanMeat", null, LawStage.DidIt, LawSeverity.Minor, "Warn", 1); + T.Check(Watch.ThingGroups(ActCategories.Ate) && Watch.MayMatch(ActCategories.Ate, ThingDefOf.RawPotatoes), + "a group that reads the thing must let every act of the category through"); + } + } +} diff --git a/Tests/BlaxLawsTests/Source/DetectionTests.cs b/Tests/BlaxLawsTests/Source/DetectionTests.cs new file mode 100644 index 0000000..bd04b0d --- /dev/null +++ b/Tests/BlaxLawsTests/Source/DetectionTests.cs @@ -0,0 +1,1036 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using BlaxLaws; +using HarmonyLib; +using RimWorld; +using Verse; +using Verse.AI; + +namespace BlaxLawsTests +{ + /// + /// The detection hooks and case filing (design: "Act catalogue and detection", Tests): every hook files + /// the act it watches on the right pawn, a break's linked act moves its case to did it, the most specific + /// row decides, player orders, other pawns' doses, quest lodgers and visitors file nothing, the cooldown keeps the log from + /// flooding, a throwing hook leaves vanilla running, and an empty book costs nothing. + /// + /// The tests call the hooked vanilla methods themselves and never tick, so no punishment runs: rows use + /// Warn and are deleted after each test. A pawn "acts on its own job" through DetectionKit.WithOwnJob, + /// which sets the job the vanilla toils would have running (hook C and U read only its targets). + /// + public static class DetectionTests + { + // ---- A: breaks, C: binge doses --------------------------------------------------------- + + [BlaxTest("detection A: under a wake-up row a wake-up binge opens one planning case, a yayo binge none")] + public static void BingePlanningByChemical() + { + DetectionKit.ClearDrugsOnMap(); + Law row = DetectionKit.Row("Break/@anyDrugBinge", LawStage.Planning, "WakeUp"); + Pawn p = DetectionKit.Colonist(); + Thing wake = DetectionKit.ItemNear(p, ThingDefOf.WakeUp, 5); + T.Check(DetectionKit.Start(p, "Binging_DrugExtreme"), "the extreme binge didn't start"); + T.Equal("WakeUp", (p.MentalState as MentalState_BingingDrug)?.chemical?.defName, "the binge's chemical with only wake-up on the map"); + LawCase c = DetectionKit.OnlyCase(p, "the wake-up binger"); + T.Equal(LawStage.Planning, c.stage, "stage"); + T.Equal(row.id, c.planningLawId, "planning row"); + T.Equal("Binging_DrugExtreme", c.breakState, "break state"); + T.Equal(0, c.count, "count before any dose"); + + wake.Destroy(); + Pawn q = DetectionKit.Colonist(); + DetectionKit.ItemNear(q, ThingDefOf.Yayo, 5); + T.Check(DetectionKit.Start(q, "Binging_DrugExtreme"), "the second extreme binge didn't start"); + T.Equal("Psychite", (q.MentalState as MentalState_BingingDrug)?.chemical?.defName, "the binge's chemical with only yayo on the map"); + DetectionKit.NoCase(q, "the yayo binger"); + } + + [BlaxTest("detection C: a wake-up dose during the binge moves its case to did it with count 1, a second dose counts 2; a dose outside a binge files nothing")] + public static void BingeDoses() + { + DetectionKit.ClearDrugsOnMap(); + DetectionKit.NoOverdose(ThingDefOf.WakeUp); + Law plan = DetectionKit.Row("Break/@anyDrugBinge", LawStage.Planning, "WakeUp"); + Law did = DetectionKit.Row("Break/@anyDrugBinge", LawStage.DidIt, "WakeUp"); + Pawn p = DetectionKit.Colonist(); + Thing wake = DetectionKit.ItemNear(p, ThingDefOf.WakeUp, 5); + T.Check(DetectionKit.Start(p, "Binging_DrugExtreme"), "the extreme binge didn't start"); + LawCase c = DetectionKit.OnlyCase(p, "the binger before the dose"); + T.Equal(plan.id, c.planningLawId, "planning row"); + + DetectionKit.Eat(p, wake); + T.Equal(4, wake.stackCount, "fixture: wake-up left after the first dose"); + T.Equal(LawStage.DidIt, c.stage, "stage after the first dose"); + T.Equal(1, c.count, "count after the first dose"); + T.Equal(did.id, c.didItLawId, "did-it row"); + T.Equal("WakeUp", c.matchedDef, "the matched def"); + DetectionKit.Eat(p, wake); + T.Equal(2, c.count, "count after the second dose; the binger's state " + (p.MentalStateDef?.defName ?? "none") + (p.Downed ? ", downed" : "") + + ", overdose " + (p.health.hediffSet.GetFirstHediffOfDef(HediffDefOf.DrugOverdose)?.Severity.ToString("0.##") ?? "none")); + T.Equal(1, DetectionKit.CasesOf(p).Count, "cases of the binger after two doses"); + + Pawn sober = DetectionKit.Colonist(); + Thing other = DetectionKit.ItemNear(sober, ThingDefOf.WakeUp, 2); + DetectionKit.Eat(sober, other); + T.Equal(1, other.stackCount, "fixture: wake-up left after the sober dose"); + DetectionKit.NoCase(sober, "a colonist dosing outside a binge"); + } + + [BlaxTest("detection A: an any-drug binge row catches a beer binge (Binging_DrugMajor)")] + public static void AnyDrugRowCatchesBeerBinge() + { + DetectionKit.ClearDrugsOnMap(); + Law row = DetectionKit.Row("Break/@anyDrugBinge", LawStage.Planning, DrugOptions.Any); + Pawn p = DetectionKit.Colonist(); + DetectionKit.ItemNear(p, ThingDefOf.Beer, 5); + T.Check(DetectionKit.Start(p, "Binging_DrugMajor"), "the major binge didn't start"); + T.Equal("Alcohol", (p.MentalState as MentalState_BingingDrug)?.chemical?.defName, "the binge's chemical with only beer on the map"); + LawCase c = DetectionKit.OnlyCase(p, "the beer binger"); + T.Equal(row.id, c.planningLawId, "planning row"); + T.Equal("Binging_DrugMajor", c.breakState, "break state"); + } + + [BlaxTest("detection C: the starter lawbook plus 'wake-up, did it, jail 10 days' gives a wake-up binger one case and 10 days")] + public static void StarterPlusWakeUpRow() + { + DetectionKit.ClearDrugsOnMap(); + DetectionKit.NoOverdose(ThingDefOf.WakeUp); + Lawbook.AddStarter(); + Law starterPlan = Lawbook.Find("Break/@anyDrugBinge", DrugOptions.Any, LawStage.Planning); + T.NotNull(starterPlan, "starter row 'any drug binge, planning'"); + Law ten = DetectionKit.Row("Break/@anyDrugBinge", LawStage.DidIt, "WakeUp", "Jail", LawSeverity.Serious, 10); + Pawn p = DetectionKit.Colonist(); + Thing wake = DetectionKit.ItemNear(p, ThingDefOf.WakeUp, 3); + T.Check(DetectionKit.Start(p, "Binging_DrugExtreme"), "the extreme binge didn't start"); + DetectionKit.Eat(p, wake); + LawCase c = DetectionKit.OnlyCase(p, "the wake-up binger"); + T.Equal(starterPlan.id, c.planningLawId, "planning row"); + T.Equal(ten.id, c.didItLawId, "did-it row: the wake-up row beats the starter's any drug"); + T.Equal(10, c.LawFor(LawStage.DidIt).days, "days of the did-it row"); + T.Equal(1, c.count, "doses counted"); + } + + // ---- A, I: fire --------------------------------------------------------------------- + + [BlaxTest("detection I: a fire-starting spree opens planning, its ignite moves it to did it with count 1; a raider's ignite files nothing")] + public static void FireSpree() + { + DetectionKit.PutOutFiresAfter(); + Law plan = DetectionKit.Row("Break/FireStartingSpree", LawStage.Planning); + Law did = DetectionKit.Row("Break/FireStartingSpree", LawStage.DidIt); + // A row of its own on the act too: the break's case still takes it (one act, one case). + DetectionKit.Row("Special/SetFire", LawStage.DidIt); + Pawn p = DetectionKit.Colonist(); + T.Check(DetectionKit.Start(p, "FireStartingSpree"), "the fire-starting spree didn't start"); + LawCase c = DetectionKit.OnlyCase(p, "the pyromaniac at the start"); + T.Equal(LawStage.Planning, c.stage, "stage at the start"); + T.Equal(plan.id, c.planningLawId, "planning row"); + + DetectionKit.Ignite(p, DetectionKit.WoodWallNear(p)); + T.Equal(LawStage.DidIt, c.stage, "stage after the ignite"); + T.Equal(1, c.count, "count after the ignite"); + T.Equal(did.id, c.didItLawId, "did-it row: the break's row on a tie with Special/SetFire"); + T.Equal(1, DetectionKit.CasesOf(p).Count, "cases of the pyromaniac: one act, one case"); + + Pawn raider = DetectionKit.Stranger(Fixtures.HostileFaction() ?? Fixtures.FriendlyFaction(), p.Position); + DetectionKit.Ignite(raider, DetectionKit.WoodWallNear(raider)); + DetectionKit.NoCase(raider, "a raider who set a fire"); + } + + // ---- A: breaks other pawns cause, self-cast breaks on a player order --------------------- + + [BlaxTest("detection A: a break another pawn's ability forces on a colonist opens no case; the same break started without a caster does")] + public static void AbilityForcedBreakFilesNothing() + { + DetectionKit.Row("Break/@anyAggressive", LawStage.Planning); + MentalStateDef tantrum = DefDatabase.GetNamed("Tantrum"); + Pawn control = DetectionKit.Colonist(); + T.Check(control.mindState.mentalStateHandler.TryStartMentalState(tantrum, null, forced: true, forceWake: true), "fixture: control tantrum did not start"); + DetectionKit.OnlyCase(control, "a colonist whose own tantrum starts"); + + Pawn victim = DetectionKit.Colonist(); + Pawn caster = DetectionKit.ColonistNear(victim); + // As CompAbilityEffect_GiveMentalState.TryGiveMentalState calls it (RimWorld/CompAbilityEffect_GiveMentalState.cs:59). + bool started = victim.mindState.mentalStateHandler.TryStartMentalState(tantrum, null, forced: true, forceWake: true, causedByMood: false, + otherPawn: caster, transitionSilently: false, causedByDamage: false, causedByPsycast: true); + T.Check(started && victim.MentalStateDef == tantrum, "fixture: the forced tantrum did not start"); + DetectionKit.NoCase(victim, "a colonist a caster's psycast put in a tantrum"); + DetectionKit.NoCase(caster, "the caster"); + } + + [BlaxTest("detection A: a drafted colonist's self-cast break opens nothing while player orders are exempt and a case when the setting is off; a drafted colonist's own break still files")] + public static void SelfCastBreakOnPlayerOrder() + { + DetectionKit.Row("Break/@anyAggressive", LawStage.Planning); + MentalStateDef tantrum = DefDatabase.GetNamed("Tantrum"); + + // A mood break that hits a drafted pawn is no order: the exemption must not reach it. + Pawn moody = DetectionKit.Colonist(); + moody.drafter.Drafted = true; + T.Check(moody.Drafted, "fixture: the colonist isn't drafted"); + T.Check(moody.mindState.mentalStateHandler.TryStartMentalState(tantrum, null, forced: true, forceWake: true, causedByMood: true), "fixture: mood tantrum did not start"); + DetectionKit.OnlyCase(moody, "a drafted colonist whose own mood break starts"); + + // A self-cast ability (the Berserk trance passes the caster as otherPawn, onlyApplyToSelf) while drafted. + Pawn caster = DetectionKit.Colonist(); + caster.drafter.Drafted = true; + T.Check(caster.Drafted, "fixture: the caster isn't drafted"); + T.Check(caster.mindState.mentalStateHandler.TryStartMentalState(tantrum, null, forced: true, forceWake: true, causedByMood: false, otherPawn: caster, causedByPsycast: false), + "fixture: self-cast tantrum did not start"); + T.Check(!caster.Drafted, "vanilla left the caster drafted, so the test no longer covers the undraft"); + DetectionKit.NoCase(caster, "a drafted colonist that put itself in the state"); + + // The same cast from an undrafted pawn on a player-forced job (a role ability's gizmo shows undrafted): + // vanilla ends that job before the state starts, so only a read before it sees the order. + Pawn ordered = DetectionKit.Colonist(); + T.Check(ordered.jobs.TryTakeOrderedJob(JobMaker.MakeJob(JobDefOf.Wait, 600)), "fixture: the colonist took no ordered job"); + Job order = ordered.CurJob; + T.Check(order != null && order.playerForced && !ordered.Drafted, "fixture: no undrafted pawn on a player-forced job"); + T.Check(ordered.mindState.mentalStateHandler.TryStartMentalState(tantrum, null, forced: true, forceWake: true, causedByMood: false, otherPawn: ordered, causedByPsycast: false), + "fixture: ordered self-cast tantrum did not start"); + T.Check(ordered.CurJob != order, "vanilla left the ordered job running, so the test no longer covers the job being ended"); + DetectionKit.NoCase(ordered, "an undrafted colonist on a player-forced job that put itself in the state"); + + Fixtures.Settings.playerOrdersExempt = false; + Pawn caster2 = DetectionKit.Colonist(); + caster2.drafter.Drafted = true; + T.Check(caster2.mindState.mentalStateHandler.TryStartMentalState(tantrum, null, forced: true, forceWake: true, causedByMood: false, otherPawn: caster2), + "fixture: second self-cast tantrum did not start"); + DetectionKit.OnlyCase(caster2, "a drafted self-caster with the setting off"); + } + + // ---- A, J: corpse obsession ---------------------------------------------------------- + + [BlaxTest("detection J: an obsession over a buried corpse opens planning with 'dug up'; the corpse shown on a table moves it to did it with 'on a table', once")] + public static void CorpseObsession() + { + var (p, c, state, _, did) = ShownCorpseObsession(keep: false); + T.Equal(LawStage.DidIt, c.stage, "stage after the display"); + T.Equal(1, c.count, "count after the display"); + T.Equal(did.id, c.didItLawId, "did-it row"); + T.Equal(CaseNotes.DugUp | CaseNotes.OnTable, c.notes, "notes after the display"); + state.MentalStateTick(1); + state.MentalStateTick(1); + T.Equal(1, c.count, "count after more ticks of the same obsession"); + T.Equal(1, DetectionKit.CasesOf(p).Count, "cases of the obsessed colonist"); + } + + /// + /// A colonist obsessed over a buried corpse that it then shows on a table, filed at did it with count 1. + /// Checks the planning case on the way. With keep, the pawns, the grave, the table and both rows stay for + /// phase 2. + /// + private static (Pawn p, LawCase c, MentalState_CorpseObsession state, Law plan, Law did) ShownCorpseObsession(bool keep) + { + Law plan = DetectionKit.Row("Break/CorpseObsession", LawStage.Planning); + Law did = DetectionKit.Row("Break/CorpseObsession", LawStage.DidIt); + Pawn p = DetectionKit.Colonist(); + Pawn dead = DetectionKit.Stranger(Fixtures.FriendlyFaction(), p.Position); + dead.Kill(null); + Corpse corpse = dead.Corpse; + T.NotNull(corpse, "fixture: the dead pawn's corpse"); + + var grave = (Building_Grave)ThingMaker.MakeThing(ThingDefOf.Grave); + grave.SetFaction(Faction.OfPlayer); + DetectionKit.Place(grave, DetectionKit.FreeCell(p.Position, ThingDefOf.Grave.size)); + corpse.DeSpawn(); + T.Check(grave.TryAcceptThing(corpse, false), "fixture: the grave refused the corpse"); + + T.Check(DetectionKit.Start(p, "CorpseObsession"), "the corpse obsession didn't start"); + var state = p.MentalState as MentalState_CorpseObsession; + T.Check(state != null && state.corpse == corpse, "the obsession chose another corpse: " + state?.corpse); + LawCase c = DetectionKit.OnlyCase(p, "the obsessed colonist"); + T.Equal(LawStage.Planning, c.stage, "stage at the start"); + T.Equal(plan.id, c.planningLawId, "planning row"); + T.Equal(CaseNotes.DugUp, c.notes, "notes at the start"); + + // A tick while the corpse is still buried, then what the haul job leaves behind: the corpse + // placed on a table and the flag set by its last toil (RimWorld/JobDriver_HaulCorpseToPublicPlace.cs:54-55, 90). + state.MentalStateTick(1); + T.Equal(0, c.count, "count before the corpse is shown"); + Thing table = ThingMaker.MakeThing(ThingDefOf.Table1x2c, ThingDefOf.WoodLog); + table.SetFaction(Faction.OfPlayer); + IntVec3 tableCell = DetectionKit.FreeCell(p.Position, ThingDefOf.Table1x2c.size); + DetectionKit.Place(table, tableCell); + T.Check(grave.GetDirectlyHeldThings().TryDrop(corpse, tableCell, Fixtures.Map, ThingPlaceMode.Direct, out Thing _), "fixture: the corpse didn't land on the table"); + T.Check(corpse.Spawned && DetectionHooks.OnTable(corpse), "fixture: the corpse lies at " + corpse.PositionHeld + ", not on the table"); + state.Notify_CorpseHauled(); + state.MentalStateTick(1); + + if (keep) + { + // Built outside a test (CarryAtSave): kept, so the first phase-2 test's cleanup leaves them. + Fixtures.Keep(p); + Fixtures.Keep(dead); + Fixtures.Keep(grave); + Fixtures.Keep(table); + Fixtures.KeepLaw(plan); + Fixtures.KeepLaw(did); + } + return (p, c, state, plan, did); + } + + private const string CorpseSaveKey = "detect.corpseSave"; + + [BlaxTest("detection J: an obsession that already showed its corpse runs at the first save (setup)")] + public static void CorpseObsessionSaveSetup() + { + // Built right before the save, after every phase-1 test, so no later test's ticks end the obsession. + T.CarryAtSave(CorpseSaveKey, CorpseObsessionForSave); + } + + private static string CorpseObsessionForSave() + { + var (p, c, state, _, _) = ShownCorpseObsession(keep: true); + T.Check(state.alreadyHauledCorpse, "fixture: the flag isn't set at the save"); + T.Equal(LawStage.DidIt, c.stage, "stage at the save"); + return string.Join("|", p.ThingID, c.id, c.count, DetectionKit.CasesOf(p).Count); + } + + [BlaxTest("detection J: after a reload with the corpse already shown, the obsession files no second did-it", phase: 2)] + public static void CorpseObsessionAfterReload() + { + T.Check(T.Carry.TryGetValue(CorpseSaveKey, out string carry) && !carry.NullOrEmpty(), "the phase-1 corpse obsession save setup did not run"); + string[] parts = carry.Split('|'); + T.Check(parts.Length == 4, "carry: " + carry); + Pawn p = Fixtures.FindPawnById(parts[0]); + T.NotNull(p, "the obsessed colonist after the reload"); + LawCase c = Fixtures.Comp.CaseById(int.Parse(parts[1])); + T.NotNull(c, "the obsession's case after the reload"); + T.Check(c.offender == p, "the case's offender didn't resolve"); + int count = int.Parse(parts[2]), cases = int.Parse(parts[3]); + T.Equal(count, c.count, "count right after the reload"); + MentalState_CorpseObsession state = p.MentalState as MentalState_CorpseObsession; + if (state == null) + T.Fail("the obsession is gone after the reload (" + (p.MentalStateDef?.defName ?? "no state") + ")"); + T.Check(state.alreadyHauledCorpse, "the reloaded obsession lost its displayed corpse"); + // The setup kept its did-it row; adding it again would be refused as a duplicate. + T.Check(Lawbook.Laws.Any(l => l.actKey == ActKey.Of(ActCategories.Break, "CorpseObsession") && l.stage == LawStage.DidIt && l.enabled), + "the kept did-it row is missing after the reload"); + DetectionKit.Row("Special/DisplayedCorpse", LawStage.DidIt); + for (int i = 0; i < 3; i++) + state.MentalStateTick(1); + T.Equal(count, c.count, "count of the phase-1 case after ticks of the reloaded obsession"); + T.Equal(cases, DetectionKit.CasesOf(p).Count, "cases of the obsessed colonist after the reload"); + } + + // ---- F, E: fights and interactions ---------------------------------------------------- + + [BlaxTest("detection F: StartSocialFight files on the recipient who swings first, not on the provoker")] + public static void SocialFight() + { + Law row = DetectionKit.Row("Special/StartedSocialFight", LawStage.DidIt); + Pawn provoker = DetectionKit.Colonist(); + Pawn fighter = DetectionKit.ColonistNear(provoker); + fighter.interactions.StartSocialFight(provoker); + T.Equal(MentalStateDefOf.SocialFighting, fighter.MentalStateDef, "fixture: the recipient's state"); + LawCase c = DetectionKit.OnlyCase(fighter, "the recipient"); + T.Equal(row.id, c.didItLawId, "did-it row"); + T.Check(c.victim == provoker, "the provoker isn't the victim"); + DetectionKit.NoCase(provoker, "the provoker"); + } + + [BlaxTest("detection E: an insult files on the initiator; a slight only under insult or slight; a second insult within a day counts, with the cooldown at 0 it files")] + public static void InsultsAndCooldown() + { + DetectionKit.QuietSocialFights(); + Law insult = DetectionKit.Row("Interaction/Insult", LawStage.DidIt); + Pawn a = DetectionKit.Colonist(); + Pawn b = DetectionKit.ColonistNear(a); + DetectionKit.Interact(a, b, InteractionDefOf.Insult); + LawCase first = DetectionKit.OnlyCase(a, "the insulter"); + T.Equal(insult.id, first.didItLawId, "did-it row of the insult"); + T.Check(first.victim == b, "the insulted pawn isn't the victim"); + DetectionKit.NoCase(b, "the insulted pawn"); + + InteractionDef slight = DefDatabase.GetNamed("Slight"); + DetectionKit.Interact(a, b, slight); + T.Equal(1, DetectionKit.CasesOf(a).Count, "cases after a slight under an Insult row"); + T.Equal(1, first.count, "the insult case counted a slight"); + Law group = DetectionKit.Row("Interaction/@insultOrSlight", LawStage.DidIt); + DetectionKit.Interact(a, b, slight); + T.Equal(2, DetectionKit.CasesOf(a).Count, "cases after a slight under insult or slight"); + T.Equal(group.id, DetectionKit.CasesOf(a).Last().didItLawId, "the slight's row"); + + DetectionKit.Interact(a, b, InteractionDefOf.Insult); + T.Equal(2, DetectionKit.CasesOf(a).Count, "cases after a second insult within the cooldown"); + T.Equal(2, first.count, "count of the insult case after the second insult"); + Fixtures.Settings.cooldownDays = 0; + DetectionKit.Interact(a, b, InteractionDefOf.Insult); + T.Equal(3, DetectionKit.CasesOf(a).Count, "cases after an insult with the cooldown at 0"); + T.Equal(insult.id, DetectionKit.CasesOf(a).Last().didItLawId, "the new insult case's row"); + } + + [BlaxTest("detection E: the cooldown counts from a closed case's open tick: acts at 0 h and 20 h give one case, a third at 30 h opens a second")] + public static void CooldownCountsFromOpenTick() + { + DetectionKit.QuietSocialFights(); + Fixtures.Settings.cooldownDays = 1; + Law insult = DetectionKit.Row("Interaction/Insult", LawStage.DidIt); + Pawn a = DetectionKit.Colonist(); + Pawn b = DetectionKit.ColonistNear(a); + DetectionKit.Interact(a, b, InteractionDefOf.Insult); + LawCase first = DetectionKit.OnlyCase(a, "the insulter"); + Fixtures.Tick(1); // the Warn runs and closes the case + T.Check(first.IsClosed, "fixture: the warned insult case is open: " + first); + // Backdating the case's ticks stands in for game hours without ticking. + int now = Find.TickManager.TicksGame; + first.openTick = now - 20 * GenDate.TicksPerHour; + first.lastActTick = first.openTick; + DetectionKit.Interact(a, b, InteractionDefOf.Insult); + T.Equal(1, DetectionKit.CasesOf(a).Count, "cases after a second insult 20 h after the first"); + T.Equal(2, first.count, "count after the second insult"); + + first.openTick = now - 30 * GenDate.TicksPerHour; + first.lastActTick = now - 10 * GenDate.TicksPerHour; + DetectionKit.Interact(a, b, InteractionDefOf.Insult); + T.Equal(2, DetectionKit.CasesOf(a).Count, "cases after a third insult 30 h after the first (10 h after the second)"); + T.Equal(insult.id, DetectionKit.CasesOf(a).Last().didItLawId, "the new insult case's row"); + T.Equal(2, first.count, "the first case did not count the third insult"); + } + + [BlaxTest("detection E: a case still open takes every repeat of its act whatever its age: no second case, no flood")] + public static void OpenCaseTakesRepeats() + { + DetectionKit.QuietSocialFights(); + Fixtures.Settings.cooldownDays = 1; + DetectionKit.Row("Interaction/Insult", LawStage.DidIt); + Pawn a = DetectionKit.Colonist(); + Pawn b = DetectionKit.ColonistNear(a); + DetectionKit.Interact(a, b, InteractionDefOf.Insult); + LawCase first = DetectionKit.OnlyCase(a, "the insulter"); + // Not ticked, so the case is still open, as a jail case waiting for "Arrest now" or a bed stays open. + T.Check(!first.IsClosed, "fixture: the insult case closed before a tick"); + int now = Find.TickManager.TicksGame; + first.openTick = now - 30 * GenDate.TicksPerHour; + first.lastActTick = first.openTick; + DetectionKit.Interact(a, b, InteractionDefOf.Insult); + T.Equal(1, DetectionKit.CasesOf(a).Count, "cases after a second insult 30 h after the first, the first still open"); + T.Equal(2, first.count, "count of the open case after the second insult"); + } + + [BlaxTest("detection E: a Chitchat row files a chitchat on the initiator")] + public static void Chitchat() + { + DetectionKit.QuietSocialFights(); + Law row = DetectionKit.Row("Interaction/Chitchat", LawStage.DidIt); + Pawn a = DetectionKit.Colonist(); + Pawn b = DetectionKit.ColonistNear(a); + DetectionKit.Interact(a, b, InteractionDefOf.Chitchat); + T.Equal(row.id, DetectionKit.OnlyCase(a, "the chatter").didItLawId, "did-it row"); + DetectionKit.NoCase(b, "the listener"); + } + + [BlaxTest("detection A, E: a jailbreaker break opens planning, its SparkJailbreak talk moves it to did it")] + public static void Jailbreaker() + { + DetectionKit.QuietSocialFights(); + Law plan = DetectionKit.Row("Break/Jailbreaker", LawStage.Planning); + Law did = DetectionKit.Row("Break/Jailbreaker", LawStage.DidIt); + Pawn j = DetectionKit.Colonist(); + Pawn prisoner = DetectionKit.Stranger(Fixtures.HostileFaction() ?? Fixtures.FriendlyFaction(), j.Position); + prisoner.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Prisoner); + T.Check(prisoner.IsPrisonerOfColony, "fixture: the prisoner"); + // A released prisoner isn't secure, so the talk starts no real prison break + // (RimWorld/InteractionWorker_SparkJailbreak.cs:11; RimWorld/Pawn_GuestTracker.cs:137-140). + prisoner.guest.Released = true; + T.Check(DetectionKit.Start(j, "Jailbreaker"), "the jailbreaker break didn't start"); + LawCase c = DetectionKit.OnlyCase(j, "the jailbreaker"); + T.Equal(plan.id, c.planningLawId, "planning row"); + DetectionKit.Interact(j, prisoner, InteractionDefOf.SparkJailbreak); + T.Equal(LawStage.DidIt, c.stage, "stage after the talk"); + T.Equal(1, c.count, "count after the talk"); + T.Equal(did.id, c.didItLawId, "did-it row"); + T.Check(c.victim == prisoner, "the prisoner isn't the victim"); + } + + // ---- C: eating --------------------------------------------------------------------- + + [BlaxTest("detection C: raw meat, a meal with meat, human meat and a meal with human meat each go to the smallest matching meat group; a vegetable meal to none")] + public static void MeatGroups() + { + Law any = DetectionKit.Row("Ate/@anyMeat", LawStage.DidIt); + Law raw = DetectionKit.Row("Ate/@rawMeatOrCorpse", LawStage.DidIt); + Law human = DetectionKit.Row("Ate/@humanMeat", LawStage.DidIt); + ThingDef cowMeat = ThingDefOf.Cow.race.meatDef; + + Pawn p1 = DetectionKit.Colonist(); + DetectionKit.Eat(p1, DetectionKit.ItemNear(p1, cowMeat, 10)); + T.Equal(raw.id, DetectionKit.OnlyCase(p1, "the raw meat eater").didItLawId, "row for raw cow meat"); + Pawn p2 = DetectionKit.Colonist(); + DetectionKit.Eat(p2, DetectionKit.MealNear(p2, cowMeat)); + T.Equal(any.id, DetectionKit.OnlyCase(p2, "the meat meal eater").didItLawId, "row for a simple meal with cow meat"); + Pawn p3 = DetectionKit.Colonist(); + DetectionKit.Eat(p3, DetectionKit.ItemNear(p3, ThingDefOf.Meat_Human, 10)); + T.Equal(human.id, DetectionKit.OnlyCase(p3, "the human meat eater").didItLawId, "row for raw human meat"); + Pawn p4 = DetectionKit.Colonist(); + DetectionKit.Eat(p4, DetectionKit.MealNear(p4, ThingDefOf.Meat_Human)); + T.Equal(human.id, DetectionKit.OnlyCase(p4, "the human meat meal eater").didItLawId, "row for a simple meal with human meat"); + Pawn p5 = DetectionKit.Colonist(); + DetectionKit.Eat(p5, DetectionKit.MealNear(p5, ThingDefOf.RawPotatoes)); + DetectionKit.NoCase(p5, "the potato meal eater"); + } + + [BlaxTest("detection C: a row on the simple meal catches the simple meal, not raw meat")] + public static void SimpleMealRow() + { + Law meal = DetectionKit.Row("Ate/MealSimple", LawStage.DidIt); + Pawn a = DetectionKit.Colonist(); + DetectionKit.Eat(a, DetectionKit.ItemNear(a, ThingDefOf.Cow.race.meatDef, 10)); + DetectionKit.NoCase(a, "the raw meat eater"); + Pawn b = DetectionKit.Colonist(); + DetectionKit.Eat(b, DetectionKit.ItemNear(b, ThingDefOf.MealSimple, 1)); + LawCase c = DetectionKit.OnlyCase(b, "the simple meal eater"); + T.Equal(meal.id, c.didItLawId, "did-it row"); + T.Equal("MealSimple", c.matchedDef, "matched def"); + } + + [BlaxTest("detection C: a drafted pawn or a player-forced eat job opens nothing while player orders are exempt; with the setting off the forced job files")] + public static void PlayerOrdersExempt() + { + DetectionKit.Row("Ate/MealSimple", LawStage.DidIt); + Pawn control = DetectionKit.Colonist(); + DetectionKit.Eat(control, DetectionKit.ItemNear(control, ThingDefOf.MealSimple, 1)); + DetectionKit.OnlyCase(control, "a colonist eating on its own"); + + Pawn drafted = DetectionKit.Colonist(); + drafted.drafter.Drafted = true; + T.Check(drafted.Drafted, "fixture: the colonist isn't drafted"); + DetectionKit.Eat(drafted, DetectionKit.ItemNear(drafted, ThingDefOf.MealSimple, 1)); + DetectionKit.NoCase(drafted, "a drafted colonist"); + + Pawn forced = DetectionKit.Colonist(); + DetectionKit.Eat(forced, DetectionKit.ItemNear(forced, ThingDefOf.MealSimple, 1), playerForced: true); + DetectionKit.NoCase(forced, "a colonist on a player-forced eat job"); + Fixtures.Settings.playerOrdersExempt = false; + DetectionKit.Eat(forced, DetectionKit.ItemNear(forced, ThingDefOf.MealSimple, 1), playerForced: true); + DetectionKit.OnlyCase(forced, "a colonist on a player-forced eat job with the setting off"); + } + + [BlaxTest("detection C, E: a quest lodger's meat meal and insult open nothing, and the same pawn files both once its quest is gone; a visitor's meat meal opens nothing")] + public static void QuestLodgerAndVisitor() + { + DetectionKit.QuietSocialFights(); + Law meat = DetectionKit.Row("Ate/@anyMeat", LawStage.DidIt); + Law insult = DetectionKit.Row("Interaction/Insult", LawStage.DidIt); + Faction home = Fixtures.FriendlyFaction() ?? Fixtures.HostileFaction(); + if (home == null) + { + T.Skip("no other humanlike faction to be the lodger's home"); + return; + } + ThingDef cowMeat = ThingDefOf.Cow.race.meatDef; + + Pawn lodger = DetectionKit.Colonist(); + Pawn b = DetectionKit.ColonistNear(lodger); + Quest quest = DetectionKit.MakeQuestLodger(lodger, home); + T.Check(lodger.IsQuestLodger(), "fixture: the pawn isn't a quest lodger"); + T.Check(lodger.IsFreeColonist, "fixture: the lodger isn't IsFreeColonist, so only the lodger check could be tested"); + T.Check(!Offenders.IsCovered(lodger), "a quest lodger is covered by the laws"); + DetectionKit.Eat(lodger, DetectionKit.MealNear(lodger, cowMeat)); + DetectionKit.NoCase(lodger, "the quest lodger after a meat meal"); + DetectionKit.Interact(lodger, b, InteractionDefOf.Insult); + DetectionKit.NoCase(lodger, "the quest lodger after an insult"); + + // Control: the same pawn without its quest is a plain colonist, so the lodger check alone blocked both acts. + Find.QuestManager.Remove(quest); + T.Check(!lodger.IsQuestLodger(), "fixture: still a quest lodger after its quest was removed"); + DetectionKit.Eat(lodger, DetectionKit.MealNear(lodger, cowMeat)); + T.Equal(meat.id, DetectionKit.OnlyCase(lodger, "the former lodger after a meat meal").didItLawId, "row of the meat meal"); + DetectionKit.Interact(lodger, b, InteractionDefOf.Insult); + T.Equal(2, DetectionKit.CasesOf(lodger).Count, "cases of the former lodger after an insult"); + T.Equal(insult.id, DetectionKit.CasesOf(lodger).Last().didItLawId, "row of the insult"); + + Pawn visitor = DetectionKit.Stranger(Fixtures.FriendlyFaction() ?? home, b.Position); + visitor.guest.SetGuestStatus(Faction.OfPlayer); + T.Check(visitor.HostFaction == Faction.OfPlayer && !visitor.IsPrisoner, "fixture: the visitor isn't a guest of the colony"); + T.Check(!Offenders.IsCovered(visitor), "a visitor is covered by the laws"); + DetectionKit.Eat(visitor, DetectionKit.MealNear(visitor, cowMeat)); + DetectionKit.NoCase(visitor, "the visitor after a meat meal"); + } + + [BlaxTest("detection C: a doctor administering a drug to a patient opens nothing for either pawn")] + public static void DoctorsDose() + { + DetectionKit.Row("Ate/@anyDrug", LawStage.DidIt); + Pawn doctor = DetectionKit.Colonist(); + Pawn patient = DetectionKit.ColonistNear(doctor); + Thing pill = DetectionKit.ItemNear(doctor, ThingDefOf.Penoxycyline, 3); + Job bill = JobMaker.MakeJob(JobDefOf.DoBill, patient, pill); + DetectionKit.WithOwnJob(doctor, bill, () => + new Recipe_AdministerIngestible().ApplyOnPawn(patient, null, doctor, new List { pill }, null)); + T.Check(pill.Destroyed || pill.stackCount < 3, "fixture: the patient took no dose"); + DetectionKit.NoCase(patient, "the patient"); + DetectionKit.NoCase(doctor, "the doctor"); + } + + [BlaxTest("detection C: a beer drunk while socially relaxing at a table files under 'Ate: beer'")] + public static void BeerAtGatheringSpot() + { + Law row = DetectionKit.Row("Ate/Beer", LawStage.DidIt); + Pawn p = DetectionKit.Colonist(); + Thing beer = DetectionKit.ItemNear(p, ThingDefOf.Beer, 1); + Thing table = ThingMaker.MakeThing(ThingDefOf.Table1x2c, ThingDefOf.WoodLog); + table.SetFaction(Faction.OfPlayer); + DetectionKit.Place(table, DetectionKit.FreeCell(p.Position, ThingDefOf.Table1x2c.size)); + // JobDriver_SocialRelax: A the gathering spot, B the seat, C the drink (RimWorld/JobDriver_SocialRelax.cs:10-14, 75). + Job relax = JobMaker.MakeJob(DefDatabase.GetNamed("SocialRelax"), table, p.Position, beer); + DetectionKit.WithOwnJob(p, relax, () => beer.Ingested(p, 0f)); + LawCase c = DetectionKit.OnlyCase(p, "the beer drinker"); + T.Equal(row.id, c.didItLawId, "did-it row"); + T.Equal("Beer", c.matchedDef, "matched def"); + } + + [BlaxTest("detection C: 60 colonists eating three meat meals each under 'any meat, warn' make 60 cases and queue 60 punishments")] + public static void SixtyMeatEaters() + { + Law row = DetectionKit.Row("Ate/@anyMeat", LawStage.DidIt); + ThingDef cowMeat = ThingDefOf.Cow.race.meatDef; + int queuedBefore = Enforcement.Pending; + var pawns = new List(); + for (int i = 0; i < 60; i++) + pawns.Add(DetectionKit.Colonist()); + var sw = Stopwatch.StartNew(); + foreach (Pawn p in pawns) + { + for (int meal = 0; meal < 3; meal++) + DetectionKit.Eat(p, DetectionKit.Meal(cowMeat)); + } + sw.Stop(); + T.Info("180 meals eaten in " + sw.ElapsedMilliseconds + " ms"); + foreach (Pawn p in pawns) + { + LawCase c = DetectionKit.OnlyCase(p, p.LabelShort); + T.Equal(row.id, c.didItLawId, "did-it row of " + p.LabelShort); + T.Equal(3, c.count, "meals counted on " + p.LabelShort + "'s case"); + } + T.Equal(60, Enforcement.Pending - queuedBefore, "punishments queued (one message each)"); + } + + // ---- U: used items ------------------------------------------------------------------- + + [BlaxTest("detection U: a colonist using a healer mech serum on its own job files; a doctor's serum files for neither pawn; a use CanBeUsedBy refuses files nothing")] + public static void UsedSerum() + { + ThingDef serumDef = DefDatabase.GetNamed("MechSerumHealer"); + Law row = DetectionKit.Row("Used/MechSerumHealer", LawStage.DidIt); + + Pawn user = DetectionKit.Colonist(); + DetectionKit.LoseHand(user); + Thing serum = DetectionKit.ItemNear(user, serumDef, 1); + CompUsable comp = serum.TryGetComp(); + T.Check(comp.CanBeUsedBy(user, false, true).Accepted, "fixture: the serum refuses a colonist missing a hand"); + DetectionKit.WithOwnJob(user, JobMaker.MakeJob(comp.Props.useJob, serum), () => comp.UsedBy(user)); + T.Equal(row.id, DetectionKit.OnlyCase(user, "the serum user").didItLawId, "did-it row"); + + Pawn doctor = DetectionKit.Colonist(); + Pawn patient = DetectionKit.ColonistNear(doctor); + DetectionKit.LoseHand(patient); + Thing serum2 = DetectionKit.ItemNear(doctor, serumDef, 1); + DetectionKit.WithOwnJob(doctor, JobMaker.MakeJob(JobDefOf.DoBill, patient, serum2), () => + new Recipe_AdministerUsableItem().ApplyOnPawn(patient, null, doctor, new List { serum2 }, null)); + T.Check(serum2.Destroyed, "fixture: the doctor's serum wasn't used"); + DetectionKit.NoCase(patient, "the patient"); + DetectionKit.NoCase(doctor, "the doctor"); + + Pawn healthy = DetectionKit.Colonist(); + healthy.health.RemoveAllHediffs(); + Thing serum3 = DetectionKit.ItemNear(healthy, serumDef, 1); + CompUsable comp3 = serum3.TryGetComp(); + T.Check(!comp3.CanBeUsedBy(healthy, false, true).Accepted, "fixture: the serum accepts a colonist with nothing to heal"); + DetectionKit.WithOwnJob(healthy, JobMaker.MakeJob(comp3.Props.useJob, serum3), () => comp3.UsedBy(healthy)); + DetectionKit.NoCase(healthy, "a colonist the serum refused"); + } + + // ---- R, H, B --------------------------------------------------------------------------- + + [BlaxTest("detection R: an increment files one case, a second the same day raises its count; AddTo files only when the record goes up")] + public static void Records() + { + Law stripped = DetectionKit.Row("Record/BodiesStripped", LawStage.DidIt); + Law eaten = DetectionKit.Row("Record/NutritionEaten", LawStage.DidIt); + Pawn p = DetectionKit.Colonist(); + p.records.Increment(RecordDefOf.BodiesStripped); + LawCase c = DetectionKit.OnlyCase(p, "the stripper"); + T.Equal(stripped.id, c.didItLawId, "did-it row"); + T.Equal(1, c.count, "count after one increment"); + p.records.Increment(RecordDefOf.BodiesStripped); + T.Equal(2, c.count, "count after the second increment"); + T.Equal(1, DetectionKit.CasesOf(p).Count, "cases after two increments"); + + Pawn q = DetectionKit.Colonist(); + q.records.AddTo(RecordDefOf.NutritionEaten, 0f); + DetectionKit.NoCase(q, "a record that didn't go up"); + q.records.AddTo(RecordDefOf.NutritionEaten, 0.9f); + T.Equal(eaten.id, DetectionKit.OnlyCase(q, "the eater by record").didItLawId, "did-it row of the Float record"); + } + + [BlaxTest("detection H: an ExecutedPrisoner event with a doer files on the doer; the same event without one files nothing")] + public static void RecordedAct() + { + Law row = DetectionKit.Row("RecordedAct/ExecutedPrisoner", LawStage.DidIt); + Pawn p = DetectionKit.Colonist(); + int before = Fixtures.Comp.Cases.Count; + // As vanilla records it, with the thought stage; the executioner may be null (RimWorld/ThoughtUtility.cs:52-56). + Find.HistoryEventsManager.RecordEvent(new HistoryEvent(HistoryEventDefOf.ExecutedPrisoner, ((Pawn)null).Named(HistoryEventArgsNames.Doer), + 0.Named(HistoryEventArgsNames.ExecutionThoughtStage))); + T.Equal(before, Fixtures.Comp.Cases.Count, "cases after the event without a doer"); + Find.HistoryEventsManager.RecordEvent(new HistoryEvent(HistoryEventDefOf.ExecutedPrisoner, p.Named(HistoryEventArgsNames.Doer), + 0.Named(HistoryEventArgsNames.ExecutionThoughtStage))); + T.Equal(row.id, DetectionKit.OnlyCase(p, "the executioner").didItLawId, "did-it row"); + } + + [BlaxTest("detection B: a finished simple meal bill files on the cook; a surgery files on the doctor with the patient as victim")] + public static void Bills() + { + Law cookRow = DetectionKit.Row("Bill/CookMealSimple", LawStage.DidIt); + Law surgeryRow = DetectionKit.Row("Bill/@anySurgery", LawStage.DidIt); + + Pawn cook = DetectionKit.Colonist(); + Job cooking = JobMaker.MakeJob(JobDefOf.DoBill, cook.Position); + cooking.bill = DefDatabase.GetNamed("CookMealSimple").MakeNewBill(); + DetectionKit.WithOwnJob(cook, cooking, () => RecordsUtility.Notify_BillDone(cook, new List { DetectionKit.Meal(null) })); + T.Equal(cookRow.id, DetectionKit.OnlyCase(cook, "the cook").didItLawId, "did-it row of the cook"); + + Pawn doctor = DetectionKit.Colonist(); + Pawn patient = DetectionKit.ColonistNear(doctor); + var surgery = new Bill_Medical(RecipeDefOf.RemoveBodyPart, null); + patient.health.surgeryBills.AddBill(surgery); + Job operating = JobMaker.MakeJob(JobDefOf.DoBill, patient); + operating.bill = surgery; + DetectionKit.WithOwnJob(doctor, operating, () => RecordsUtility.Notify_BillDone(doctor, new List())); + LawCase c = DetectionKit.OnlyCase(doctor, "the surgeon"); + T.Equal(surgeryRow.id, c.didItLawId, "did-it row of the surgeon"); + T.Check(c.victim == patient, "the patient isn't the victim"); + DetectionKit.NoCase(patient, "the patient"); + } + + [BlaxTest("detection B: a mech gestation bill files on the pawn who finishes it (needs Biotech)")] + public static void MechGestationBill() + { + T.NeedsDlc("Biotech", ModsConfig.BiotechActive); + RecipeDef gestation = DefDatabase.AllDefsListForReading.FirstOrDefault(r => r.gestationCycles > 0); + T.NotNull(gestation, "a mech gestation recipe"); + Law row = DetectionKit.Row(ActKey.Of(ActCategories.Bill, gestation.defName), LawStage.DidIt); + Pawn mechanitor = DetectionKit.Colonist(); + Job job = JobMaker.MakeJob(JobDefOf.DoBill, mechanitor.Position); + job.bill = gestation.MakeNewBill(); + DetectionKit.WithOwnJob(mechanitor, job, () => RecordsUtility.Notify_BillDone(mechanitor, new List())); + T.Equal(row.id, DetectionKit.OnlyCase(mechanitor, "the pawn finishing the gestation").didItLawId, "did-it row"); + } + + // ---- guards and cost ---------------------------------------------------------------- + + [BlaxTest("detection: a hook whose filing throws logs once and the interaction still happens")] + public static void ThrowingHookKeepsVanilla() + { + DetectionKit.QuietSocialFights(); + DetectionKit.Row("Interaction/Insult", LawStage.DidIt); + Pawn a = DetectionKit.Colonist(); + Pawn b = DetectionKit.ColonistNear(a); + LawsLog.ResetOnce(); + LawsTestHooks.ReportThrows = true; + T.ExpectErrors(Patch_Pawn_InteractionsTracker_TryInteractWith.Where + " failed", 1); + DetectionKit.Interact(a, b, InteractionDefOf.Insult); + T.Equal(InteractionDefOf.Insult, a.interactions.LastInteractionDef, "the insult vanilla recorded"); + DetectionKit.Interact(a, b, InteractionDefOf.Insult); + DetectionKit.NoCase(a, "the insulter while filing throws"); + } + + [BlaxTest("cost: with an empty book the hooks of TryInteractWith, Increment and RecordEvent allocate nothing and cost under 2% of 100000 calls (at least 3 ns a call allowed)")] + public static void EmptyBookCost() + { + T.Check(!Watch.Interaction && !Watch.Record && !Watch.RecordedAct, "a row kept by an earlier test watches interactions, records or recorded acts"); + DetectionKit.QuietSocialFights(); + const int N = 100000; + Pawn a = DetectionKit.Colonist(); + Pawn b = DetectionKit.ColonistNear(a); + Pawn_RecordsTracker records = a.records; + RecordDef rec = RecordDefOf.BodiesStripped; + HistoryEventsManager history = Find.HistoryEventsManager; + // An event no precept reacts to and without a doer: the cost is RecordEvent's own. + var ev = new HistoryEvent(DefDatabase.GetNamed("Traded")); + InteractionDef chat = InteractionDefOf.Chitchat; + + // The calls: the first interaction happens, the rest return early as too soon (Pawn_InteractionsTracker.cs:154-157). + long interact = DetectionKit.BestOf(() => { for (int i = 0; i < N; i++) a.interactions.TryInteractWith(b, chat); }); + long increment = DetectionKit.BestOf(() => { for (int i = 0; i < N; i++) records.Increment(rec); }); + long record = DetectionKit.BestOf(() => { for (int i = 0; i < N; i++) history.RecordEvent(ev, false); }); + // The hooks alone, as Harmony calls them after each of those calls. + long hookE = DetectionKit.BestOf(() => { for (int i = 0; i < N; i++) Patch_Pawn_InteractionsTracker_TryInteractWith.Postfix(a, b, chat, true); }); + long hookR = DetectionKit.BestOf(() => { for (int i = 0; i < N; i++) Patch_Pawn_RecordsTracker_Increment.Postfix(records, rec); }); + long hookH = DetectionKit.BestOf(() => { for (int i = 0; i < N; i++) Patch_HistoryEventsManager_RecordEvent.Postfix(ev); }); + + long allocated = GC.GetAllocatedBytesForCurrentThread(); + for (int i = 0; i < N; i++) + { + Patch_Pawn_InteractionsTracker_TryInteractWith.Postfix(a, b, chat, true); + Patch_Pawn_RecordsTracker_Increment.Postfix(records, rec); + Patch_HistoryEventsManager_RecordEvent.Postfix(ev); + } + allocated = GC.GetAllocatedBytesForCurrentThread() - allocated; + T.Equal(0L, allocated, "bytes the empty-book hooks allocated in " + N + " calls each"); + + double floor = 3e-9 * N * Stopwatch.Frequency; + void Within(string what, long hook, long method) + { + double limit = Math.Max(0.02 * method, floor); + T.Info(what + ": " + N + " calls " + DetectionKit.Ms(method) + " ms, hook " + DetectionKit.Ms(hook) + " ms, limit " + DetectionKit.Ms((long)limit) + " ms"); + T.Check(hook <= limit, what + ": the empty-book hook costs " + DetectionKit.Ms(hook) + " ms, over " + DetectionKit.Ms((long)limit) + " ms"); + } + Within("TryInteractWith", hookE, interact); + Within("Increment", hookR, increment); + Within("RecordEvent", hookH, record); + } + } + + /// Fixtures for the detection tests: rows, pawns, things on free cells, a pawn's own job. + internal static class DetectionKit + { + public static Law Row(string key, LawStage stage, string option = null, string punishment = "Warn", LawSeverity severity = LawSeverity.Minor, int days = 1) => + Fixtures.LawRow(key, option, stage, severity, punishment, days); + + public static List CasesOf(Pawn p) => Fixtures.Comp.CasesOf(p).ToList(); + + public static LawCase OnlyCase(Pawn p, string who) + { + List list = CasesOf(p); + T.Equal(1, list.Count, "cases of " + who); + return list[0]; + } + + public static void NoCase(Pawn p, string who) => T.Equal(0, CasesOf(p).Count, "cases of " + who); + + /// A spawned free colonist without addictions: a binge would pick the addiction's chemical (Verse.AI/MentalState_BingingDrug.cs:51-66). + public static Pawn Colonist() => Clean(Fixtures.Colonist()); + + /// A free colonist on a free cell next to the other pawn, close enough to talk. + public static Pawn ColonistNear(Pawn other) => Clean(Fixtures.Spawn(Fixtures.Generate(PawnKindDefOf.Colonist, Faction.OfPlayer), FreeCell(other.Position))); + + /// A pawn of another faction (or none) next to the position. + public static Pawn Stranger(Faction faction, IntVec3 near) => Fixtures.Spawn(Fixtures.Generate(PawnKindDefOf.Slave, faction), FreeCell(near)); + + /// + /// Makes the pawn a quest lodger: an ongoing quest names another faction as its home faction + /// (RimWorld/QuestUtility.cs:524-531, 706-720). acceptanceTick alone makes the quest Ongoing + /// (RimWorld/Quest.cs:154-183) without sending its Initiate signal. Returns the quest; the cleanup removes it. + /// + public static Quest MakeQuestLodger(Pawn p, Faction home) + { + Quest quest = Quest.MakeRaw(); + quest.acceptanceTick = Find.TickManager.TicksGame; + var part = new QuestPart_ExtraFaction { extraFaction = new ExtraFaction(home, ExtraFactionType.HomeFaction) }; + part.affectedPawns.Add(p); + quest.AddPart(part); + Find.QuestManager.Add(quest); + Fixtures.OnCleanup(() => + { + if (Find.QuestManager.Contains(quest)) + Find.QuestManager.Remove(quest); + }); + return quest; + } + + private static Pawn Clean(Pawn p) + { + foreach (Hediff h in p.health.hediffSet.hediffs.OfType().ToList()) + p.health.RemoveHediff(h); + return p; + } + + /// The nearest cell (or spot for a bigger thing) that is standable, in a district and holds nothing. + public static IntVec3 FreeCell(IntVec3 near, IntVec2 size = default) + { + Map map = Fixtures.Map; + IntVec2 s = size.x <= 0 || size.z <= 0 ? IntVec2.One : size; + foreach (IntVec3 c in GenRadial.RadialCellsAround(near, 15f, false)) + { + bool ok = true; + foreach (IntVec3 x in GenAdj.OccupiedRect(c, Rot4.North, s).Cells) + { + if (!x.InBounds(map) || !x.Standable(map) || x.Fogged(map) || x.GetDistrict(map) == null || x.GetFirstItem(map) != null || + x.GetFirstPawn(map) != null || x.GetEdifice(map) != null) + { + ok = false; + break; + } + } + if (ok) + return c; + } + T.Fail("no free " + s + " spot near " + near); + return IntVec3.Invalid; + } + + public static TT Place(TT thing, IntVec3 cell) where TT : Thing + { + Fixtures.Track(thing); + GenSpawn.Spawn(thing, cell, Fixtures.Map, Rot4.North); + return thing; + } + + public static Thing ItemNear(Pawn p, ThingDef def, int count) + { + Thing t = ThingMaker.MakeThing(def); + t.stackCount = count; + return Place(t, FreeCell(p.Position)); + } + + /// An unspawned simple meal with one ingredient (none for null). + public static Thing Meal(ThingDef ingredient) + { + Thing meal = Fixtures.Track(ThingMaker.MakeThing(ThingDefOf.MealSimple)); + if (ingredient != null) + meal.TryGetComp().RegisterIngredient(ingredient); + return meal; + } + + public static Thing MealNear(Pawn p, ThingDef ingredient) + { + Thing meal = ThingMaker.MakeThing(ThingDefOf.MealSimple); + meal.TryGetComp().RegisterIngredient(ingredient); + return Place(meal, FreeCell(p.Position)); + } + + public static Thing WoodWallNear(Pawn p) + { + Thing wall = ThingMaker.MakeThing(ThingDefOf.Wall, ThingDefOf.WoodLog); + wall.SetFaction(Faction.OfPlayer); + return Place(wall, FreeCell(p.Position)); + } + + /// + /// Runs the action while the job is the pawn's current job, as the vanilla toils would have it, and + /// puts the pawn's own job back. Hooks C and U read only the job's targets and playerForced. + /// + public static void WithOwnJob(Pawn p, Job job, Action act) + { + Job before = p.jobs.curJob; + p.jobs.curJob = job; + try + { + act(); + } + finally + { + if (p.jobs != null && p.jobs.curJob == job) + p.jobs.curJob = before; + } + } + + /// The pawn eats one portion of the food on its own Ingest job (RimWorld/Toils_Ingest.cs:402-428). + public static void Eat(Pawn p, Thing food, bool playerForced = false) + { + Job job = JobMaker.MakeJob(JobDefOf.Ingest, food); + job.count = 1; + job.playerForced = playerForced; + // A small want takes one unit (Verse/Thing.cs:2192-2202). + WithOwnJob(p, job, () => food.Ingested(p, 0.01f)); + } + + public static bool Start(Pawn p, string stateDefName) => + p.mindState.mentalStateHandler.TryStartMentalState(DefDatabase.GetNamed(stateDefName), forced: true, forceWake: true); + + /// Removes the drugs lying on the map, so a binge can only choose the test's drug (RimWorld/AddictionUtility.cs:120-139). + public static void ClearDrugsOnMap() + { + List drugs = Fixtures.Map.listerThings.ThingsInGroup(ThingRequestGroup.Drug).ToList(); + if (drugs.Count > 0) + T.Info("removed " + drugs.Count + " drug stack(s) lying on the map"); + foreach (Thing t in drugs) + { + if (!t.Destroyed) + t.Destroy(); + } + } + + /// + /// The drug gives no overdose during the test. Each wake-up dose adds 0.18 to 0.35 overdose, or with a + /// chance of 0.005 jumps it to 0.85 to 0.99 (RimWorld/CompDrug.cs:62-93; Defs/Drugs/WakeUp.xml). From + /// 0.5 the overdose caps Consciousness at 0.5, from 0.75 at 0.1 (Defs/HediffDefs/Hediffs_Global_Misc.xml), + /// which can down the pawn inside the dose and end its binge, so that dose would rightly file nothing. + /// + public static void NoOverdose(ThingDef drug) + { + CompProperties_Drug props = drug.GetCompProperties(); + T.NotNull(props, "fixture: " + drug.defName + " is no drug"); + float chance = props.largeOverdoseChance; + FloatRange offset = props.overdoseSeverityOffset; + props.largeOverdoseChance = 0f; + props.overdoseSeverityOffset = FloatRange.Zero; + Fixtures.OnCleanup(() => + { + props.largeOverdoseChance = chance; + props.overdoseSeverityOffset = offset; + }); + } + + /// No social fight starts from an interaction during the test (Pawn_InteractionsTracker.cs:357-360). + public static void QuietSocialFights() + { + bool was = DebugSettings.enableRandomMentalStates; + DebugSettings.enableRandomMentalStates = false; + Fixtures.OnCleanup(() => DebugSettings.enableRandomMentalStates = was); + } + + /// The initiator talks to the recipient now, however recently it talked (the 120-tick minimum, :154-157). + public static void Interact(Pawn initiator, Pawn recipient, InteractionDef def) + { + AccessTools.Field(typeof(Pawn_InteractionsTracker), "lastInteractionTime").SetValue(initiator.interactions, -9999); + T.Check(initiator.interactions.TryInteractWith(recipient, def), "fixture: " + initiator.LabelShort + " couldn't " + def.defName + " " + recipient.LabelShort); + } + + /// Casts the pawn's native ignite verb on the target at once, skipping the warmup (Verse/Verb.cs:324-368, 375-380). + public static void Ignite(Pawn p, Thing target) + { + Verb_Ignite verb = p.natives.IgniteVerb; + T.NotNull(verb, "ignite verb of " + p.LabelShort); + T.Check(verb.TryStartCastOn(target), "fixture: " + p.LabelShort + "'s ignite verb refused " + target); + verb.WarmupComplete(); + p.stances.CancelBusyStanceHard(); + } + + /// Fires the test started are put out after it. + public static void PutOutFiresAfter() => Fixtures.OnCleanup(() => + { + foreach (Thing f in Fixtures.Map.listerThings.ThingsOfDef(ThingDefOf.Fire).ToList()) + { + if (!f.Destroyed) + f.Destroy(); + } + }); + + /// A missing hand: the healer mech serum's condition to fix (Verse/HealthUtility.cs:620-625). + public static void LoseHand(Pawn p) + { + BodyPartRecord hand = p.health.hediffSet.GetNotMissingParts().FirstOrDefault(x => x.def == BodyPartDefOf.Hand); + T.NotNull(hand, "fixture: a hand of " + p.LabelShort); + p.health.AddHediff(HediffMaker.MakeHediff(HediffDefOf.MissingBodyPart, p, hand), hand); + } + + /// The faster of two runs after a warm-up run, in Stopwatch ticks. + public static long BestOf(Action run) + { + // Warm up for a while first: the runtime compiles a method unoptimized at first and swaps in the + // optimized code in the background after a delay of about 100 ms (tiered compilation), so a few + // quick runs measure the first compile, not the hook. + var warm = Stopwatch.StartNew(); + do + run(); + while (warm.ElapsedMilliseconds < 400); + long best = long.MaxValue; + for (int r = 0; r < 3; r++) + { + var sw = Stopwatch.StartNew(); + run(); + sw.Stop(); + best = Math.Min(best, sw.ElapsedTicks); + } + return best; + } + + public static string Ms(long ticks) => (ticks * 1000.0 / Stopwatch.Frequency).ToString("0.000"); + } +} diff --git a/Tests/BlaxLawsTests/Source/EnforcementTests.cs b/Tests/BlaxLawsTests/Source/EnforcementTests.cs new file mode 100644 index 0000000..71ba9b4 --- /dev/null +++ b/Tests/BlaxLawsTests/Source/EnforcementTests.cs @@ -0,0 +1,1567 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using BlaxLaws; +using RimWorld; +using RimWorld.Planet; +using Verse; +using Verse.AI; + +namespace BlaxLawsTests +{ + /// A walled 5x5 prison cell with a door and one prisoner bed (EnforceFixtures.PrisonCell). + public sealed class PrisonRoom + { + public Building_Bed bed; + + /// A free cell inside the room, beside the bed. + public IntVec3 inside; + + public readonly List things = new List(); + } + + /// + /// Fixtures of the enforcement and jail tests. Pawns and things go through Fixtures, so the runner removes + /// them after each test unless kept. Rows use act keys no catalogue knows ("Ate/BlaxLawsTest_Enforce3"), + /// so no detection hook ever files a second case for them; cases are opened with CaseFiler.Open and + /// queued with Enforcement.Enqueue, the way CaseFiler.Report does it. + /// + public static class EnforceFixtures + { + public const int SubdueTicks = 2500; + + /// A tantrum or a rage walks from target to target, so the warden lands about half its hits (about 1300 ticks to down one, against about 1000 for a binge). + public const int MovingSubdueTicks = 2 * SubdueTicks; + + /// A pawn with both arms bionic offers only the torso, legs and feet to the subdue, so it takes far more hits to down. + public const int BionicSubdueTicks = 3 * SubdueTicks; + + /// Cells per second a warden fixture walks at least; a healthy adult walks 4.6. + public const float MinWardenSpeed = 4f; + + private static int keyCounter; + + public static Map Map => Find.CurrentMap; + + public static int Now => Find.TickManager.TicksGame; + + /// The social drug binge: Core, the recovery thought is Catharsis (MentalStates_Mood.xml:276). + public static MentalStateDef DrugBinge => DefDatabase.GetNamed("Binging_DrugMajor"); + + public static HediffDef Bruise => DefDatabase.GetNamed("Bruise"); + + // ---- pawns ----------------------------------------------------------------------- + + /// Rested, fed and on "anything" every hour, so it neither sleeps nor eats during a test. + public static Pawn Ready(Pawn p) + { + if (p.needs?.rest != null) + p.needs.rest.CurLevel = 1f; + if (p.needs?.food != null) + p.needs.food.CurLevel = p.needs.food.MaxLevel; + if (p.needs?.joy != null) + p.needs.joy.CurLevel = 1f; + if (p.timetable != null) + { + for (int h = 0; h < GenDate.HoursPerDay; h++) + p.timetable.SetAssignment(h, TimeAssignmentDefOf.Anything); + } + return p; + } + + /// + /// A spawned free adult colonist with normal pain, ready. The subdue tests count on a normal adult going + /// down at about 64 points of bruises (design: "Subdue"); a colonist with halved pain (Biotech's reduced + /// pain gene) needs twice the hits, more than SubdueTicks allows. + /// + public static Pawn Offender(IntVec3? at = null) + { + for (int i = 0; i < 40; i++) + { + Pawn p = Fixtures.Generate(PawnKindDefOf.Colonist, Faction.OfPlayer); + // An addict is generated with its drug in its pocket (PawnInventoryGenerator.cs:51, 82-110) and a binger + // doses what it carries: a go-juice dose cuts pain to a tenth and the subdue gives up. + if (p.health.hediffSet.hediffs.Any(h => h is Hediff_Addiction || h is Hediff_High)) + continue; + if (Math.Abs(PainFactor(p) - 1f) < 0.001f) + { + foreach (Thing t in p.inventory.innerContainer.Where(t => t.def.IsDrug).ToList()) + p.inventory.innerContainer.Remove(t); + return Ready(Fixtures.Spawn(p, at)); + } + } + T.Fail("no generated colonist had normal pain"); + return null; + } + + /// Every pain factor of the pawn's hediffs, genes and traits multiplied (HediffSet.cs:1351-1365): 1 for most colonists. + public static float PainFactor(Pawn p) + { + float f = 1f; + foreach (Hediff h in p.health.hediffSet.hediffs) + f *= h.PainFactor; + if (p.genes != null) + f *= p.genes.PainFactor; + if (p.story?.traits != null) + { + foreach (Trait t in p.story.traits.allTraits) + f *= t.CurrentData.painFactor; + } + return f; + } + + /// + /// A spawned colonist with Warden work at priority 1 who can do violence and carry people, and walks at a + /// normal pace: a generated colonist with an old leg wound or a bad back can walk at half speed, which + /// doubles every chase. + /// + public static Pawn Warden(IntVec3? at = null) + { + for (int i = 0; i < 40; i++) + { + Pawn p = Fixtures.Generate(PawnKindDefOf.Colonist, Faction.OfPlayer); + if (p.WorkTypeIsDisabled(WorkTypeDefOf.Warden) || p.WorkTagIsDisabled(WorkTags.Violent) || p.GetStatValue(StatDefOf.MoveSpeed) < MinWardenSpeed) + continue; + Fixtures.Spawn(p, at); + p.workSettings?.EnableAndInitializeIfNotAlreadyInitialized(); + p.workSettings?.SetPriority(WorkTypeDefOf.Warden, 1); + T.Check(Enforcers.IsWarden(p), "warden fixture has no active Warden work"); + return Ready(p); + } + T.Fail("no generated colonist could do Warden work and violence at a normal walking pace"); + return null; + } + + /// + /// Only these wardens enforce during the test: "Wardens only", and Warden work off for every other free + /// colonist on the map (the quick test's starting colonists), put back after the test. + /// + public static void OnlyWardens(params Pawn[] wardens) + { + Fixtures.Settings.enforcers = EnforcerMode.WardensOnly; + var old = new List<(Pawn pawn, int priority)>(); + foreach (Pawn p in Map.mapPawns.FreeColonistsSpawned) + { + if (wardens.Contains(p) || !Enforcers.IsWarden(p)) + continue; + old.Add((p, p.workSettings.GetPriority(WorkTypeDefOf.Warden))); + p.workSettings.SetPriority(WorkTypeDefOf.Warden, 0); + } + Fixtures.OnCleanup(() => + { + foreach (var (pawn, priority) in old) + { + if (!pawn.Destroyed && pawn.workSettings != null) + pawn.workSettings.SetPriority(WorkTypeDefOf.Warden, priority); + } + }); + } + + /// A standable cell in the root's district, between the distances, with nobody on it. + public static IntVec3 CellNear(IntVec3 root, float minDist, float maxDist) + { + Map map = Map; + District district = root.GetDistrict(map); + if (CellFinder.TryFindRandomCellNear(root, map, (int)maxDist + 1, c => + c.Standable(map) && !c.Fogged(map) && c.GetDistrict(map) == district && c.GetFirstPawn(map) == null && + c.InHorDistOf(root, maxDist) && !c.InHorDistOf(root, minDist), out IntVec3 cell)) + return cell; + T.Fail("no free cell " + minDist + " to " + maxDist + " cells from " + root); + return IntVec3.Invalid; + } + + /// A hostile pawn far from the colony, unarmed so it can't shoot in the few ticks a test keeps it. + public static Pawn Raider() + { + Faction f = Fixtures.HostileFaction(); + if (f == null) + T.Skip("this world has no hostile humanlike faction"); + Map map = Map; + IntVec3 anchor = Fixtures.PawnCell(); + District district = anchor.GetDistrict(map); + if (!CellFinder.TryFindRandomCellNear(anchor, map, 80, c => c.Standable(map) && !c.Fogged(map) && c.GetDistrict(map) == district && + c.GetFirstPawn(map) == null && !c.InHorDistOf(anchor, 45f), out IntVec3 cell)) + T.Fail("no cell 45 or more cells from the colony for a raider"); + Pawn p = Fixtures.Generate(f.def.basicMemberKind ?? PawnKindDefOf.Villager, f); + p.equipment?.DestroyAllEquipment(); + Fixtures.Spawn(p, cell); + T.Check(GenHostility.AnyHostileActiveThreatToPlayer(map), "the raider fixture is no active threat"); + return p; + } + + // ---- breaks, rows and cases ----------------------------------------------------- + + public static void ForceBreak(Pawn p, MentalStateDef def, bool causedByMood = true, Pawn otherPawn = null) + { + bool started = p.mindState.mentalStateHandler.TryStartMentalState(def, null, forced: true, forceWake: true, causedByMood: causedByMood, otherPawn: otherPawn); + T.Check(started && p.MentalStateDef == def, "could not start " + def.defName + " on " + p.LabelShort); + } + + /// A row on an act key no catalogue knows, so only CaseFiler.Open files cases for it. + public static Law Row(string category, string punishment, LawStage stage, int days, LawSeverity severity = LawSeverity.Serious) => + Fixtures.LawRow(category + "/BlaxLawsTest_Enforce" + (++keyCounter), null, stage, severity, punishment, days); + + /// A did-it case outside a break under a new row. + public static LawCase ActCase(Pawn offender, string punishment, int days) + { + Law law = Row(ActCategories.Ate, punishment, LawStage.DidIt, days); + LawCase c = CaseFiler.Open(law, new ActEvent(ActCategories.Ate, ThingDefOf.MealSimple, offender), LawStage.DidIt); + T.NotNull(c, "CaseFiler.Open"); + return c; + } + + /// A case for the break the offender is in, at the stage, under a new row. + public static LawCase BreakCase(Pawn offender, string punishment, LawStage stage, int days) + { + T.Check(offender.InMentalState, offender.LabelShort + " is in no break"); + Law law = Row(ActCategories.Break, punishment, stage, days); + var act = new ActEvent(ActCategories.Break, offender.MentalStateDef, offender) { mentalState = offender.MentalState }; + LawCase c = CaseFiler.Open(law, act, stage); + T.NotNull(c, "CaseFiler.Open"); + c.breakState = offender.MentalStateDef.defName; + c.breakStartTick = CaseFiler.BreakStartTick(offender.MentalState); + T.Check(CaseFiler.StillInBreak(c), "the break case doesn't recognise its own break"); + return c; + } + + /// Queues the stage's punishment and runs the one tick that dispatches it. + public static void Dispatch(LawCase c, LawStage stage) + { + Enforcement.Enqueue(c, stage); + Fixtures.Tick(1); + } + + /// Ticks one at a time until done is true, at most maxTicks. Returns done. + public static bool RunUntil(Func done, int maxTicks) + { + for (int i = 0; i < maxTicks; i++) + { + if (done()) + return true; + Find.TickManager.DoSingleTick(); + } + return done(); + } + + /// Ticks through the next 2500-tick sentence sweep. + public static void TickPastSentenceSweep() + { + int ticks = Enforcement.SentenceInterval - Now % Enforcement.SentenceInterval + 1; + Fixtures.Tick(ticks); + } + + // ---- things ---------------------------------------------------------------------- + + /// + /// A walled 5x5 room with a door and one prisoner bed, on clear ground near the map center. A closed + /// door keeps the room's district off the map edge, so a prisoner inside never tries to escape + /// (JobGiver_PrisonerEscape.cs:28-58). + /// + public static PrisonRoom PrisonCell(bool keep = false) + { + Map map = Map; + const int size = 5; + IntVec3 anchor = Fixtures.PawnCell(); + District district = anchor.GetDistrict(map); + bool Clear(IntVec3 c) => c.InBounds(map) && c.Standable(map) && !c.Fogged(map) && c.GetEdifice(map) == null && + c.GetFirstItem(map) == null && c.GetFirstPawn(map) == null && c.GetDistrict(map) == district && + !c.GetTerrain(map).IsWater; + bool Square(IntVec3 o, Func ok) + { + for (int x = -1; x <= size; x++) + { + for (int z = -1; z <= size; z++) + { + if (!ok(o + new IntVec3(x, 0, z))) + return false; + } + } + return true; + } + // Clear ground first; else a square a player would clear of plants and loose items first (a wild map + // such as a dense jungle has few 7x7 squares without a tree or a starting item). + bool Buildable(IntVec3 c) => Fixtures.Buildable(c, map, district) && c.GetFirstPawn(map) == null; + if (!CellFinder.TryFindRandomCellNear(anchor, map, 50, o => Square(o, Clear), out IntVec3 origin)) + { + if (!CellFinder.TryFindRandomCellNear(anchor, map, 50, o => Square(o, Buildable), out origin)) + T.Fail("no clear 7x7 square near the colony for a prison cell; " + GroundStory(anchor, 50, Buildable)); + Fixtures.ClearGround(CellRect.FromLimits(origin.x - 1, origin.z - 1, origin.x + size, origin.z + size).Cells, map); + } + + var room = new PrisonRoom(); + IntVec3 doorCell = origin + new IntVec3(0, 0, 2); + for (int x = 0; x < size; x++) + { + for (int z = 0; z < size; z++) + { + if (x != 0 && x != size - 1 && z != 0 && z != size - 1) + continue; + IntVec3 cell = origin + new IntVec3(x, 0, z); + Thing t = ThingMaker.MakeThing(cell == doorCell ? ThingDefOf.Door : ThingDefOf.Wall, ThingDefOf.WoodLog); + t.SetFaction(Faction.OfPlayer); + GenSpawn.Spawn(t, cell, map); + room.things.Add(t); + } + } + map.regionAndRoomUpdater.TryRebuildDirtyRegionsAndRooms(); + var bed = (Building_Bed)ThingMaker.MakeThing(ThingDefOf.Bed, ThingDefOf.WoodLog); + bed.SetFaction(Faction.OfPlayer); + GenSpawn.Spawn(bed, origin + new IntVec3(2, 0, 2), map, Rot4.North); + bed.ForPrisoners = true; + room.things.Add(bed); + room.bed = bed; + room.inside = origin + new IntVec3(1, 0, 1); + map.regionAndRoomUpdater.TryRebuildDirtyRegionsAndRooms(); + // The ForPrisoners setter only marks the room's stats dirty (Building_Bed.cs:72, Room.cs:673-676); + // a room becomes a prison cell in Notify_RoomShapeChanged (Room.cs:686-728), which the bed gizmo + // calls after it changes the owner type (Building_Bed.cs:466-473). + bed.GetDistrict()?.Notify_RoomShapeOrContainedBedsChanged(); + bed.GetRoom()?.Notify_RoomShapeChanged(); + foreach (Thing t in room.things) + { + if (keep) + Fixtures.Keep(t); + else + Fixtures.Track(t); + } + T.Check(bed.GetRoom()?.IsPrisonCell == true, "the prison cell fixture is no prison cell"); + return room; + } + + /// Why the cells around the anchor refuse a fixture building: counts by the first reason, for a failure message. + public static string GroundStory(IntVec3 anchor, int radius, Func ok) + { + Map map = Map; + District district = anchor.GetDistrict(map); + int all = 0, good = 0, fogged = 0, otherDistrict = 0, water = 0, edifice = 0, pawn = 0, other = 0; + var blockers = new Dictionary(); + void Count(string key) => blockers[key] = (blockers.TryGetValue(key, out int n) ? n : 0) + 1; + foreach (IntVec3 c in GenRadial.RadialCellsAround(anchor, radius, true)) + { + if (!c.InBounds(map)) + continue; + all++; + if (ok(c)) good++; + else if (c.Fogged(map)) fogged++; + else if (c.GetDistrict(map) != district) otherDistrict++; + else if (c.GetTerrain(map).IsWater || c.GetTerrain(map).passability != Traversability.Standable) water++; + else if (c.GetEdifice(map) is Building b) + { + edifice++; + Count(b.def.defName); + } + else if (c.GetFirstPawn(map) != null) pawn++; + else + { + other++; + foreach (Thing t in c.GetThingList(map)) + Count(t.def.defName); + } + } + return "anchor " + anchor + " in a district of " + (district?.CellCount ?? 0) + " cells (map edge " + (district?.TouchesMapEdge ?? false) + + "); of " + all + " cells " + good + " fit, fogged " + fogged + ", other district " + otherDistrict + ", water or impassable " + water + + ", building " + edifice + ", pawn " + pawn + ", other " + other + "; blockers " + + string.Join(", ", blockers.OrderByDescending(kv => kv.Value).Take(8).Select(kv => kv.Key + " " + kv.Value)); + } + + /// A colonist bed (or a medical one) near the cell. + public static Building_Bed ColonistBed(IntVec3 near, bool medical = false) + { + Map map = Map; + District district = near.GetDistrict(map); + // Every cell the bed covers is free ground in the same district, so it never stands in a wall or on a pawn. + bool Fits(IntVec3 c) => c.InHorDistOf(near, 10f) && !c.InHorDistOf(near, 2f) && + GenAdj.OccupiedRect(c, Rot4.North, ThingDefOf.Bed.size).Cells.All(x => + x.InBounds(map) && x.Standable(map) && !x.Fogged(map) && x.GetEdifice(map) == null && + x.GetFirstItem(map) == null && x.GetFirstPawn(map) == null && x.GetDistrict(map) == district); + if (!CellFinder.TryFindRandomCellNear(near, map, 11, Fits, out IntVec3 cell)) + { + // A wild map: a spot a player would clear of plants and loose items first. + bool Buildable(IntVec3 c) => c.InHorDistOf(near, 10f) && !c.InHorDistOf(near, 2f) && + GenAdj.OccupiedRect(c, Rot4.North, ThingDefOf.Bed.size).Cells.All(x => + Fixtures.Buildable(x, map, district) && x.GetFirstPawn(map) == null); + if (!CellFinder.TryFindRandomCellNear(near, map, 11, Buildable, out cell)) + T.Fail("no free spot for a bed 2 to 10 cells from " + near + "; " + GroundStory(near, 10, c => Fixtures.Buildable(c, map, district))); + Fixtures.ClearGround(GenAdj.OccupiedRect(cell, Rot4.North, ThingDefOf.Bed.size).Cells, map); + } + var bed = (Building_Bed)ThingMaker.MakeThing(ThingDefOf.Bed, ThingDefOf.WoodLog); + bed.SetFaction(Faction.OfPlayer); + GenSpawn.Spawn(bed, cell, Map, Rot4.North); + if (medical) + bed.Medical = true; + Fixtures.Track(bed); + return bed; + } + + /// + /// A bed of its own for every other free colonist on the map that has none (the quick test's starting + /// colonists sleep on the ground), so none of them claims a bed the test frees: a pawn going to sleep + /// takes its own bed first and an unowned one only without it (RestUtility.cs:294-324). The beds go + /// after the test, and with them the ownership. + /// + public static void BedsForBystanders(params Pawn[] except) + { + foreach (Pawn p in Map.mapPawns.FreeColonistsSpawned.ToList()) + { + if (except.Contains(p) || p.ownership == null || p.ownership.OwnedBed != null) + continue; + Building_Bed bed = ColonistBed(p.Position); + T.Check(p.ownership.ClaimBedIfNonMedical(bed), "fixture: " + p.LabelShort + " can't claim a bed of its own"); + } + } + + // ---- reads ----------------------------------------------------------------------- + + /// Some pawn on the map runs or has queued a subdue, arrest or capture of the offender. + public static bool AnyEnforcementJobOn(Pawn offender) + { + foreach (Pawn p in Map.mapPawns.AllPawnsSpawned) + { + if (EnforcerJobs.IsEnforcementJob(p.CurJob, offender)) + return true; + JobQueue q = p.jobs?.jobQueue; + for (int i = 0; q != null && i < q.Count; i++) + { + if (EnforcerJobs.IsEnforcementJob(q[i]?.job, offender)) + return true; + } + } + return false; + } + + /// The pawns on the map whose current job is a subdue, arrest or capture of the offender. + public static IEnumerable EnforcersOn(Pawn offender) => + Map.mapPawns.AllPawnsSpawned.Where(p => EnforcerJobs.IsEnforcementJob(p.CurJob, offender)); + + public static HashSet Injuries(Pawn p) => new HashSet(p.health.hediffSet.hediffs.OfType()); + + /// + /// The part's HP: its maximum minus its injuries, as HediffSet.GetPartHealth counts it (HediffSet.cs:581-605) but + /// not rounded, since the rounding would hide up to half a point below the subdue's cap. + /// + public static float PartHealth(Pawn p, BodyPartRecord part) + { + float hp = part.def.GetMaxHealth(p); + foreach (Hediff_Injury h in p.health.hediffSet.hediffs.OfType().Where(h => h.Part == part)) + hp = h.destroysBodyParts ? hp - h.Severity : Math.Max(hp - h.Severity, 1f); + return hp; + } + + /// Why an enforcer is or isn't sent: its job, lord and the checks Enforcers.Pick makes, for a failure message. + public static string EnforcerStory(Pawn p, LawCase c) + { + if (p == null) + return "no pawn"; + Pawn o = c?.offender; + return p.LabelShort + ": job " + (p.CurJobDef?.defName ?? "none") + (p.CurJob?.playerForced == true ? " (forced)" : "") + + ", queue " + (p.jobs?.jobQueue?.Count ?? 0) + ", lord " + (Verse.AI.Group.LordUtility.GetLord(p)?.LordJob?.GetType().Name ?? "none") + + ", drafted " + p.Drafted + ", awake " + p.Awake() + ", mental " + (p.MentalStateDef?.defName ?? "none") + + ", warden " + Enforcers.IsWarden(p) + ", able " + (o != null && Enforcers.IsAble(p, o, EnforcerNeed.SubdueAndArrest, Fixtures.Settings.enforcers == EnforcerMode.WardensOnly)) + + ", free " + Enforcers.IsFree(p, c) + ", reach " + (o != null && o.Spawned && p.Spawned && p.CanReach(o, PathEndMode.Touch, Danger.Deadly)) + + ", danger " + (o != null && Enforcers.DangerBlocks(o)) + ", enforcer " + (c?.enforcer?.LabelShort ?? "none"); + } + + /// Where a subdue stands, for a message: the case, the hits so far, the pain, and what both pawns do. + public static string SubdueStory(LawCase c, Pawn offender, HashSet before) + { + List fresh = NewInjuries(offender, before); + Pawn e = c.enforcer; + return "case " + c + ", wait " + c.waitReason + "; " + fresh.Count + " hits (" + fresh.Sum(h => h.Severity).ToString("0") + " points), pain " + + offender.health.hediffSet.PainTotal.ToString("0.00") + " of " + offender.GetStatValue(StatDefOf.PainShockThreshold).ToString("0.00") + + ", room left " + SubdueHits.RoomToLive(offender).ToString("0") + ", drugs " + + (offender.health.hediffSet.hediffs.Any(h => h is Hediff_High) ? string.Join(" ", offender.health.hediffSet.hediffs.Where(h => h is Hediff_High).Select(h => h.def.defName)) : "none") + + "; the offender " + (offender.CurJobDef?.defName ?? "idle") + + (e == null ? ", no enforcer" : "; the enforcer " + e.LabelShort + " " + (e.CurJobDef?.defName ?? "idle") + ", " + + e.Position.DistanceTo(offender.Position).ToString("0") + " cells off, speed " + e.GetStatValue(StatDefOf.MoveSpeed).ToString("0.0")); + } + + /// An injury for a message: def, part, severity and what made it. + public static string Describe(Hediff_Injury h) => + h.def.defName + " on " + (h.Part?.Label ?? "the whole body") + " " + h.Severity.ToString("0.###") + " from " + + (h.sourceLabel.NullOrEmpty() ? "?" : h.sourceLabel) + (h.sourceToolLabel.NullOrEmpty() ? "" : " (" + h.sourceToolLabel + ")") + + (h.IsPermanent() ? ", permanent" : ""); + + public static List NewInjuries(Pawn p, HashSet before) => + p.health.hediffSet.hediffs.OfType().Where(h => !before.Contains(h)).ToList(); + + /// Live letters with exactly this label. + public static int LettersLabeled(string label) => + Find.LetterStack.LettersListForReading.Count(l => l.Label.ToString() == label); + + /// Archived messages containing the text (messages start with a capital letter). + public static int MessagesWith(string text) => + Find.Archive.ArchivablesListForReading.OfType().Count(m => m.text != null && m.text.IndexOf(text, StringComparison.OrdinalIgnoreCase) >= 0); + + public static Dictionary Priorities(Pawn p) => + DefDatabase.AllDefsListForReading.ToDictionary(w => w, w => p.workSettings.GetPriority(w)); + + public static string PriorityDiff(Dictionary before, Pawn p) + { + var diff = before.Where(kv => p.workSettings.GetPriority(kv.Key) != kv.Value) + .Select(kv => kv.Key.defName + " " + kv.Value + " to " + p.workSettings.GetPriority(kv.Key)).ToList(); + return diff.Count == 0 ? null : string.Join(", ", diff); + } + + /// Runs the body while the pawn's current job reads as the given one, for the enforcer filter. No tick passes. + public static void WithCurJob(Pawn p, Job job, Action body) + { + Job old = p.jobs.curJob; + p.jobs.curJob = job; + try + { + body(); + } + finally + { + p.jobs.curJob = old; + } + } + + /// + /// A jail case whose enforcer has just made the capture: the case set up as an Arrest leaves it, then + /// the vanilla CapturedBy, so hook K starts the sentence. No tick passes. + /// + public static LawCase JailDirect(Pawn offender, Pawn enforcer, int days) + { + LawCase c = ActCase(offender, "Jail", days); + c.MarkPunished(LawStage.DidIt); + c.activePunishment = "Jail"; + c.activeStage = LawStage.DidIt; + c.enforcer = enforcer; + c.status = CaseStatus.Enforcing; + offender.guest.CapturedBy(Faction.OfPlayer, enforcer); + T.Check(offender.IsPrisonerOfColony, "CapturedBy left " + offender.LabelShort + " free"); + T.Equal(CaseStatus.Jailed, c.status, "status after the capture (hook K)"); + return c; + } + } + + /// + /// "Enforcement and cases", "Warn and guilty" and "Subdue": the enforcer pick, danger and reservation + /// waits, the hand-over between stages, "Enforce laws" off, a berserk jail, guilt, and the subdue job + /// with its save rule. + /// + public static class EnforcementTests + { + // ---- Enforcement and cases ------------------------------------------------------- + + [BlaxTest("enforcement: a warden tending, beating a fire, carrying a downed colonist or doing surgery is never picked; the next one is")] + public static void BusyWardensSkipped() + { + Pawn offender = EnforceFixtures.Offender(); + Pawn busy = EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 1f, 3f)); + Pawn next = EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 6f, 12f)); + LawCase c = EnforceFixtures.ActCase(offender, "Jail", 3); + var candidates = new List { busy, next }; + + T.Check(Enforcers.PickFrom(c, EnforcerNeed.Arrest, candidates, out _) == busy, "with both free, the nearer warden isn't picked"); + + foreach (JobDef def in new[] { JobDefOf.TendPatient, JobDefOf.BeatFire }) + { + EnforceFixtures.WithCurJob(busy, JobMaker.MakeJob(def, offender), () => + T.Check(Enforcers.PickFrom(c, EnforcerNeed.Arrest, candidates, out _) == next, "a warden doing " + def.defName + " was picked")); + } + RecipeDef surgery = DefDatabase.AllDefsListForReading.FirstOrDefault(r => r.IsSurgery); + T.NotNull(surgery, "a surgery recipe"); + Job doBill = JobMaker.MakeJob(JobDefOf.DoBill, offender); + doBill.bill = new Bill_Medical(surgery, null); + EnforceFixtures.WithCurJob(busy, doBill, () => + T.Check(Enforcers.PickFrom(c, EnforcerNeed.Arrest, candidates, out _) == next, "a warden doing surgery was picked")); + + Pawn downed = EnforceFixtures.Offender(EnforceFixtures.CellNear(busy.Position, 1f, 3f)); + HealthUtility.DamageUntilDowned(downed, allowBleedingWounds: false); + T.Check(downed.Downed, "fixture: the colonist to carry isn't downed"); + downed.DeSpawn(); + T.Check(busy.carryTracker.TryStartCarry(downed), "fixture: the warden can't carry the downed colonist"); + Fixtures.OnCleanup(() => + { + if (busy.carryTracker.CarriedThing != null) + busy.carryTracker.TryDropCarriedThing(busy.Position, ThingPlaceMode.Near, out Thing _); + }); + T.Check(busy.IsCarryingPawn(downed), "fixture: the warden isn't carrying the colonist"); + T.Check(Enforcers.PickFrom(c, EnforcerNeed.Arrest, candidates, out _) == next, "a warden carrying a downed colonist was picked"); + busy.carryTracker.TryDropCarriedThing(busy.Position, ThingPlaceMode.Near, out Thing _); + T.Check(Enforcers.PickFrom(c, EnforcerNeed.Arrest, candidates, out _) == busy, "after the drop the nearer warden isn't picked again"); + + Settings.enforcers = EnforcerMode.WardensOnly; + next.workSettings.SetPriority(WorkTypeDefOf.Warden, 0); + busy.workSettings.SetPriority(WorkTypeDefOf.Warden, 0); + T.Check(Enforcers.PickFrom(c, EnforcerNeed.Arrest, candidates, out string reason) == null, "'Wardens only' picked a pawn without Warden work"); + T.Equal(WaitReasons.NoEnforcer, reason, "wait reason with nobody able"); + } + + [BlaxTest("enforcement: during a raid a binge case waits and nobody is sent; after the raid the sweep enforces it")] + public static void RaidBlocks() + { + // No drug to binge on and no social fight: either could down the binger or end its break during the + // wait, which would close the case for a reason this test isn't about. + DetectionKit.ClearDrugsOnMap(); + DetectionKit.QuietSocialFights(); + Pawn offender = EnforceFixtures.Offender(); + EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 2f, 6f)); + EnforceFixtures.ForceBreak(offender, EnforceFixtures.DrugBinge); + LawCase c = EnforceFixtures.BreakCase(offender, "Subdue", LawStage.Planning, 3); + Pawn raider = EnforceFixtures.Raider(); + EnforceFixtures.Dispatch(c, LawStage.Planning); + T.Equal(CaseStatus.Open, c.status, "status during the raid"); + T.Equal(WaitReasons.Danger, c.waitReason, "wait reason during the raid"); + T.Check(!EnforceFixtures.AnyEnforcementJobOn(offender), "someone was sent during the raid"); + raider.Destroy(DestroyMode.Vanish); + bool sent = EnforceFixtures.RunUntil(() => SubdueFlow.Runs(c), Enforcement.SweepInterval + 5); + T.Check(sent, "no subdue within a sweep after the raid; status " + c.status + ", wait " + c.waitReason); + } + + [BlaxTest("enforcement: a raid that lands while a subdue runs calls the warden off and the case waits for the danger; after the raid the sweep subdues again")] + public static void RaidCallsOffSubdue() + { + // No drug to binge on and no social fight: either could down the binger or end its break during the + // wait, which would close the case for a reason this test isn't about. + DetectionKit.ClearDrugsOnMap(); + DetectionKit.QuietSocialFights(); + Pawn offender = EnforceFixtures.Offender(); + EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 2f, 6f)); + EnforceFixtures.ForceBreak(offender, EnforceFixtures.DrugBinge); + LawCase c = EnforceFixtures.BreakCase(offender, "Subdue", LawStage.Planning, 3); + EnforceFixtures.Dispatch(c, LawStage.Planning); + T.Check(SubdueFlow.Runs(c), "fixture: no subdue before the raid; wait " + c.waitReason); + Pawn raider = EnforceFixtures.Raider(); + // The worker's sweep directly, so the warden can't down the binger between the raid and the check. + BlaxLawsDefOf.Subdue.Worker.Sweep(c); + T.Check(!SubdueFlow.Runs(c), "the subdue still runs during the raid"); + T.Check(!EnforceFixtures.AnyEnforcementJobOn(offender), "an enforcement job on the offender during the raid"); + T.Check(!c.IsClosed, "the case closed: " + c); + T.Equal(CaseStatus.Open, c.status, "status during the raid"); + T.Equal(WaitReasons.Danger, c.waitReason, "wait reason during the raid"); + raider.Destroy(DestroyMode.Vanish); + T.Check(EnforceFixtures.RunUntil(() => SubdueFlow.Runs(c), Enforcement.SweepInterval + 5), + "no subdue within a sweep after the raid; case " + c + ", wait " + c.waitReason + ", offender " + (offender.MentalStateDef?.defName ?? "no break") + (offender.Downed ? ", downed" : "")); + } + + [BlaxTest("enforcement: a raid that lands while the beating of 'Subdue then jail' runs calls the warden off and the case waits for the danger")] + public static void RaidCallsOffSubdueThenJail() + { + EnforceFixtures.PrisonCell(); + Pawn offender = EnforceFixtures.Offender(); + EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 2f, 6f)); + EnforceFixtures.ForceBreak(offender, EnforceFixtures.DrugBinge); + LawCase c = EnforceFixtures.BreakCase(offender, "SubdueThenJail", LawStage.DidIt, 3); + EnforceFixtures.Dispatch(c, LawStage.DidIt); + T.Check(SubdueFlow.Runs(c), "fixture: no subdue before the raid; wait " + c.waitReason); + EnforceFixtures.Raider(); + BlaxLawsDefOf.SubdueThenJail.Worker.Sweep(c); + T.Check(!SubdueFlow.Runs(c), "the subdue still runs during the raid"); + T.Check(!EnforceFixtures.AnyEnforcementJobOn(offender), "an enforcement job on the offender during the raid"); + T.Equal(WaitReasons.Danger, c.waitReason, "wait reason during the raid"); + T.Check(!offender.IsPrisonerOfColony, "jailed during the raid"); + } + + /// After a raid lands and the jail sweep runs: the capture is called off and the case waits for the danger. + private static void CheckCaptureCalledOff(LawCase c, Pawn warden, Pawn offender) + { + T.Check(!JailFlow.ArrestRuns(c), "the capture still runs or waits in the queue during the raid"); + T.Check(!CaptureBy(warden, offender), "a capture of the offender on the warden during the raid: " + (warden.CurJobDef?.defName ?? "no job")); + T.Check(!EnforceFixtures.AnyEnforcementJobOn(offender), "an enforcement job on the offender during the raid"); + T.Check(!warden.IsCarryingPawn(offender), "the warden carries the offender during the raid"); + T.Check(!c.IsClosed, "the case closed: " + c); + T.Equal(CaseStatus.Open, c.status, "status during the raid"); + T.Equal(WaitReasons.Danger, c.waitReason, "wait reason during the raid"); + T.Check(!offender.IsPrisonerOfColony, "jailed during the raid"); + } + + [BlaxTest("enforcement: a raid that lands while 'Subdue then jail' has its capture queued after the downing hit calls the capture off and the case waits for the danger")] + public static void RaidCallsOffQueuedCapture() + { + EnforceFixtures.PrisonCell(); + DetectionKit.QuietSocialFights(); + Pawn offender = EnforceFixtures.Offender(); + Pawn warden = EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 2f, 5f)); + EnforceFixtures.OnlyWardens(warden); + EnforceFixtures.ForceBreak(offender, EnforceFixtures.DrugBinge); + LawCase c = EnforceFixtures.BreakCase(offender, "SubdueThenJail", LawStage.DidIt, 3); + EnforceFixtures.Dispatch(c, LawStage.DidIt); + T.Check(SubdueFlow.Runs(c) && c.enforcer == warden, "fixture: no subdue; enforcer " + c.enforcer?.LabelShort + ", wait " + c.waitReason); + DownByHits(warden, offender); + // As the driver does it: OnDowned inside the toil queues the capture, then the subdue job ends. + InvokeSubdueFlow("OnDowned", c, warden); + SubdueFlow.End(c); + T.Equal("Jail", c.activePunishment, "fixture: the running punishment after the downing"); + T.Check(EnforcerJobs.Queued(warden, JobDefOf.Capture, offender) && !warden.IsCarryingPawn(offender), + "fixture: no queued capture before the raid: " + (warden.CurJobDef?.defName ?? "no job") + ", wait " + c.waitReason); + Pawn raider = EnforceFixtures.Raider(); + BlaxLawsDefOf.Jail.Worker.Sweep(c); + CheckCaptureCalledOff(c, warden, offender); + raider.Destroy(DestroyMode.Vanish); + } + + [BlaxTest("enforcement: a raid that lands while the warden walks to capture a downed offender for a jail row calls the capture off and the case waits for the danger")] + public static void RaidCallsOffRunningCapture() + { + EnforceFixtures.PrisonCell(); + Pawn offender = EnforceFixtures.Offender(); + Pawn warden = EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 10f, 18f)); + EnforceFixtures.OnlyWardens(warden); + HealthUtility.DamageUntilDowned(offender, allowBleedingWounds: false); + T.Check(offender.Downed, "fixture: the offender isn't downed"); + LawCase c = EnforceFixtures.ActCase(offender, "Jail", 3); + EnforceFixtures.Dispatch(c, LawStage.DidIt); + T.Check(EnforcerJobs.Runs(warden, JobDefOf.Capture, offender) && !warden.IsCarryingPawn(offender), + "fixture: the warden isn't on its way to capture the offender: " + (warden.CurJobDef?.defName ?? "no job") + ", wait " + c.waitReason); + Pawn raider = EnforceFixtures.Raider(); + BlaxLawsDefOf.Jail.Worker.Sweep(c); + CheckCaptureCalledOff(c, warden, offender); + raider.Destroy(DestroyMode.Vanish); + } + + [BlaxTest("enforcement: a downed offender a doctor reserved gets no capture and no reservation error; the sweep captures it once the reservation is gone")] + public static void ReservedOffenderWaits() + { + EnforceFixtures.PrisonCell(); + Pawn offender = EnforceFixtures.Offender(); + EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 2f, 6f)); + Pawn doctor = EnforceFixtures.Offender(EnforceFixtures.CellNear(offender.Position, 1f, 3f)); + HealthUtility.DamageUntilDowned(offender, allowBleedingWounds: false); + T.Check(offender.Downed, "fixture: the offender isn't downed"); + Job hold = JobMaker.MakeJob(JobDefOf.Wait); + hold.expiryInterval = 20000; + hold.playerForced = true; + doctor.jobs.StartJob(hold, JobCondition.InterruptForced); + T.Check(doctor.Reserve(offender, doctor.CurJob, errorOnFailed: false), "fixture: the doctor can't reserve the offender"); + + LawCase c = EnforceFixtures.ActCase(offender, "Jail", 3); + var logBefore = new HashSet(Log.Messages); + EnforceFixtures.Dispatch(c, LawStage.DidIt); + T.Equal(WaitReasons.Reserved, c.waitReason, "wait reason while the doctor holds the offender"); + T.Check(!EnforceFixtures.AnyEnforcementJobOn(offender), "a capture started on a reserved offender"); + var logged = Log.Messages.Where(m => !logBefore.Contains(m) && (m.type == LogMessageType.Warning || m.type == LogMessageType.Error)).ToList(); + T.Check(logged.Count == 0, "logged on a reserved offender: " + string.Join(" | ", logged.Take(3).Select(m => m.text))); + + doctor.jobs.EndCurrentJob(JobCondition.InterruptForced); + bool captured = EnforceFixtures.RunUntil(() => JailFlow.ArrestRuns(c) || offender.IsPrisonerOfColony, EnforceFixtures.SubdueTicks); + T.Check(captured, "no capture after the reservation was released; status " + c.status + ", wait " + c.waitReason); + } + + [BlaxTest("enforcement: hand-over: a binger beside its drug under the starter rows meets one enforcer, ends a prisoner never in a medical bed, with one did-it outcome")] + public static void HandOver() + { + T.Check(ActCatalogue.Get(ActKey.OfGroup(ActCategories.Break, ActGroups.AnyDrugBinge)) != null, + "the catalogue has no 'any drug binge' entry: the hand-over needs the catalogue and detection packages"); + EnforceFixtures.PrisonCell(); + DetectionKit.ClearDrugsOnMap(); + Pawn offender = EnforceFixtures.Offender(); + // The warden is sent at the binge's start from far off, so the binger reaches its drug first: a dose + // beside the drug takes it about 150 ticks (the walk, CarryIngestibleToChewSpot and 100 ticks of + // chewing, JobDriver_Ingest.cs:140-167; WakeUp's baseIngestTicks, Defs/Drugs/DrugBases.xml), the + // warden 40 cells off over 400. A warden that gets there first wins every time: each hit re-thinks + // the binger's job (at most every 180 ticks, Pawn_JobTracker.cs:974-990), and with the drug in its + // hands the binge finds no drug on the map (JobGiver_BingeDrug.cs:83) and wanders off, dropping it. + // That path, the subdue before any dose, is the subdue tests'. + Pawn warden = EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 40f, 60f)); + // A second warden beside the binger, drafted until the first is on its way: a did-it arrest that picked + // its enforcer anew instead of handing over would take this one. + Pawn near = EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 2f, 5f)); + near.drafter.Drafted = true; + EnforceFixtures.OnlyWardens(warden, near); + EnforceFixtures.ColonistBed(offender.Position, medical: true); + Lawbook.AddStarter(); + T.NotNull(Lawbook.Find(ActKey.OfGroup(ActCategories.Break, ActGroups.AnyDrugBinge), DrugOptions.Any, LawStage.DidIt), "starter row 'any drug binge, did it'"); + ThingDef wakeUp = DefDatabase.GetNamed("WakeUp"); + DetectionKit.NoOverdose(wakeUp); + IntVec3 drugCell = EnforceFixtures.CellNear(offender.Position, 1f, 1.9f); + Thing drug = Fixtures.Track(GenSpawn.Spawn(ThingMaker.MakeThing(wakeUp), drugCell, EnforceFixtures.Map)); + + EnforceFixtures.ForceBreak(offender, DefDatabase.GetNamed("Binging_DrugExtreme")); + ((MentalState_BingingDrug)offender.MentalState).chemical = wakeUp.GetCompProperties().chemical; + LawCase c = Fixtures.Comp.CasesOf(offender).LastOrDefault(x => x.IsBreakCase && !x.IsClosed); + T.NotNull(c, "the binge opened no planning case"); + + var enforcers = new HashSet(); + var timeline = new List(); + bool everColonistBed = false; + int start = EnforceFixtures.Now; + HashSet injuriesBefore = EnforceFixtures.Injuries(offender); + bool hit = false, dosed = false, handOver = false; + string lastJob = null, arrest = null; + bool jailed = EnforceFixtures.RunUntil(() => + { + int at = EnforceFixtures.Now - start; + if (near.Drafted && SubdueFlow.Runs(c)) + near.drafter.Drafted = false; + if (!hit && EnforceFixtures.NewInjuries(offender, injuriesBefore).Count > 0) + { + hit = true; + timeline.Add("[hit at " + at + "]"); + } + if (!dosed && c.stage == LawStage.DidIt) + { + // The dose filed in the last tick; Enforcement hands over in the next one. + dosed = true; + handOver = SubdueFlow.Runs(c) && c.enforcer == warden && !hit; + timeline.Add("[dose at " + at + ", warden " + (int)warden.Position.DistanceTo(offender.Position) + " cells off; " + EnforceFixtures.EnforcerStory(warden, c) + "]"); + } + if (dosed && arrest == null && c.activePunishment == "Jail") + arrest = "the arrest went to " + (c.enforcer?.LabelShort ?? "nobody") + " (wait " + c.waitReason + "), the warden sent to subdue was on " + (warden.CurJobDef?.defName ?? "no job") + " at " + at; + string job = offender.CurJobDef?.defName ?? "none"; + if (job != lastJob) + { + lastJob = job; + timeline.Add(job + "@" + at); + } + foreach (Pawn p in EnforceFixtures.EnforcersOn(offender)) + enforcers.Add(p); + if (offender.InBed() && !offender.CurrentBed().ForPrisoners) + everColonistBed = true; + return offender.IsPrisonerOfColony && c.status == CaseStatus.Jailed; + }, 4000); + string story = "case " + c + ", wait " + c.waitReason + "; at the end " + EnforceFixtures.EnforcerStory(warden, c) + "; the binger's jobs " + string.Join(" > ", timeline) + + ", wake-up left " + (drug.Destroyed ? 0 : drug.stackCount) + ", mental state " + (offender.MentalStateDef?.defName ?? "none"); + T.Check(handOver, "fixture: the binger didn't dose while the warden was on its way to subdue it; " + story); + T.Check(jailed, "the binger isn't jailed; " + story); + T.Equal(1, enforcers.Count, "pawns that enforced (" + string.Join(", ", enforcers.Select(p => p.LabelShort)) + "); " + arrest); + T.Check(enforcers.Contains(warden), "the warden sent to subdue didn't make the arrest; " + arrest); + T.Check(!everColonistBed, "the binger lay in a colonist or medical bed"); + int didIt = Fixtures.Comp.CasesOf(offender).Count(x => x.stage == LawStage.DidIt); + T.Equal(1, didIt, "did-it cases of the binger"); + T.Equal(LawStage.DidIt, c.stage, "the binge case's stage"); + } + + [BlaxTest("enforcement: hand-over: the did-it arrest goes to the warden whose subdue it ends, even with a player order waiting in that warden's queue")] + public static void HandOverKeepsEnforcer() + { + EnforceFixtures.PrisonCell(); + Pawn offender = EnforceFixtures.Offender(); + Pawn warden = EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 20f, 30f)); + Pawn near = EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 2f, 5f)); + near.drafter.Drafted = true; + EnforceFixtures.OnlyWardens(warden, near); + EnforceFixtures.ForceBreak(offender, EnforceFixtures.DrugBinge); + LawCase c = EnforceFixtures.BreakCase(offender, "Subdue", LawStage.Planning, 3); + EnforceFixtures.Dispatch(c, LawStage.Planning); + T.Check(SubdueFlow.Runs(c) && c.enforcer == warden, "fixture: the far warden isn't on the subdue; enforcer " + c.enforcer?.LabelShort); + near.drafter.Drafted = false; + // Ending the subdue would let the think tree hand the warden its next job at once, and a queued job + // comes first (ThinkNode_QueuedJob.cs:29-31): here a player order, which Laws never pulls a pawn off. + Job order = JobMaker.MakeJob(JobDefOf.Wait, 600); + order.playerForced = true; + warden.jobs.jobQueue.EnqueueLast(order); + + // The dose, as CaseFiler.Report files it during a binge. + c.SetLaw(LawStage.DidIt, EnforceFixtures.Row(ActCategories.Break, "Jail", LawStage.DidIt, 3)); + c.stage = LawStage.DidIt; + c.count = 1; + EnforceFixtures.Dispatch(c, LawStage.DidIt); + T.Check(JailFlow.ArrestRuns(c), "no arrest after the hand-over; wait " + c.waitReason + ", the warden on " + (warden.CurJobDef?.defName ?? "no job")); + T.Check(c.enforcer == warden, "the arrest went to " + c.enforcer?.LabelShort + ", not to the warden whose subdue it ended"); + T.Check(!EnforcerJobs.Runs(near, JobDefOf.Arrest, offender), "the warden beside the binger makes the arrest"); + } + + // A did-it Jail filed while the planning subdue runs, queued just before the subdue would close the case. + + /// A binger under a planning Subdue row with the only warden on the subdue. With alignToSweep the subdue starts on the tick before the one before a sweep. + private static LawCase SubdueRunning(out Pawn offender, out Pawn warden, bool alignToSweep = false) + { + EnforceFixtures.PrisonCell(); + DetectionKit.QuietSocialFights(); + offender = EnforceFixtures.Offender(); + warden = EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 2f, 5f)); + EnforceFixtures.OnlyWardens(warden); + EnforceFixtures.ForceBreak(offender, EnforceFixtures.DrugBinge); + LawCase c = EnforceFixtures.BreakCase(offender, "Subdue", LawStage.Planning, 3); + if (alignToSweep) + { + // Dispatch ticks once, so the subdue then starts at SweepInterval - 1 and the next tick sweeps. + for (int i = 0; i < Enforcement.SweepInterval && EnforceFixtures.Now % Enforcement.SweepInterval != Enforcement.SweepInterval - 2; i++) + Fixtures.Tick(1); + } + EnforceFixtures.Dispatch(c, LawStage.Planning); + T.Check(SubdueFlow.Runs(c) && c.enforcer == warden, "fixture: no subdue; enforcer " + c.enforcer?.LabelShort + ", wait " + c.waitReason); + return c; + } + + /// Files the dose as CaseFiler.Report does during a binge, under a did-it Jail row, and queues it. + private static void FileDidItJail(LawCase c, int delay) + { + c.SetLaw(LawStage.DidIt, EnforceFixtures.Row(ActCategories.Break, "Jail", LawStage.DidIt, 3)); + c.stage = LawStage.DidIt; + c.count = 1; + Enforcement.Schedule(c, CaseTask.Punish, LawStage.DidIt, delay); // delay 1 is what CaseFiler.Enqueue uses + } + + /// Downs the offender as JobDriver_Subdue.Hit does, without ticking. + private static void DownByHits(Pawn warden, Pawn offender) + { + for (int i = 0; i < 60 && !offender.Downed; i++) + SubdueHits.Hit(warden, offender); + T.Check(offender.Downed, "fixture: 60 hits didn't down the offender"); + } + + private static void InvokeSubdueFlow(string method, LawCase c, Pawn warden) + { + MethodInfo m = typeof(SubdueFlow).GetMethod(method, BindingFlags.NonPublic | BindingFlags.Static); + T.NotNull(m, "SubdueFlow." + method); + m.Invoke(null, new object[] { c, warden }); + } + + private static bool CaptureBy(Pawn warden, Pawn offender) => + EnforcerJobs.Runs(warden, JobDefOf.Capture, offender) || EnforcerJobs.Queued(warden, JobDefOf.Capture, offender); + + [BlaxTest("enforcement: hand-over: a did-it jail filed in the tick the subdue downs the offender still runs, as a capture")] + public static void DidItSurvivesDowningHit() + { + LawCase c = SubdueRunning(out Pawn offender, out Pawn warden); + FileDidItJail(c, 1); + DownByHits(warden, offender); + InvokeSubdueFlow("OnDowned", c, warden); + T.Check(!c.IsClosed, "the downing closed the case before the queued did-it: " + c); + Fixtures.Tick(1); + T.Check(!c.IsClosed, "the case closed: " + c); + T.Check(c.HasPunished(LawStage.DidIt), "the did-it stage was dropped"); + T.Equal("Jail", c.activePunishment, "the running punishment after the hand-over"); + T.Check(JailFlow.ArrestRuns(c), "no capture after the hand-over; wait " + c.waitReason); + T.Check(CaptureBy(warden, offender), "the warden doesn't capture the downed offender: " + (warden.CurJobDef?.defName ?? "no job")); + T.Check(EnforceFixtures.RunUntil(() => offender.IsPrisonerOfColony && c.status == CaseStatus.Jailed, 2500), + "not jailed within 2500 ticks; case " + c + ", wait " + c.waitReason); + } + + [BlaxTest("enforcement: hand-over: a did-it jail filed in the tick the subdue gives up still arrests")] + public static void DidItSurvivesGaveUp() + { + LawCase c = SubdueRunning(out Pawn offender, out Pawn warden); + FileDidItJail(c, 1); + // The driver gives up and its job ends. + SubdueFlow.End(c); + InvokeSubdueFlow("OnGaveUp", c, warden); + T.Check(!c.IsClosed, "giving up closed the case before the queued did-it: " + c); + Fixtures.Tick(1); + T.Check(!c.IsClosed, "the case closed: " + c); + T.Check(c.HasPunished(LawStage.DidIt), "the did-it stage was dropped"); + T.Equal("Jail", c.activePunishment, "the running punishment after the hand-over"); + T.Check(JailFlow.ArrestRuns(c), "no arrest after the hand-over; wait " + c.waitReason); + } + + [BlaxTest("enforcement: hand-over: a subdue sweep in the tick before a queued did-it jail doesn't close the case")] + public static void DidItSurvivesSubdueSweep() + { + LawCase c = SubdueRunning(out Pawn offender, out Pawn warden, alignToSweep: true); + T.Equal(Enforcement.SweepInterval - 1, EnforceFixtures.Now % Enforcement.SweepInterval, "fixture: the tick before the sweep"); + DownByHits(warden, offender); + SubdueFlow.End(c); // status stays Enforcing, the job is gone: the sweep's downed branch + T.Equal(CaseStatus.Enforcing, c.status, "fixture: status after the downing"); + FileDidItJail(c, 2); // the next tick sweeps, the one after drains + Fixtures.Tick(1); + T.Check(!c.IsClosed, "the sweep closed the case before the queued did-it: " + c); + Fixtures.Tick(1); + T.Check(c.HasPunished(LawStage.DidIt), "the did-it stage was dropped"); + T.Equal("Jail", c.activePunishment, "the running punishment after the hand-over"); + T.Check(JailFlow.ArrestRuns(c), "no capture after the hand-over; wait " + c.waitReason); + T.Check(CaptureBy(warden, offender), "the warden doesn't capture the downed offender: " + (warden.CurJobDef?.defName ?? "no job")); + } + + /// Files the dose as CaseFiler.Report does during a binge, under a did-it row with the punishment, and queues it. + private static void FileDidIt(LawCase c, string punishment, int delay) + { + c.SetLaw(LawStage.DidIt, EnforceFixtures.Row(ActCategories.Break, punishment, LawStage.DidIt, 3)); + c.stage = LawStage.DidIt; + c.count = 1; + Enforcement.Schedule(c, CaseTask.Punish, LawStage.DidIt, delay); + } + + private static bool SubdueJobOn(Pawn warden, Pawn offender) => + EnforcerJobs.Runs(warden, BlaxLawsDefOf.BlaxLaws_Subdue, offender) || EnforcerJobs.Queued(warden, BlaxLawsDefOf.BlaxLaws_Subdue, offender); + + [BlaxTest("enforcement: a did-it subdue filed in the tick the planning subdue downs the offender closes the case as subdued with the did-it stage done, no second beating")] + public static void DidItSubdueOnDowningHit() + { + LawCase c = SubdueRunning(out Pawn offender, out Pawn warden); + FileDidIt(c, "Subdue", 1); + DownByHits(warden, offender); + InvokeSubdueFlow("OnDowned", c, warden); + SubdueFlow.End(c); // the driver's job ends after its only toil + Fixtures.Tick(1); + T.Check(c.IsClosed, "the case is open: " + c); + T.Equal(CaseOutcomes.Subdued, c.outcome, "outcome"); + T.Check(c.HasPunished(LawStage.DidIt), "the did-it stage was dropped"); + T.Check(!SubdueJobOn(warden, offender), "a second subdue job on the downed offender"); + } + + [BlaxTest("enforcement: a did-it subdue filed in the tick the planning subdue gives up closes the case as not subdued and starts no second beating")] + public static void DidItSubdueOnGaveUp() + { + LawCase c = SubdueRunning(out Pawn offender, out Pawn warden); + FileDidIt(c, "Subdue", 1); + // As the driver does it: OnGaveUp inside the toil, then the job ends. + InvokeSubdueFlow("OnGaveUp", c, warden); + SubdueFlow.End(c); + Fixtures.Tick(1); + T.Check(c.IsClosed, "the case is open: " + c); + T.Equal(EnforcementOutcomes.NotSubdued, c.outcome, "outcome"); + T.Check(!SubdueJobOn(warden, offender), "a second subdue job after the subdue gave up"); + Fixtures.Tick(Enforcement.SweepInterval); + T.Check(!SubdueJobOn(warden, offender), "a subdue job a sweep after the subdue gave up"); + } + + [BlaxTest("enforcement: a subdue sweep in the tick before a queued did-it subdue on the downed offender closes the case as subdued with the did-it stage done")] + public static void DidItSubdueSurvivesSubdueSweep() + { + LawCase c = SubdueRunning(out Pawn offender, out Pawn warden, alignToSweep: true); + T.Equal(Enforcement.SweepInterval - 1, EnforceFixtures.Now % Enforcement.SweepInterval, "fixture: the tick before the sweep"); + DownByHits(warden, offender); + SubdueFlow.End(c); // status stays Enforcing, the job is gone: the sweep's downed branch + T.Equal(CaseStatus.Enforcing, c.status, "fixture: status after the downing"); + FileDidIt(c, "Subdue", 2); + Fixtures.Tick(1); + T.Check(c.IsClosed, "the case is open after the sweep: " + c); + T.Equal(CaseOutcomes.Subdued, c.outcome, "outcome"); + T.Check(c.HasPunished(LawStage.DidIt), "the did-it stage was dropped"); + T.Check(!SubdueJobOn(warden, offender), "a second subdue job on the downed offender"); + } + + [BlaxTest("enforcement: a did-it guilty filed in the tick the planning subdue downs the offender still makes it guilty; the case closes as subdued")] + public static void DidItGuiltyOnDowningHit() + { + LawCase c = SubdueRunning(out Pawn offender, out Pawn warden); + T.Equal(0, offender.guilt.TicksUntilInnocent, "fixture: guilt before the dose"); + FileDidIt(c, "Guilty", 1); + DownByHits(warden, offender); + InvokeSubdueFlow("OnDowned", c, warden); + SubdueFlow.End(c); + Fixtures.Tick(1); + T.Check(c.HasPunished(LawStage.DidIt), "the did-it stage was dropped"); + T.Check(offender.guilt.IsGuilty, "the offender isn't guilty after the did-it guilty row"); + Fixtures.Tick(Enforcement.SweepInterval); + T.Check(c.IsClosed, "the case is open a sweep later: " + c); + T.Equal(CaseOutcomes.Subdued, c.outcome, "outcome"); + } + + [BlaxTest("enforcement: with 'Enforce laws' off cases open and close and nothing is enforced")] + public static void EnforceLawsOff() + { + Settings.enforceLaws = false; + Pawn offender = EnforceFixtures.Offender(); + EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 2f, 6f)); + EnforceFixtures.ForceBreak(offender, EnforceFixtures.DrugBinge); + LawCase subdue = EnforceFixtures.BreakCase(offender, "Subdue", LawStage.Planning, 3); + LawCase jail = EnforceFixtures.ActCase(offender, "Jail", 3); + Enforcement.Enqueue(subdue, LawStage.Planning); + Enforcement.Enqueue(jail, LawStage.DidIt); + Fixtures.Tick(1); + T.Check(Fixtures.Comp.Cases.Contains(subdue) && Fixtures.Comp.Cases.Contains(jail), "the cases aren't in the store"); + T.Check(subdue.IsClosed && subdue.outcome == CaseOutcomes.NotEnforced, "subdue case: " + subdue); + T.Check(jail.IsClosed && jail.outcome == CaseOutcomes.NotEnforced, "jail case: " + jail); + T.Check(!EnforceFixtures.AnyEnforcementJobOn(offender), "something was enforced"); + T.Equal(0, offender.guilt.TicksUntilInnocent, "guilt without enforcement"); + } + + [BlaxTest("enforcement: a berserk pawn under a jail row waits while it rages; after the break a raid still blocks, then it is arrested")] + public static void BerserkJailWaits() + { + EnforceFixtures.PrisonCell(); + Pawn offender = EnforceFixtures.Offender(); + EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 10f, 18f)); + EnforceFixtures.ForceBreak(offender, MentalStateDefOf.Berserk); + LawCase c = EnforceFixtures.BreakCase(offender, "Jail", LawStage.Planning, 3); + EnforceFixtures.Dispatch(c, LawStage.Planning); + T.Check(c.status == CaseStatus.Open && (c.waitReason == WaitReasons.HostileBreak || c.waitReason == WaitReasons.Danger), + "while it rages: " + c.status + ", wait " + c.waitReason); + T.Check(!EnforceFixtures.AnyEnforcementJobOn(offender), "someone was sent at a berserk pawn"); + + Pawn raider = EnforceFixtures.Raider(); + offender.MentalState.RecoverFromState(); + T.Check(!offender.InMentalState, "fixture: the berserk break didn't end"); + Fixtures.Tick(Enforcement.SweepInterval + 2); + T.Equal(WaitReasons.Danger, c.waitReason, "wait reason after the break with a raider on the map"); + T.Check(!EnforceFixtures.AnyEnforcementJobOn(offender), "someone was sent during the raid"); + raider.Destroy(DestroyMode.Vanish); + bool arrest = EnforceFixtures.RunUntil(() => JailFlow.ArrestRuns(c) || offender.IsPrisonerOfColony, Enforcement.SweepInterval + 5); + T.Check(arrest, "no arrest after the break and the raid; wait " + c.waitReason); + } + + [BlaxTest("enforcement: a berserk pawn under a jail row is captured once it is downed")] + public static void BerserkDownedCaptured() + { + EnforceFixtures.PrisonCell(); + Pawn offender = EnforceFixtures.Offender(); + EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 10f, 18f)); + EnforceFixtures.ForceBreak(offender, MentalStateDefOf.Berserk); + LawCase c = EnforceFixtures.BreakCase(offender, "Jail", LawStage.Planning, 3); + EnforceFixtures.Dispatch(c, LawStage.Planning); + T.Check(!EnforceFixtures.AnyEnforcementJobOn(offender), "someone was sent at a berserk pawn"); + HealthUtility.DamageUntilDowned(offender, allowBleedingWounds: false); + T.Check(offender.Downed, "fixture: the berserk pawn isn't downed"); + bool captured = EnforceFixtures.RunUntil(() => offender.IsPrisonerOfColony || + (c.enforcer != null && EnforcerJobs.Runs(c.enforcer, JobDefOf.Capture, offender)), EnforceFixtures.SubdueTicks); + T.Check(captured, "the downed berserk pawn wasn't captured; wait " + c.waitReason); + } + + // ---- Warn and guilty -------------------------------------------------------------- + + [BlaxTest("guilty: a 3-day row leaves TicksUntilInnocent at 180000; a longer guilt stays")] + public static void GuiltyDays() + { + Pawn p = EnforceFixtures.Offender(); + LawCase c = EnforceFixtures.ActCase(p, "Guilty", 3); + BlaxLawsDefOf.Guilty.Worker.Start(c, c.LawFor(LawStage.DidIt), LawStage.DidIt); + T.Equal(180000, p.guilt.TicksUntilInnocent, "ticks until innocent after a 3-day row"); + T.Check(c.IsClosed && c.outcome == CaseOutcomes.Guilty, "the case after guilty: " + c); + + Pawn q = EnforceFixtures.Offender(); + q.guilt.Notify_Guilty(500000); + LawCase d = EnforceFixtures.ActCase(q, "Guilty", 3); + EnforceFixtures.Dispatch(d, LawStage.DidIt); + T.Check(q.guilt.TicksUntilInnocent > 400000, "a longer guilt was shortened to " + q.guilt.TicksUntilInnocent); + T.Check(d.IsClosed && d.outcome == CaseOutcomes.Guilty, "the queued case after guilty: " + d); + } + + [BlaxTest("warn: a warn row closes the case as warned and touches nothing else")] + public static void WarnCloses() + { + Pawn p = EnforceFixtures.Offender(); + LawCase c = EnforceFixtures.ActCase(p, "Warn", 1); + EnforceFixtures.Dispatch(c, LawStage.DidIt); + T.Check(c.IsClosed && c.outcome == CaseOutcomes.Warned, "the case after warn: " + c); + T.Equal(0, p.guilt.TicksUntilInnocent, "guilt after a warning"); + T.Check(!EnforceFixtures.AnyEnforcementJobOn(p), "a warning sent an enforcer"); + } + + [BlaxTest("guilty: a guilty colonist accepts the arrest of a Social 0 arrester")] + public static void GuiltyAcceptsArrest() + { + Pawn p = EnforceFixtures.Offender(); + Pawn arrester = EnforceFixtures.Warden(); + arrester.skills.GetSkill(SkillDefOf.Social).Level = 0; + LawCase c = EnforceFixtures.ActCase(p, "Guilty", 3); + BlaxLawsDefOf.Guilty.Worker.Start(c, c.LawFor(LawStage.DidIt), LawStage.DidIt); + T.Equal(1f, p.GetAcceptArrestChance(arrester), "accept-arrest chance of a guilty colonist"); + } + + [BlaxTest("guilty: banishing a guilty colonist lists no colony-wide thought; banishing it to die lists its spouse's grief and none colony-wide")] + public static void GuiltyBanishThoughts() + { + Pawn victim = EnforceFixtures.Offender(); + Pawn spouse = EnforceFixtures.Offender(); + victim.relations.AddDirectRelation(PawnRelationDefOf.Spouse, spouse); + Fixtures.OnCleanup(() => + { + if (victim.relations.DirectRelationExists(PawnRelationDefOf.Spouse, spouse)) + victim.relations.RemoveDirectRelation(PawnRelationDefOf.Spouse, spouse); + }); + victim.relations.everSeenByPlayer = true; + var individual = new List(); + var all = new List(); + + // Innocent first: the colony-wide thought exists, so the check below can fail. + PawnDiedOrDownedThoughtsUtility.GetThoughts(victim, null, PawnDiedOrDownedThoughtsKind.Banished, individual, all); + T.Check(all.Any(t => t.thoughtDef == ThoughtDefOf.ColonistBanished), "fixture: an innocent banishment gives no ColonistBanished"); + + LawCase c = EnforceFixtures.ActCase(victim, "Guilty", 3); + BlaxLawsDefOf.Guilty.Worker.Start(c, c.LawFor(LawStage.DidIt), LawStage.DidIt); + PawnDiedOrDownedThoughtsUtility.GetThoughts(victim, null, PawnDiedOrDownedThoughtsKind.Banished, individual, all); + T.Check(all.Count == 0, "colony-wide thoughts for banishing a guilty colonist: " + string.Join(", ", all.Select(t => t.thoughtDef.defName))); + PawnDiedOrDownedThoughtsUtility.GetThoughts(victim, null, PawnDiedOrDownedThoughtsKind.BanishedToDie, individual, all); + T.Check(all.Count == 0, "colony-wide thoughts for banishing a guilty colonist to die: " + string.Join(", ", all.Select(t => t.thoughtDef.defName))); + T.Check(individual.Any(t => t.addTo == spouse), "the spouse's grief is missing for banishing to die"); + } + + // ---- Subdue --------------------------------------------------------------------- + + /// A binging offender, a warden beside it, a planning Subdue case queued; runs until downed or the ticks (SubdueTicks by default). + private static LawCase SubdueBinge(Pawn offender, out HashSet before, string punishment = "Subdue", LawStage stage = LawStage.Planning, int ticks = EnforceFixtures.SubdueTicks) + { + // Only the subdue hits the offender: no social fight (a fistfight of its own, Pawn_InteractionsTracker.cs:355-370) + // and no random break of a bystander. + DetectionKit.QuietSocialFights(); + EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 2f, 5f)); + before = EnforceFixtures.Injuries(offender); + EnforceFixtures.ForceBreak(offender, EnforceFixtures.DrugBinge, causedByMood: true); + LawCase c = EnforceFixtures.BreakCase(offender, punishment, stage, 3); + Enforcement.Enqueue(c, stage); + EnforceFixtures.RunUntil(() => offender.Downed || c.IsClosed, ticks); + return c; + } + + private static void CheckSubdued(Pawn offender, LawCase c, HashSet before, bool catharsisRemoved) + { + T.Check(offender.Downed, "not downed within " + EnforceFixtures.SubdueTicks + " ticks; " + EnforceFixtures.SubdueStory(c, offender, before)); + List fresh = EnforceFixtures.NewInjuries(offender, before); + T.Check(fresh.Count > 0, "downed without a hit"); + List notBruises = fresh.Where(h => h.def != EnforceFixtures.Bruise).Select(EnforceFixtures.Describe).ToList(); + T.Check(notBruises.Count == 0, "injuries that aren't bruises: " + string.Join("; ", notBruises)); + List onHead = fresh.Where(h => h.Part == null || SubdueHits.InHeadOrNeck(offender, h.Part)).Select(EnforceFixtures.Describe).ToList(); + T.Check(onHead.Count == 0, "hits on the head or neck: " + string.Join("; ", onHead)); + var low = new List(); + foreach (BodyPartRecord part in fresh.Select(h => h.Part).Distinct()) + { + float max = part.def.GetMaxHealth(offender); + float hp = EnforceFixtures.PartHealth(offender, part); + if (hp < max * 0.5f - 0.001f) + { + low.Add(part.Label + " at " + hp.ToString("0.###") + " of " + max + " (" + + string.Join(", ", offender.health.hediffSet.hediffs.OfType().Where(h => h.Part == part).Select(EnforceFixtures.Describe)) + ")"); + } + } + T.Check(low.Count == 0, low.Count + " hit part(s) below half their HP: " + string.Join("; ", low)); + Thought_Memory catharsis = offender.needs.mood.thoughts.memories.GetFirstMemoryOfDef(ThoughtDefOf.Catharsis); + if (catharsisRemoved) + T.Check(catharsis == null, "the subdued pawn has Catharsis"); + else + T.Check(catharsis != null, "with the setting off the subdued pawn has no Catharsis"); + T.NotNull(c.enforcer, "the case's enforcer"); + T.Check(!c.enforcer.guilt.IsGuilty, "the enforcer is guilty"); + T.Check(offender.mindState.meleeThreat == null, "the offender has a melee threat: " + offender.mindState.meleeThreat); + T.Check(c.IsClosed && c.outcome == CaseOutcomes.Subdued, "the case after the subdue: " + c); + } + + [BlaxTest("subdue: a binge planning case is downed within 2500 ticks with bruises only, every hit part at half its HP or more, no head hit, no catharsis, an innocent enforcer and no melee threat")] + public static void SubdueDowns() + { + Pawn offender = EnforceFixtures.Offender(); + LawCase c = SubdueBinge(offender, out HashSet before); + CheckSubdued(offender, c, before, catharsisRemoved: true); + } + + [BlaxTest("subdue: with the camera off the map the subdue still downs the binger within 2500 ticks")] + public static void SubdueOffCamera() + { + WorldRenderer renderer = Find.World.renderer; + WorldRenderMode old = renderer.wantedMode; + renderer.wantedMode = WorldRenderMode.Planet; + Fixtures.OnCleanup(() => renderer.wantedMode = old); + Pawn offender = EnforceFixtures.Offender(); + T.Equal(15, GenTicks.GetCameraUpdateRate(offender), "the pawns' tick interval with the camera off the map"); + LawCase c = SubdueBinge(offender, out HashSet before); + CheckSubdued(offender, c, before, catharsisRemoved: true); + } + + [BlaxTest("subdue: with 'Subdued pawns lose their catharsis' off the subdued binger keeps its catharsis")] + public static void SubdueKeepsCatharsis() + { + Settings.subdueRemovesCatharsis = false; + Pawn offender = EnforceFixtures.Offender(); + LawCase c = SubdueBinge(offender, out HashSet before); + CheckSubdued(offender, c, before, catharsisRemoved: false); + } + + [BlaxTest("subdue: hits until nothing is left to hit keep the pawn alive, its injuries at nine tenths of the lethal sum, every hit part at half its HP or more, for a plain and a Tough colonist and through a race's rounded blunt multiplier")] + public static void SubdueCapHolds() + { + Pawn enforcer = EnforceFixtures.Warden(); + foreach (string variant in new[] { "plain", "Tough", "blunt x1.3", "bionic arms and legs" }) + { + Pawn target = EnforceFixtures.Offender(EnforceFixtures.CellNear(enforcer.Position, 2f, 12f)); + if (variant == "Tough") + target.story.traits.GainTrait(new Trait(DefDatabase.GetNamed("Tough"))); + if (variant == "bionic arms and legs") + { + // Only the torso is left to hit, so its own cap ends the beating before the total does. + foreach (BodyPartRecord shoulder in target.RaceProps.body.GetPartsWithDef(BodyPartDefOf.Shoulder)) + target.health.AddHediff(DefDatabase.GetNamed("BionicArm"), shoulder); + foreach (BodyPartRecord leg in target.RaceProps.body.GetPartsWithDef(BodyPartDefOf.Leg)) + target.health.AddHediff(DefDatabase.GetNamed("BionicLeg"), leg); + } + if (variant == "blunt x1.3") + { + // Thing.TakeDamage multiplies by the race's factor and rounds to a whole point (Thing.cs:1487-1497). + ThingDef race = target.def; + List old = race.damageMultipliers; + race.damageMultipliers = new List { new DamageMultiplier { damageDef = DamageDefOf.Blunt, multiplier = 1.3f } }; + Fixtures.OnCleanup(() => race.damageMultipliers = old); + } + HashSet before = EnforceFixtures.Injuries(target); + int hits = 0; + while (hits < 300 && SubdueHits.PickPart(target, out _) != null) + { + SubdueHits.Hit(enforcer, target); + hits++; + } + T.Check(!target.Dead, variant + ": the target died after " + hits + " hits"); + T.Check(SubdueHits.PickPart(target, out _) == null, variant + ": parts still had room after " + hits + " hits"); + // Vanilla kills at an injury sum of 150 times the health scale (Pawn_HealthTracker.cs:73, 705-719). + float sum = target.health.hediffSet.hediffs.OfType().Sum(h => h.Severity); + float cap = 150f * target.HealthScale * 0.9f; + T.Check(sum <= cap + 0.001f, variant + ": injuries add up to " + sum.ToString("0.###") + ", over " + cap.ToString("0.###")); + List fresh = EnforceFixtures.NewInjuries(target, before); + var low = new List(); + foreach (BodyPartRecord part in fresh.Select(h => h.Part).Distinct()) + { + float max = part.def.GetMaxHealth(target); + float hp = EnforceFixtures.PartHealth(target, part); + if (hp < max * 0.5f - 0.001f) + low.Add(part.Label + " at " + hp.ToString("0.###") + " of " + max); + } + T.Check(low.Count == 0, variant + ": " + low.Count + " hit part(s) below half their HP after " + hits + " hits: " + string.Join("; ", low)); + T.Check(fresh.All(h => h.def == EnforceFixtures.Bruise), variant + ": an injury that isn't a bruise"); + } + } + + [BlaxTest("subdue: a Tough colonist and one with two bionic arms both go down; the bionic arms take no injury")] + public static void SubdueToughAndBionic() + { + Pawn tough = EnforceFixtures.Offender(); + tough.story.traits.GainTrait(new Trait(DefDatabase.GetNamed("Tough"))); + T.Check(tough.GetStatValue(StatDefOf.IncomingDamageFactor) < 0.99f, "fixture: Tough doesn't lower the incoming damage"); + LawCase c1 = SubdueBinge(tough, out HashSet before1); + T.Check(tough.Downed, "the Tough colonist isn't downed; case " + c1); + T.Check(EnforceFixtures.NewInjuries(tough, before1).All(h => h.def == EnforceFixtures.Bruise), "the Tough colonist has an injury that isn't a bruise"); + + Pawn bionic = EnforceFixtures.Offender(EnforceFixtures.CellNear(Fixtures.PawnCell(), 0f, 20f)); + HediffDef arm = DefDatabase.GetNamed("BionicArm"); + foreach (BodyPartRecord shoulder in bionic.RaceProps.body.GetPartsWithDef(BodyPartDefOf.Shoulder)) + bionic.health.AddHediff(arm, shoulder); + T.Check(bionic.RaceProps.body.GetPartsWithDef(BodyPartDefOf.Shoulder).All(s => bionic.health.hediffSet.HasDirectlyAddedPartFor(s)), + "fixture: the bionic arms aren't installed"); + // Without the arms only the torso, the legs and the feet are left to hit, each down to half its HP: about 75 + // points of room against the 64 that down a normal adult, so the beating nearly fills them, with capped hits + // clipped, and takes far more hits than on a pawn with its arms. + LawCase c2 = SubdueBinge(bionic, out HashSet before2, ticks: EnforceFixtures.BionicSubdueTicks); + T.Check(bionic.Downed, "the colonist with bionic arms isn't downed within " + EnforceFixtures.BionicSubdueTicks + " ticks; " + EnforceFixtures.SubdueStory(c2, bionic, before2)); + List onArms = EnforceFixtures.NewInjuries(bionic, before2) + .Where(h => h.Part != null && bionic.health.hediffSet.PartOrAnyAncestorHasDirectlyAddedParts(h.Part)).ToList(); + T.Check(onArms.Count == 0, "the bionic arms took injuries: " + string.Join(", ", onArms.Select(h => h.Part.Label))); + } + + [BlaxTest("subdue: on a go-juice offender the job ends after three hits without new pain, with one message")] + public static void SubdueGivesUpOnGoJuice() + { + Pawn offender = EnforceFixtures.Offender(); + offender.health.AddHediff(DefDatabase.GetNamed("GoJuiceHigh")); + LawCase c = SubdueBinge(offender, out HashSet before); + T.Check(c.IsClosed && c.outcome == EnforcementOutcomes.NotSubdued, "the case after the beating: " + c); + T.Check(!offender.Downed, "the go-juice offender went down"); + T.Equal(3, EnforceFixtures.NewInjuries(offender, before).Count, "hits on the go-juice offender"); + T.NotNull(c.enforcer, "the case's enforcer"); + T.Check(!SubdueFlow.Runs(c), "the subdue job still runs"); + string text = "BlaxLaws_MsgSubdueGaveUp".Translate(offender.LabelShort, c.enforcer.LabelShort); + T.Equal(1, EnforceFixtures.MessagesWith(text), "messages that the subdue gave up"); + } + + [BlaxTest("subdue: a child with a subdue row is warned, with a subdue then jail row jailed without a beating (needs Biotech)")] + public static void SubdueChild() + { + Pawn child = EnforceFixtures.Ready(Fixtures.Child()); + EnforceFixtures.PrisonCell(); + EnforceFixtures.Warden(EnforceFixtures.CellNear(child.Position, 2f, 5f)); + HashSet before = EnforceFixtures.Injuries(child); + LawCase warn = EnforceFixtures.ActCase(child, "Subdue", 1); + EnforceFixtures.Dispatch(warn, LawStage.DidIt); + T.Check(warn.IsClosed && warn.outcome == CaseOutcomes.Warned, "the child's subdue case: " + warn); + T.Check(!EnforceFixtures.AnyEnforcementJobOn(child), "someone was sent at the child"); + + LawCase jail = EnforceFixtures.ActCase(child, "SubdueThenJail", 3); + bool everSubdued = false; + Enforcement.Enqueue(jail, LawStage.DidIt); + bool jailed = EnforceFixtures.RunUntil(() => + { + if (EnforceFixtures.EnforcersOn(child).Any(p => p.CurJobDef == BlaxLawsDefOf.BlaxLaws_Subdue)) + everSubdued = true; + return child.IsPrisonerOfColony; + }, EnforceFixtures.SubdueTicks); + T.Check(jailed, "the child isn't jailed; case " + jail + ", wait " + jail.waitReason); + T.Check(!everSubdued, "the child was subdued"); + T.Equal(0, EnforceFixtures.NewInjuries(child, before).Count, "injuries of the child"); + } + + [BlaxTest("subdue: subdue then jail ends with the pawn a prisoner in a prisoner bed, never in the medical bed a doctor could rescue it to")] + public static void SubdueThenJail() + { + PrisonRoom room = EnforceFixtures.PrisonCell(); + Pawn offender = EnforceFixtures.Offender(); + Pawn doctor = EnforceFixtures.Offender(EnforceFixtures.CellNear(offender.Position, 3f, 8f)); + doctor.workSettings?.EnableAndInitializeIfNotAlreadyInitialized(); + if (!doctor.WorkTypeIsDisabled(WorkTypeDefOf.Doctor)) + doctor.workSettings.SetPriority(WorkTypeDefOf.Doctor, 1); + EnforceFixtures.ColonistBed(doctor.Position, medical: true); + HashSet before = EnforceFixtures.Injuries(offender); + EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 2f, 5f)); + EnforceFixtures.ForceBreak(offender, EnforceFixtures.DrugBinge); + LawCase c = EnforceFixtures.BreakCase(offender, "SubdueThenJail", LawStage.DidIt, 3); + Enforcement.Enqueue(c, LawStage.DidIt); + bool everColonistBed = false; + bool jailed = EnforceFixtures.RunUntil(() => + { + if (offender.InBed() && !offender.CurrentBed().ForPrisoners) + everColonistBed = true; + return offender.IsPrisonerOfColony && offender.InBed(); + }, EnforceFixtures.SubdueTicks + 1500); + T.Check(jailed, "not a prisoner in bed; case " + c + ", wait " + c.waitReason); + T.Check(!everColonistBed, "the pawn lay in a colonist or medical bed"); + T.Check(offender.CurrentBed() == room.bed, "the pawn lies in " + offender.CurrentBed() + ", not the prisoner bed"); + T.Check(EnforceFixtures.NewInjuries(offender, before).Any(h => h.def == EnforceFixtures.Bruise), "jailed without the beating"); + T.Equal(CaseStatus.Jailed, c.status, "the case's status"); + } + + [BlaxTest("subdue: a forced tantrum goes down and never attacks the enforcer")] + public static void SubdueTantrum() + { + Pawn offender = EnforceFixtures.Offender(); + EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 2f, 5f)); + HashSet offenderBefore = EnforceFixtures.Injuries(offender); + EnforceFixtures.ForceBreak(offender, DefDatabase.GetNamed("Tantrum")); + LawCase c = EnforceFixtures.BreakCase(offender, "Subdue", LawStage.Planning, 3); + var injuriesBefore = Fixtures.Map.mapPawns.FreeColonistsSpawned.ToDictionary(p => p, EnforceFixtures.Injuries); + Enforcement.Enqueue(c, LawStage.Planning); + EnforceFixtures.RunUntil(() => offender.Downed || c.IsClosed, EnforceFixtures.MovingSubdueTicks); + T.Check(offender.Downed, "the tantrum isn't downed; " + EnforceFixtures.SubdueStory(c, offender, offenderBefore)); + T.NotNull(c.enforcer, "the case's enforcer"); + if (injuriesBefore.TryGetValue(c.enforcer, out HashSet before)) + T.Equal(0, EnforceFixtures.NewInjuries(c.enforcer, before).Count, "injuries of the enforcer"); + } + + [BlaxTest("subdue: a forced murderous rage goes down; its named victim is never the enforcer, and the enforcer is never attacked")] + public static void SubdueMurderousRage() + { + Pawn offender = EnforceFixtures.Offender(); + Pawn victim = EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 1f, 2f)); + Pawn other = EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 4f, 8f)); + EnforceFixtures.ForceBreak(offender, DefDatabase.GetNamed("MurderousRage"), otherPawn: victim); + ((MentalState_MurderousRage)offender.MentalState).target = victim; + LawCase c = EnforceFixtures.BreakCase(offender, "Subdue", LawStage.Planning, 3); + T.Check(!Enforcers.IsFree(victim, c), "the rage's victim counts as free to enforce"); + HashSet offenderBefore = EnforceFixtures.Injuries(offender); + var injuriesBefore = Fixtures.Map.mapPawns.FreeColonistsSpawned.ToDictionary(p => p, EnforceFixtures.Injuries); + Enforcement.Enqueue(c, LawStage.Planning); + Pawn firstEnforcer = null; + EnforceFixtures.RunUntil(() => + { + if (firstEnforcer == null && c.enforcer != null) + firstEnforcer = c.enforcer; + return offender.Downed || c.IsClosed; + }, EnforceFixtures.MovingSubdueTicks); + T.Check(firstEnforcer != victim && c.enforcer != victim, "the rage's victim was sent"); + T.Check(offender.Downed, "the rage isn't downed; " + EnforceFixtures.SubdueStory(c, offender, offenderBefore)); + if (injuriesBefore.TryGetValue(c.enforcer, out HashSet before)) + T.Equal(0, EnforceFixtures.NewInjuries(c.enforcer, before).Count, "injuries of the enforcer"); + } + + // ---- the subdue job never enters a save --------------------------------------------- + + private const string SubdueSaveKey = "enforce.subdueSave"; + + [BlaxTest("subdue save: two subdues run at the first save, one enforcer vomiting with resumeCurJobAfterwards (setup)")] + public static void SubdueSaveSetup() + { + // The jobs start right before the save, after every phase-1 test, so no other test's ticks end them. + T.CarryAtSave(SubdueSaveKey, StartSubduesForSave); + } + + private static string StartSubduesForSave() + { + Pawn o1 = Fixtures.Keep(EnforceFixtures.Offender()); + Pawn w1 = Fixtures.Keep(EnforceFixtures.Warden(EnforceFixtures.CellNear(o1.Position, 2f, 5f))); + Pawn o2 = Fixtures.Keep(EnforceFixtures.Offender(EnforceFixtures.CellNear(o1.Position, 10f, 20f))); + Pawn w2 = Fixtures.Keep(EnforceFixtures.Warden(EnforceFixtures.CellNear(o2.Position, 2f, 5f))); + EnforceFixtures.ForceBreak(o1, EnforceFixtures.DrugBinge); + EnforceFixtures.ForceBreak(o2, EnforceFixtures.DrugBinge); + LawCase c1 = StartSubdue(o1, w1, keep: true); + LawCase c2 = StartSubdue(o2, w2, keep: true); + bool running1 = SubdueFlow.Runs(c1); + bool running2 = SubdueFlow.Runs(c2); + w2.jobs.StartJob(JobMaker.MakeJob(JobDefOf.Vomit), JobCondition.InterruptForced, null, resumeCurJobAfterwards: true); + bool queued = EnforcerJobs.Queued(w2, BlaxLawsDefOf.BlaxLaws_Subdue, o2); + return string.Join("|", c1.id, c2.id, w1.ThingID, w2.ThingID, running1, running2, w2.CurJobDef?.defName ?? "none", queued); + } + + private static LawCase StartSubdue(Pawn offender, Pawn enforcer, bool keep = false) + { + LawCase c = EnforceFixtures.BreakCase(offender, "Subdue", LawStage.Planning, 3); + if (keep) + Fixtures.KeepLaw(c.LawFor(LawStage.Planning)); + c.MarkPunished(LawStage.Planning); + c.activePunishment = "Subdue"; + c.activeStage = LawStage.Planning; + SubdueFlow.TryStartWith(c, enforcer); + return c; + } + + private const string InPlaceSaveName = "BlaxLawsTestInPlace"; + + [BlaxTest("subdue save: a save in play puts the running subdue, its driver and the queue back at once; the save holds no subdue")] + public static void SubdueSurvivesSaveInPlay() + { + Pawn offender = EnforceFixtures.Offender(); + Pawn warden = EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 2f, 5f)); + EnforceFixtures.ForceBreak(offender, EnforceFixtures.DrugBinge); + LawCase c = StartSubdue(offender, warden); + T.Check(SubdueFlow.Runs(c), "the subdue didn't start; case " + c + ", wait " + c.waitReason); + // Vanilla never queues the subdue (its JobDef isn't suspendable), so the queue backstop is exercised by hand: + // one subdue entry and one other entry the filter keeps. + warden.jobs.jobQueue.EnqueueLast(JobMaker.MakeJob(BlaxLawsDefOf.BlaxLaws_Subdue, offender)); + warden.jobs.jobQueue.EnqueueLast(JobMaker.MakeJob(JobDefOf.Wait, 60)); + Job job = warden.CurJob; + JobDriver driver = warden.jobs.curDriver; + JobQueue queue = warden.jobs.jobQueue; + string path = GenFilePaths.FilePathForSavedGame(InPlaceSaveName); + try + { + // The same synchronous full save the autosave makes; it goes to the -DataDir save folder. + GameDataSaveLoader.SaveGame(InPlaceSaveName); + T.Check(File.Exists(path), "the in-play save wasn't written"); + T.Check(!File.ReadAllText(path).Contains("BlaxLaws_Subdue"), "the in-play save holds a BlaxLaws_Subdue job"); + T.Check(warden.CurJob == job, "the enforcer's job after the save: " + (warden.CurJobDef?.defName ?? "none")); + T.Check(warden.jobs.curDriver == driver, "the enforcer's job driver wasn't put back after the save"); + T.Check(ReferenceEquals(warden.jobs.jobQueue, queue), "the enforcer's job queue wasn't put back after the save"); + T.Equal(2, warden.jobs.jobQueue.Count, "queued jobs after the save"); + T.Check(EnforcerJobs.Queued(warden, BlaxLawsDefOf.BlaxLaws_Subdue, offender), "the queued subdue is gone after the save"); + T.Check(SubdueFlow.Runs(c), "the subdue doesn't run right after the save"); + Fixtures.Tick(1); + T.Check(warden.CurJob == job && warden.jobs.curDriver == driver, "the enforcer lost its subdue one tick after the save: " + (warden.CurJobDef?.defName ?? "none")); + T.Check(SubdueFlow.Runs(c), "the subdue doesn't run one tick after the save"); + } + finally + { + warden.jobs?.ClearQueuedJobs(); + try + { + if (File.Exists(path)) + File.Delete(path); + } + catch (IOException) + { + } + } + } + + [BlaxTest("subdue save: the save holds no subdue job and no queued one; after the reload the sweep subdues again within 250 ticks", phase: 2)] + public static void SubdueSaveRoundTrip() + { + T.Check(T.Carry.TryGetValue(SubdueSaveKey, out string carry) && !carry.NullOrEmpty(), "the phase-1 save setup did not run"); + string[] parts = carry.Split('|'); + T.Check(parts.Length == 8, "carry: " + carry); + T.Check(parts[4] == "True" && parts[5] == "True", "the subdues didn't run at the save: " + carry); + T.Equal("Vomit", parts[6], "the second enforcer's job at the save"); + T.Equal("False", parts[7], "the vomiting enforcer queued its subdue"); + + string xml = File.ReadAllText(GenFilePaths.FilePathForSavedGame(TestRunner.SaveName)); + T.Check(!xml.Contains("BlaxLaws_Subdue"), "the save holds a BlaxLaws_Subdue job"); + + foreach (Pawn p in EnforceFixtures.Map.mapPawns.AllPawnsSpawned) + { + JobQueue q = p.jobs?.jobQueue; + for (int i = 0; q != null && i < q.Count; i++) + T.Check(q[i]?.job?.def != BlaxLawsDefOf.BlaxLaws_Subdue, p.LabelShort + " has a queued subdue after the reload"); + } + LawCase c1 = Fixtures.Comp.CaseById(int.Parse(parts[0])); + T.NotNull(c1, "the first subdue case after the reload"); + T.NotNull(c1.offender, "the first case's offender after the reload"); + bool again = EnforceFixtures.RunUntil(() => SubdueFlow.Runs(c1) || c1.outcome == CaseOutcomes.Subdued, Enforcement.SweepInterval + 5); + T.Check(again, "no new subdue within a sweep after the reload; case " + c1 + ", wait " + c1.waitReason); + } + + [BlaxTest("removal: no pawn runs or queues a Blax Laws job after the component was removed", phase: 3)] + public static void NoLawsJobsAfterRemoval() + { + foreach (Map map in Find.Maps) + { + foreach (Pawn p in map.mapPawns.AllPawnsSpawned) + { + T.Check(p.CurJobDef?.defName?.StartsWith("BlaxLaws") != true, p.LabelShort + " runs " + p.CurJobDef?.defName); + JobQueue q = p.jobs?.jobQueue; + for (int i = 0; q != null && i < q.Count; i++) + T.Check(q[i]?.job?.def?.defName?.StartsWith("BlaxLaws") != true, p.LabelShort + " has queued " + q[i]?.job?.def?.defName); + } + } + } + + private static BlaxLawsSettings Settings => Fixtures.Settings; + } +} diff --git a/Tests/BlaxLawsTests/Source/Fixtures.cs b/Tests/BlaxLawsTests/Source/Fixtures.cs new file mode 100644 index 0000000..1d329d0 --- /dev/null +++ b/Tests/BlaxLawsTests/Source/Fixtures.cs @@ -0,0 +1,372 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using BlaxLaws; +using RimWorld; +using RimWorld.Planet; +using Verse; +using Verse.AI; + +namespace BlaxLawsTests +{ + /// + /// Shared helpers for tests. Pawns and things made here are removed after each test unless passed to + /// Keep(). Mod settings are restored after each test, and lawbook rows a test added are deleted unless + /// passed to KeepLaw(), so tests may change both freely. + /// + public static partial class Fixtures + { + private static readonly List made = new List(); + private static readonly HashSet kept = new HashSet(); + private static readonly List madeThings = new List(); + private static readonly HashSet keptThings = new HashSet(); + private static readonly HashSet keptLaws = new HashSet(); + private static readonly List cleanups = new List(); + + public static Map Map => Find.CurrentMap; + + public static BlaxLawsSettings Settings => BlaxLawsMod.Settings; + + public static GameComponent_BlaxLaws Comp => GameComponent_BlaxLaws.Instance; + + // ---- factions -------------------------------------------------------------------- + + /// A visible, non-player, humanlike faction that is not hostile to the player. + public static Faction FriendlyFaction() => + Find.FactionManager.AllFactionsVisible + .Where(f => !f.IsPlayer && !f.defeated && f.def.humanlikeFaction && !f.HostileTo(Faction.OfPlayer)) + .OrderBy(f => f.loadID).FirstOrDefault(); + + /// A visible, non-player, humanlike faction hostile to the player. + public static Faction HostileFaction() => + Find.FactionManager.AllFactionsVisible + .Where(f => !f.IsPlayer && !f.defeated && f.def.humanlikeFaction && f.HostileTo(Faction.OfPlayer)) + .OrderBy(f => f.loadID).FirstOrDefault(); + + // ---- pawns ----------------------------------------------------------------------- + + /// A fresh pawn, not spawned. Relations off so no accidental family ties. + public static Pawn Generate(PawnKindDef kind, Faction faction, DevelopmentalStage stage = DevelopmentalStage.Adult) + { + var req = new PawnGenerationRequest(kind, faction, PawnGenerationContext.NonPlayer, + forceGenerateNewPawn: true, allowDowned: stage.Baby(), canGeneratePawnRelations: false, + colonistRelationChanceFactor: 0f, developmentalStages: stage); + Pawn p = PawnGenerator.GeneratePawn(req); + made.Add(p); + return p; + } + + /// + /// A standable, unfogged cell near the map center that belongs to a district, so pawns spawned there + /// path, find beds and count as in a room like any colonist. The district reaches the map edge: never + /// the inside of a room a fixture built, such as a prison cell, where no other pawn fits beside it. + /// + public static IntVec3 PawnCell() + { + Map map = Map; + if (CellFinder.TryFindRandomCellNear(map.Center, map, 20, + c => c.Standable(map) && !c.Fogged(map) && c.GetDistrict(map) is District d && d.TouchesMapEdge && c.GetFirstPawn(map) == null, out IntVec3 cell)) + return cell; + if (CellFinder.TryFindRandomCellNear(map.Center, map, 60, c => c.Standable(map) && c.GetDistrict(map) != null, out cell)) + return cell; + T.Fail("no standable cell with a district near the map center"); + return IntVec3.Invalid; + } + + /// Spawns the pawn at the cell, or on PawnCell() when none is given. + public static Pawn Spawn(Pawn p, IntVec3? at = null) + { + IntVec3 cell = at ?? PawnCell(); + T.Check(cell.GetDistrict(Map) != null, "spawn cell " + cell + " has no district"); + GenSpawn.Spawn(p, cell, Map); + return p; + } + + /// A spawned free adult colonist. + public static Pawn Colonist() => Spawn(Generate(PawnKindDefOf.Colonist, Faction.OfPlayer)); + + /// A spawned slave of the colony. Skips the test without Ideology. + public static Pawn ColonySlave(Faction origin = null) + { + T.NeedsDlc("Ideology", ModsConfig.IdeologyActive); + Pawn p = Generate(PawnKindDefOf.Slave, origin ?? FriendlyFaction()); + Spawn(p); + p.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Slave); + T.Check(p.IsSlaveOfColony, "slave fixture is not a slave of the colony"); + return p; + } + + /// A spawned prisoner of the colony, from a hostile faction when there is one. + public static Pawn Prisoner() + { + Faction from = HostileFaction() ?? FriendlyFaction(); + Pawn p = Spawn(Generate(PawnKindDefOf.Slave, from)); + p.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Prisoner); + T.Check(p.IsPrisonerOfColony, "prisoner fixture is not a prisoner of the colony"); + return p; + } + + /// A spawned child of the colony. Skips the test without Biotech. + public static Pawn Child() + { + T.NeedsDlc("Biotech", ModsConfig.BiotechActive); + Pawn p = Spawn(Generate(PawnKindDefOf.Colonist, Faction.OfPlayer, DevelopmentalStage.Child)); + T.Check(p.DevelopmentalStage.Child(), "child fixture is " + p.DevelopmentalStage + ", not a child"); + return p; + } + + /// Exclude a pawn from the per-test cleanup (phase-1 setup for phase-2 checks). + public static Pawn Keep(Pawn p) + { + kept.Add(p); + return p; + } + + public static Pawn FindPawnById(string thingId) + { + if (thingId == null) return null; + foreach (Map m in Find.Maps) + foreach (Pawn p in m.mapPawns.AllPawns) + if (p.ThingID == thingId) return p; + foreach (Pawn p in Find.WorldPawns.AllPawnsAliveOrDead) + if (p.ThingID == thingId) return p; + return null; + } + + // ---- things ---------------------------------------------------------------------- + + /// Destroy this thing after the test unless kept. + public static TT Track(TT thing) where TT : Thing + { + madeThings.Add(thing); + return thing; + } + + public static TT Keep(TT thing) where TT : Thing + { + keptThings.Add(thing); + return thing; + } + + /// A thing a test made or kept, so a fixture never clears it away. + public static bool IsFixtureThing(Thing t) => madeThings.Contains(t) || keptThings.Contains(t); + + /// + /// Ground a fixture building may go on once cleared, as a player clears a building site: walkable terrain + /// that is not water, unfogged, in the district, with no building and no pawn, and nothing on it but plants, + /// filth and items no test made. A wild map (a dense jungle) has few cells free of trees and starting items. + /// + public static bool Buildable(IntVec3 c, Map map, District district) + { + if (!c.InBounds(map) || c.Fogged(map) || c.GetDistrict(map) != district) + return false; + TerrainDef terrain = c.GetTerrain(map); + if (terrain.IsWater || terrain.passability != Traversability.Standable) + return false; + List things = c.GetThingList(map); + for (int i = 0; i < things.Count; i++) + { + Thing t = things[i]; + if (t is Plant || t.def.category == ThingCategory.Filth || t.def.category == ThingCategory.Mote) + continue; + if (t.def.category == ThingCategory.Item && !IsFixtureThing(t)) + continue; + return false; + } + return true; + } + + /// Removes the plants and items on the cells, so a building fits (see Buildable). + public static void ClearGround(IEnumerable cells, Map map) + { + foreach (IntVec3 c in cells) + { + if (!c.InBounds(map)) + continue; + foreach (Thing t in c.GetThingList(map).ToList()) + { + if ((t is Plant || t.def.category == ThingCategory.Item) && !IsFixtureThing(t) && !t.Destroyed) + t.Destroy(DestroyMode.Vanish); + } + } + } + + // ---- lawbook --------------------------------------------------------------------- + + /// + /// Adds a row through Lawbook.TryAdd and returns it; fails the test when a row with the key exists. + /// Deleted after the test unless passed to KeepLaw. + /// + public static Law LawRow(string actKey, string option, LawStage stage, LawSeverity severity, string punishment, int days, + string savedMod = null, string savedPackageId = null) + { + var law = new Law + { + actKey = actKey, + option = option, + stage = stage, + severity = severity, + punishment = punishment, + days = days, + enabled = true, + savedLabel = ActKey.NameOf(actKey), + savedMod = savedMod, + savedPackageId = savedPackageId, + }; + T.Check(Lawbook.TryAdd(law, out Law existing), "LawRow " + actKey + ": refused, existing " + existing); + return law; + } + + public static Law KeepLaw(Law law) + { + keptLaws.Add(law.id); + return law; + } + + /// The ids of the rows before a test (used by the runner). + public static HashSet SnapshotLawbook() => new HashSet(Lawbook.Laws.Select(l => l.id)); + + /// Deletes every row a test added that it didn't keep (used by the runner). + public static void RestoreLawbook(HashSet before) + { + foreach (Law l in Lawbook.Laws.ToList()) + { + if (!before.Contains(l.id) && !keptLaws.Contains(l.id)) + Lawbook.Delete(l); + } + } + + /// Runs after the test, before things are removed (undo a test-only patch, for example). + public static void OnCleanup(Action action) => cleanups.Add(action); + + // ---- time ------------------------------------------------------------------------ + + public static void Tick(int ticks) + { + for (int i = 0; i < ticks; i++) Find.TickManager.DoSingleTick(); + } + + /// + /// No incidents, and no mental break a test didn't start: the quick test's own colonists sleep on the + /// ground, eat what they find and hear of every fixture colonist that dies, so over the suite's + /// simulated days their mood sinks and they would break (MentalBreaker checks + /// DebugSettings.enableRandomMentalStates first). Tests start breaks with forced: true, which ignores it. + /// + public static void QuietStoryteller() + { + Find.Storyteller.incidentQueue.Clear(); + Find.Storyteller.storytellerComps.Clear(); + DebugSettings.enableRandomMentalStates = false; + } + + /// + /// Before each phase-1 test: the pawns no test made stay out of the next test's way. The quick test's + /// colonists are fed and taken out of any break, and an animal in a manhunter state calms down. A + /// starving or breaking colonist wanders off and can turn an animal manhunter, and a manhunter is an + /// active threat that keeps every later enforcement waiting for the danger to pass + /// (Enforcers.DangerBlocks; RimWorld/GenHostility.cs:227). Each such fix is noted in the results. + /// + public static void CalmBystanders() + { + Map map = Map; + if (map == null) + return; + foreach (Pawn p in map.mapPawns.AllPawnsSpawned.ToList()) + { + if (p == null || p.Dead || kept.Contains(p) || made.Contains(p)) + continue; + if (p.IsFreeColonist) + { + if (p.needs?.food != null) + p.needs.food.CurLevel = p.needs.food.MaxLevel; + if (p.needs?.joy != null) + p.needs.joy.CurLevel = 1f; + } + if ((p.IsFreeColonist || p.RaceProps.Animal) && p.InMentalState) + { + TestRunner.Note("calmed " + p.LabelShort + " out of " + p.MentalStateDef.defName + " before the test"); + p.MentalState.RecoverFromState(); + } + } + } + + // ---- settings and cleanup (used by the runner) ----------------------------------- + + public static Dictionary SnapshotSettings() + { + var d = new Dictionary(); + if (Settings == null) return d; + foreach (FieldInfo f in typeof(BlaxLawsSettings).GetFields(BindingFlags.Public | BindingFlags.Instance)) + d[f] = f.GetValue(Settings); + return d; + } + + public static void RestoreSettings(Dictionary snapshot) + { + if (Settings == null) return; + foreach (var kv in snapshot) kv.Key.SetValue(Settings, kv.Value); + BlaxLawsMod.ApplyTabVisibility(); + } + + public static void Cleanup() + { + List actions = cleanups.ToList(); + cleanups.Clear(); + foreach (Action a in actions) + { + try { a(); } + catch (Exception e) { TestRunner.Note("cleanup action threw: " + e.Message); } + } + + Find.Selector?.ClearSelection(); + + foreach (Thing t in madeThings) + { + if (t == null || keptThings.Contains(t) || t.Destroyed) continue; + if (t.Spawned || t.holdingOwner != null) t.Destroy(DestroyMode.Vanish); + } + madeThings.Clear(); + + // Two passes: a pawn another fixture pawn carries (an arrest or capture cut off by the test's end) is + // held, not spawned, and destroying the carrier drops it onto the map, where it would stay as a + // prisoner that claims the next test's prisoner bed. + for (int pass = 0; pass < 2; pass++) + { + foreach (Pawn p in made) + { + if (p == null || kept.Contains(p) || p.Destroyed) continue; + if (pass == 0) DropRitualObligations(p); + if (p.Corpse != null && (p.Corpse.Spawned || p.Corpse.holdingOwner != null)) p.Corpse.Destroy(DestroyMode.Vanish); + else if (p.Spawned || p.holdingOwner != null) p.Destroy(DestroyMode.Vanish); + else if (p.IsWorldPawn()) Find.WorldPawns.RemoveAndDiscardPawnViaGC(p); + } + } + made.Clear(); + } + + /// + /// A fixture colonist that died gets a funeral obligation, and a living one can get a scarification or + /// 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. + /// + private static void DropRitualObligations(Pawn p) + { + if (!ModsConfig.IdeologyActive || Find.IdeoManager == null) return; + Corpse corpse = p.Corpse; + bool Hits(TargetInfo t) => t.HasThing && (t.Thing == p || (corpse != null && t.Thing == corpse)); + foreach (Ideo ideo in Find.IdeoManager.IdeosListForReading) + { + foreach (Precept precept in ideo.PreceptsListForReading) + { + if (!(precept is Precept_Ritual ritual) || ritual.activeObligations == null) continue; + foreach (RitualObligation o in ritual.activeObligations.ToList()) + { + if (o != null && (Hits(o.targetA) || Hits(o.targetB) || Hits(o.targetC))) + ritual.RemoveObligation(o); + } + } + } + } + } +} diff --git a/Tests/BlaxLawsTests/Source/Harness.cs b/Tests/BlaxLawsTests/Source/Harness.cs new file mode 100644 index 0000000..f142df3 --- /dev/null +++ b/Tests/BlaxLawsTests/Source/Harness.cs @@ -0,0 +1,656 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text.RegularExpressions; +using BlaxLaws; +using RimWorld; +using RimWorld.Planet; +using UnityEngine; +using Verse; + +namespace BlaxLawsTests +{ + /// + /// Marks a public static void method without parameters as a test. Phase 1 runs in a fresh quick-test + /// colony. Phase 2 runs after the runner saved that game and loaded it again. Phase 3 runs after the + /// runner saved again, replaced the GameComponent_BlaxLaws class in the save with one that doesn't exist + /// and loaded that: the vanilla side of a save whose mod was removed. + /// + [AttributeUsage(AttributeTargets.Method)] + public sealed class BlaxTestAttribute : Attribute + { + public readonly string Name; + public readonly int Phase; + + public BlaxTestAttribute(string name, int phase = 1) + { + Name = name; + Phase = phase; + } + } + + public class TestFailure : Exception + { + public TestFailure(string message) : base(message) { } + } + + public class TestSkipped : Exception + { + public TestSkipped(string message) : base(message) { } + } + + /// Assertions and notes for test bodies. + public static class T + { + /// Values carried from phase 1 into phases 2 and 3. Store ThingIDs, ids or def names, never objects. + public static readonly Dictionary Carry = new Dictionary(); + + /// Carry values read right before the first save, after every phase-1 test ran. + internal static readonly Dictionary> CarryAtSaveTime = new Dictionary>(); + + /// Carries a value read right before the save instead of now, for state later phase-1 tests may still change. + public static void CarryAtSave(string key, Func read) => CarryAtSaveTime[key] = read; + + public static void Check(bool condition, string message) + { + if (!condition) throw new TestFailure(message); + } + + public static void Equal(TV expected, TV actual, string what) + { + if (!EqualityComparer.Default.Equals(expected, actual)) + throw new TestFailure($"{what}: expected {Show(expected)}, got {Show(actual)}"); + } + + public static void NotNull(object value, string what) + { + if (value == null) throw new TestFailure(what + " is null"); + } + + public static void Fail(string message) => throw new TestFailure(message); + + public static void Skip(string reason) => throw new TestSkipped(reason); + + /// Skips the test unless the DLC is active, with "needs <DLC>" as the reason. + public static void NeedsDlc(string dlc, bool active) + { + if (!active) throw new TestSkipped("needs " + dlc); + } + + /// Adds an INFO line under the current test in the results file. + public static void Info(string message) => TestRunner.Note(message); + + /// + /// Expects exactly errors whose text contains , + /// logged during this test or, in phase 3, during the phase-3 load. Checked when the test ends, so call + /// it before or after the action. Matching errors are excused: they never count as Blax Laws errors, + /// here or as stray errors. Several tests may expect the same errors. + /// + public static void ExpectErrors(string fragment, int count) => TestRunner.Expect(fragment, count); + + /// Error texts (one line each) logged while the phase-3 save loaded. Empty before phase 3. + public static List Phase3LoadErrors => TestRunner.LoadErrors(); + + /// "Could not resolve reference" warnings logged while the phase-3 save loaded. + public static int Phase3ResolveWarnings => TestRunner.ResolveWarnings; + + /// "Could not resolve reference" warnings (one line each) logged while the phase-1 save loaded for phase 2. + public static List Phase2ResolveWarnings => TestRunner.Phase2Warnings(); + + /// + /// The warning names a pawn vanilla's TaleData_Pawn.GenerateRandom made for a book or tale and never + /// saved (a vanilla leak, see TestRunner.vanillaTalePawns), not anything Blax Laws saved. + /// + public static bool NamesVanillaTalePawn(string warning) => TestRunner.NamesVanillaTalePawn(warning); + + /// + /// The warning names a pawn a relation already pointed at, with no save holding it, when the suite + /// began (left by the world's generation, see TestRunner.unsavedAtStart), not anything Blax Laws saved. + /// + public static bool NamesPawnUnsavedAtStart(string warning) => TestRunner.NamesPawnUnsavedAtStart(warning); + + private static string Show(object o) => o == null ? "null" : o.ToString(); + } + + /// + /// Drives the suite when the game runs with -quicktest -blaxlawstests: phase 1, save, load, phase 2, save, + /// strip the component class, load, phase 3, then writes BlaxLawsTestResults.txt into the save data + /// folder and quits. + /// + public class TestRunner : GameComponent + { + public const string SaveName = "BlaxLawsTest"; + public const string Phase3SaveName = "BlaxLawsTest3"; + public const string ResultFile = "BlaxLawsTestResults.txt"; + + /// The class attribute phase 3 replaces in the save. + public const string ComponentClassAttr = "Class=\"BlaxLaws.GameComponent_BlaxLaws\""; + + /// A class that doesn't exist; the phase-3 save names it instead of GameComponent_BlaxLaws. + public const string RemovedComponentClass = "BlaxLawsRemoved.GameComponent_BlaxLaws"; + + /// Where errors logged during the phase-3 load are filed. + public const string Phase3LoadTag = "(phase 3 load)"; + + /// Where errors logged while the phase-1 save loads for phase 2 are filed. + public const string Phase2LoadTag = "(phase 2 load)"; + + private class LogEntry + { + public string where; + public string text; + public bool ours; + public bool excused; + public bool warning; + } + + private static int stage; // 0 waiting, 1 phase 1 done + reload queued, 2 phase 2 done + phase-3 load queued, 3 finished + private static int loadsSeen; + private static int pass, fail, skip; + private static string currentTest; + private static readonly List errors = new List(); + private static readonly List<(string fragment, int count)> expectations = new List<(string, int)>(); + private static int resolveWarnings; + private static readonly List phase2Warnings = new List(); + private static readonly HashSet danglingSeen = new HashSet(); + private static bool hooked; + private int settleFrames; + + public static bool Enabled => GenCommandLine.CommandLineArgPassed("blaxlawstests"); + + public static string ResultPath => Path.Combine(GenFilePaths.SaveDataFolderPath, ResultFile); + + /// Component nodes phase 3 replaced in the save. Set before the phase-3 load. + public static int Phase3ReplacedCount { get; private set; } + + public static int ResolveWarnings => resolveWarnings; + + public TestRunner(Game game) { } + + public override void LoadedGame() + { + if (Enabled && (stage == 1 || stage == 2)) loadsSeen++; + } + + public override void GameComponentUpdate() + { + if (!Enabled || stage == 3) return; + if (LongEventHandler.AnyEventNowOrWaiting || Find.CurrentMap == null) return; + if (++settleFrames < 30) return; + + if (stage == 0) + { + stage = 1; + Begin(); + RunPhase(1); + Line("STAGE save+reload"); + try + { + foreach (var kv in T.CarryAtSaveTime) + { + try { T.Carry[kv.Key] = kv.Value(); } + catch (Exception e) { Note("carry " + kv.Key + " failed: " + e.Message); } + } + NoteDanglingRelations(); + GameDataSaveLoader.SaveGame(SaveName); + lock (errors) phase2Warnings.Clear(); + currentTest = Phase2LoadTag; + GameDataSaveLoader.LoadGame(SaveName); + } + catch (Exception e) + { + currentTest = null; + Record("FAIL", "save and reload", e.ToString()); + Finish(); + } + } + else if (stage == 1 && loadsSeen >= 1) + { + stage = 2; + currentTest = null; + Line("STAGE phase 2 (after reload)"); + Note("phase 2 load: " + Phase2Warnings().Count + " 'Could not resolve reference' warning(s)"); + RunPhase(2); + Line("STAGE phase 3 (component class removed from the save)"); + try + { + StartPhase3Load(); + } + catch (Exception e) + { + currentTest = null; + Record("FAIL", "phase 3 save and load", e.ToString()); + Finish(); + } + } + else if (stage == 2 && loadsSeen >= 2) + { + currentTest = null; + Note("phase 3 load: " + Phase3ReplacedCount + " component node(s) replaced, " + LoadErrors().Count + " error(s), " + + resolveWarnings + " 'Could not resolve reference' warning(s)"); + RunPhase(3); + Finish(); + } + } + + /// + /// Saves as BlaxLawsTest3 (saves are plain XML in 1.7, ScribeSaver.cs:45-49), replaces the component's + /// class with one that doesn't exist and loads it. Laws' assembly stays loaded, so Game.FillComponents + /// adds a fresh, empty component after the load. + /// + private static void StartPhase3Load() + { + GameDataSaveLoader.SaveGame(Phase3SaveName); + string path = GenFilePaths.FilePathForSavedGame(Phase3SaveName); + string xml = File.ReadAllText(path); + int count = 0; + for (int i = xml.IndexOf(ComponentClassAttr, StringComparison.Ordinal); i >= 0; i = xml.IndexOf(ComponentClassAttr, i + 1, StringComparison.Ordinal)) + count++; + if (count == 0) + throw new Exception("the phase-3 save holds no " + ComponentClassAttr); + Phase3ReplacedCount = count; + File.WriteAllText(path, xml.Replace(ComponentClassAttr, "Class=\"" + RemovedComponentClass + "\"")); + lock (errors) resolveWarnings = 0; + currentTest = Phase3LoadTag; + GameDataSaveLoader.LoadGame(Phase3SaveName); + } + + /// The game log as it stood when the suite began, before any test ran (the startup test reads it). + public static List StartupLog { get; private set; } = new List(); + + /// + /// The new game as it stood when the suite began, before any test ran: rows, cases, the watch flags and + /// the enforcement queue. Test classes run in name order, so the empty-book test reads this instead of + /// the state other tests left behind. + /// + public static NewGameState AtStart { get; private set; } + + public sealed class NewGameState + { + public int laws, cases, pending; + public bool watchAny, categoryFlag, specialFlag; + } + + private static void Begin() + { + try { File.Delete(ResultPath); } catch { } + StartupLog = Log.Messages.ToList(); + GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance; + AtStart = new NewGameState + { + laws = comp?.Laws.Count ?? -1, + cases = comp?.Cases.Count ?? -1, + pending = Enforcement.Pending, + watchAny = Watch.Any, + categoryFlag = Watch.Break || Watch.Ate || Watch.Used || Watch.Interaction || Watch.RecordedAct || Watch.Record || Watch.Bill || Watch.Special, + specialFlag = Watch.SetFire || Watch.DisplayedCorpse || Watch.StartedSocialFight, + }; + HookLog(); + HookPawnWatchers(); + Line("BEGIN Blax Laws in-game tests, RimWorld " + VersionControl.CurrentVersionStringWithRev); + Line("DLCs: Royalty " + ModsConfig.RoyaltyActive + ", Ideology " + ModsConfig.IdeologyActive + ", Biotech " + ModsConfig.BiotechActive + + ", Anomaly " + ModsConfig.AnomalyActive + ", Odyssey " + ModsConfig.OdysseyActive); + Fixtures.QuietStoryteller(); + Find.TickManager.CurTimeSpeed = TimeSpeed.Paused; + NoteUnsavedAtStart(); + } + + private static void HookLog() + { + if (hooked) return; + hooked = true; + Application.logMessageReceivedThreaded += (text, stack, type) => + { + if (type == LogType.Warning) + { + if (text != null && text.Contains("Could not resolve reference")) + { + if (currentTest == Phase3LoadTag) + lock (errors) resolveWarnings++; + else if (currentTest == Phase2LoadTag) + lock (errors) phase2Warnings.Add(OneLine(text)); + } + // Blax Laws' own warnings ("[Blax Laws] ...") between tests count as stray mod warnings. + if (text != null && text.Contains("[Blax Laws]")) + lock (errors) errors.Add(new LogEntry { where = currentTest ?? "(between tests)", text = OneLine(text), ours = true, warning = true }); + return; + } + if (type != LogType.Error && type != LogType.Exception) return; + bool ours = !IsKnownForeignError(text, stack) + && ((text != null && (text.Contains("BlaxLaws") || text.Contains("Blax Laws"))) || (stack != null && stack.Contains("BlaxLaws"))); + var entry = new LogEntry { where = currentTest ?? "(between tests)", text = OneLine(text), ours = ours }; + lock (errors) errors.Add(entry); + }; + } + + /// + /// 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 Laws; these show as LOGERR lines instead. Each entry is a + /// text fragment and the frame that logs it. Add one per mod, with the reason, as Zones does: + /// - Prison Labor (-Compat): its postfix on Pawn_GuestTracker.SetGuestStatus passes its own + /// PrisonLabor_workOption, a non-exclusive mode in 1.7, to SetExclusiveInteraction, so the game logs + /// "Attempted to set guest exclusive interaction to a non-exclusive interaction type" once for the + /// first pawn made a prisoner (the prisoner fixture). + /// - Prisoner Realism (-Compat): HediffComp_Solitary ticks on a prisoner the release job carries + /// (JobDriver_ReleasePrisoner.cs:27), and SolitaryUtility.IsInSolitary passes pawn.Map, null while it is + /// carried, to GetDoor (its Source/Features/Solitary/SolitaryUtility.cs:56-59): an NRE the game logs as + /// "Exception ticking hediff (PR_Solitary ...)" whenever a warden releases a prisoner from a cell. + /// + private static readonly (string text, string frame)[] KnownForeignErrors = + { + ("non-exclusive interaction type: PrisonLabor_", "Patch_DefaultInteractionMode"), + ("PrisonerRealism.SolitaryUtility.IsInSolitary", "Pawn_HealthTracker.HealthTick"), + }; + + 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; + } + + internal static void Expect(string fragment, int count) + { + if (fragment.NullOrEmpty()) throw new TestFailure("ExpectErrors needs a text fragment"); + expectations.Add((fragment, count)); + } + + internal static List LoadErrors() + { + lock (errors) return errors.Where(e => e.where == Phase3LoadTag && !e.warning).Select(e => e.text).ToList(); + } + + internal static List Phase2Warnings() + { + lock (errors) return phase2Warnings.ToList(); + } + + /// + /// Notes every pawn relation, new since the last check, whose other pawn no save holds (discarded, or + /// on no map, in no container and not a world pawn). Each one becomes a "Could not resolve reference" + /// warning when the save loads. Runs after every test and once more right before the phase-1 save. + /// Pawns vanilla made for books and tales are left out here (see vanillaTalePawns); the reload test + /// counts them. + /// + private static void NoteDanglingRelations() + { + try + { + foreach (var (p, r, o) in DanglingRelations()) + { + if (!danglingSeen.Add(p.ThingID + ">" + (o?.ThingID ?? "null"))) + continue; + if (o != null && (IsVanillaTalePawn(o.ThingID) || IsUnsavedAtStart(o.ThingID))) + continue; + Note("dangling relation: " + p.ThingID + " (" + p.LabelShort + ", " + (p.Faction?.GetUniqueLoadID() ?? "no faction") + ") " + + r.def.defName + " -> " + Describe(o)); + } + } + catch (Exception e) + { + Note("relation check threw: " + OneLine(e.Message)); + } + } + + /// Every pawn relation whose other pawn no save holds (discarded, or on no map, in no container and not a world pawn). + private static List<(Pawn p, DirectPawnRelation r, Pawn o)> DanglingRelations() + { + var found = new List<(Pawn, DirectPawnRelation, Pawn)>(); + var all = new HashSet(PawnsFinder.All_AliveOrDead); + foreach (Pawn p in all.ToList()) + { + if (p?.relations == null) + continue; + foreach (DirectPawnRelation r in p.relations.DirectRelations) + { + Pawn o = r.otherPawn; + if (o != null && !o.Discarded && all.Contains(o)) + continue; + found.Add((p, r, o)); + } + } + return found; + } + + /// + /// Pawns that relations already pointed at, with no save holding them, when the suite began: the new + /// world's generation left them so (seen with an AncientSoldier ex-lover of a faction pawn), before any + /// test ran and with an empty lawbook. The reload test excuses them like the tale pawns. + /// + private static readonly HashSet unsavedAtStart = new HashSet(); + + private static bool IsUnsavedAtStart(string thingId) => thingId != null && unsavedAtStart.Contains(thingId); + + /// The "Could not resolve reference" warning names a pawn no save held when the suite began. + internal static bool NamesPawnUnsavedAtStart(string warning) + { + Match m = warning == null ? null : ResolveWarningId.Match(warning); + return m != null && m.Success && IsUnsavedAtStart(m.Groups[1].Value); + } + + private static void NoteUnsavedAtStart() + { + try + { + foreach (var (p, r, o) in DanglingRelations()) + { + if (o == null || !unsavedAtStart.Add(o.ThingID)) + continue; + Note("unsaved at the start (world generation): " + p.ThingID + " (" + p.LabelShort + ") " + r.def.defName + " -> " + Describe(o)); + } + } + catch (Exception e) + { + Note("start relation check threw: " + OneLine(e.Message)); + } + } + + private static string Describe(Pawn o) + { + if (o == null) + return "null"; + string removed; + lock (worldRemovals) worldRemovals.TryGetValue(o.ThingID, out removed); + return o.ThingID + " (" + o.LabelShort + ", kind " + o.kindDef?.defName + ", " + (o.Faction?.GetUniqueLoadID() ?? "no faction") + + ", destroyed " + o.Destroyed + ", discarded " + o.Discarded + ", dead " + o.Dead + ", spawned " + o.Spawned + + ", world pawn " + o.IsWorldPawn() + ", held by " + (o.ParentHolder?.ToString() ?? "nothing") + ")" + + (IsVanillaTalePawn(o.ThingID) ? "; vanilla: made by TaleData_Pawn.GenerateRandom and never saved" : "") + + (removed != null ? "; left the world pawns from: " + removed : ""); + } + + /// Who took each pawn out of WorldPawns this run (ThingID to the calling frames), for the dangling-relation notes. + private static readonly Dictionary worldRemovals = new Dictionary(); + + private static bool pawnWatchersHooked; + + /// + /// Pawns vanilla's TaleData_Pawn.GenerateRandom made this run (ThingIDs). It generates a pawn for a + /// book's text (Book.GenerateBook, Book.cs:235), a unique weapon's name or a tale, keeps only its + /// TaleData and never saves or discards the pawn (TaleData_Pawn.cs:110-115). Relations to such a pawn + /// point at a pawn no save holds. + /// + private static readonly HashSet vanillaTalePawns = new HashSet(); + + private static readonly Regex ResolveWarningId = new Regex(@"loadID Thing_(\S+) of type Verse\.Pawn"); + + private static bool IsVanillaTalePawn(string thingId) + { + lock (vanillaTalePawns) return thingId != null && vanillaTalePawns.Contains(thingId); + } + + /// The "Could not resolve reference" warning names a pawn vanilla's TaleData_Pawn.GenerateRandom made and never saved. + internal static bool NamesVanillaTalePawn(string warning) + { + Match m = warning == null ? null : ResolveWarningId.Match(warning); + return m != null && m.Success && IsVanillaTalePawn(m.Groups[1].Value); + } + + /// Installs the WorldPawns.RemovePawn and TaleData_Pawn.GenerateRandom watchers once, at startup (QuickTestMap), before the world exists. + internal static void HookPawnWatchers() + { + if (pawnWatchersHooked) + return; + pawnWatchersHooked = true; + try + { + var harmony = new HarmonyLib.Harmony("blax.laws.tests.harness"); + harmony.Patch(HarmonyLib.AccessTools.Method(typeof(WorldPawns), nameof(WorldPawns.RemovePawn)), + postfix: new HarmonyLib.HarmonyMethod(HarmonyLib.AccessTools.Method(typeof(TestRunner), nameof(OnWorldPawnRemoved)))); + harmony.Patch(HarmonyLib.AccessTools.Method(typeof(TaleData_Pawn), nameof(TaleData_Pawn.GenerateRandom)), + postfix: new HarmonyLib.HarmonyMethod(HarmonyLib.AccessTools.Method(typeof(TestRunner), nameof(OnTalePawnGenerated)))); + } + catch (Exception e) + { + Note("could not watch WorldPawns.RemovePawn or TaleData_Pawn.GenerateRandom: " + OneLine(e.Message)); + } + } + + private static void OnTalePawnGenerated(TaleData_Pawn __result) + { + string id = __result?.pawn?.ThingID; + if (id != null) + lock (vanillaTalePawns) vanillaTalePawns.Add(id); + } + + private static void OnWorldPawnRemoved(Pawn p) + { + if (p == null) + return; + var frames = new System.Diagnostics.StackTrace(2, false).GetFrames() ?? new System.Diagnostics.StackFrame[0]; + string where = string.Join(" < ", frames.Take(8).Select(f => f.GetMethod()).Where(m => m != null) + .Select(m => m.DeclaringType?.Name + "." + m.Name)); + lock (worldRemovals) worldRemovals[p.ThingID] = where; + } + + private static void RunPhase(int phase) + { + var tests = typeof(TestRunner).Assembly.GetTypes() + .SelectMany(t => t.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static)) + .Select(m => (method: m, attr: m.GetCustomAttribute())) + .Where(x => x.attr != null && x.attr.Phase == phase) + .OrderBy(x => x.method.DeclaringType.FullName) + .ThenBy(x => x.method.MetadataToken) + .ToList(); + foreach (var (method, attr) in tests) RunOne(attr.Name, method, phase); + } + + private static void RunOne(string name, MethodInfo method, int phase) + { + currentTest = name; + expectations.Clear(); + int before; + lock (errors) before = errors.Count; + var settings = Fixtures.SnapshotSettings(); + var lawbook = Fixtures.SnapshotLawbook(); + string status = "PASS", detail = ""; + try + { + Find.TickManager.CurTimeSpeed = TimeSpeed.Paused; + if (phase == 1) + Fixtures.CalmBystanders(); + method.Invoke(null, null); + } + catch (TargetInvocationException tie) when (tie.InnerException is TestSkipped s) + { + status = "SKIP"; detail = s.Message; + } + catch (TargetInvocationException tie) when (tie.InnerException is TestFailure f) + { + status = "FAIL"; detail = f.Message; + } + catch (TargetInvocationException tie) + { + status = "FAIL"; detail = "exception: " + tie.InnerException; + } + catch (Exception e) + { + status = "FAIL"; detail = "runner exception: " + e; + } + finally + { + Fixtures.RestoreSettings(settings); + try { Fixtures.RestoreLawbook(lawbook); } catch (Exception e) { Note("lawbook restore threw: " + OneLine(e.Message)); } + try { Fixtures.Cleanup(); } catch (Exception e) { Note("cleanup threw: " + OneLine(e.Message)); } + LawsTestHooks.Reset(); + Compat.SimulatedActive.Clear(); + NoteDanglingRelations(); + } + + List newErrors; + lock (errors) + { + newErrors = errors.Skip(before).Where(e => !e.warning).ToList(); + var window = phase == 3 ? newErrors.Concat(errors.Take(before).Where(e => e.where == Phase3LoadTag && !e.warning)).ToList() : newErrors; + foreach (var (fragment, count) in expectations) + { + var matches = window.Where(e => e.text.Contains(fragment)).ToList(); + foreach (LogEntry m in matches) m.excused = true; + if (matches.Count != count && status == "PASS") + { + status = "FAIL"; + detail = $"expected {count} error(s) containing '{fragment}', got {matches.Count}"; + } + } + } + expectations.Clear(); + var newModErrors = newErrors.Where(e => e.ours && !e.excused).ToList(); + var newOtherErrors = newErrors.Where(e => !e.ours && !e.excused).ToList(); + if (status == "PASS" && newModErrors.Count > 0) + { + status = "FAIL"; + detail = "Blax Laws logged errors: " + string.Join(" | ", newModErrors.Take(3).Select(e => e.text)); + } + Record(status, name, detail); + foreach (LogEntry e in newOtherErrors.Take(5)) Line(" LOGERR " + e.where + ": " + e.text); + currentTest = null; + } + + private static void Finish() + { + stage = 3; + currentTest = null; + List stray, strayWarnings; + lock (errors) + { + stray = errors.Where(e => e.where.StartsWith("(") && e.ours && !e.excused && !e.warning).ToList(); + strayWarnings = errors.Where(e => e.where.StartsWith("(") && e.warning).ToList(); + } + foreach (LogEntry e in stray.Take(10)) Line(" MODERR " + e.where + ": " + e.text); + foreach (LogEntry e in strayWarnings.Take(10)) Line(" MODWARN " + e.where + ": " + e.text); + Line($"SUMMARY pass={pass} fail={fail} skip={skip} strayModErrors={stray.Count} strayModWarnings={strayWarnings.Count}"); + Line("END"); + Log.Message($"[BlaxTest] finished: pass={pass} fail={fail} skip={skip}"); + Root.Shutdown(); + } + + internal static void Note(string message) => Line(" INFO " + OneLine(message)); + + private static void Record(string status, string name, string detail) + { + if (status == "PASS") pass++; + else if (status == "FAIL") fail++; + else skip++; + Line(string.IsNullOrEmpty(detail) ? $"{status} {name}" : $"{status} {name}: {OneLine(detail)}"); + } + + private static void Line(string text) + { + Log.Message("[BlaxTest] " + text); + try { File.AppendAllText(ResultPath, text + Environment.NewLine); } catch { } + } + + private static string OneLine(string s) + { + if (s == null) return ""; + s = s.Replace("\r", " ").Replace("\n", " | "); + return s.Length > 1500 ? s.Substring(0, 1500) + "..." : s; + } + } +} diff --git a/Tests/BlaxLawsTests/Source/JailTests.cs b/Tests/BlaxLawsTests/Source/JailTests.cs new file mode 100644 index 0000000..baa93b7 --- /dev/null +++ b/Tests/BlaxLawsTests/Source/JailTests.cs @@ -0,0 +1,655 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using BlaxLaws; +using RimWorld; +using Verse; +using Verse.AI; + +namespace BlaxLawsTests +{ + /// + /// "Jail for N days": the arrest, hook K, "Maintain only" two ticks after the capture, the release, the + /// old bed, a late arrest, no prisoner bed, the holds and fallbacks, the early end, and a jailed colonist + /// through the save and the removal. + /// + public static class JailTests + { + private const string PrisonLaborId = "avius.prisonlabor"; // Prison Labor's About.xml (Workshop 1899474310), read 2026-12-01 + private const string CastesId = "blax.castes"; + + private static int Now => Find.TickManager.TicksGame; + + // ---- the sentence ----------------------------------------------------------------- + + [BlaxTest("jail: a did-it binge case with jail 3 days: a prisoner within 2500 ticks, the break over without catharsis, guilt for the sentence plus a day, Maintain only two ticks after the capture; at the release tick Release, a warden releases it with WasImprisoned and the same work priorities")] + public static void JailThreeDays() + { + EnforceFixtures.PrisonCell(); + Pawn o = EnforceFixtures.Offender(); + EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 6f)); + Dictionary priorities = EnforceFixtures.Priorities(o); + EnforceFixtures.ForceBreak(o, EnforceFixtures.DrugBinge, causedByMood: true); + LawCase c = EnforceFixtures.BreakCase(o, "Jail", LawStage.DidIt, 3); + Enforcement.Enqueue(c, LawStage.DidIt); + + int arrestStart = -1; + bool jailed = EnforceFixtures.RunUntil(() => + { + if (arrestStart < 0 && c.status == CaseStatus.Enforcing) + arrestStart = Now; + return o.IsPrisonerOfColony; + }, EnforceFixtures.SubdueTicks); + T.Check(jailed, "not a prisoner within 2500 ticks; case " + c + ", wait " + c.waitReason); + T.Equal(CaseStatus.Jailed, c.status, "the case's status at the capture"); + T.Equal(Now, c.captureTick, "the capture tick"); + T.Equal(c.captureTick + 3 * GenDate.TicksPerDay, c.releaseTick, "the release tick"); + T.Check(o.MentalState == null, "the break goes on in jail: " + o.MentalStateDef?.defName); + T.Check(o.needs.mood.thoughts.memories.GetFirstMemoryOfDef(ThoughtDefOf.Catharsis) == null, "the jailed pawn has Catharsis"); + int minGuilt = 4 * GenDate.TicksPerDay - (Now - arrestStart) - 30; + T.Check(o.guilt.TicksUntilInnocent >= minGuilt, "guilt " + o.guilt.TicksUntilInnocent + ", expected at least " + minGuilt); + + Fixtures.Tick(2); + T.Equal(PrisonerInteractionModeDefOf.MaintainOnly, o.guest.ExclusiveInteractionMode, "the mode two ticks after the capture"); + bool labor = LaborOn(o); + T.Check(c.maintainOnlyDone, "maintainOnlyDone after the write"); + + c.releaseTick = Now; + EnforceFixtures.TickPastSentenceSweep(); + T.Equal(PrisonerInteractionModeDefOf.Release, o.guest.ExclusiveInteractionMode, "the mode at the release tick"); + bool released = EnforceFixtures.RunUntil(() => !o.IsPrisonerOfColony, 4000); + T.Check(released, "no warden released the pawn"); + T.Check(o.IsFreeColonist, o.LabelShort + " isn't a free colonist after the release"); + T.NotNull(o.needs.mood.thoughts.memories.GetFirstMemoryOfDef(ThoughtDefOf.WasImprisoned), "WasImprisoned after the release"); + string diff = PriorityDiff(priorities, o, labor); + T.Check(diff == null, "work priorities changed: " + diff); + EnforceFixtures.TickPastSentenceSweep(); + T.Check(c.IsClosed && c.outcome == CaseOutcomes.Served, "the case after the release: " + c); + } + + [BlaxTest("jail: a mode written at capture plus 1 (Enslave with Ideology, else Reduce resistance) reads Maintain only at capture plus 2, with Laws' component first")] + public static void MaintainOnlyLandsLast() + { + MoveLawsComponentFirst(); + EnforceFixtures.PrisonCell(); + Pawn o = EnforceFixtures.Offender(); + EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 6f)); + LawCase c = EnforceFixtures.ActCase(o, "Jail", 3); + Enforcement.Enqueue(c, LawStage.DidIt); + T.Check(EnforceFixtures.RunUntil(() => o.IsPrisonerOfColony, EnforceFixtures.SubdueTicks), "not a prisoner; case " + c + ", wait " + c.waitReason); + T.Equal(Now, c.captureTick, "the capture tick"); + Fixtures.Tick(1); + PrisonerInteractionModeDef other = ModsConfig.IdeologyActive && PrisonerInteractionModeDefOf.Enslave != null + ? PrisonerInteractionModeDefOf.Enslave + : PrisonerInteractionModeDefOf.ReduceResistance; + o.guest.SetExclusiveInteraction(other); + T.Equal(other, o.guest.ExclusiveInteractionMode, "the mode written at capture plus 1"); + Fixtures.Tick(1); + T.Equal(PrisonerInteractionModeDefOf.MaintainOnly, o.guest.ExclusiveInteractionMode, "the mode at capture plus 2"); + } + + /// Puts Laws' component before Castes' in Game.components for the test (Castes writes its default a tick after the capture). + private static void MoveLawsComponentFirst() + { + List list = Current.Game.components; + GameComponent_BlaxLaws laws = Fixtures.Comp; + int at = list.FindIndex(x => x.GetType().FullName == "BlaxCastes.GameComponent_BlaxCastes"); + int mine = list.IndexOf(laws); + if (at < 0 || mine < 0 || mine < at) + return; + List before = list.ToList(); + list.Remove(laws); + list.Insert(at, laws); + Fixtures.OnCleanup(() => + { + list.Clear(); + list.AddRange(before); + }); + } + + [BlaxTest("jail: with Prison Labor's work option off the released pawn has the work priorities it had before the arrest; with it on only the work types Prison Labor bars prisoners from are off (needs Prison Labor)")] + public static void PrisonLaborKeepsPriorities() + { + if (!Compat.IsActive(PrisonLaborId)) + T.Skip("needs Prison Labor"); + PrisonerInteractionModeDef work = DefDatabase.GetNamedSilentFail("PrisonLabor_workOption"); + T.NotNull(work, "Prison Labor's PrisonLabor_workOption mode"); + foreach (bool on in new[] { false, true }) + { + Pawn o = EnforceFixtures.Offender(); + Dictionary priorities = EnforceFixtures.Priorities(o); + LawCase c = JailAndRelease(o, () => o.guest.ToggleNonExclusiveInteraction(work, on)); + string diff = PriorityDiff(priorities, o, on); + T.Check(diff == null, "work priorities changed with the work option " + (on ? "on" : "off") + ": " + diff); + T.Check(c.IsClosed, "the case after the release: " + c); + } + } + + /// Prison Labor's work option is on for the prisoner (PrisonLaborUtility.LaborEnabled in its 1.7 PrisonLabor.dll). + private static bool LaborOn(Pawn o) + { + PrisonerInteractionModeDef work = DefDatabase.GetNamedSilentFail("PrisonLabor_workOption"); + return work != null && o.guest != null && o.guest.IsInteractionEnabled(work); + } + + /// + /// The changed work priorities, or null. While Prison Labor's work option is on, its JobGiver_Labor runs + /// WorkSettings.InitWorkSettings, which disables every work type its settings bar prisoners from + /// (WorkSettings.WorkDisabled, Pawn_WorkSettings.Disable), and those stay at 0 after the release: Prison + /// Labor's call, not Laws' (design: "Jail for N days", Overlaps). Only those may read 0 afterwards. + /// + private static string PriorityDiff(Dictionary before, Pawn o, bool labor) + { + Func barred = _ => false; + if (labor) + { + MethodInfo m = GenTypes.GetTypeInAnyAssembly("PrisonLabor.Core.LaborWorkSettings.WorkSettings")? + .GetMethod("WorkDisabled", BindingFlags.Public | BindingFlags.Static, null, new[] { typeof(WorkTypeDef) }, null); + T.NotNull(m, "Prison Labor's WorkSettings.WorkDisabled(WorkTypeDef)"); + barred = wt => (bool)m.Invoke(null, new object[] { wt }); + } + var diff = before.Where(kv => o.workSettings.GetPriority(kv.Key) != kv.Value && !(o.workSettings.GetPriority(kv.Key) == 0 && barred(kv.Key))) + .Select(kv => kv.Key.defName + " " + kv.Value + " to " + o.workSettings.GetPriority(kv.Key)).ToList(); + return diff.Count == 0 ? null : string.Join(", ", diff); + } + + [BlaxTest("jail: with Blax Castes the released pawn is back in its old caste (needs Blax Castes)")] + public static void CastesKeepsCaste() + { + if (!Compat.IsActive(CastesId)) + T.Skip("needs Blax Castes"); + GameComponent castes = Current.Game.components.FirstOrDefault(x => x.GetType().FullName == "BlaxCastes.GameComponent_BlaxCastes"); + T.NotNull(castes, "Castes' game component"); + MethodInfo casteOf = castes.GetType().GetMethod("CasteOf", new[] { typeof(Pawn) }); + T.NotNull(casteOf, "GameComponent_BlaxCastes.CasteOf(Pawn)"); + // A generated colonist joins no caste (Castes' join hooks see no SetFaction or SetGuestStatus), so the + // offender is put into a caste of its own, which no join row names: only "back to its old caste" + // brings it back there after the release. + Type manager = GenTypes.GetTypeInAnyAssembly("BlaxCastes.CasteManager"); + MethodInfo create = manager?.GetMethod("CreateCaste", BindingFlags.Public | BindingFlags.Static); + MethodInfo assign = manager?.GetMethod("Assign", BindingFlags.Public | BindingFlags.Static); + MethodInfo delete = manager?.GetMethod("DeleteCaste", BindingFlags.Public | BindingFlags.Static); + T.Check(create != null && assign != null && delete != null, "CasteManager.CreateCaste, Assign and DeleteCaste"); + object caste = create.Invoke(null, new object[] { "BlaxLawsTest caste" }); + T.NotNull(caste, "the test caste"); + Fixtures.OnCleanup(() => delete.Invoke(null, new[] { caste })); + Pawn o = EnforceFixtures.Offender(); + T.Check((bool)assign.Invoke(null, new object[] { o, caste, false, null }), "fixture: the offender can't join the test caste"); + Fixtures.Tick(2); + object before = casteOf.Invoke(castes, new object[] { o }); + T.Check(Equals(before, caste), "fixture: the offender isn't in the test caste: " + before); + JailAndRelease(o, null); + Fixtures.Tick(5); + object after = casteOf.Invoke(castes, new object[] { o }); + T.Check(Equals(before, after), "the caste after the release isn't the old one: " + before + " to " + after); + } + + /// Jails the pawn through a 1-day row and releases it through the fallback. atJail runs while it is jailed. + private static LawCase JailAndRelease(Pawn o, Action atJail) + { + // The fallback below backdates the release tick by a day. Before day 2 that tick would be negative, + // which Sentences.Check reads as "not set yet" and recomputes from the capture, so the game clock + // is moved past a day first, before anything of this test is scheduled. + if (Now < 2 * Sentences.FallbackTicks) + Find.TickManager.DebugSetTicksGame(2 * Sentences.FallbackTicks); + EnforceFixtures.PrisonCell(); + EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 6f)); + LawCase c = EnforceFixtures.ActCase(o, "Jail", 1); + Enforcement.Enqueue(c, LawStage.DidIt); + // An arrested colonist turns prisoner when the warden picks it up (JobDriver_TakeToBed.cs:124-129) and + // stays held, not spawned, until it is tucked in; the fallback releases only a spawned pawn. atJail runs + // at the pick-up, before the prisoner thinks once (Prison Labor's default work option is set there). + T.Check(EnforceFixtures.RunUntil(() => o.IsPrisonerOfColony, EnforceFixtures.SubdueTicks), "not a prisoner; case " + c + ", wait " + c.waitReason); + atJail?.Invoke(); + T.Check(EnforceFixtures.RunUntil(() => o.Spawned && o.InBed(), EnforceFixtures.SubdueTicks), + "the prisoner isn't in its bed; case " + c + ", prisoner " + o.IsPrisonerOfColony + ", spawned " + o.Spawned); + Fixtures.Tick(5); + c.releaseTick = Now - Sentences.FallbackTicks - 1; + Sentences.Check(c); + T.Check(!o.IsPrisonerOfColony, "the fallback didn't release the pawn; case " + c + ", spawned " + o.Spawned + ", in bed " + o.InBed()); + return c; + } + + // ---- the arrest ------------------------------------------------------------------- + + [BlaxTest("jail: an arrest interrupted after its first toil leaves the colonist its old bed by the next sweep; a bed someone else claimed meanwhile stays theirs")] + public static void OldBedBack() + { + PrisonRoom room = EnforceFixtures.PrisonCell(); + Pawn o = EnforceFixtures.Offender(); + EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 4f, 8f)); + Building_Bed own = EnforceFixtures.ColonistBed(o.Position); + T.Check(o.ownership.ClaimBedIfNonMedical(own), "fixture: the colonist can't claim its bed"); + // Bystanders without a bed would take the freed bed when they go to sleep before the sweep: the case + // of a bed someone else claimed, which the second half tests on purpose. + EnforceFixtures.BedsForBystanders(o); + LawCase c = EnforceFixtures.ActCase(o, "Jail", 3); + EnforceFixtures.Dispatch(c, LawStage.DidIt); + T.Check(JailFlow.ArrestRuns(c), "no arrest started; wait " + c.waitReason); + T.Equal(own, c.oldBed, "the old bed noted in the case"); + T.Check(o.ownership.OwnedBed == room.bed, "the arrest's first toil didn't claim the prisoner bed: " + o.ownership.OwnedBed); + + Pawn raider = EnforceFixtures.Raider(); // keeps the retry waiting, so the sweep's give-back shows + c.enforcer.jobs.EndCurrentJob(JobCondition.InterruptForced); + Fixtures.Tick(Enforcement.SweepInterval + 1); + T.Check(o.ownership.OwnedBed == own, "the colonist doesn't own its old bed after the sweep: it owns " + (o.ownership.OwnedBed?.ToString() ?? "no bed") + + ", the old bed's owners " + Owners(own) + "; case " + c + ", wait " + c.waitReason + ", arrest runs " + JailFlow.ArrestRuns(c)); + T.Equal(WaitReasons.Danger, c.waitReason, "the case's wait while the raider is on the map"); + + raider.Destroy(DestroyMode.Vanish); + T.Check(EnforceFixtures.RunUntil(() => JailFlow.ArrestRuns(c), Enforcement.SweepInterval + 5), "no second arrest; wait " + c.waitReason); + T.Check(o.ownership.OwnedBed == room.bed, "the second arrest didn't claim the prisoner bed"); + Pawn other = EnforceFixtures.Offender(EnforceFixtures.CellNear(o.Position, 6f, 12f)); + T.Check(other.ownership.ClaimBedIfNonMedical(own), "fixture: another colonist can't claim the free old bed"); + EnforceFixtures.Raider(); + c.enforcer.jobs.EndCurrentJob(JobCondition.InterruptForced); + Fixtures.Tick(Enforcement.SweepInterval + 1); + T.Check(own.OwnersForReading.Contains(other), "the other colonist lost the bed it claimed"); + T.Check(!own.OwnersForReading.Contains(o), "the offender took back a bed someone else claimed"); + } + + [BlaxTest("jail: a raid that lands while the arrest walks to the colonist calls it off, gives the old bed back and waits for the danger; after the raid the sweep arrests")] + public static void RaidCallsOffArrest() + { + PrisonRoom room = EnforceFixtures.PrisonCell(); + Pawn o = EnforceFixtures.Offender(); + EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 4f, 8f)); + Building_Bed own = EnforceFixtures.ColonistBed(o.Position); + T.Check(o.ownership.ClaimBedIfNonMedical(own), "fixture: the colonist can't claim its bed"); + EnforceFixtures.BedsForBystanders(o); + LawCase c = EnforceFixtures.ActCase(o, "Jail", 3); + EnforceFixtures.Dispatch(c, LawStage.DidIt); + T.Check(JailFlow.ArrestRuns(c), "fixture: no arrest started; wait " + c.waitReason); + T.Check(!c.enforcer.IsCarryingPawn(o), "fixture: the warden already carries the colonist"); + Pawn raider = EnforceFixtures.Raider(); + // The worker's sweep directly, so the arrest can't finish between the raid and the check. + BlaxLawsDefOf.Jail.Worker.Sweep(c); + T.Check(!JailFlow.ArrestRuns(c), "the arrest still runs during the raid"); + T.Check(!EnforceFixtures.AnyEnforcementJobOn(o), "an enforcement job on the colonist during the raid"); + T.Equal(CaseStatus.Open, c.status, "status during the raid"); + T.Equal(WaitReasons.Danger, c.waitReason, "wait reason during the raid"); + T.Check(!o.IsPrisonerOfColony, "a prisoner during the raid"); + T.Check(o.ownership.OwnedBed == own, "the old bed wasn't given back: owns " + (o.ownership.OwnedBed?.ToString() ?? "no bed")); + raider.Destroy(DestroyMode.Vanish); + T.Check(EnforceFixtures.RunUntil(() => JailFlow.ArrestRuns(c) || o.IsPrisonerOfColony, Enforcement.SweepInterval + 5), "no arrest after the raid; wait " + c.waitReason); + T.Check(o.ownership.OwnedBed == room.bed || o.IsPrisonerOfColony, "the second arrest didn't claim the prisoner bed"); + } + + [BlaxTest("jail: a raid that lands while the warden already carries the arrested colonist doesn't call the arrest off: the carry finishes and the case is jailed")] + public static void RaidLetsCarryFinish() + { + PrisonRoom room = EnforceFixtures.PrisonCell(); + Pawn o = EnforceFixtures.Offender(); + EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 4f, 8f)); + EnforceFixtures.BedsForBystanders(o); + LawCase c = EnforceFixtures.ActCase(o, "Jail", 3); + EnforceFixtures.Dispatch(c, LawStage.DidIt); + T.Check(JailFlow.ArrestRuns(c), "fixture: no arrest started; wait " + c.waitReason); + Pawn enforcer = c.enforcer; + T.Check(EnforceFixtures.RunUntil(() => enforcer.IsCarryingPawn(o), EnforceFixtures.SubdueTicks), + "fixture: the warden never carried the colonist; case " + c + ", warden on " + (enforcer.CurJobDef?.defName ?? "no job")); + EnforceFixtures.Raider(); + // A carried pawn is despawned, so the raider counts through the enforcer's map (Raider() checks the threat). + T.Check(GenHostility.AnyHostileActiveThreatToPlayer(enforcer.Map), "fixture: the raider is no threat on the warden's map"); + // The worker's sweep directly, while the warden carries the colonist. + BlaxLawsDefOf.Jail.Worker.Sweep(c); + T.Check(JailFlow.ArrestRuns(c), "the arrest was called off mid-carry"); + T.Check(enforcer.IsCarryingPawn(o), "the warden dropped the colonist"); + T.Check(c.waitReason != WaitReasons.Danger, "the case waits for the danger while the carry goes on"); + T.Check(EnforceFixtures.RunUntil(() => c.status == CaseStatus.Jailed, EnforceFixtures.SubdueTicks), + "the carry didn't end in a jailing with the raider on the map; case " + c + ", wait " + c.waitReason); + T.Check(o.IsPrisonerOfColony && o.ownership.OwnedBed == room.bed, "the colonist isn't a prisoner owning the cell's bed: " + (o.ownership.OwnedBed?.ToString() ?? "no bed")); + } + + private static string Owners(Building_Bed bed) + { + List owners = bed.OwnersForReading; + if (owners.Count == 0) + return "none"; + return string.Join(", ", owners.Select(p => p.LabelShort + (p.Awake() ? " (awake)" : " (asleep)"))); + } + + [BlaxTest("jail: a 5-day row whose guilt ran out while no prisoner bed existed: once a bed is built the arrest is accepted against Social 0 and the release comes 5 days after the capture")] + public static void LateArrest() + { + Pawn o = EnforceFixtures.Offender(); + EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 6f)); + SocialZeroForAll(); + LawCase c = EnforceFixtures.ActCase(o, "Jail", 5); + EnforceFixtures.Dispatch(c, LawStage.DidIt); + T.Equal(WaitReasons.NoBed, c.waitReason, "the wait without a prisoner bed"); + T.Check(o.guilt.TicksUntilInnocent >= 5 * GenDate.TicksPerDay - 30, "no guilt for the sentence at filing: " + o.guilt.TicksUntilInnocent); + o.guilt.Notify_Guilty(0); // the six days without a bed: the guilt from filing has run out + T.Check(!o.guilt.IsGuilty, "fixture: the guilt didn't run out"); + + EnforceFixtures.PrisonCell(); + int guiltAtArrest = -1; + bool jailed = EnforceFixtures.RunUntil(() => + { + if (guiltAtArrest < 0 && JailFlow.ArrestRuns(c)) + guiltAtArrest = o.guilt.TicksUntilInnocent; + return o.IsPrisonerOfColony || o.InMentalState; + }, Enforcement.SentenceInterval + EnforceFixtures.SubdueTicks); + T.Check(guiltAtArrest >= 6 * GenDate.TicksPerDay - 30, "guilt when the arrest started: " + guiltAtArrest); + T.Check(!o.InMentalState, "the arrest was refused: " + o.MentalStateDef?.defName); + T.Check(jailed, "no arrest after the bed was built; case " + c + ", wait " + c.waitReason); + T.Equal(c.captureTick + 5 * GenDate.TicksPerDay, c.releaseTick, "the release tick"); + } + + /// Every free colonist's Social at 0 for the test, restored after. + private static void SocialZeroForAll() + { + var old = new List<(SkillRecord skill, int level)>(); + foreach (Pawn p in EnforceFixtures.Map.mapPawns.FreeColonistsSpawned) + { + SkillRecord s = p.skills?.GetSkill(SkillDefOf.Social); + if (s == null) + continue; + old.Add((s, s.Level)); + s.Level = 0; + } + Fixtures.OnCleanup(() => + { + foreach (var (skill, level) in old) + skill.Level = level; + }); + } + + [BlaxTest("jail: no prisoner bed gives one letter and no arrest; building one leads to the arrest at the next sweep")] + public static void NoPrisonerBed() + { + Pawn o = EnforceFixtures.Offender(); + EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 6f)); + LawCase c = EnforceFixtures.ActCase(o, "Jail", 3); + string label = "BlaxLaws_LetterNoBedLabel".Translate(c.OffenderLabel); + EnforceFixtures.Dispatch(c, LawStage.DidIt); + T.Equal(WaitReasons.NoBed, c.waitReason, "the wait without a prisoner bed"); + EnforceFixtures.TickPastSentenceSweep(); + EnforceFixtures.TickPastSentenceSweep(); + T.Equal(1, EnforceFixtures.LettersLabeled(label), "no-bed letters"); + T.Check(!EnforceFixtures.AnyEnforcementJobOn(o), "an arrest started without a bed"); + EnforceFixtures.PrisonCell(); + bool arrest = EnforceFixtures.RunUntil(() => JailFlow.ArrestRuns(c) || o.IsPrisonerOfColony, Enforcement.SentenceInterval + 5); + T.Check(arrest, "no arrest after the bed was built; wait " + c.waitReason); + } + + // ---- holds and fallbacks ---------------------------------------------------------- + + [BlaxTest("jail: a role holder gets no arrest and one letter; Arrest now arrests (needs Ideology)")] + public static void HoldRoleHolder() + { + T.NeedsDlc("Ideology", ModsConfig.IdeologyActive); + Pawn o = null; + for (int i = 0; i < 10 && o == null; i++) + { + Pawn candidate = EnforceFixtures.Offender(); + if (GiveRole(candidate)) + o = candidate; + } + if (o == null) + T.Skip("ten generated colonists met the requirements of no role of their ideoligion"); + Fixtures.Tick(1); + T.Check(DlcSupport.HoldsRole(o), "fixture: the colonist holds no role after a tick"); + CheckHoldAndArrestNow(o); + } + + [BlaxTest("jail: a mechanitor with a mech gets no arrest and one letter; Arrest now arrests (needs Biotech)")] + public static void HoldMechanitor() + { + T.NeedsDlc("Biotech", ModsConfig.BiotechActive); + Pawn o = EnforceFixtures.Offender(); + MakeMechanitor(o, keep: false); + CheckHoldAndArrestNow(o); + } + + [BlaxTest("jail: a pawn that becomes a mechanitor with a mech while its case waits for a bed is held, not arrested (needs Biotech)")] + public static void HoldAfterOtherWait() + { + T.NeedsDlc("Biotech", ModsConfig.BiotechActive); + Pawn o = EnforceFixtures.Offender(); + EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 6f)); + LawCase c = EnforceFixtures.ActCase(o, "Jail", 3); + EnforceFixtures.Dispatch(c, LawStage.DidIt); + T.Equal(WaitReasons.NoBed, c.waitReason, "fixture: the wait without a prisoner bed"); + MakeMechanitor(o, keep: false); + EnforceFixtures.PrisonCell(); + JailFlow.TryArrest(c, ignoreHold: false); + T.Equal(WaitReasons.Hold, c.waitReason, "the wait after the pawn got a mech"); + T.Check(!JailFlow.ArrestRuns(c) && !o.IsPrisonerOfColony, "Laws arrested a mechanitor on its own after a bed wait"); + T.Check(!c.holdLifted, "the hold counts as lifted without Arrest now"); + } + + /// + /// Gives the colonist a mechlink and a lifter it oversees (needs Biotech). With keep the mech stays for + /// phase 2 and the relation is left in place; otherwise the cleanup removes the relation. + /// + private static void MakeMechanitor(Pawn o, bool keep) + { + o.health.AddHediff(HediffDefOf.MechlinkImplant, o.health.hediffSet.GetBrain()); + T.Check(MechanitorUtility.IsMechanitor(o), "fixture: the mechlink made no mechanitor"); + PawnKindDef kind = DefDatabase.GetNamedSilentFail("Mech_Lifter"); + T.NotNull(kind, "PawnKindDef Mech_Lifter"); + Pawn mech = Fixtures.Spawn(Fixtures.Generate(kind, Faction.OfPlayer), EnforceFixtures.CellNear(o.Position, 2f, 5f)); + o.relations.AddDirectRelation(PawnRelationDefOf.Overseer, mech); + o.mechanitor.Notify_BandwidthChanged(); // rebuilds ControlledPawns from the control groups (Pawn_MechanitorTracker.cs:268-290) + if (keep) + Fixtures.Keep(mech); + else + Fixtures.OnCleanup(() => + { + if (o.relations.DirectRelationExists(PawnRelationDefOf.Overseer, mech)) + o.relations.RemoveDirectRelation(PawnRelationDefOf.Overseer, mech); + }); + T.Check(DlcSupport.IsMechanitorWithMechs(o), "fixture: the mechanitor controls no mech"); + } + + private static void CheckHoldAndArrestNow(Pawn o) + { + EnforceFixtures.PrisonCell(); + EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 6f)); + LawCase c = EnforceFixtures.ActCase(o, "Jail", 3); + string label = "BlaxLaws_LetterHoldLabel".Translate(c.OffenderLabel); + EnforceFixtures.Dispatch(c, LawStage.DidIt); + T.Equal(WaitReasons.Hold, c.waitReason, "the wait of a held pawn"); + Fixtures.Tick(Enforcement.SweepInterval + 1); + T.Check(!EnforceFixtures.AnyEnforcementJobOn(o), "a held pawn was arrested"); + T.Equal(1, EnforceFixtures.LettersLabeled(label), "hold letters"); + T.Check(Sentences.CanArrestNow(c), "Arrest now isn't offered"); + o.guilt.Notify_Guilty(0); + Sentences.ArrestNow(c); + T.Check(JailFlow.ArrestRuns(c), "Arrest now started no arrest; wait " + c.waitReason); + T.Check(o.guilt.TicksUntilInnocent >= 4 * GenDate.TicksPerDay - 30, "Arrest now didn't renew the guilt: " + o.guilt.TicksUntilInnocent); + Fixtures.Tick(Enforcement.SweepInterval + 1); + T.Check(JailFlow.ArrestRuns(c) || o.IsPrisonerOfColony, "the sweep put the hold back; wait " + c.waitReason); + } + + /// + /// Gives the colonist a role of its ideoligion whose requirements it meets, a multi role when there is + /// one, among the active roles; undone before the cleanup. Returns false when no role fits. A role whose requirements the pawn + /// misses (a skill, not a child) is taken away again on the next role tick (Precept_RoleSingle.cs:66-70; + /// Precept_Role.cs:508-520, 582-597). + /// + private static bool GiveRole(Pawn o) + { + Ideo ideo = o.Ideo; + if (ideo == null) + return false; + Precept_Role role = ideo.PreceptsListForReading.OfType().FirstOrDefault(r => r.Active && r.RequirementsMet(o)) + ?? (Precept_Role)ideo.PreceptsListForReading.OfType().FirstOrDefault(r => r.Active && r.RequirementsMet(o)); + if (role == null) + return false; + Pawn previous = (role as Precept_RoleSingle)?.ChosenPawnValue; + role.Assign(o, addThoughts: false); + Fixtures.OnCleanup(() => + { + if (role.IsAssigned(o)) + role.Unassign(o, generateThoughts: false); + if (previous != null && !previous.Destroyed && role is Precept_RoleSingle single && single.ChosenPawnValue == null) + single.Assign(previous, addThoughts: false); + }); + return true; + } + + [BlaxTest("jail: a slave in a binge with a jail row is subdued; the same row outside a break warns (needs Ideology)")] + public static void SlaveFallsBack() + { + Pawn slave = EnforceFixtures.Ready(Fixtures.ColonySlave()); + EnforceFixtures.Warden(EnforceFixtures.CellNear(slave.Position, 2f, 5f)); + LawCase quiet = EnforceFixtures.ActCase(slave, "Jail", 3); + EnforceFixtures.Dispatch(quiet, LawStage.DidIt); + T.Check(quiet.IsClosed && quiet.outcome == CaseOutcomes.Warned, "the slave's case outside a break: " + quiet); + T.Check(!slave.IsPrisoner && !EnforceFixtures.AnyEnforcementJobOn(slave), "the slave was arrested outside a break"); + + EnforceFixtures.ForceBreak(slave, EnforceFixtures.DrugBinge); + LawCase binge = EnforceFixtures.BreakCase(slave, "Jail", LawStage.DidIt, 3); + EnforceFixtures.Dispatch(binge, LawStage.DidIt); + T.Equal("Subdue", binge.activePunishment, "the binging slave's punishment"); + T.Check(SubdueFlow.Runs(binge), "no subdue for the binging slave; wait " + binge.waitReason); + T.Check(!slave.IsPrisoner, "the slave was jailed"); + } + + // ---- the early end and the fallback ----------------------------------------------- + + [BlaxTest("jail: recruiting the jailed pawn closes the sentence as released early")] + public static void RecruitEndsEarly() + { + Pawn o = EnforceFixtures.Offender(); + Pawn warden = EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 5f)); + LawCase c = EnforceFixtures.JailDirect(o, warden, 3); + RecruitUtility.Recruit(o, Faction.OfPlayer, warden); + T.Check(!o.IsPrisonerOfColony, "fixture: the recruited pawn is still a prisoner"); + Sentences.Check(c); + T.Check(c.IsClosed && c.outcome == CaseOutcomes.ReleasedEarly, "the case after the recruitment: " + c); + } + + [BlaxTest("jail: a day after the sentence without a release, Laws releases the pawn in place")] + public static void FallbackRelease() + { + // A release tick a day and a tick in the past must be a real tick (-1 means "not set yet"). + if (Now < Sentences.FallbackTicks + 1) + Fixtures.Tick(Sentences.FallbackTicks + 1 - Now); + Pawn o = EnforceFixtures.Offender(); + Pawn warden = EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 5f)); + LawCase c = EnforceFixtures.JailDirect(o, warden, 3); + c.releaseTick = Now - Sentences.FallbackTicks - 1; + Sentences.Check(c); + T.Check(!o.IsPrisonerOfColony && o.IsFreeColonist, o.LabelShort + " isn't free after the fallback"); + T.NotNull(o.needs.mood.thoughts.memories.GetFirstMemoryOfDef(ThoughtDefOf.WasImprisoned), "WasImprisoned after the fallback"); + T.Check(c.IsClosed && c.outcome == CaseOutcomes.Served, "the case after the fallback: " + c); + } + + [BlaxTest("jail: repealing the law of a jailed pawn sets Release on it")] + public static void RepealReleases() + { + Pawn o = EnforceFixtures.Offender(); + Pawn warden = EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 5f)); + LawCase c = EnforceFixtures.JailDirect(o, warden, 3); + Sentences.WriteMaintainOnly(c); + string confirm = LawbookUi.DeleteConfirmText(c.LawFor(LawStage.DidIt)) ?? ""; + T.Check(confirm.Contains("Release"), "the delete confirmation doesn't say the jailed pawn is set to Release: " + confirm); + T.Equal(1, Lawbook.Delete(c.LawFor(LawStage.DidIt)), "cases the repeal closed"); + T.Check(c.IsClosed && c.outcome == CaseOutcomes.Repealed, "the case after the repeal: " + c); + T.Equal(PrisonerInteractionModeDefOf.Release, o.guest.ExclusiveInteractionMode, "the jailed pawn's mode after the repeal"); + } + + // ---- save and removal --------------------------------------------------------------- + + private const string JailSaveKey = "jail.savedPrisoner"; + + [BlaxTest("jail save: a colonist jailed for 50 days at the first save (setup)")] + public static void JailSaveSetup() + { + T.CarryAtSave(JailSaveKey, JailForSave); + } + + private static string JailForSave() + { + PrisonRoom room = EnforceFixtures.PrisonCell(keep: true); + Pawn o = Fixtures.Keep(EnforceFixtures.Offender(room.inside)); + Pawn warden = Fixtures.Keep(EnforceFixtures.Warden()); + LawCase c = EnforceFixtures.JailDirect(o, warden, 50); + Fixtures.KeepLaw(c.LawFor(LawStage.DidIt)); + Sentences.WriteMaintainOnly(c); + return c.id + "|" + o.ThingID + "|" + c.captureTick; + } + + [BlaxTest("jail save: the jailed colonist is still Laws' prisoner on Maintain only after the reload", phase: 2)] + public static void JailSaveRoundTrip() + { + T.Check(T.Carry.TryGetValue(JailSaveKey, out string carry) && !carry.NullOrEmpty(), "the phase-1 jail setup did not run"); + string[] parts = carry.Split('|'); + LawCase c = Fixtures.Comp.CaseById(int.Parse(parts[0])); + Pawn o = Fixtures.FindPawnById(parts[1]); + T.NotNull(c, "the jail case after the reload"); + T.NotNull(o, "the jailed colonist after the reload"); + T.Check(c.offender == o, "the case's offender didn't resolve"); + T.Equal(CaseStatus.Jailed, c.status, "the case's status"); + T.Equal(int.Parse(parts[2]), c.captureTick, "the capture tick"); + T.Equal(c.captureTick + 50 * GenDate.TicksPerDay, c.releaseTick, "the release tick"); + T.Check(c.maintainOnlyDone, "maintainOnlyDone after the reload"); + T.Check(o.IsPrisonerOfColony, o.LabelShort + " isn't a prisoner after the reload"); + T.Equal(PrisonerInteractionModeDefOf.MaintainOnly, o.guest.ExclusiveInteractionMode, "the mode after the reload"); + } + + private const string HoldSaveKey = "jail.holdLifted"; + + [BlaxTest("jail save: a mechanitor's case with Arrest now pressed at the first save (setup, needs Biotech)")] + public static void HoldLiftSaveSetup() + { + T.NeedsDlc("Biotech", ModsConfig.BiotechActive); + T.CarryAtSave(HoldSaveKey, HoldLiftForSave); + } + + private static string HoldLiftForSave() + { + Pawn o = Fixtures.Keep(EnforceFixtures.Offender()); + Fixtures.Keep(EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 6f))); + MakeMechanitor(o, keep: true); + LawCase c = EnforceFixtures.ActCase(o, "Jail", 3); + Fixtures.KeepLaw(c.LawFor(LawStage.DidIt)); + EnforceFixtures.Dispatch(c, LawStage.DidIt); + if (c.waitReason != WaitReasons.Hold) + throw new InvalidOperationException("the mechanitor's case waits for " + (c.waitReason ?? "nothing") + ", not the hold"); + Sentences.ArrestNow(c); + // The state a failed arrest leaves (PunishmentWorker_Jail.Sweep): no job, Open, no wait. + JailFlow.EndArrest(c); + c.status = CaseStatus.Open; + c.waitReason = null; + return c.id + "|" + o.ThingID; + } + + [BlaxTest("jail save: Arrest now still holds after the reload; a failed arrest retries without a second hold", phase: 2)] + public static void HoldLiftRoundTrip() + { + T.NeedsDlc("Biotech", ModsConfig.BiotechActive); + T.Check(T.Carry.TryGetValue(HoldSaveKey, out string carry) && !carry.NullOrEmpty(), "the phase-1 hold setup did not run"); + string[] parts = carry.Split('|'); + T.Check(parts.Length == 2, "carry: " + carry); + LawCase c = Fixtures.Comp.CaseById(int.Parse(parts[0])); + Pawn o = Fixtures.FindPawnById(parts[1]); + T.NotNull(c, "the held case after the reload"); + T.NotNull(o, "the mechanitor after the reload"); + T.Check(DlcSupport.IsMechanitorWithMechs(o), "fixture: the mechanitor lost its mech in the reload"); + T.Check(c.holdLifted, "holdLifted after the reload"); + T.Check(c.waitReason != WaitReasons.Hold, "a sweep after the reload put the hold back"); + if (!JailFlow.ArrestRuns(c) && !o.IsPrisonerOfColony) + { + c.status = CaseStatus.Open; + c.waitReason = null; + JailFlow.TryArrest(c, ignoreHold: false); + T.Check(c.waitReason != WaitReasons.Hold && !Sentences.CanArrestNow(c), "the retry after the reload went back to the hold; wait " + c.waitReason); + } + } + + [BlaxTest("removal: the colonist Laws jailed is still a prisoner of the colony", phase: 3)] + public static void JailedAfterRemoval() + { + T.Check(T.Carry.TryGetValue(JailSaveKey, out string carry) && !carry.NullOrEmpty(), "the phase-1 jail setup did not run"); + Pawn o = Fixtures.FindPawnById(carry.Split('|')[1]); + T.NotNull(o, "the jailed colonist after the removal"); + T.Check(o.IsPrisonerOfColony, o.LabelShort + " isn't a prisoner of the colony after the removal"); + T.Equal(0, Fixtures.Comp.Cases.Count, "cases in the fresh component"); + } + } +} diff --git a/Tests/BlaxLawsTests/Source/QuickTestMap.cs b/Tests/BlaxLawsTests/Source/QuickTestMap.cs new file mode 100644 index 0000000..ad587cf --- /dev/null +++ b/Tests/BlaxLawsTests/Source/QuickTestMap.cs @@ -0,0 +1,53 @@ +using HarmonyLib; +using RimWorld; +using RimWorld.Planet; +using Verse; + +namespace BlaxLawsTests +{ + /// + /// The vanilla quick test picks a random tile at 250x250 (Root_Play.cs:94-96), and a hilly or mountainous + /// tile can leave too little open ground for the fixtures. While -blaxlawstests is on, the quick-test map + /// is 325x325 on a flat or small-hills tile, as in Blax Zones' suite. The tile and every position on it + /// still vary per run. + /// + [StaticConstructorOnStartup] + public static class QuickTestMap + { + public const int MapSize = 325; + private const int TileAttempts = 200; + + static QuickTestMap() + { + if (!TestRunner.Enabled) + return; + new Harmony("blax.laws.tests.quicktestmap").Patch( + AccessTools.Method(typeof(Root_Play), nameof(Root_Play.SetupForQuickTestPlay)), + postfix: new HarmonyMethod(typeof(QuickTestMap), nameof(Postfix))); + // Jail tests tick whole days, so the autosaver fires. Its "Autosaving" long event is synchronous with + // text, so it waits to be drawn (LongEventHandler.cs:52-58, 410-413), which never happens headless, and + // every later long event, the suite's own save+reload included, queues behind it forever. + new Harmony("blax.laws.tests.noautosave").Patch( + AccessTools.Method(typeof(Autosaver), nameof(Autosaver.AutosaverTick)), + prefix: new HarmonyMethod(typeof(QuickTestMap), nameof(SkipAutosave))); + // Before the world and map are made, so every pawn vanilla makes for a book or tale is known. + TestRunner.HookPawnWatchers(); + } + + public static bool SkipAutosave() => false; + + public static void Postfix() + { + GameInitData init = Find.GameInitData; + init.mapSize = MapSize; + for (int i = 0; i < TileAttempts && !Open(init.startingTile); i++) + init.startingTile = TileFinder.RandomStartingTile(); + } + + private static bool Open(PlanetTile tile) + { + Hilliness h = Find.WorldGrid[tile].hilliness; + return h == Hilliness.Flat || h == Hilliness.SmallHills; + } + } +} diff --git a/Tests/BlaxLawsTests/Source/SmokeTests.cs b/Tests/BlaxLawsTests/Source/SmokeTests.cs new file mode 100644 index 0000000..04d9c85 --- /dev/null +++ b/Tests/BlaxLawsTests/Source/SmokeTests.cs @@ -0,0 +1,220 @@ +using System.Collections.Generic; +using System.Linq; +using BlaxLaws; +using HarmonyLib; +using RimWorld; +using Verse; + +namespace BlaxLawsTests +{ + /// The skeleton and the harness work: patches, settings, defs, the component, the empty book, all three phases. + public static class SmokeTests + { + private static readonly string[] SharedKeys = + { + "BlaxLaws_NeedsDlc", "BlaxLaws_MissingMod", "BlaxLaws_Stage_Planning", "BlaxLaws_Stage_DidIt", + "BlaxLaws_Severity_Minor", "BlaxLaws_Severity_Moderate", "BlaxLaws_Severity_Serious", "BlaxLaws_Severity_Grave", + "BlaxLaws_Status_Open", "BlaxLaws_Status_Enforcing", "BlaxLaws_Status_Jailed", "BlaxLaws_Status_Closed", + "BlaxLaws_Outcome_Repealed", "BlaxLaws_Outcome_BreakEnded", "BlaxLaws_Outcome_NotEnforced", + "BlaxLaws_DrugOption_Any", "BlaxLaws_DrugOption_Hard", "BlaxLaws_DrugOption_Social", + "BlaxLaws_EmptyBook", "BlaxLaws_CaseFiled", + "BlaxLaws_SettingEnforceLaws", "BlaxLaws_SettingShowTab", "BlaxLaws_SettingCaseMessages", "BlaxLaws_SettingJailLetters", + "BlaxLaws_SettingEnforcers", "BlaxLaws_EnforcersWardensFirst", "BlaxLaws_EnforcersWardensOnly", + "BlaxLaws_SettingSubdueCatharsis", "BlaxLaws_SettingPlayerOrdersExempt", "BlaxLaws_SettingCooldownDays", + "BlaxLaws_SettingKeepClosedDays", "BlaxLaws_SettingsReset", + }; + + [BlaxTest("startup: every patch class applied and logged, no errors mentioning Blax Laws")] + public static void StartupLogged() + { + int ours = Harmony.GetAllPatchedMethods() + .Select(Harmony.GetPatchInfo) + .Where(info => info != null) + .SelectMany(info => info.Prefixes.Concat(info.Postfixes).Concat(info.Finalizers).Concat(info.Transpilers)) + .Count(p => p.owner == BlaxLawsStartup.HarmonyId); + T.Info("patch classes applied: " + BlaxLawsStartup.Applied + ", Harmony patches owned by " + BlaxLawsStartup.HarmonyId + ": " + ours); + T.Check(BlaxLawsStartup.FailedPatches.Count == 0, "patch classes failed: " + string.Join(", ", BlaxLawsStartup.FailedPatches)); + // Only what was logged before the first test: later tests log expected errors on purpose. + var startup = TestRunner.StartupLog; + string line = startup.FirstOrDefault(m => m.text != null && m.text.Contains("[Blax Laws]") && m.text.Contains("patches applied"))?.text; + T.Check(line != null, "startup line '[Blax Laws] N patches applied' not in the log"); + T.Check(line.Contains("[Blax Laws] " + BlaxLawsStartup.Applied + " patches applied"), "startup line names another count: " + line); + var errors = startup.Where(m => m.type == LogMessageType.Error && m.text != null && (m.text.Contains("Blax Laws") || m.text.Contains("BlaxLaws"))).ToList(); + T.Check(errors.Count == 0, "errors mentioning Blax Laws at startup: " + string.Join(" | ", errors.Take(3).Select(e => e.text))); + var warnings = startup.Where(m => m.type == LogMessageType.Warning && m.text != null && (m.text.Contains("Blax Laws") || m.text.Contains("BlaxLaws"))).ToList(); + T.Check(warnings.Count == 0, "warnings mentioning Blax Laws at startup: " + string.Join(" | ", warnings.Take(3).Select(e => e.text))); + } + + [BlaxTest("startup: every Blax Laws finalizer returns void, so Harmony rethrows exceptions with their stack trace")] + public static void FinalizersReturnVoid() + { + // One finalizer returning Exception on a method makes Harmony "throw ex" instead of "rethrow" + // (0Harmony EmitFinalizers), which cuts the inner frames off every exception passing through it. + var finalizers = Harmony.GetAllPatchedMethods() + .Select(Harmony.GetPatchInfo) + .Where(info => info != null) + .SelectMany(info => info.Finalizers) + .Where(p => p.owner == BlaxLawsStartup.HarmonyId) + .ToList(); + T.Info("Blax Laws finalizers: " + finalizers.Count); + var bad = finalizers.Where(p => p.PatchMethod.ReturnType != typeof(void)).Select(p => p.PatchMethod.DeclaringType?.Name).ToList(); + T.Check(bad.Count == 0, "finalizers that return a value: " + string.Join(", ", bad)); + } + + [BlaxTest("startup: settings, shared strings, defs and exactly one game component")] + public static void Loaded() + { + T.NotNull(BlaxLawsMod.Settings, "BlaxLawsMod.Settings"); + var missing = SharedKeys.Where(k => !k.CanTranslate()).ToList(); + T.Check(missing.Count == 0, "strings missing from Keyed: " + string.Join(", ", missing)); + + T.NotNull(BlaxLawsDefOf.Warn, "PunishmentDef Warn"); + T.NotNull(BlaxLawsDefOf.Guilty, "PunishmentDef Guilty"); + T.NotNull(BlaxLawsDefOf.Subdue, "PunishmentDef Subdue"); + T.NotNull(BlaxLawsDefOf.Jail, "PunishmentDef Jail"); + T.NotNull(BlaxLawsDefOf.SubdueThenJail, "PunishmentDef SubdueThenJail"); + T.NotNull(BlaxLawsDefOf.BlaxLaws_Subdue, "JobDef BlaxLaws_Subdue"); + T.Check(!BlaxLawsDefOf.BlaxLaws_Subdue.suspendable, "BlaxLaws_Subdue is suspendable, so an interrupt would queue it into the save"); + T.NotNull(BlaxLawsDefOf.BlaxLaws_Laws, "MainButtonDef BlaxLaws_Laws"); + foreach (string cat in ActCategories.All) + T.NotNull(DefDatabase.GetNamedSilentFail(cat), "ActCategoryDef " + cat); + foreach (string act in new[] { SpecialActs.SetFire, SpecialActs.DisplayedCorpse, SpecialActs.StartedSocialFight }) + T.NotNull(DefDatabase.GetNamedSilentFail(act), "ActDef " + act); + T.Equal(6, DefDatabase.DefCount, "BreakLinkDefs"); + + int comps = Current.Game.components.Count(c => c is GameComponent_BlaxLaws); + T.Equal(1, comps, "GameComponent_BlaxLaws in the game"); + T.NotNull(GameComponent_BlaxLaws.Instance, "GameComponent_BlaxLaws.Instance"); + T.Check(GameComponent_BlaxLaws.Instance == Current.Game.GetComponent(), "Instance is not the game's component"); + T.Check(GameComponent_BlaxLaws.Instance.SaveToken != 0, "the save token is 0"); + } + + [BlaxTest("new game: an empty book, no cases, every watch flag off, nothing queued")] + public static void EmptyBook() + { + // The new game as the suite found it, before any test ran (tests of other classes run first). + TestRunner.NewGameState start = TestRunner.AtStart; + T.NotNull(start, "the state at the start of the suite"); + T.Equal(0, start.laws, "rows in a new game"); + T.Equal(0, start.cases, "cases in a new game"); + T.Check(!start.watchAny, "Watch.Any is on for an empty book"); + T.Check(!start.categoryFlag, "a category flag is on for an empty book"); + T.Check(!start.specialFlag, "a special act flag is on for an empty book"); + T.Equal(0, start.pending, "queued enforcement entries"); + + // The book is empty again between tests: the flags are off and an act files nothing. + GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance; + T.Equal(0, comp.Laws.Count, "rows left by earlier tests"); + T.Check(!Watch.Any, "Watch.Any is on for an empty book"); + int cases = comp.Cases.Count; + Pawn p = Fixtures.Colonist(); + T.Check(CaseFiler.Report(new ActEvent(ActCategories.Ate, ThingDefOf.MealSimple, p)) == null, "an act against an empty book filed a case"); + Fixtures.Tick(Enforcement.SweepInterval + 1); + T.Equal(cases, comp.Cases.Count, "cases after ticking an empty book"); + } + + [BlaxTest("settings: cooldown clamps to 0..7 days, kept cases to 7..360, defaults")] + public static void SettingClamps() + { + BlaxLawsSettings s = Fixtures.Settings; + var d = new BlaxLawsSettings(); + T.Equal(1, d.cooldownDays, "default cooldown days"); + T.Equal(60, d.keepClosedDays, "default kept days"); + T.Check(d.enforceLaws && d.showLawsTab && d.caseMessages && d.jailLetters && d.subdueRemovesCatharsis && d.playerOrdersExempt, + "a default toggle is off"); + T.Equal(EnforcerMode.WardensFirst, d.enforcers, "default enforcers"); + s.cooldownDays = -3; + T.Equal(0, s.CooldownDaysClamped, "cooldown -3 clamped"); + s.cooldownDays = 99; + T.Equal(7, s.CooldownDaysClamped, "cooldown 99 clamped"); + T.Equal(7 * GenDate.TicksPerDay, s.CooldownTicks, "cooldown ticks at 7 days"); + s.keepClosedDays = 1; + T.Equal(7, s.KeepClosedDaysClamped, "kept days 1 clamped"); + s.keepClosedDays = 999; + T.Equal(360, s.KeepClosedDaysClamped, "kept days 999 clamped"); + } + + [BlaxTest("settings: Show Laws tab off hides the button at once, on shows it")] + public static void ShowTabLive() + { + MainButtonDef button = BlaxLawsDefOf.BlaxLaws_Laws; + Fixtures.Settings.showLawsTab = false; + BlaxLawsMod.ApplyTabVisibility(); + T.Check(!button.buttonVisible, "buttonVisible stays true with the setting off"); + Fixtures.Settings.showLawsTab = true; + BlaxLawsMod.ApplyTabVisibility(); + T.Check(button.buttonVisible, "buttonVisible stays false with the setting on"); + } + + [BlaxTest("harness: colonist, prisoner, colony slave and child fixtures stand in a district")] + public static void PawnFixtures() + { + Pawn c = Fixtures.Colonist(); + T.Check(c.Spawned && c.IsFreeColonist, "colonist fixture is not a spawned free colonist"); + T.Check(c.GetDistrict() != null, "colonist fixture stands in no district"); + T.Check(Offenders.IsCovered(c), "a free colonist isn't covered by the laws"); + Pawn pr = Fixtures.Prisoner(); + T.Check(pr.IsPrisonerOfColony, "prisoner fixture is not a prisoner of the colony"); + T.Check(!Offenders.IsCovered(pr), "a prisoner is covered by the laws"); + if (ModsConfig.IdeologyActive) + { + Pawn s = Fixtures.ColonySlave(); + T.Check(Offenders.IsCovered(s), "a colony slave isn't covered by the laws"); + } + if (ModsConfig.BiotechActive) + { + Pawn ch = Fixtures.Child(); + T.Check(Offenders.IsCovered(ch), "a colony child isn't covered by the laws"); + T.Check(DlcSupport.IsChild(ch), "DlcSupport.IsChild is false for the child fixture"); + } + if (!ModsConfig.IdeologyActive || !ModsConfig.BiotechActive) + T.Info("slave fixture needs Ideology, child fixture needs Biotech; skipped what is off"); + } + + [BlaxTest("harness: exactly one component after the reload", phase: 2)] + public static void ComponentAfterReload() + { + T.Equal(1, Current.Game.components.Count(c => c is GameComponent_BlaxLaws), "GameComponent_BlaxLaws after the reload"); + T.Check(GameComponent_BlaxLaws.Instance == Current.Game.GetComponent(), "Instance is not the reloaded game's component"); + } + + [BlaxTest("harness: the reload logs no 'Could not resolve reference' warning except for vanilla's unsaved tale pawns, pawns the new world left unsaved and Hospitality's stale lords", phase: 2)] + public static void ReloadResolvesEveryReference() + { + // A reference Blax Laws saves but can't load would show here. Three leaks of other code are excused + // by name: + // - vanilla: a pawn TaleData_Pawn.GenerateRandom made for a book or tale and never saved; + // - vanilla: a pawn a relation already named, with no save holding it, when the suite began (world + // generation, before any test and with an empty lawbook); + // - Hospitality (-Compat): CompGuest.PostSpawnSetup stores Pawn.GetLord() on every humanlike pawn and + // saves it with Scribe_References, and nothing clears it when the pawn leaves the map + // (Hospitality Source/CompGuest.cs, lord). Blax Laws saves no Lord reference. + List all = T.Phase2ResolveWarnings; + List vanilla = all.Where(T.NamesVanillaTalePawn).ToList(); + List atStart = all.Where(w => !vanilla.Contains(w) && T.NamesPawnUnsavedAtStart(w)).ToList(); + bool hospitality = Compat.IsActive("Orion.Hospitality"); + List staleLords = hospitality ? all.Where(w => w.Contains("of type Verse.AI.Group.Lord.")).ToList() : new List(); + List rest = all.Where(w => !vanilla.Contains(w) && !atStart.Contains(w) && !staleLords.Contains(w)).ToList(); + T.Info(all.Count + " warning(s) on the reload: " + vanilla.Count + " for pawns vanilla made for books or tales and never saved, " + + atStart.Count + " for pawns the new world left unsaved, " + + staleLords.Count + " for lords Hospitality's CompGuest still names"); + T.Equal(0, rest.Count, "other 'Could not resolve reference' warnings while the phase-1 save loaded (first: " + + string.Join(" | ", rest.Take(3)) + ")"); + } + + [BlaxTest("harness: phase 3 loads with exactly the two removal errors and a fresh, empty component", phase: 3)] + public static void Phase3Removal() + { + T.Equal(1, TestRunner.Phase3ReplacedCount, "component nodes replaced in the phase-3 save"); + T.ExpectErrors("Could not find class " + TestRunner.RemovedComponentClass, 1); + T.ExpectErrors("Can't load abstract class Verse.GameComponent", 1); + T.Info("load errors: " + T.Phase3LoadErrors.Count + ", resolve warnings: " + T.Phase3ResolveWarnings); + T.Equal(2, T.Phase3LoadErrors.Count, "errors while loading the phase-3 save"); + T.Equal(1, Current.Game.components.Count(c => c is GameComponent_BlaxLaws), "fresh GameComponent_BlaxLaws"); + GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance; + T.Equal(0, comp.Laws.Count, "rows in the fresh component"); + T.Equal(0, comp.Cases.Count, "cases in the fresh component"); + T.Check(!Watch.Any, "Watch.Any is on after the removal load"); + } + } +} diff --git a/Tests/BlaxLawsTests/Source/StoreTests.cs b/Tests/BlaxLawsTests/Source/StoreTests.cs new file mode 100644 index 0000000..741fb0b --- /dev/null +++ b/Tests/BlaxLawsTests/Source/StoreTests.cs @@ -0,0 +1,161 @@ +using System.Linq; +using BlaxLaws; +using RimWorld; +using Verse; + +namespace BlaxLawsTests +{ + /// + /// The lawbook and case store: rows keyed on Action, Option and Stage, rows whose entry is missing, the + /// starter lawbook, and rows and cases through the save as names and numbers. + /// + public static class StoreTests + { + private const string MissingCoreKey = "Ate/BlaxLawsTest_NoSuchFood"; + private const string MissingIdeologyKey = "RecordedAct/BlaxLawsTest_NoSuchEvent"; + + [BlaxTest("lawbook: a row whose entry is missing stays, reads Missing: Core or Needs Ideology, watches nothing and files nothing")] + public static void MissingEntryRows() + { + Law core = Fixtures.LawRow(MissingCoreKey, null, LawStage.DidIt, LawSeverity.Moderate, "Warn", 3, "Core", "ludeon.rimworld"); + Law ideo = Fixtures.LawRow(MissingIdeologyKey, null, LawStage.DidIt, LawSeverity.Moderate, "Warn", 3, "Ideology", "ludeon.rimworld.ideology"); + T.Check(Lawbook.Laws.Contains(core) && Lawbook.Laws.Contains(ideo), "a row with a missing entry left the book"); + T.Check(!core.Resolves && !ideo.Resolves, "a made-up act key resolves"); + T.Equal("Missing: Core", core.MissingText, "missing text of a Core row"); + T.Equal("Needs Ideology", ideo.MissingText, "missing text of an Ideology row"); + T.Equal("Needs Ideology", DlcSupport.MissingText("Ideology", null), "missing text from the DLC name alone"); + T.Equal("Missing: Some Mod", DlcSupport.MissingText("Some Mod", "someone.somemod"), "missing text of a mod row"); + T.Check(!Watch.Any, "a row whose entry is missing turned a watch flag on"); + Pawn p = Fixtures.Colonist(); + T.Check(CaseFiler.Report(new ActEvent(ActCategories.Ate, ThingDefOf.MealSimple, p)) == null, "a row whose entry is missing filed a case"); + } + + [BlaxTest("lawbook: a second row with the same action, option and stage is refused and names the first")] + public static void DuplicateRefused() + { + Law a = Fixtures.LawRow(MissingCoreKey, null, LawStage.DidIt, LawSeverity.Minor, "Warn", 1); + var dup = new Law { actKey = MissingCoreKey, stage = LawStage.DidIt, punishment = "Jail", days = 5 }; + T.Check(!Lawbook.TryAdd(dup, out Law existing), "the duplicate row was added"); + T.Check(existing == a, "the refusal names " + existing + ", not the first row"); + var otherStage = new Law { actKey = MissingCoreKey, stage = LawStage.Planning, punishment = "Warn", days = 1 }; + T.Check(Lawbook.TryAdd(otherStage, out _), "a row with another stage was refused"); + var binge = new Law { actKey = "Break/@anyDrugBinge", option = DrugOptions.Any, stage = LawStage.DidIt, punishment = "Warn", days = 3 }; + T.Check(Lawbook.TryAdd(binge, out _), "a binge row was refused"); + var bingeNull = new Law { actKey = "Break/@anyDrugBinge", option = null, stage = LawStage.DidIt, punishment = "Warn", days = 3 }; + T.Check(!Lawbook.TryAdd(bingeNull, out Law e2) && e2 == binge, "a binge row with no option counts as Any and must be refused"); + var bingeWake = new Law { actKey = "Break/@anyDrugBinge", option = "WakeUpChemical", stage = LawStage.DidIt, punishment = "Warn", days = 3 }; + T.Check(Lawbook.TryAdd(bingeWake, out _), "a binge row with another option was refused"); + T.Check(a.id > 0 && otherStage.id > a.id, "row ids are not handed out in order: " + a.id + ", " + otherStage.id); + } + + [BlaxTest("lawbook: Moderate to Serious moves untouched days from 3 to 5 and leaves typed days alone; days clamp to 1..50")] + public static void SeverityMovesDefaultDays() + { + Law a = Fixtures.LawRow(MissingCoreKey, null, LawStage.DidIt, LawSeverity.Moderate, "Jail", 3); + Lawbook.SetSeverity(a, LawSeverity.Serious); + T.Equal(5, a.days, "untouched days after Moderate to Serious"); + Lawbook.SetDays(a, 7); + Lawbook.SetSeverity(a, LawSeverity.Grave); + T.Equal(7, a.days, "typed days after Serious to Grave"); + Lawbook.SetDays(a, 0); + T.Equal(1, a.days, "days 0 clamped"); + Lawbook.SetDays(a, 80); + T.Equal(50, a.days, "days 80 clamped"); + T.Equal(1, Lawbook.DefaultDays(LawSeverity.Minor), "Minor days"); + T.Equal(10, Lawbook.DefaultDays(LawSeverity.Grave), "Grave days"); + } + + [BlaxTest("lawbook: Starter lawbook adds 7 rows, pressing it again adds none")] + public static void StarterLawbook() + { + int before = Lawbook.Laws.Count; + T.Equal(7, Lawbook.AddStarter(), "rows the starter lawbook added"); + T.Equal(before + 7, Lawbook.Laws.Count, "rows in the book after the starter lawbook"); + T.Equal(0, Lawbook.AddStarter(), "rows a second press added"); + Law jail = Lawbook.Find("Break/@anyDrugBinge", DrugOptions.Any, LawStage.DidIt); + T.NotNull(jail, "starter row 'any drug binge, did it'"); + T.Equal("Jail", jail.punishment, "punishment of 'any drug binge, did it'"); + T.Equal(5, jail.days, "days of 'any drug binge, did it'"); + T.Equal(LawSeverity.Serious, jail.severity, "severity of 'any drug binge, did it'"); + Law fire = Lawbook.Find("Break/FireStartingSpree", null, LawStage.DidIt); + T.Check(fire != null && fire.punishment == "Jail" && fire.days == 10 && fire.severity == LawSeverity.Grave, "starter fire-starting spree did-it row: " + fire); + T.NotNull(Lawbook.Find("Interaction/Insult", null, LawStage.DidIt), "starter row 'Insult, did it'"); + T.NotNull(Lawbook.Find("Special/StartedSocialFight", null, LawStage.DidIt), "starter row 'started a social fight'"); + T.Check(Lawbook.Laws.All(l => l.savedMod == "Core" || l.Resolves), "a starter row saved another mod than Core"); + } + + [BlaxTest("cases: a filed case closes with its outcome, and deleting its row closes the open ones as repealed")] + public static void CaseLifecycle() + { + GameComponent_BlaxLaws comp = Fixtures.Comp; + Pawn p = Fixtures.Colonist(); + Law a = Fixtures.LawRow(MissingCoreKey, null, LawStage.DidIt, LawSeverity.Serious, "Warn", 5); + LawCase c = CaseFiler.Open(a, new ActEvent(ActCategories.Ate, ThingDefOf.MealSimple, p), LawStage.DidIt); + T.NotNull(c, "CaseFiler.Open"); + T.Check(comp.Cases.Contains(c) && comp.CasesOf(p).Contains(c), "the case is not in the store or its offender index"); + T.Equal(a.id, c.didItLawId, "the case's did-it row"); + T.Equal(LawSeverity.Serious, c.severity, "the case's severity"); + T.Equal(1, c.count, "the count of a new did-it case"); + T.Equal(p.LabelShort, c.offenderName, "the offender's saved name"); + T.Equal(1, Lawbook.OpenCaseCount(a), "open cases of the row"); + T.Equal(1, Lawbook.Delete(a), "cases the delete closed"); + T.Check(c.IsClosed && c.outcome == CaseOutcomes.Repealed, "the case after the delete: " + c); + T.Equal("Law repealed", CaseOutcomes.Label(c.outcome), "the repealed label"); + } + + [BlaxTest("save: a row and a case go into the save as names and numbers (setup)")] + public static void SaveSetup() + { + Pawn p = Fixtures.Keep(Fixtures.Colonist()); + Law a = Fixtures.KeepLaw(Fixtures.LawRow(MissingIdeologyKey, null, LawStage.DidIt, LawSeverity.Grave, "Jail", 12, "Ideology", "ludeon.rimworld.ideology")); + Lawbook.SetEnabled(a, false); + LawCase c = CaseFiler.Open(a, new ActEvent(ActCategories.RecordedAct, null, p) { notes = CaseNotes.OnTable | CaseNotes.DugUp }, LawStage.DidIt); + c.count = 4; + c.breakState = "Binging_DrugExtreme"; + c.breakStartTick = 1234; + c.MarkPunished(LawStage.DidIt); + c.status = CaseStatus.Jailed; + c.captureTick = 2000; + c.releaseTick = 2000 + 12 * GenDate.TicksPerDay; + T.Carry["save.law"] = a.id.ToString(); + T.Carry["save.case"] = c.id.ToString(); + T.Carry["save.pawn"] = p.ThingID; + } + + [BlaxTest("save: the row and the case keep every field through the reload", phase: 2)] + public static void SaveRoundTrip() + { + T.Check(T.Carry.ContainsKey("save.law"), "phase-1 setup did not run"); + GameComponent_BlaxLaws comp = Fixtures.Comp; + Law a = comp.LawById(int.Parse(T.Carry["save.law"])); + T.NotNull(a, "the kept row after the reload"); + T.Equal(MissingIdeologyKey, a.actKey, "act key"); + T.Equal(LawStage.DidIt, a.stage, "stage"); + T.Equal(LawSeverity.Grave, a.severity, "severity"); + T.Equal("Jail", a.punishment, "punishment"); + T.Equal(12, a.days, "days"); + T.Check(!a.enabled, "the row's On flag came back on"); + T.Equal("Ideology", a.savedMod, "saved mod"); + T.Equal("Needs Ideology", a.MissingText, "missing text after the reload"); + T.Check(comp.NextLawId > a.id, "next row id " + comp.NextLawId + " would repeat " + a.id); + + LawCase c = comp.CaseById(int.Parse(T.Carry["save.case"])); + T.NotNull(c, "the kept case after the reload"); + Pawn p = Fixtures.FindPawnById(T.Carry["save.pawn"]); + T.NotNull(p, "the kept colonist after the reload"); + T.Check(c.offender == p, "the case's offender reference didn't resolve to the colonist"); + T.Check(comp.CasesOf(p).Contains(c), "the offender index lacks the case after the reload"); + T.Equal(a.id, c.didItLawId, "did-it row"); + T.Equal(4, c.count, "count"); + T.Equal(CaseNotes.OnTable | CaseNotes.DugUp, c.notes, "notes"); + T.Equal("Binging_DrugExtreme", c.breakState, "break state"); + T.Equal(1234, c.breakStartTick, "break start tick"); + T.Check(c.HasPunished(LawStage.DidIt) && !c.HasPunished(LawStage.Planning), "punished stages: " + c.punishedStages); + T.Equal(CaseStatus.Jailed, c.status, "status"); + T.Equal(2000, c.captureTick, "capture tick"); + T.Equal(2000 + 12 * GenDate.TicksPerDay, c.releaseTick, "release tick"); + T.Equal(LawSeverity.Grave, c.severity, "severity"); + T.Check(comp.NextCaseId > c.id, "next case id " + comp.NextCaseId + " would repeat " + c.id); + } + } +} diff --git a/Tests/BlaxLawsTests/Source/UiTests.cs b/Tests/BlaxLawsTests/Source/UiTests.cs new file mode 100644 index 0000000..1699a07 --- /dev/null +++ b/Tests/BlaxLawsTests/Source/UiTests.cs @@ -0,0 +1,558 @@ +using System.Collections.Generic; +using System.Linq; +using BlaxLaws; +using RimWorld; +using Verse; + +namespace BlaxLawsTests +{ + /// + /// The Laws tab, the act picker, the case log and the letters (design: "Lawbook tab", Tests). Headless + /// runs have no GUI, so these drive the logic behind the widgets: what each column's dropdown offers and + /// what picking it writes, what a pick from the act picker adds, the picker's tree and search, the + /// overlap icon, the delete confirmation, the case log's lines and "Arrest now", and the letters. + /// Drawing is checked by hand. + /// + public static class UiTests + { + private const string Binge = "Break/@anyDrugBinge"; + private const string Insult = "Interaction/Insult"; + private const string MissingKey = "Ate/BlaxLawsTest_UiNoSuchFood"; + + // ---- helpers ----------------------------------------------------------------------------- + + private static ActEntry Entry(string key) + { + ActEntry e = ActCatalogue.Get(key); + T.NotNull(e, "catalogue entry " + key); + return e; + } + + /// A fresh row through the picker's "Add law" path; fails when the book had one. + private static Law Add(string key) + { + Entry(key); + Law row = LawbookUi.AddFromPicker(key, out Law existing); + T.Check(row != null, "Add law for " + key + " added nothing, existing " + existing); + return row; + } + + private static List Names(List choices) => + choices.Select(c => c.payload is Def d ? d.defName : c.payload?.ToString()).ToList(); + + private static string Show(List choices) => string.Join(" | ", choices.Select(c => c.ToString())); + + private static RowChoice Choice(List choices, string name) + { + RowChoice c = choices.FirstOrDefault(x => (x.payload is Def d ? d.defName : x.payload?.ToString()) == name); + T.NotNull(c, "menu entry " + name + " in " + Show(choices)); + return c; + } + + /// Turns the other rows of a category off for this test, so its watch flag reads only this test's rows. + private static void SilenceOtherRows(string categoryId) + { + foreach (Law l in Lawbook.Laws.Where(l => l.enabled && l.CategoryId == categoryId).ToList()) + { + Lawbook.SetEnabled(l, false); + Law kept = l; + Fixtures.OnCleanup(() => Lawbook.SetEnabled(kept, true)); + } + } + + /// Removes the letters a test sent from the stack and the archive, so the save never holds their targets. + private static void RemoveNewLettersAfterTest() + { + var before = new HashSet(Find.LetterStack.LettersListForReading); + Fixtures.OnCleanup(() => + { + foreach (Letter l in Find.LetterStack.LettersListForReading.Where(l => !before.Contains(l)).ToList()) + { + Find.LetterStack.RemoveLetter(l); + Find.Archive.Remove(l); + } + }); + } + + private static List LettersSince(HashSet before) => + Find.LetterStack.LettersListForReading.Where(l => !before.Contains(l)).ToList(); + + private static LawCase OpenCase(Law law, Pawn p) => + CaseFiler.Open(law, new ActEvent(ActCategories.Ate, ThingDefOf.MealSimple, p), law.stage); + + // ---- the tab ----------------------------------------------------------------------------- + + [BlaxTest("ui: the Laws button opens MainTabWindow_Laws after Ideoligions, also without a map; Show Laws tab writes buttonVisible")] + public static void MainButton() + { + MainButtonDef def = BlaxLawsDefOf.BlaxLaws_Laws; + T.NotNull(def, "MainButtonDef BlaxLaws_Laws"); + T.Equal(typeof(MainTabWindow_Laws), def.tabWindowClass, "tab window class"); + T.Equal(105, def.order, "button order"); + T.Check(def.validWithoutMap, "the Laws tab is not valid without a map"); + T.Check(def.TabWindow is MainTabWindow_Laws, "TabWindow is " + def.TabWindow?.GetType().Name); + Fixtures.Settings.showLawsTab = false; + BlaxLawsMod.ApplyTabVisibility(); + T.Check(!def.buttonVisible, "Show Laws tab off left the button visible"); + Fixtures.Settings.showLawsTab = true; + BlaxLawsMod.ApplyTabVisibility(); + T.Check(def.buttonVisible, "Show Laws tab on left the button hidden"); + } + + [BlaxTest("ui: Add law gives a row at the entry's first stage, Moderate, Warn, 3 days and On; a binge row gets Any drug")] + public static void AddLawDefaults() + { + Law binge = Add(Binge); + T.Equal(LawStage.Planning, binge.stage, "stage of a new binge row"); + T.Equal(LawSeverity.Moderate, binge.severity, "severity of a new row"); + T.Equal("Warn", binge.punishment, "punishment of a new row"); + T.Equal(3, binge.days, "days of a new row"); + T.Check(binge.enabled, "a new row is off"); + T.Equal(DrugOptions.Any, DrugOptions.Normalize(binge.option), "option of a new binge row"); + T.Check(LawbookUi.HasOption(binge), "a binge row has no Drug column"); + T.Equal(binge.id, LawbookUi.FocusLawId, "the tab doesn't show the new row"); + + Law insult = Add(Insult); + T.Equal(LawStage.DidIt, insult.stage, "stage of a new Insult row (no planning outside the breaks)"); + T.Check(insult.option == null && !LawbookUi.HasOption(insult), "an Insult row has a drug option: " + insult.option); + T.Equal(0, LawbookUi.OptionChoices(insult).Count, "drug options of an Insult row"); + T.Check(insult.savedLabel == Entry(Insult).label && insult.savedMod == "Core", "the row didn't save the entry's label and mod: " + insult.savedLabel + ", " + insult.savedMod); + } + + [BlaxTest("ui: Add law on an entry whose stages all have rows adds nothing and shows the existing row")] + public static void AddLawDuplicateShowsRow() + { + Law planning = Add(Binge); + ActEntry e = Entry(Binge); + T.Check(e.HasStage(LawStage.DidIt), "the any drug binge entry has no Did it stage (break link missing)"); + Law didIt = Add(Binge); + T.Equal(LawStage.DidIt, didIt.stage, "stage of the second binge row"); + int count = Lawbook.Laws.Count; + LawbookUi.ClearFocus(); + Law third = LawbookUi.AddFromPicker(Binge, out Law existing); + T.Check(third == null, "a third binge row was added: " + third); + T.Equal(count, Lawbook.Laws.Count, "rows after the refused pick"); + T.Check(existing == planning, "the refusal names " + existing + ", not the planning row"); + T.Equal(planning.id, LawbookUi.FocusLawId, "the tab doesn't jump to the existing row"); + T.Check(LawbookUi.ScrollPending, "the tab isn't asked to scroll to the existing row"); + + Law insult = Add(Insult); + T.Check(!LawbookUi.ChangeAction(didIt, Insult), "changing an action to a key in the book was allowed"); + T.Equal(Binge, didIt.actKey, "the refused action change still changed the row"); + T.Equal(insult.id, LawbookUi.FocusLawId, "the refused action change doesn't show the existing row"); + } + + [BlaxTest("ui: an any drug binge row turns the Break flag on and watches both binge breaks; deleting it turns them off")] + public static void BingeRowWatches() + { + SilenceOtherRows(ActCategories.Break); + MentalStateDef extreme = DefDatabase.GetNamed("Binging_DrugExtreme"); + MentalStateDef major = DefDatabase.GetNamed("Binging_DrugMajor"); + T.Check(!Watch.Break, "the Break flag is on before the row"); + Law row = Add(Binge); + T.Check(Watch.Break && Watch.Any, "the Break flag is off after adding the row"); + T.Check(Watch.IsWatched(ActCategories.Break, extreme), "Binging_DrugExtreme is not watched"); + T.Check(Watch.IsWatched(ActCategories.Break, major), "Binging_DrugMajor is not watched"); + T.Check(!Watch.IsWatched(ActCategories.Break, DefDatabase.GetNamed("FireStartingSpree")), "a binge row watches the fire-starting spree"); + Lawbook.SetEnabled(row, false); + T.Check(!Watch.Break, "the Break flag is on with the row off"); + Lawbook.SetEnabled(row, true); + Lawbook.Delete(row); + T.Check(!Watch.Break, "the Break flag is on after deleting the row"); + T.Check(!Watch.IsWatched(ActCategories.Break, extreme) && !Watch.IsWatched(ActCategories.Break, major), "a binge break is still watched after the delete"); + } + + // ---- column dropdowns ------------------------------------------------------------------ + + [BlaxTest("ui: a Planning row never offers Reprimand, Banish or Execute; a Berserk row never offers Subdue; a Tantrum row does")] + public static void PunishmentMenus() + { + Law planning = Add(Binge); + List p = Names(LawbookUi.PunishmentChoices(planning)); + T.Check(p.Contains("Warn") && p.Contains("Subdue") && p.Contains("Jail"), "a binge planning row lacks Warn, Subdue or Jail: " + string.Join(", ", p)); + foreach (string never in new[] { "Reprimand", "Banish", "Execute", "Guilty", "SubdueThenJail" }) + T.Check(!p.Contains(never), "a binge planning row offers " + never); + + Law didIt = Add(Binge); + List d = Names(LawbookUi.PunishmentChoices(didIt)); + foreach (string must in new[] { "Warn", "Guilty", "Subdue", "Jail", "SubdueThenJail" }) + T.Check(d.Contains(must), "a binge did-it row lacks " + must + ": " + string.Join(", ", d)); + + Law berserk = Add("Break/Berserk"); + List b = Names(LawbookUi.PunishmentChoices(berserk)); + T.Check(Entry("Break/Berserk").hostileBreak, "the Berserk entry isn't marked hostile"); + T.Check(!b.Contains("Subdue") && !b.Contains("SubdueThenJail"), "a Berserk row offers a subdue: " + string.Join(", ", b)); + T.Check(b.Contains("Warn") && b.Contains("Guilty") && b.Contains("Jail"), "a Berserk row lacks Warn, Guilty or Jail: " + string.Join(", ", b)); + + Law tantrum = Add("Break/Tantrum"); + T.Check(Names(LawbookUi.PunishmentChoices(tantrum)).Contains("Subdue"), "a Tantrum row doesn't offer Subdue"); + + Law insult = Add(Insult); + List a = Names(LawbookUi.PunishmentChoices(insult)); + T.Check(a.Contains("Warn") && a.Contains("Guilty") && a.Contains("Jail") && !a.Contains("Subdue") && !a.Contains("SubdueThenJail"), + "an Insult row offers " + string.Join(", ", a) + " (expected Warn, Guilty, Jail, no subdue)"); + + Choice(LawbookUi.PunishmentChoices(insult), "Jail").action(); + T.Equal("Jail", insult.punishment, "picking Jail in the menu"); + T.Check(LawbookUi.UsesDays(insult), "a Jail row shows no Days field"); + Choice(LawbookUi.PunishmentChoices(insult), "Warn").action(); + T.Check(!LawbookUi.UsesDays(insult), "a Warn row shows a Days field"); + } + + [BlaxTest("ui: switching a Subdue row's action to Ate: any meat resets it to Warn and Did it; Severity moves untouched days")] + public static void ActionAndSeverityResets() + { + Law row = Add(Binge); + Choice(LawbookUi.PunishmentChoices(row), "Subdue").action(); + T.Equal("Subdue", row.punishment, "picking Subdue in the menu"); + T.Check(LawbookUi.ChangeAction(row, "Ate/@anyMeat"), "changing the action to Ate: any meat was refused"); + T.Equal("Ate/@anyMeat", row.actKey, "act key after the change"); + T.Equal("Warn", row.punishment, "punishment after switching a Subdue row to Ate: any meat"); + T.Equal(LawStage.DidIt, row.stage, "stage after switching to an entry without Planning"); + T.Check(row.option == null, "the option stayed after switching away from a binge: " + row.option); + T.Check(row.savedLabel == Entry("Ate/@anyMeat").label, "the row didn't save the new entry's label: " + row.savedLabel); + + Choice(LawbookUi.SeverityChoices(row), nameof(LawSeverity.Serious)).action(); + T.Equal(5, row.days, "untouched days after Moderate to Serious in the menu"); + Lawbook.SetDays(row, 8); + Choice(LawbookUi.SeverityChoices(row), nameof(LawSeverity.Grave)).action(); + T.Equal(8, row.days, "typed days after Serious to Grave in the menu"); + T.Check(LawbookUi.SeverityChoices(row).Single(c => c.selected).payload.Equals(LawSeverity.Grave), "the severity menu marks another value as selected"); + + // The first binge row became Ate: any meat, so the binge's planning key is free again. + Law planning = Add(Binge); + T.Equal(LawStage.Planning, planning.stage, "stage of the next binge row"); + Law didIt = Add(Binge); + T.Equal(LawStage.DidIt, didIt.stage, "stage of the binge row after that"); + Choice(LawbookUi.PunishmentChoices(didIt), "SubdueThenJail").action(); + T.Equal("SubdueThenJail", didIt.punishment, "picking Subdue then jail in the menu"); + T.Check(!LawbookUi.ChangeStage(didIt, LawStage.Planning), "the stage menu made a second binge planning row"); + T.Equal(planning.id, LawbookUi.FocusLawId, "the refused stage change doesn't show the existing row"); + Lawbook.Delete(planning); + Choice(LawbookUi.StageChoices(didIt), nameof(LawStage.Planning)).action(); + T.Equal(LawStage.Planning, didIt.stage, "stage after picking Planning"); + T.Equal("Warn", didIt.punishment, "Subdue then jail, which planning doesn't offer, didn't reset to Warn on the stage change"); + Choice(LawbookUi.PunishmentChoices(didIt), "Jail").action(); + Choice(LawbookUi.StageChoices(didIt), nameof(LawStage.DidIt)).action(); + T.Equal("Jail", didIt.punishment, "a Jail row that still fits lost its punishment on the stage change"); + } + + [BlaxTest("ui: the drug option list holds WakeUp and no non-drug chemical; picking an option keeps the key unique")] + public static void DrugOptionMenu() + { + Law row = Add(Binge); + List choices = LawbookUi.OptionChoices(row); + List names = Names(choices); + T.Check(names.Count > 3 && names[0] == DrugOptions.Any && names[1] == DrugOptions.Hard && names[2] == DrugOptions.Social, + "the option menu doesn't start with Any, Hard, Social: " + string.Join(", ", names.Take(4))); + T.Check(names.Contains("WakeUp"), "the option menu lacks the wake-up chemical: " + string.Join(", ", names)); + var drugChemicals = new HashSet(); + foreach (ThingDef t in DefDatabase.AllDefsListForReading) + { + CompProperties_Drug drug = t.GetCompProperties(); + if (drug?.chemical != null) + drugChemicals.Add(drug.chemical.defName); + } + foreach (string n in names.Skip(3)) + T.Check(drugChemicals.Contains(n), "the option menu lists " + n + ", a chemical no drug names"); + T.Equal(names.Count, names.Distinct().Count(), "options listed twice"); + List others = DefDatabase.AllDefsListForReading.Select(c => c.defName).Where(n => !drugChemicals.Contains(n)).ToList(); + T.Info("chemicals no drug names (left out): " + (others.Count == 0 ? "none" : string.Join(", ", others))); + + Choice(choices, "WakeUp").action(); + T.Equal("WakeUp", row.option, "option after picking wake-up"); + T.Equal(DrugOptions.Label("WakeUp"), DefDatabase.GetNamed("WakeUp").LabelCap.ToString(), "the wake-up option's label"); + // The planning key with Any drug is free again, so the next pick adds a planning row with Any drug. + Law second = Add(Binge); + T.Equal(LawStage.Planning, second.stage, "stage of the second binge row"); + T.Equal(DrugOptions.Any, DrugOptions.Normalize(second.option), "option of the second binge row"); + T.Check(!LawbookUi.ChangeOption(second, "WakeUp"), "a second planning row with the wake-up option was allowed"); + T.Equal(row.id, LawbookUi.FocusLawId, "the refused option doesn't show the existing row"); + T.Check(LawbookUi.ChangeOption(second, DrugOptions.Hard), "the hard drugs option was refused"); + T.Equal(DrugOptions.Hard, second.option, "option after picking hard drugs"); + } + + [BlaxTest("ui: a row whose entry is missing shows its saved label and why, keeps its stage and punishment and offers nothing else")] + public static void MissingEntryRow() + { + Law row = Fixtures.LawRow(MissingKey, null, LawStage.DidIt, LawSeverity.Moderate, "Jail", 4, "Ideology", "ludeon.rimworld.ideology"); + T.Check(LawbookUi.ActionLabel(row).Contains(ActKey.NameOf(MissingKey)), "the action label lacks the saved label: " + LawbookUi.ActionLabel(row)); + T.Check(LawbookUi.ActionTooltip(row).Contains("Needs Ideology"), "the action tooltip doesn't say Needs Ideology: " + LawbookUi.ActionTooltip(row)); + List stages = LawbookUi.StageChoices(row); + T.Check(stages.Count == 1 && stages[0].action == null && stages[0].selected && stages[0].reason == "Needs Ideology", "stage menu of a missing row: " + Show(stages)); + List punishments = LawbookUi.PunishmentChoices(row); + T.Check(punishments.Count == 1 && punishments[0].action == null && Equals(punishments[0].payload, BlaxLawsDefOf.Jail), "punishment menu of a missing row: " + Show(punishments)); + T.Check(LawbookUi.UsesDays(row), "a missing Jail row lost its Days field"); + T.Equal(0, ActOverlaps.Of(row).Count, "overlaps of a missing row"); + } + + // ---- act picker -------------------------------------------------------------------------- + + [BlaxTest("ui: the picker's search for 'wake' lists Wake-up under Ate and make wake-up under Bills; 'insult' lists Insult and the insulting sprees")] + public static void PickerSearch() + { + var tree = new ActPickerTree { SearchText = "wake" }; + List rows = tree.Rows.ToList(); + List entries = rows.Where(r => !r.IsHeader).ToList(); + T.Check(entries.Any(r => r.category.defName == ActCategories.Ate && r.entry.def?.defName == "WakeUp"), "'wake' doesn't list Wake-up under Ate"); + T.Check(entries.Any(r => r.category.defName == ActCategories.Bill && r.entry.def is RecipeDef rd && rd.ProducedThingDef?.defName == "WakeUp"), + "'wake' doesn't list make wake-up under Bills"); + T.Check(entries.All(r => tree.Matches(r.entry)), "a listed entry doesn't match 'wake'"); + T.Check(!entries.Any(r => r.entry.def?.defName == "Beer"), "'wake' lists Beer"); + foreach (ActPickerRow h in rows.Where(r => r.IsHeader)) + { + T.Check(h.open && h.count > 0, "searching shows the category " + h.category.defName + " closed or empty"); + T.Equal(h.count, entries.Count(r => r.category == h.category), "entries listed under " + h.category.defName); + } + T.Equal(entries.Count, tree.Hits, "hits of 'wake'"); + + tree.SearchText = "insult"; + entries = tree.Rows.Where(r => !r.IsHeader).ToList(); + T.Check(entries.Any(r => r.category.defName == ActCategories.Interaction && r.entry.def?.defName == "Insult"), "'insult' doesn't list Insult under interactions"); + T.Check(entries.Any(r => r.category.defName == ActCategories.Break && r.entry.def?.defName == "InsultingSpree"), "'insult' doesn't list the insulting spree under breaks"); + T.Check(entries.Any(r => r.category.defName == ActCategories.Break && r.entry.def?.defName == "TargetedInsultingSpree"), "'insult' doesn't list the targeted insulting spree under breaks"); + + tree.SearchText = "blaxlawstest no act is called this"; + T.Equal(0, tree.Rows.Count, "lines for a search without hits"); + T.Equal(0, tree.Hits, "hits for a search without hits"); + } + + [BlaxTest("ui: the picker opens with every category closed, opens one on a click, groups first; entries in the book show a tick")] + public static void PickerTree() + { + var tree = new ActPickerTree(); + IReadOnlyList cats = ActCatalogue.Categories; + T.Equal(cats.Count, tree.Rows.Count, "lines with every category closed"); + T.Check(tree.Rows.All(r => r.IsHeader && !r.open), "a closed tree shows an entry"); + T.Check(cats.Select(c => c.defName).SequenceEqual(ActCategories.All.Where(id => cats.Any(c => c.defName == id))), "categories not in picker order: " + string.Join(", ", cats.Select(c => c.defName))); + tree.Toggle(ActCategories.Break); + List rows = tree.Rows.ToList(); + List breaks = rows.Where(r => !r.IsHeader).ToList(); + T.Equal(ActCatalogue.EntriesOf(ActCategories.Break).Count, breaks.Count, "entries under an opened Mental breaks"); + T.Check(breaks.Count > 0 && breaks.All(r => r.category.defName == ActCategories.Break), "an opened category lists another category's entries"); + int firstDef = breaks.FindIndex(r => !r.entry.IsGroup); + T.Check(firstDef > 0 && breaks.Skip(firstDef).All(r => !r.entry.IsGroup), "groups don't come first under Mental breaks"); + T.Equal(1, rows.Count(r => r.IsHeader && r.open), "open categories after one click"); + + Law insult = Add(Insult); + tree.SearchText = "insult"; + ActPickerRow insultLine = tree.Rows.First(r => !r.IsHeader && r.entry.key == Insult); + T.Check(insultLine.inBook, "Insult has a row but shows no tick"); + T.Check(tree.Rows.Where(r => !r.IsHeader && r.entry.key != Insult).All(r => !r.inBook), "an entry without a row shows a tick"); + T.Check(Dialog_PickAct.EntryTooltip(insultLine.entry, true).Contains("Core"), "the entry tooltip lacks its source mod"); + + Dialog_PickAct forRow = Dialog_PickAct.ForRow(insult); + T.Check(forRow.Tree.IsOpen(ActCategories.Interaction), "the picker for a row doesn't open the row's category"); + tree.SearchText = ""; + tree.Toggle(ActCategories.Break); + T.Equal(cats.Count, tree.Rows.Count, "lines after closing Mental breaks again"); + } + + // ---- overlap icon ------------------------------------------------------------------------ + + [BlaxTest("ui: Ate: wake-up next to Recorded acts: ingested a drug shows the overlap icon on both; a cook's bill overlaps meals cooked")] + public static void OverlapIcon() + { + Law ate = Fixtures.LawRow("Ate/WakeUp", null, LawStage.DidIt, LawSeverity.Moderate, "Warn", 3); + Law recorded = Fixtures.LawRow("RecordedAct/IngestedDrug", null, LawStage.DidIt, LawSeverity.Moderate, "Warn", 3); + Law insult = Fixtures.LawRow(Insult, null, LawStage.DidIt, LawSeverity.Minor, "Warn", 1); + T.Check(ate.Resolves && recorded.Resolves && insult.Resolves, "an overlap row doesn't resolve: " + ate.MissingText + ", " + recorded.MissingText + ", " + insult.MissingText); + T.Check(ActOverlaps.Of(ate).Contains(recorded), "Ate: wake-up shows no overlap with Recorded acts: ingested a drug"); + T.Check(ActOverlaps.Of(recorded).Contains(ate), "Recorded acts: ingested a drug shows no overlap with Ate: wake-up"); + T.Equal(0, ActOverlaps.Of(insult).Count, "overlaps of an Insult row"); + T.Check(!ActOverlaps.Of(ate).Contains(insult), "Ate: wake-up overlaps Insult"); + + Lawbook.SetEnabled(recorded, false); + T.Equal(0, ActOverlaps.Of(ate).Count, "overlaps of Ate: wake-up with the recorded-act row off"); + Lawbook.SetEnabled(recorded, true); + T.Check(ActOverlaps.Of(ate).Contains(recorded), "the overlap didn't come back with the row on again"); + + Law meal = Fixtures.LawRow("Ate/MealSimple", null, LawStage.DidIt, LawSeverity.Minor, "Warn", 1); + T.Check(!ActOverlaps.Of(meal).Contains(recorded), "a simple meal overlaps ingested a drug"); + + Law cook = Fixtures.LawRow("Bill/CookMealSimple", null, LawStage.DidIt, LawSeverity.Minor, "Warn", 1); + Law cooked = Fixtures.LawRow("Record/MealsCooked", null, LawStage.DidIt, LawSeverity.Minor, "Warn", 1); + T.Check(cook.Resolves && cooked.Resolves, "the bill or record row doesn't resolve: " + cook.MissingText + ", " + cooked.MissingText); + T.Check(ActOverlaps.Of(cook).Contains(cooked) && ActOverlaps.Of(cooked).Contains(cook), "cooking a simple meal shows no overlap with meals cooked"); + T.Check(!ActOverlaps.Of(cooked).Contains(ate), "meals cooked overlaps eating wake-up"); + } + + // ---- delete and starter ------------------------------------------------------------------ + + [BlaxTest("ui: deleting a law with open cases asks first and names the count; without open cases it deletes at once")] + public static void DeleteAsksFirst() + { + Law quiet = Fixtures.LawRow(MissingKey, null, LawStage.DidIt, LawSeverity.Minor, "Warn", 1); + T.Check(LawbookUi.DeleteConfirmText(quiet) == null, "a row without cases asks before the delete"); + LawbookUi.RequestDelete(quiet); + T.Check(!Lawbook.Laws.Contains(quiet), "a row without cases wasn't deleted at once"); + + Law busy = Fixtures.LawRow(MissingKey, null, LawStage.DidIt, LawSeverity.Minor, "Warn", 1); + Pawn p = Fixtures.Colonist(); + LawCase c1 = OpenCase(busy, p); + LawCase c2 = OpenCase(busy, Fixtures.Colonist()); + string text = LawbookUi.DeleteConfirmText(busy); + T.Check(text != null && text.Contains("(2)"), "the confirmation doesn't name 2 open cases: " + text); + int windows = Find.WindowStack.Count; + LawbookUi.RequestDelete(busy); + Dialog_MessageBox box = Find.WindowStack.WindowOfType(); + T.Check(box != null && Find.WindowStack.Count == windows + 1, "no confirmation opened"); + T.Check(Lawbook.Laws.Contains(busy) && !c1.IsClosed, "the row was deleted before the confirmation"); + Find.WindowStack.TryRemove(box, doCloseSound: false); + T.Check(Lawbook.Laws.Contains(busy), "closing the confirmation deleted the row"); + T.Equal(2, Lawbook.Delete(busy), "cases the confirmed delete closed"); + T.Check(c1.outcome == CaseOutcomes.Repealed && c2.outcome == CaseOutcomes.Repealed, "the cases didn't close as repealed: " + c1 + "; " + c2); + } + + [BlaxTest("ui: the Starter lawbook button adds 7 rows; pressing it again adds none")] + public static void StarterButton() + { + foreach (Lawbook.StarterRow s in Lawbook.StarterRows) + T.Check(Lawbook.Find(s.actKey, s.option, s.stage) == null, "setup: starter row " + s.actKey + " is already in the book"); + T.Equal(7, LawbookUi.PressStarter(), "rows the button added"); + T.Equal(0, LawbookUi.PressStarter(), "rows a second press added"); + foreach (Lawbook.StarterRow s in Lawbook.StarterRows) + { + Law l = Lawbook.Find(s.actKey, s.option, s.stage); + T.Check(l != null && l.Resolves, "starter row " + s.actKey + " " + s.stage + " is missing or doesn't resolve: " + l?.MissingText); + } + } + + // ---- case log ---------------------------------------------------------------------------- + + [BlaxTest("ui: the case log lists newest first with who, what, stage, when, punishment and status; closed cases only when asked")] + public static void CaseLogLines() + { + GameComponent_BlaxLaws comp = Fixtures.Comp; + int now = Find.TickManager.TicksGame; + Law warn = Fixtures.LawRow(MissingKey, null, LawStage.DidIt, LawSeverity.Minor, "Warn", 1); + Law jail = Fixtures.LawRow("Ate/BlaxLawsTest_UiNoSuchDrug", null, LawStage.DidIt, LawSeverity.Grave, "Jail", 5); + Pawn a = Fixtures.Colonist(); + Pawn b = Fixtures.Colonist(); + LawCase older = OpenCase(warn, a); + older.openTick = older.lastActTick = now - 3 * GenDate.TicksPerDay; + LawCase newer = OpenCase(jail, b); + newer.count = 3; + newer.notes = CaseNotes.OnTable; + + List rows = CaseLog.Rows(true).Where(c => c == older || c == newer).ToList(); + T.Check(rows.Count == 2 && rows[0] == newer && rows[1] == older, "the log isn't newest first: " + string.Join("; ", rows)); + T.Equal(a.LabelShort, CaseLog.Who(older), "who"); + T.Check(CaseLog.What(newer).Contains("3 times") && CaseLog.What(newer).Contains("on a table"), "what lacks the count or the note: " + CaseLog.What(newer)); + T.Check(CaseLog.What(older).Contains(ActKey.NameOf(MissingKey)), "what lacks the row's label: " + CaseLog.What(older)); + T.Equal("Did it", CaseLog.Stage(older), "stage"); + T.Check(CaseLog.When(older).Contains("3 days") && CaseLog.When(older).Contains("ago"), "when: " + CaseLog.When(older)); + T.Check(CaseLog.Punishment(newer).Contains("5"), "punishment lacks the days: " + CaseLog.Punishment(newer)); + T.Equal("Open", CaseLog.Status(older), "status of an open case"); + + newer.status = CaseStatus.Jailed; + newer.releaseTick = now + 2 * GenDate.TicksPerDay; + T.Check(CaseLog.Status(newer).Contains("2 days"), "a jailed case doesn't count down: " + CaseLog.Status(newer)); + newer.status = CaseStatus.Open; + newer.waitReason = WaitReasons.Danger; + T.Check(CaseLog.Status(newer).Contains("danger"), "a waiting case doesn't say why: " + CaseLog.Status(newer)); + + comp.CloseCase(older, CaseOutcomes.Warned); + T.Equal("Warned", CaseLog.Status(older), "status of a closed case"); + T.Check(!CaseLog.Rows(false).Contains(older), "a closed case shows with closed cases hidden"); + T.Check(CaseLog.Rows(false).Contains(newer), "an open case is hidden"); + T.Check(CaseLog.CanJump(newer), "no jump button for a spawned offender"); + } + + [BlaxTest("ui: the Cases tab refills one list in place, newest first, then severity, then id within a tick, and follows closing and severity changes")] + public static void CaseRowsFillInPlace() + { + GameComponent_BlaxLaws comp = Fixtures.Comp; + int now = Find.TickManager.TicksGame; + Law minor = Fixtures.LawRow("Ate/BlaxLawsTest_UiRowOrderMinor", null, LawStage.DidIt, LawSeverity.Minor, "Warn", 1); + Law moderate = Fixtures.LawRow("Ate/BlaxLawsTest_UiRowOrderModerate", null, LawStage.DidIt, LawSeverity.Moderate, "Warn", 1); + Law grave = Fixtures.LawRow("Ate/BlaxLawsTest_UiRowOrderGrave", null, LawStage.DidIt, LawSeverity.Grave, "Warn", 1); + LawCase older = OpenCase(grave, Fixtures.Colonist()); + older.openTick = older.lastActTick = now - GenDate.TicksPerDay; + LawCase m = OpenCase(moderate, Fixtures.Colonist()); + LawCase b = OpenCase(minor, Fixtures.Colonist()); + LawCase g = OpenCase(grave, Fixtures.Colonist()); + LawCase b2 = OpenCase(minor, Fixtures.Colonist()); + var mine = new HashSet { older, m, b, g, b2 }; + string Order(List l) => string.Join("; ", l.Where(mine.Contains).Select(x => x.id + "/" + x.severity)); + + var rows = new List(); + CaseLog.FillRows(rows, true); + List got = rows.Where(mine.Contains).ToList(); + T.Check(got.SequenceEqual(new[] { g, m, b2, b, older }), "not newest first, then severity, then id: " + Order(rows)); + T.Check(CaseLog.Rows(true).SequenceEqual(rows), "Rows and FillRows disagree"); + + int capacity = rows.Capacity; + CaseLog.FillRows(rows, true); + T.Equal(capacity, rows.Capacity, "a second fill of the same cases grew the list"); + + b.SetLaw(LawStage.Planning, grave); // raises b to Grave; same tick as g, lower id + CaseLog.FillRows(rows, true); + T.Check(rows.Where(mine.Contains).SequenceEqual(new[] { g, b, m, b2, older }), "a raised severity didn't reorder the rows: " + Order(rows)); + + comp.CloseCase(m, CaseOutcomes.Warned); + CaseLog.FillRows(rows, false); + T.Check(!rows.Contains(m) && rows.Contains(g) && rows.Contains(older), "closing a case didn't hide only it: " + Order(rows)); + CaseLog.FillRows(rows, true); + T.Check(rows.Contains(m), "a closed case is missing with closed cases shown"); + m.status = CaseStatus.Open; + m.outcome = null; + m.closeTick = -1; + CaseLog.FillRows(rows, false); + T.Check(rows.Contains(m), "a reopened case stays hidden"); + + foreach (LawCase c in mine) + comp.CloseCase(c, CaseOutcomes.Warned); + } + + [BlaxTest("ui: Arrest now shows only for a held case and the Cases tab says it waits for it; not for another wait or a closed case")] + public static void ArrestNowShowsForHold() + { + Law jail = Fixtures.LawRow(MissingKey, null, LawStage.DidIt, LawSeverity.Serious, "Jail", 5); + Pawn p = Fixtures.Colonist(); + LawCase c = OpenCase(jail, p); + try + { + c.activePunishment = "Jail"; + c.activeStage = LawStage.DidIt; + T.Check(!CaseLog.CanArrestNow(c), "Arrest now shows for a case that doesn't wait"); + WaitReasons.Set(c, WaitReasons.Danger); + T.Check(!CaseLog.CanArrestNow(c), "Arrest now shows for a case that waits for the danger to pass"); + T.Check(CaseLog.Status(c).Contains("danger"), "the status of a danger wait doesn't say why: " + CaseLog.Status(c)); + // The hold JailFlow sets for a role holder or a mechanitor (JailTests drive the real hold and its letter). + WaitReasons.Set(c, WaitReasons.Hold); + T.Check(CaseLog.CanArrestNow(c), "Arrest now doesn't show for a held case"); + T.Check(CaseLog.Status(c).Contains("Arrest now"), "the status of a held case doesn't say it waits for Arrest now: " + CaseLog.Status(c)); + T.Check(!CaseLog.HoldReason(p).NullOrEmpty(), "no hold reason for the tooltip"); + Fixtures.Comp.CloseCase(c, CaseOutcomes.NotEnforced); + T.Check(!CaseLog.CanArrestNow(c), "Arrest now shows for a closed case"); + } + finally + { + c.activePunishment = null; + } + } + + [BlaxTest("ui: the jail letter names the offender, the law, the days and the release day; none with letters off")] + public static void JailLetter() + { + RemoveNewLettersAfterTest(); + var before = new HashSet(Find.LetterStack.LettersListForReading); + Law jail = Fixtures.LawRow(MissingKey, null, LawStage.DidIt, LawSeverity.Serious, "Jail", 5); + Pawn p = Fixtures.Colonist(); + LawCase c = OpenCase(jail, p); + c.activeStage = LawStage.DidIt; + c.captureTick = Find.TickManager.TicksGame; + c.releaseTick = c.captureTick + 5 * GenDate.TicksPerDay; + CaseLetters.Jailed(c); + List sent = LettersSince(before); + T.Equal(1, sent.Count, "jail letters"); + string text = (sent[0] as ChoiceLetter)?.Text.ToString() ?? ""; + T.Check(text.Contains(p.LabelShort) && text.Contains("5 days") && text.Contains(ActKey.NameOf(MissingKey)), "the jail letter: " + text); + T.Check(text.Contains(Sentences.ReleaseDate(c)) && !Sentences.ReleaseDate(c).NullOrEmpty(), "the jail letter lacks the release day: " + text); + Fixtures.Settings.jailLetters = false; + CaseLetters.Jailed(c); + T.Equal(1, LettersSince(before).Count, "jail letters with letters off"); + } + } +} diff --git a/Tests/run-tests.ps1 b/Tests/run-tests.ps1 new file mode 100644 index 0000000..b411911 --- /dev/null +++ b/Tests/run-tests.ps1 @@ -0,0 +1,248 @@ +<# +Runs the in-game test suite. RimWorld 1.7 starts headless (no window, no focus change) with its +own save data folder, so your mod list, saves and settings stay untouched. Needs Steam running and +the Harmony mod from the Workshop. Exit code: 0 all passed, 1 failures or Blax Laws errors outside +the tests, 2 the run didn't finish. + + .\Tests\run-tests.ps1 Harmony, the installed DLCs, Blax Laws + .\Tests\run-tests.ps1 -Compat also Blax Castes, Blax Zones, Blax Slaves, Blax Defaults and the installed + mods Laws is tested next to: Prison Labor, Prisoner Realism, Custom Prisoner + Interactions, Hospitality, Vanilla Social Interactions Expanded and Humanoid + Alien Races once it is installed + .\Tests\run-tests.ps1 -NoDlc core only, no DLC (tests that need a DLC skip with "needs ") + .\Tests\run-tests.ps1 -Dlc Royalty,Biotech only these installed DLCs + .\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 -DataDir another save data folder, for runs in parallel (one folder each) + .\Tests\run-tests.ps1 -Worktree run from a copy of the repo (a work package built in parallel): Mods\BlaxLaws + points at this copy for the run and back at its old target afterwards + .\Tests\run-tests.ps1 -WaitSeconds 1800 wait up to this long for another run's lock instead of failing at once + +Call it with literal switches or hashtable splatting (@{ NoDlc = $true }), never array splatting: an array +passes a switch as a positional value. +Mods\BlaxLaws must be a directory junction to this repo; it is created if missing and left in place. With -Worktree +it may point at another copy: it is retargeted for the run and restored afterwards, under the lock. +While the suite runs, the test mod is linked into the game's Mods folder as Mods\BlaxLawsTests; that link is +removed afterwards (cmd /c rmdir, never a recursive delete). A link another run left that already points at this +test mod is used as it is and left in place, so parallel runs can share one link made before and removed after. +Only one run per data folder: a lock file in the data folder holds the running script's process id. +Every run starts from default mod settings: the Blax Laws, Blax Castes, Blax Zones, Blax Slaves and Blax Defaults +settings files in the data folder are deleted. +The results go to BlaxLawsTestResults.txt in the data folder, and a copy per DLC set next to it: +BlaxLawsTestResults.all.txt (every installed DLC), .nodlc.txt, or .dlc-.txt. Runs with -Compat write +.-compat.txt instead (.all-compat.txt, .nodlc-compat.txt, ...). Each copy starts with a "REPO " line +naming the copy of the repo that was tested, so a -Worktree run never counts for the main checkout. The Workshop +upload checks the "all" and "nodlc" copies. +#> +param( + [string]$RimWorldDir = 'E:\SteamLibrary\steamapps\common\RimWorld', + [string]$DataDir = (Join-Path $env:TEMP 'BlaxLawsTest'), + [switch]$Compat, + [switch]$NoDlc, + [string[]]$Dlc, + [switch]$NoBuild, + [switch]$AllowWhileRunning, + [switch]$Worktree, + [int]$WaitSeconds = 0, + [int]$TimeoutSeconds = 900 +) +$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 +$testMod = Join-Path $PSScriptRoot 'BlaxLawsTests' +$modLink = Join-Path $RimWorldDir 'Mods\BlaxLaws' +$link = Join-Path $RimWorldDir 'Mods\BlaxLawsTests' +$workshop = Join-Path $RimWorldDir '..\..\workshop\content\294100' +$lockFile = Join-Path $DataDir 'run.lock' + +if ((Get-Process -Name RimWorld -ErrorAction SilentlyContinue) -and -not $AllowWhileRunning) { + throw 'RimWorld is running. Close it first, or pass -AllowWhileRunning.' +} + +function Get-FullPath([string]$path) { [IO.Path]::GetFullPath($path).TrimEnd('\') } + +# One run per data folder. A lock whose process is gone is stale and taken over; a live one is waited for up to -WaitSeconds. +New-Item -ItemType Directory -Force $DataDir | Out-Null +function Enter-Lock { + $deadline = [DateTime]::UtcNow.AddSeconds([Math]::Max(0, $WaitSeconds)) + $stale = 0 + $waiting = $false + while ($true) { + try { + $stream = [IO.File]::Open($lockFile, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::Read) + $bytes = [Text.Encoding]::ASCII.GetBytes([string]$PID) + $stream.Write($bytes, 0, $bytes.Length) + $stream.Close() + return + } + catch [IO.IOException] { + $owner = (Get-Content -LiteralPath $lockFile -Raw -ErrorAction SilentlyContinue) + $ownerPid = 0 + if ($owner -and [int]::TryParse($owner.Trim(), [ref]$ownerPid) -and $ownerPid -ne $PID -and (Get-Process -Id $ownerPid -ErrorAction SilentlyContinue)) { + if ([DateTime]::UtcNow -ge $deadline) { throw "Another test run (process $ownerPid) is in progress. Lock: $lockFile" } + if (-not $waiting) { Write-Host "Waiting for test run $ownerPid to finish..."; $waiting = $true } + Start-Sleep -Seconds 5 + continue + } + if (++$stale -gt 3) { throw "Could not take the lock $lockFile" } + Write-Warning "removing stale lock from process $owner" + Remove-Item -LiteralPath $lockFile -Force -ErrorAction SilentlyContinue + } + } +} +Enter-Lock + +$restoreTarget = $null +try { + # Mods\BlaxLaws: a junction to this repo. Created if missing; replaced only with -Worktree, and put back afterwards. + if (Test-Path -LiteralPath $modLink) { + $item = Get-Item -LiteralPath $modLink -Force + if (-not ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) { + throw "$modLink is a real folder, not a junction to $repo. Move it away and run again." + } + $target = @($item.Target)[0] + if (-not $target -or (Get-FullPath $target) -ne (Get-FullPath $repo)) { + if (-not $Worktree) { throw "$modLink points to '$target', not to $repo. Pass -Worktree to run from this copy." } + cmd /c rmdir "$modLink" | Out-Null + New-Item -ItemType Junction -Path $modLink -Target $repo | Out-Null + $restoreTarget = $target + Write-Host "Mods\BlaxLaws points at $repo for this run (was $target)" + } + } + else { + New-Item -ItemType Junction -Path $modLink -Target $repo | Out-Null + Write-Host "Created junction $modLink -> $repo" + } + + if (-not $NoBuild) { + foreach ($proj in (Join-Path $repo 'Source\BlaxLaws\BlaxLaws.csproj'), (Join-Path $testMod 'Source\BlaxLawsTests.csproj')) { + & dotnet build $proj -c Release -nologo -v q "-p:RimWorldDir=$RimWorldDir" + if ($LASTEXITCODE -ne 0) { throw "build failed: $proj" } + } + } + + # packageId (lower case) -> About.xml, for every installed local and Workshop mod + $installed = @{} + foreach ($about in @(Get-ChildItem (Join-Path $RimWorldDir 'Mods\*\About\About.xml') -ErrorAction SilentlyContinue) + + @(Get-ChildItem (Join-Path $workshop '*\About\About.xml') -ErrorAction SilentlyContinue)) { + $x = [xml](Get-Content -LiteralPath $about.FullName -Raw -Encoding UTF8) + if ($x.ModMetaData.packageId) { $installed[$x.ModMetaData.packageId.Trim().ToLower()] = $x } + } + function Add-WithDependencies([string]$id, [System.Collections.ArrayList]$list) { + $id = $id.ToLower() + if ($list -contains $id -or $id -like 'ludeon.*') { return } + $x = $installed[$id] + if (-not $x) { Write-Warning "not installed, skipped: $id"; return } + foreach ($dep in @($x.ModMetaData.modDependencies.li)) { if ($dep.packageId) { Add-WithDependencies $dep.packageId $list } } + [void]$list.Add($id) + } + + # Load order: Harmony, core, DLCs, the mods Laws is tested next to, Blax Castes, Blax Zones, Blax Slaves, + # Blax Defaults, Blax Laws, the tests (Laws lists the other Blax mods in loadAfter; Zones lists Castes, + # Slaves lists Zones). + # 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 + $expansions = @($installedDlcs | ForEach-Object { 'ludeon.rimworld.' + $_.ToLower() }) + [void]$mods.Add('brrainz.harmony') + [void]$mods.Add('ludeon.rimworld') + foreach ($d in $loadDlcs) { [void]$mods.Add('ludeon.rimworld.' + $d.ToLower()) } + Write-Host ("DLCs: " + $(if ($loadDlcs.Count) { $loadDlcs -join ', ' } else { 'none' })) + # Name of this DLC set for the per-set copy of the results. + $dlcSet = if ($loadDlcs.Count -eq 0) { 'nodlc' } elseif ($loadDlcs.Count -eq $installedDlcs.Count) { 'all' } else { 'dlc-' + ($loadDlcs -join '-').ToLower() } + # Other mods change what runs and what skips, so their runs never stand in for the plain ones. + if ($Compat) { $dlcSet += '-compat' } + $setResults = Join-Path $DataDir "BlaxLawsTestResults.$dlcSet.txt" + if ($Compat) { + # Package ids read from the installed copies' About/About.xml (2026-12-01). Humanoid Alien Races + # (erdelf.humanoidalienraces) is skipped with a warning while it is not installed. + foreach ($id in 'avius.prisonlabor', 'legator.prisonerrealism', 'mlie.customprisonerinteractions', 'orion.hospitality', + 'vanillaexpanded.vanillasocialinteractionsexpanded', 'erdelf.humanoidalienraces') { + Add-WithDependencies $id $mods + } + foreach ($id in 'blax.castes', 'blax.zones', 'blax.slaves', 'blax.defaults') { Add-WithDependencies $id $mods } + } + [void]$mods.Add('blax.laws') + [void]$mods.Add('blax.laws.tests') + + # fresh test data folder: mod list only, no old saves, results or mod settings (files are named Mod__.xml) + New-Item -ItemType Directory -Force (Join-Path $DataDir 'Config') | Out-Null + Remove-Item -Force -ErrorAction SilentlyContinue (Join-Path $DataDir 'Saves\BlaxLawsTest.rws'), (Join-Path $DataDir 'Saves\BlaxLawsTest3.rws'), + (Join-Path $DataDir 'BlaxLawsTestResults.txt'), $setResults + Get-ChildItem -LiteralPath (Join-Path $DataDir 'Config') -Filter 'Mod_*.xml' -ErrorAction SilentlyContinue | + Where-Object { $_.Name -like 'Mod_BlaxLaws_*' -or $_.Name -like 'Mod_blax.laws_*' -or + $_.Name -like 'Mod_BlaxCastes_*' -or $_.Name -like 'Mod_blax.castes_*' -or + $_.Name -like 'Mod_BlaxZones_*' -or $_.Name -like 'Mod_blax.zones_*' -or + $_.Name -like 'Mod_BlaxSlaves_*' -or $_.Name -like 'Mod_blax.slaves_*' -or + $_.Name -like 'Mod_BlaxDefaults_*' -or $_.Name -like 'Mod_blax.defaults_*' } | + Remove-Item -Force -ErrorAction SilentlyContinue + $li = { param($ids) ($ids | ForEach-Object { "
  • $_
  • " }) -join "`n" } + $modsConfig = "`n`n 1.7`n `n" + + (& $li $mods) + "`n `n `n" + (& $li $expansions) + "`n `n`n" + [IO.File]::WriteAllText((Join-Path $DataDir 'Config\ModsConfig.xml'), $modsConfig) + Write-Host ("Mods: " + ($mods -join ', ')) + + $createdLink = $false + try { + # A test-mod link that points elsewhere (a run from another copy that died) is replaced; one that points + # at this test mod is used as it is and left for whoever made it. + if (Test-Path -LiteralPath $link) { + $item = Get-Item -LiteralPath $link -Force + if (-not ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) { throw "$link is a real folder, not a junction. Move it away and run again." } + $target = @($item.Target)[0] + if (-not $target -or (Get-FullPath $target) -ne (Get-FullPath $testMod)) { + Write-Warning "replacing stale test-mod link $link -> $target" + cmd /c rmdir "$link" | Out-Null + } + } + if (-not (Test-Path -LiteralPath $link)) { + New-Item -ItemType Junction -Path $link -Target $testMod | Out-Null + $createdLink = $true + } + $gameArgs = "-headless -quicktest -blaxlawstests -NoFileLog -NoCrashDialog `"-savedatafolder=$DataDir`"" + $sw = [Diagnostics.Stopwatch]::StartNew() + $p = Start-Process -FilePath (Join-Path $RimWorldDir 'RimWorld.exe') -WorkingDirectory $RimWorldDir -ArgumentList $gameArgs ` + -RedirectStandardOutput (Join-Path $DataDir 'game.log') -RedirectStandardError (Join-Path $DataDir 'game.err.log') ` + -WindowStyle Hidden -PassThru + if ($AllowWhileRunning) { + try { $p.PriorityClass = [Diagnostics.ProcessPriorityClass]::BelowNormal } catch { Write-Warning "could not lower the test game's priority: $_" } + } + if (-not $p.WaitForExit($TimeoutSeconds * 1000)) { + $p.Kill() + Write-Warning "timed out after $TimeoutSeconds s, test game (process $($p.Id)) killed" + } + Write-Host ("Game ran {0:N0} s. Log: {1}" -f $sw.Elapsed.TotalSeconds, (Join-Path $DataDir 'game.log')) + } + finally { + if ($createdLink -and (Test-Path $link)) { cmd /c rmdir "$link" | Out-Null } + } +} +finally { + if ($restoreTarget) { + cmd /c rmdir "$modLink" | Out-Null + New-Item -ItemType Junction -Path $modLink -Target $restoreTarget | Out-Null + Write-Host "Mods\BlaxLaws points at $restoreTarget again" + } + Remove-Item -LiteralPath $lockFile -Force -ErrorAction SilentlyContinue +} + +$results = Join-Path $DataDir 'BlaxLawsTestResults.txt' +if (-not (Test-Path $results)) { Write-Host 'No results file: the suite never started. See game.log.'; exit 2 } +# The per-set copy names the tested copy of the repo, so the Workshop upload never takes another copy's run. +[IO.File]::WriteAllLines($setResults, [string[]](@("REPO $repo") + @(Get-Content -LiteralPath $results -Encoding UTF8)), (New-Object Text.UTF8Encoding $false)) +$lines = Get-Content -LiteralPath $results -Encoding UTF8 +$lines | ForEach-Object { Write-Host $_ } +if (-not ($lines -match '^END$')) { Write-Host 'The run did not finish.'; exit 2 } +if ($lines -match '^FAIL ') { exit 1 } +# Errors Blax Laws logged outside the tests (while a save loads, between tests) fail the run too. +$summary = @($lines -match '^SUMMARY ') | Select-Object -Last 1 +if ($summary -match '\bstrayModErrors=[1-9]') { Write-Host 'Blax Laws logged errors outside the tests (MODERR lines).'; exit 1 } +exit 0 diff --git a/Tools/WorkshopUpload/Program.cs b/Tools/WorkshopUpload/Program.cs new file mode 100644 index 0000000..7d22f13 --- /dev/null +++ b/Tools/WorkshopUpload/Program.cs @@ -0,0 +1,485 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; +using Steamworks; + +// Creates or updates a RimWorld Steam Workshop item through the running, logged-in Steam client. +// No password: SteamAPI attaches to the client as RimWorld (app 294100), like the game does. +// Without --publish it never calls a Steam write API: it checks the login and the RimWorld license, for an +// existing item reads it and checks that this Steam account owns it, and for a new one checks that no earlier, +// cut-off create left an item behind. +internal static class Program +{ + private const uint RimWorldAppId = 294100; + private const int MaxTextBytes = 8000; // Steam's limit for a description and a change note (k_cchPublishedDocumentDescriptionMax) + private const int MaxTitleBytes = 128; // k_cchPublishedDocumentTitleMax without the terminating zero + private const long MaxPreviewBytes = 1024 * 1024; // Steam refuses a preview over 1 MB + private const string LegalAgreementHint = + "Steam hides the item until you accept the Workshop legal agreement: https://steamcommunity.com/sharedfiles/workshoplegalagreement"; + + private static int Main(string[] args) + { + Options o; + try { o = Options.Parse(args); } + catch (ArgumentException e) + { + Console.Error.WriteLine(e.Message); + Console.Error.WriteLine(Options.Usage); + return 64; + } + + // Everything that can be checked without Steam comes first. + if (o.Content != null && !CheckContent(o.Content)) return 65; + if (o.Preview != null && !CheckPreview(o.Preview)) return 65; + if (o.Title != null && Encoding.UTF8.GetByteCount(o.Title) > MaxTitleBytes) + { + Console.Error.WriteLine($"The title is over Steam's {MaxTitleBytes}-byte limit."); + return 65; + } + string note = o.NoteFile != null ? File.ReadAllText(o.NoteFile, Encoding.UTF8).Trim() : null; + string description = o.DescriptionFile != null ? File.ReadAllText(o.DescriptionFile, Encoding.UTF8).Trim() : null; + if (description != null && Encoding.UTF8.GetByteCount(description) > MaxTextBytes) + { + Console.Error.WriteLine($"The description is over Steam's {MaxTextBytes}-byte limit."); + return 65; + } + if (note != null && Encoding.UTF8.GetByteCount(note) > MaxTextBytes) + { + Console.Error.WriteLine($"The change note is over Steam's {MaxTextBytes}-byte limit."); + return 65; + } + if (o.Create && File.Exists(o.IdFile)) + { + Console.Error.WriteLine($"{o.IdFile} already exists ({File.ReadAllText(o.IdFile).Trim()}): the item was created before. Update it with --item."); + return 65; + } + + // SteamAPI.Init looks for steam_appid.txt in the working directory; the env var covers other callers. + Directory.SetCurrentDirectory(AppContext.BaseDirectory); + Environment.SetEnvironmentVariable("SteamAppId", RimWorldAppId.ToString()); + if (!Packsize.Test() || !DllCheck.Test()) + { + Console.Error.WriteLine("Steamworks.NET and steam_api64.dll don't match. Rebuild the tool against the current RimWorld install."); + return 2; + } + // Never call SteamAPI.RestartAppIfNecessary here: it would make Steam launch RimWorld. + if (!SteamAPI.Init()) + { + Console.Error.WriteLine("SteamAPI.Init failed. Is Steam running and logged in, under the same Windows user, not as administrator?"); + return 2; + } + try + { + return Run(o, note, description); + } + finally + { + SteamAPI.Shutdown(); + } + } + + private static int Run(Options o, string note, string description) + { + Console.WriteLine($"Steam account: {SteamFriends.GetPersonaName()}"); + if (!SteamUser.BLoggedOn()) + { + Console.Error.WriteLine("Steam is not logged on (offline mode?). Go online in Steam and try again."); + return 3; + } + if (!SteamApps.BIsSubscribedApp(new AppId_t(RimWorldAppId))) + { + Console.Error.WriteLine("This Steam account has no RimWorld license, so it can't publish RimWorld Workshop items."); + return 3; + } + return o.Create ? RunCreate(o, note, description) : RunUpdate(o, note, description); + } + + private static int RunUpdate(Options o, string note, string description) + { + var item = new PublishedFileId_t(o.Item); + if (!QueryDetails(item, o.Timeout, out SteamUGCDetails_t d, out string[] descriptors)) return 3; + Console.WriteLine($"Item {o.Item}: \"{d.m_rgchTitle}\""); + Console.WriteLine($" updated {DateTimeOffset.FromUnixTimeSeconds(d.m_rtimeUpdated).ToLocalTime():yyyy-MM-dd HH:mm}"); + Console.WriteLine($" tags {d.m_rgchTags}"); + Console.WriteLine($" size {d.m_nFileSize / 1024.0:N0} KB"); + Console.WriteLine($" visible {VisibilityName(d.m_eVisibility)}"); + if (d.m_bBanned) Console.WriteLine(" BANNED on Steam"); + // Mature-content descriptors hide the item page from logged-out visitors and from players who didn't opt in. + Console.WriteLine($" content {(descriptors.Length > 0 ? string.Join(", ", descriptors) : "no mature-content descriptors")}"); + if (d.m_nConsumerAppID.m_AppId != RimWorldAppId) + { + Console.Error.WriteLine($"The item belongs to app {d.m_nConsumerAppID.m_AppId}, not RimWorld."); + return 3; + } + if (d.m_ulSteamIDOwner != SteamUser.GetSteamID().m_SteamID) + { + Console.Error.WriteLine("This Steam account doesn't own the item."); + return 3; + } + Console.WriteLine(" owner this account"); + + if (!o.Publish) + { + Console.WriteLine(); + Console.WriteLine("Dry run: nothing was uploaded."); + if (o.Title != null) + Console.WriteLine($" would set the title \"{o.Title}\"" + (o.Title == d.m_rgchTitle ? " (unchanged)" : $" (now \"{d.m_rgchTitle}\")")); + PrintPlan(o, note, description); + return 0; + } + + bool descriptionOnly = o.Content == null && note == null && description != null; + if (!descriptionOnly && (o.Content == null || note == null)) + { + Console.Error.WriteLine("--publish needs --content and --note-file, or only --description-file."); + return 64; + } + return Submit(item, o, note, description, false); + } + + private static int RunCreate(Options o, string note, string description) + { + Console.WriteLine(" logged on, owns RimWorld"); + int found = CheckNoEarlierItem(o); + if (found != 0) return found; + if (!o.Publish) + { + Console.WriteLine(); + Console.WriteLine("Dry run: nothing was created or uploaded."); + Console.WriteLine($" would create a new RimWorld Workshop item \"{o.Title}\""); + Console.WriteLine($" would write its id to {o.IdFile}"); + PrintPlan(o, note, description); + if (o.Visibility == null) Console.WriteLine(" visibility Steam's default for a new item, as with the in-game uploader"); + return 0; + } + + Console.WriteLine("Creating the Workshop item..."); + bool got = false, ioFailure = false; + CreateItemResult_t created = default; + var call = CallResult.Create((r, io) => { created = r; ioFailure = io; got = true; }); + call.Set(SteamUGC.CreateItem(new AppId_t(RimWorldAppId), EWorkshopFileType.k_EWorkshopFileTypeFirst)); + bool finished = Pump(() => got, o.Timeout); + GC.KeepAlive(call); + string myItems = $"https://steamcommunity.com/profiles/{SteamUser.GetSteamID().m_SteamID}/myworkshopfiles/?appid={RimWorldAppId}"; + if (!finished) + { + Console.Error.WriteLine($"No answer from Steam in time. Steam may still create the item: check {myItems} before retrying."); + return 5; + } + if (ioFailure) return Fail($"Steam reported an IO failure while creating the item. Check {myItems} before retrying."); + if (created.m_eResult != EResult.k_EResultOK) return Fail($"Steam refused to create the item: {created.m_eResult}. {Hint(created.m_eResult)}"); + + // Write the id before anything else: a failed upload must lead to an update on retry, never to a second item. + PublishedFileId_t item = created.m_nPublishedFileId; + string id = item.m_PublishedFileId.ToString(); + try + { + File.WriteAllText(o.IdFile, id); + // The game copies the id into the uploaded folder too, so the uploaded About folder matches the repo. + if (o.Content != null) File.WriteAllText(Path.Combine(o.Content, "About", "PublishedFileId.txt"), id); + } + catch (Exception e) + { + Console.Error.WriteLine($"Created item {id}, but couldn't write {o.IdFile}: {e.Message}"); + Console.Error.WriteLine($"Write {id} into that file by hand before retrying, or the next run creates a second item."); + return 4; + } + Console.WriteLine($"Created item {id}: https://steamcommunity.com/sharedfiles/filedetails/?id={id}"); + Console.WriteLine($" wrote {o.IdFile}"); + + int code = Submit(item, o, note, description, created.m_bUserNeedsToAcceptWorkshopLegalAgreement); + if (code != 0) + Console.Error.WriteLine($"Item {id} exists, but the upload didn't finish. Run the upload again: with {Path.GetFileName(o.IdFile)} in place it updates this item instead of creating another."); + return code; + } + + // A create that was cut off (no answer in time, an IO failure, the process killed or Ctrl+C between Steam + // creating the item and the answer) can leave an item on Steam with no id file, and the next run would create + // a second one. Such an item has no title yet: the title only comes with the first SubmitItemUpdate. So before + // creating, look at this account's newest RimWorld items for one with this title or none. + private static int CheckNoEarlierItem(Options o) + { + var appId = new AppId_t(RimWorldAppId); + UGCQueryHandle_t q = SteamUGC.CreateQueryUserUGCRequest(SteamUser.GetSteamID().GetAccountID(), + EUserUGCList.k_EUserUGCList_Published, EUGCMatchingUGCType.k_EUGCMatchingUGCType_Items, + EUserUGCListSortOrder.k_EUserUGCListSortOrder_CreationOrderDesc, appId, appId, 1); + bool got = false, ioFailure = false; + SteamUGCQueryCompleted_t done = default; + var call = CallResult.Create((r, io) => { done = r; ioFailure = io; got = true; }); + call.Set(SteamUGC.SendQueryUGCRequest(q)); + try + { + if (!Pump(() => got, o.Timeout)) + { + Console.Error.WriteLine("No answer from Steam for this account's Workshop items, so it is unclear whether an earlier create left an item. Try again."); + return 3; + } + if (ioFailure || done.m_eResult != EResult.k_EResultOK) + { + Console.Error.WriteLine($"The query for this account's Workshop items failed: {(ioFailure ? "IO failure" : done.m_eResult.ToString())}. Try again."); + return 3; + } + var earlier = new List(); + for (uint i = 0; i < done.m_unNumResultsReturned; i++) + { + if (!SteamUGC.GetQueryUGCResult(q, i, out SteamUGCDetails_t d) || d.m_eResult != EResult.k_EResultOK) continue; + string title = (d.m_rgchTitle ?? "").Trim(); + if (title.Length == 0 || string.Equals(title, o.Title, StringComparison.OrdinalIgnoreCase)) + earlier.Add($"{d.m_nPublishedFileId.m_PublishedFileId} ({(title.Length == 0 ? "no title" : $"\"{title}\"")})"); + } + if (earlier.Count > 0) + { + Console.Error.WriteLine("This Steam account already has a RimWorld Workshop item with this title or with no title: " + string.Join(", ", earlier) + "."); + Console.Error.WriteLine($"If it is this mod (an untitled one is an earlier create that was cut off), write its id to {o.IdFile} and run again to update it."); + Console.Error.WriteLine($"If it is not, rename or delete it on Steam first: https://steamcommunity.com/profiles/{SteamUser.GetSteamID().m_SteamID}/myworkshopfiles/?appid={RimWorldAppId}"); + return 65; + } + Console.WriteLine($" no earlier item with this title or without a title ({done.m_unNumResultsReturned} newest checked)"); + return 0; + } + finally + { + GC.KeepAlive(call); + SteamUGC.ReleaseQueryUGCRequest(q); + } + } + + private static void PrintPlan(Options o, string note, string description) + { + if (o.Content != null) Console.WriteLine($" would upload {o.Content}"); + if (o.Tags != null) Console.WriteLine($" would tag {string.Join(", ", o.Tags)}"); + if (o.Preview != null) Console.WriteLine($" would set the preview {o.Preview} ({new FileInfo(o.Preview).Length / 1024.0:N0} KB)"); + if (description != null) Console.WriteLine($" would {(o.Create ? "set" : "replace")} the description ({Encoding.UTF8.GetByteCount(description)} bytes)"); + if (o.Visibility != null) Console.WriteLine($" would set the visibility to {VisibilityName(o.Visibility.Value)}"); + if (note != null) Console.WriteLine(" change note:\n" + Indent(note)); + } + + private static int Submit(PublishedFileId_t item, Options o, string note, string description, bool legalAgreementPending) + { + UGCUpdateHandle_t h = SteamUGC.StartItemUpdate(new AppId_t(RimWorldAppId), item); + // Same fields as the game's uploader: title, description, preview, tags, content. + if (o.Title != null && !SteamUGC.SetItemTitle(h, o.Title)) return Fail("SetItemTitle refused the title."); + // Description-only updates send no content and no change note (null), so Steam lists no new change note. + if (description != null && !SteamUGC.SetItemDescription(h, description)) return Fail("SetItemDescription refused the text."); + if (o.Preview != null && !SteamUGC.SetItemPreview(h, o.Preview)) return Fail("SetItemPreview refused the preview image."); + if (o.Tags != null && !SteamUGC.SetItemTags(h, o.Tags)) return Fail("SetItemTags refused the tags."); + if (o.Content != null && !SteamUGC.SetItemContent(h, o.Content)) return Fail("SetItemContent refused the content folder."); + if (o.Visibility != null && !SteamUGC.SetItemVisibility(h, o.Visibility.Value)) return Fail("SetItemVisibility refused the visibility."); + + bool got = false, ioFailure = false; + SubmitItemUpdateResult_t result = default; + var call = CallResult.Create((r, io) => { result = r; ioFailure = io; got = true; }); + call.Set(SteamUGC.SubmitItemUpdate(h, note)); + + Console.WriteLine("Uploading..."); + EItemUpdateStatus last = EItemUpdateStatus.k_EItemUpdateStatusInvalid; + bool finished = Pump(() => got, o.Timeout, () => + { + EItemUpdateStatus s = SteamUGC.GetItemUpdateProgress(h, out ulong done, out ulong total); + if (s != last && s != EItemUpdateStatus.k_EItemUpdateStatusInvalid) + { + Console.WriteLine($" {s.ToString().Replace("k_EItemUpdateStatus", "")}" + (total > 0 ? $" {done / 1024}/{total / 1024} KB" : "")); + last = s; + } + }); + GC.KeepAlive(call); + if (!finished) + { + Console.Error.WriteLine("No answer from Steam in time. Steam may still finish the upload; check the item page before retrying."); + return 5; + } + if (ioFailure) return Fail("Steam reported an IO failure."); + if (result.m_eResult != EResult.k_EResultOK) return Fail($"Steam refused the update: {result.m_eResult}. {Hint(result.m_eResult)}"); + + Console.WriteLine($"Done: https://steamcommunity.com/sharedfiles/filedetails/?id={item.m_PublishedFileId}"); + if (legalAgreementPending || result.m_bUserNeedsToAcceptWorkshopLegalAgreement) Console.WriteLine(LegalAgreementHint); + return 0; + } + + private static bool QueryDetails(PublishedFileId_t item, TimeSpan timeout, out SteamUGCDetails_t details, out string[] descriptors) + { + details = default; + descriptors = Array.Empty(); + UGCQueryHandle_t q = SteamUGC.CreateQueryUGCDetailsRequest(new[] { item }, 1); + bool got = false, ioFailure = false; + SteamUGCQueryCompleted_t done = default; + var call = CallResult.Create((r, io) => { done = r; ioFailure = io; got = true; }); + call.Set(SteamUGC.SendQueryUGCRequest(q)); + try + { + if (!Pump(() => got, timeout)) { Console.Error.WriteLine("No answer from Steam for the item query."); return false; } + if (ioFailure || done.m_eResult != EResult.k_EResultOK || done.m_unNumResultsReturned < 1) + { + Console.Error.WriteLine($"The item query failed: {(ioFailure ? "IO failure" : done.m_eResult.ToString())}."); + return false; + } + if (!SteamUGC.GetQueryUGCResult(q, 0, out details) || details.m_eResult != EResult.k_EResultOK) + { + Console.Error.WriteLine($"Steam has no item {item}: {details.m_eResult}."); + return false; + } + var ids = new EUGCContentDescriptorID[8]; + uint count = SteamUGC.GetQueryUGCContentDescriptors(q, 0, ids, (uint)ids.Length); + descriptors = ids.Take((int)Math.Min(count, (uint)ids.Length)) + .Select(id => id.ToString().Replace("k_EUGCContentDescriptor_", "")).ToArray(); + return true; + } + finally + { + GC.KeepAlive(call); + SteamUGC.ReleaseQueryUGCRequest(q); + } + } + + private static bool Pump(Func done, TimeSpan timeout, Action eachTick = null) + { + var sw = Stopwatch.StartNew(); + while (!done()) + { + SteamAPI.RunCallbacks(); + eachTick?.Invoke(); + if (sw.Elapsed > timeout) return false; + Thread.Sleep(100); + } + return true; + } + + private static bool CheckContent(string dir) + { + if (!Directory.Exists(dir)) { Console.Error.WriteLine($"No content folder at {dir}."); return false; } + if (!File.Exists(Path.Combine(dir, "About", "About.xml"))) { Console.Error.WriteLine($"{dir} has no About\\About.xml."); return false; } + string[] devOnly = { ".git", "Source", "Tests", "obj", "bin" }; + var found = Directory.GetDirectories(dir, "*", SearchOption.AllDirectories) + .Where(p => devOnly.Contains(Path.GetFileName(p), StringComparer.OrdinalIgnoreCase)).ToList(); + if (found.Count > 0) + { + Console.Error.WriteLine("The content folder holds development folders that players don't need:\n" + Indent(string.Join("\n", found))); + return false; + } + var files = Directory.GetFiles(dir, "*", SearchOption.AllDirectories); + Console.WriteLine($"Content: {dir} ({files.Length} files, {files.Sum(f => new FileInfo(f).Length) / 1024.0:N0} KB)"); + return true; + } + + private static bool CheckPreview(string file) + { + if (!File.Exists(file)) { Console.Error.WriteLine($"No preview image at {file}."); return false; } + long size = new FileInfo(file).Length; + if (size > MaxPreviewBytes) + { + Console.Error.WriteLine($"The preview {file} is {size / 1024.0:N0} KB; Steam takes at most 1 MB."); + return false; + } + return true; + } + + private static string VisibilityName(ERemoteStoragePublishedFileVisibility v) => + v.ToString().Replace("k_ERemoteStoragePublishedFileVisibility", ""); + + private static string Hint(EResult r) => r switch + { + EResult.k_EResultAccessDenied => "The account needs a RimWorld license.", + EResult.k_EResultFileNotFound => "Steam couldn't read the content folder or the preview.", + EResult.k_EResultLimitExceeded => "The preview is over 1 MB, or the Steam Cloud quota is full.", + EResult.k_EResultLockingFailed => "Steam couldn't lock the item; try again in a minute.", + EResult.k_EResultInvalidParam => "Steam rejected a field; check the title, the tags and the content path.", + EResult.k_EResultInsufficientPrivilege => "Steam restricts this account from uploading (a ban, an account lock or a limited account).", + EResult.k_EResultBanned => "Steam restricts this account from uploading (a ban, an account lock or a limited account).", + EResult.k_EResultNotLoggedOn => "Steam is not logged on.", + EResult.k_EResultTimeout or EResult.k_EResultServiceUnavailable => "The Workshop didn't answer; try again later.", + _ => "", + }; + + private static int Fail(string message) + { + Console.Error.WriteLine(message); + return 4; + } + + private static string Indent(string text) => string.Join("\n", text.Split('\n').Select(l => " " + l.TrimEnd('\r'))); + + private sealed class Options + { + public const string Usage = + "Usage: WorkshopUpload (--item | --create --id-file ) [--content ] [--note-file ]\n" + + " [--tags Mod,1.7] [--title ] [--preview ] [--description-file ]\n" + + " [--visibility public|friends|private|unlisted] [--timeout ] [--publish]\n" + + "Without --publish it calls no Steam write API: it checks the login and the RimWorld license, and with --item\n" + + "reads the item and checks ownership. With --item and only --description-file (title, preview and visibility\n" + + "optional) --publish replaces the description and nothing else. --create --publish creates a new item, writes\n" + + "its id to --id-file at once, then uploads; it needs --title, --content, --note-file, --description-file and\n" + + "--preview. --create, also without --publish, first refuses if this account has an item with the same title\n" + + "or with no title (an earlier create that was cut off). Without --visibility the item keeps its visibility\n" + + "(a new item gets Steam's default)."; + + public ulong Item; + public bool Create; + public string Content, NoteFile, DescriptionFile, Title, Preview, IdFile; + public List Tags; + public ERemoteStoragePublishedFileVisibility? Visibility; + public TimeSpan Timeout = TimeSpan.FromMinutes(15); + public bool Publish; + + public static Options Parse(string[] args) + { + var o = new Options(); + for (int i = 0; i < args.Length; i++) + { + string Next() => i + 1 < args.Length ? args[++i] : throw new ArgumentException($"{args[i]} needs a value."); + switch (args[i]) + { + case "--item": + if (!ulong.TryParse(Next(), out o.Item)) throw new ArgumentException("--item must be a number."); + break; + case "--create": o.Create = true; break; + case "--id-file": o.IdFile = Path.GetFullPath(Next()); break; + case "--content": o.Content = Path.GetFullPath(Next()); break; + case "--note-file": o.NoteFile = ExistingFile(Next()); break; + case "--description-file": o.DescriptionFile = ExistingFile(Next()); break; + case "--tags": o.Tags = Next().Split(',').Select(t => t.Trim()).Where(t => t.Length > 0).ToList(); break; + case "--title": + o.Title = Next().Trim(); + if (o.Title.Length == 0) throw new ArgumentException("--title is empty."); + break; + case "--preview": o.Preview = Path.GetFullPath(Next()); break; + case "--visibility": o.Visibility = ParseVisibility(Next()); break; + case "--timeout": o.Timeout = TimeSpan.FromSeconds(int.Parse(Next())); break; + case "--publish": o.Publish = true; break; + default: throw new ArgumentException($"Unknown argument {args[i]}."); + } + } + if (o.Create && o.Item != 0) throw new ArgumentException("--item and --create don't go together."); + if (!o.Create && o.Item == 0) throw new ArgumentException("--item or --create is required."); + if (o.Create) + { + if (o.IdFile == null) throw new ArgumentException("--create needs --id-file, where the new item's id goes."); + if (!Directory.Exists(Path.GetDirectoryName(o.IdFile))) throw new ArgumentException($"No folder for --id-file {o.IdFile}."); + if (o.Title == null) throw new ArgumentException("--create needs --title."); + if (o.Publish && (o.Content == null || o.NoteFile == null || o.DescriptionFile == null || o.Preview == null)) + throw new ArgumentException("--create --publish needs --content, --note-file, --description-file and --preview."); + } + else if (o.IdFile != null) throw new ArgumentException("--id-file goes with --create."); + return o; + } + + private static ERemoteStoragePublishedFileVisibility ParseVisibility(string value) => value.ToLowerInvariant() switch + { + "public" => ERemoteStoragePublishedFileVisibility.k_ERemoteStoragePublishedFileVisibilityPublic, + "friends" => ERemoteStoragePublishedFileVisibility.k_ERemoteStoragePublishedFileVisibilityFriendsOnly, + "private" => ERemoteStoragePublishedFileVisibility.k_ERemoteStoragePublishedFileVisibilityPrivate, + "unlisted" => ERemoteStoragePublishedFileVisibility.k_ERemoteStoragePublishedFileVisibilityUnlisted, + _ => throw new ArgumentException($"--visibility must be public, friends, private or unlisted, not {value}."), + }; + + private static string ExistingFile(string path) + { + string full = Path.GetFullPath(path); + if (!File.Exists(full)) throw new ArgumentException($"No file at {full}."); + return full; + } + } +} diff --git a/Tools/WorkshopUpload/WorkshopUpload.csproj b/Tools/WorkshopUpload/WorkshopUpload.csproj new file mode 100644 index 0000000..dfe772d --- /dev/null +++ b/Tools/WorkshopUpload/WorkshopUpload.csproj @@ -0,0 +1,33 @@ + + + + + Exe + net10.0 + x64 + latest + disable + disable + false + false + E:\SteamLibrary\steamapps\common\RimWorld + + + + + $(RimWorldDir)\com.rlabrecque.steamworks.net.dll + true + + + + + + + + + + diff --git a/Tools/workshop-stage.ps1 b/Tools/workshop-stage.ps1 new file mode 100644 index 0000000..d18b7f1 --- /dev/null +++ b/Tools/workshop-stage.ps1 @@ -0,0 +1,63 @@ +<# +Fallback for the game's own Workshop button; the usual way is Tools\workshop-upload.ps1. RimWorld's uploader +copies the whole mod folder, hidden files included, and this repo is the mod folder (junctioned into +Mods\, where is the name in About\About.xml without spaces). So: + + .\Tools\workshop-stage.ps1 swap the dev junction for a clean copy (only what players need) + (upload in game: Options > Development mode, Mods > the mod > Advanced... > Upload to Steam Workshop) + .\Tools\workshop-stage.ps1 -Done copy About\PublishedFileId.txt back into the repo, restore the junction + +A first upload in game creates the Workshop item and writes About\PublishedFileId.txt into the clean copy. +-Done copies it into the repo; commit it. From then on Tools\workshop-upload.ps1 updates that item. + +Run with RimWorld closed. +#> +param( + [string]$RimWorldDir = 'E:\SteamLibrary\steamapps\common\RimWorld', + [switch]$Done +) +$ErrorActionPreference = 'Stop' +$repo = Split-Path -Parent $PSScriptRoot +$about = [xml](Get-Content -LiteralPath (Join-Path $repo 'About\About.xml') -Raw -Encoding UTF8) +$name = "$($about.ModMetaData.name)".Trim() +if (-not $name) { throw 'About.xml has no name.' } +$modDir = Join-Path $RimWorldDir ('Mods\' + ($name -replace '\s', '')) +$ship = 'About', '1.7', 'Defs', 'Patches', 'Languages', 'Textures', 'Sounds' + +if (Get-Process -Name RimWorld -ErrorAction SilentlyContinue) { throw 'Close RimWorld first.' } + +function Test-Junction([string]$path) { + (Test-Path $path) -and ((Get-Item $path -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) +} + +if (-not $Done) { + if (Test-Path $modDir) { + if (-not (Test-Junction $modDir)) { throw "$modDir is already a real folder. Run with -Done first." } + cmd /c rmdir "$modDir" | Out-Null + } + New-Item -ItemType Directory $modDir | Out-Null + foreach ($dir in $ship) { + $src = Join-Path $repo $dir + if (Test-Path $src) { Copy-Item $src (Join-Path $modDir $dir) -Recurse } + } + Get-ChildItem $modDir -Recurse -File | Where-Object { $_.Extension -in '.pdb' } | Remove-Item + $files = Get-ChildItem $modDir -Recurse -File + Write-Host ("Clean copy ready at {0}: {1} files, {2:N0} KB" -f $modDir, $files.Count, (($files | Measure-Object Length -Sum).Sum / 1KB)) + $files | ForEach-Object { ' ' + $_.FullName.Substring($modDir.Length + 1) } | Write-Host + $action = if (Test-Path (Join-Path $repo 'About\PublishedFileId.txt')) { 'Update on Steam Workshop' } else { 'Upload to Steam Workshop (creates the item)' } + Write-Host "Now in game: Options > Development mode, Mods > $name > Advanced... > $action." + Write-Host 'Then run: .\Tools\workshop-stage.ps1 -Done' +} +else { + if (Test-Junction $modDir) { Write-Host 'Already restored.'; exit 0 } + $id = Join-Path $modDir 'About\PublishedFileId.txt' + if (Test-Path $id) { + Copy-Item $id (Join-Path $repo 'About\PublishedFileId.txt') -Force + Write-Host ("Workshop item: https://steamcommunity.com/sharedfiles/filedetails/?id=" + (Get-Content $id -Raw).Trim()) + Write-Host 'Commit About\PublishedFileId.txt.' + } + else { Write-Warning 'No PublishedFileId.txt: the upload did not happen (or failed).' } + if (Test-Path $modDir) { Remove-Item $modDir -Recurse -Force } + New-Item -ItemType Junction -Path $modDir -Target $repo | Out-Null + Write-Host 'Dev junction restored.' +} diff --git a/Tools/workshop-upload.ps1 b/Tools/workshop-upload.ps1 new file mode 100644 index 0000000..0a8f751 --- /dev/null +++ b/Tools/workshop-upload.ps1 @@ -0,0 +1,337 @@ +<# +Uploads this mod to the Steam Workshop from the command line, through the running Steam client: no password, +no game window, no dev mode. RimWorld may stay open. Everything per mod comes from About\About.xml (name, +packageId, modVersion, supportedVersions), so the same script works in every mod that has this Tools folder. + +Without About\PublishedFileId.txt it creates a new Workshop item; with it, it updates that item. + + .\Tools\workshop-upload.ps1 dry run: builds, stages a clean copy, checks the Steam login and the + RimWorld license, and for an existing item reads it and checks that + this Steam account owns it. Lists what -Publish would refuse. Uploads nothing. + .\Tools\workshop-upload.ps1 -Check release check: runs every -Publish check and the dry run, then lists + each problem. Exit code 0 when there is none, 1 otherwise. Uploads nothing. + .\Tools\workshop-upload.ps1 -Publish uploads the staged copy. The change note is every CHANGELOG.md entry + newer than the version in Tools\workshop-published.txt. + -DescriptionFile docs\workshop-description.txt also replaces the Workshop description (BBCode). It defaults + to docs\workshop-description.txt when that file exists and nothing was + published from here yet (no Tools\workshop-published.txt). A new item needs one. + -DescriptionOnly with -DescriptionFile: replaces only the description. No build, no + content upload, no change note, no title or preview. + -Visibility public|friends|private|unlisted who sees the item. Left out, an existing item keeps its + visibility and a new item is created Public (Steam's own default + for a new item is Private). Pass -Visibility private to review a + new item before anyone else sees it. + +The title is About.xml's name and the preview is About\Preview.png (under 1 MB), set on every upload like the +in-game uploader does. + +A new item: -Publish creates it and writes its id to About\PublishedFileId.txt at once, before the content +upload, so a failed upload is retried as an update and never makes a second item. After a successful upload +it writes Tools\workshop-published.txt. Commit both files. Before it creates an item, and in the dry run, the +tool looks at this Steam account's newest RimWorld items and refuses if one has the same title or no title (an +earlier create that was cut off before its id was written): put that id into About\PublishedFileId.txt instead. + +-Publish refuses unless: +- the shipped files, CHANGELOG.md and the description file are committed and pushed, and the top CHANGELOG.md + entry matches About.xml's modVersion; +- two Tests\run-tests.ps1 runs from this copy of the repo passed after the last change to the shipped files + (1.7, Defs, Patches, Languages, About\About.xml): one with every installed DLC (TestResults.all.txt) + and one with -NoDlc (TestResults.nodlc.txt). Passed means its SUMMARY line shows fail=0, at least one + pass and no strayModErrors or strayModWarnings (errors the mod logged between tests, for example while a save + loads). is the mod name without spaces; the files are in -TestResultsDir, by default + $env:TEMP\Test like the runner's -DataDir. -Compat runs write .all-compat.txt and .nodlc-compat.txt + copies, which don't count; +- About\Preview.png exists and is under 1 MB; +- the description file is in the repo, fits Steam's 8000-byte limit, every [img] in it loads with an + Access-Control-Allow-Origin header (Steam loads description images cross-origin and shows a broken image + otherwise), and every forgejo.blax.at link in it, in any form, opens without a login; +- a new item has a description file. +With -DescriptionOnly only the description checks apply, plus: pushed, and the description file committed. +-SkipChecks skips those checks. The in-game button (Tools\workshop-stage.ps1) still works as a fallback. +#> +param( + [string]$RimWorldDir = 'E:\SteamLibrary\steamapps\common\RimWorld', + [switch]$Publish, + [switch]$Check, + [string]$DescriptionFile, + [switch]$DescriptionOnly, + [ValidateSet('public', 'friends', 'private', 'unlisted')] + [string]$Visibility, + [string]$TestResultsDir, + [switch]$SkipChecks +) +$ErrorActionPreference = 'Stop' +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$repo = Split-Path -Parent $PSScriptRoot +$ship = 'About', '1.7', 'Defs', 'Patches', 'Languages', 'Textures', 'Sounds' +$toolProj = Join-Path $PSScriptRoot 'WorkshopUpload\WorkshopUpload.csproj' +$toolExe = Join-Path $PSScriptRoot 'WorkshopUpload\bin\Release\WorkshopUpload.exe' +$idFile = Join-Path $repo 'About\PublishedFileId.txt' +$previewFile = Join-Path $repo 'About\Preview.png' +$publishedFile = Join-Path $PSScriptRoot 'workshop-published.txt' +$utf8 = New-Object Text.UTF8Encoding $false +if ($Publish -and $Check) { throw '-Publish and -Check do not go together: -Check never uploads.' } +if ($Check -and $SkipChecks) { throw '-Check and -SkipChecks do not go together.' } +if ($DescriptionOnly -and -not $DescriptionFile) { throw '-DescriptionOnly needs -DescriptionFile.' } + +$about = [xml](Get-Content -LiteralPath (Join-Path $repo 'About\About.xml') -Raw -Encoding UTF8) +$name = "$($about.ModMetaData.name)".Trim() +$packageId = "$($about.ModMetaData.packageId)".Trim() +$modVersion = "$($about.ModMetaData.modVersion)".Trim() +if (-not $name -or -not $packageId) { throw 'About.xml needs a name and a packageId.' } +# Same prefix as the mod folder junction and the test runner's files: the name without spaces. +$prefix = $name -replace '\s', '' +if (-not $TestResultsDir) { $TestResultsDir = Join-Path $env:TEMP "${prefix}Test" } +# Same tags the in-game uploader sets: "Mod" plus Major.Minor of every supported version. +$tags = @('Mod') + @($about.ModMetaData.supportedVersions.li | ForEach-Object { $v = [version]"$_".Trim(); "$($v.Major).$($v.Minor)" }) + +$create = -not (Test-Path -LiteralPath $idFile) +if ($create) { + if ($DescriptionOnly) { throw 'There is no Workshop item yet (no About\PublishedFileId.txt), so there is no description to replace.' } + Write-Host "$name ${modVersion}: creates a new Workshop item (no About\PublishedFileId.txt yet)." +} +else { + $itemId = (Get-Content -LiteralPath $idFile -Raw).Trim() + if ($itemId -notmatch '^\d+$') { throw "About\PublishedFileId.txt holds '$itemId', not a Workshop item id." } + Write-Host "$name ${modVersion}: updates Workshop item $itemId." +} +$defaultDescription = Join-Path $repo 'docs\workshop-description.txt' +if (-not $DescriptionFile -and ($create -or -not (Test-Path -LiteralPath $publishedFile)) -and (Test-Path -LiteralPath $defaultDescription)) { + $DescriptionFile = $defaultDescription + Write-Host 'Description: docs\workshop-description.txt' +} +if ($DescriptionFile) { $DescriptionFile = (Resolve-Path -LiteralPath $DescriptionFile).Path } + +# Change note: every CHANGELOG.md entry newer than the last version published from here +# (Tools\workshop-published.txt, written after each successful -Publish). +$lastPublished = if (Test-Path -LiteralPath $publishedFile) { [version](Get-Content -LiteralPath $publishedFile -Raw).Trim() } else { [version]'0.0' } +$sections = [ordered]@{} +$current = $null +foreach ($line in Get-Content -LiteralPath (Join-Path $repo 'CHANGELOG.md') -Encoding UTF8) { + if ($line -match '^##\s+(.+)$') { $current = $Matches[1].Trim(); $sections[$current] = New-Object System.Collections.ArrayList; continue } + if ($current -and $line.Trim()) { [void]$sections[$current].Add($line.TrimEnd()) } +} +if ($sections.Count -eq 0) { throw 'CHANGELOG.md has no "## " entry.' } +$topVersion = @($sections.Keys)[0] +$noteLines = @() +foreach ($v in $sections.Keys) { + if ([version]$v -le $lastPublished) { break } + if ($noteLines) { $noteLines += '' } + $noteLines += @("$name $v") + $sections[$v] +} +if (-not $noteLines) { $noteLines = @("$name $topVersion") + $sections[$topVersion] } +$note = ($noteLines -join "`n").Trim() + +# Native commands write to stderr; under 'Stop' PowerShell 5.1 would turn that into an error. +function Invoke-Git([string[]]$gitArgs) { + $ErrorActionPreference = 'Continue' + & git -C $repo $gitArgs 2>$null +} + +# HTTP status of a GET without following redirects (a login redirect must not count as "opens"). +function Get-HttpStatus([string]$url) { + $req = [Net.HttpWebRequest]::Create($url) + $req.AllowAutoRedirect = $false + $req.Timeout = 20000 + $req.UserAgent = 'workshop-upload' + try { + $resp = $req.GetResponse() + $code = [int]$resp.StatusCode + $resp.Close() + return $code + } + catch { + $e = $_.Exception + while ($e -and -not ($e -is [Net.WebException])) { $e = $e.InnerException } + if ($e -and $e.Response) { + $code = [int]$e.Response.StatusCode + $e.Response.Close() + return $code + } + return "no answer ($(if ($e) { $e.Message } else { $_.Exception.Message }))" + } +} + +# Steam adds crossorigin to description images, so a host without Access-Control-Allow-Origin shows a broken image. +function Test-DescriptionImages([string]$text) { + $found = @() + foreach ($m in [regex]::Matches($text, '\[img\](.*?)\[/img\]')) { + $url = $m.Groups[1].Value.Trim() + try { + $r = Invoke-WebRequest -Uri $url -UseBasicParsing -Headers @{ Origin = 'https://steamcommunity.com' } + $type = "$($r.Headers['Content-Type'])" + $acao = "$($r.Headers['Access-Control-Allow-Origin'])" + if ($type -notlike 'image/*') { $found += "$url is not an image ($type)." } + elseif ($acao -ne '*' -and $acao -ne 'https://steamcommunity.com') { $found += "$url sends no Access-Control-Allow-Origin header; Steam would show it broken." } + } + catch { $found += "$url does not load: $($_.Exception.Message)" } + } + $found +} + +# A link to a private Forgejo repo shows players a 404 or a login page. Every form counts: [url=...], +# [url]...[/url] and a bare link, which Steam turns into a link too. +function Test-DescriptionLinks([string]$text) { + $found = @() + $urls = @([regex]::Matches($text, 'https?://forgejo\.blax\.at/[^\s\[\]"]+') | ForEach-Object { $_.Value.TrimEnd('.', ',', ';', ':', '!', '?', ')') } | Select-Object -Unique) + foreach ($url in $urls) { + if ($url -like 'http://*') { $found += "$url uses http. Link to the https address."; continue } + $status = Get-HttpStatus $url + if ($status -ne 200) { $found += "$url answers $status without a login: the repo is private. Make it public first." } + } + $found +} + +if (-not $DescriptionOnly) { + foreach ($proj in Get-ChildItem (Join-Path $repo 'Source\*\*.csproj')) { + & dotnet build $proj.FullName -c Release -nologo -v q "-p:RimWorldDir=$RimWorldDir" + if ($LASTEXITCODE -ne 0) { throw "build failed: $($proj.Name)" } + } +} +& dotnet build $toolProj -c Release -nologo -v q "-p:RimWorldDir=$RimWorldDir" +if ($LASTEXITCODE -ne 0) { throw 'build failed: WorkshopUpload' } + +# Publish checks. Image problems are always shown; the rest is skipped with -SkipChecks. +$imageProblems = @() +$problems = @() +if ($DescriptionFile) { + $descText = [IO.File]::ReadAllText($DescriptionFile, [Text.Encoding]::UTF8).Trim() + $imageProblems = @(Test-DescriptionImages $descText) +} +if (-not $SkipChecks) { + $problems += $imageProblems + if ($DescriptionFile) { + $bytes = [Text.Encoding]::UTF8.GetByteCount($descText) + if ($bytes -gt 8000) { $problems += "The description is $bytes bytes; Steam takes at most 8000." } + $problems += @(Test-DescriptionLinks $descText) + } + elseif ($create) { $problems += 'A new Workshop item needs a description: write docs\workshop-description.txt or pass -DescriptionFile.' } + $ahead = Invoke-Git @('rev-list', '--count', '@{u}..HEAD') + if ($LASTEXITCODE -ne 0) { $problems += 'The branch has no upstream to compare with.' } + elseif ([int]$ahead -gt 0) { $problems += "$ahead commit(s) not pushed yet, so the Workshop would show what the repo doesn't." } + # The description and the change note go to Steam too, so they must be in the pushed repo like the shipped files. + $textFiles = @() + if ($DescriptionFile) { + if ($DescriptionFile.StartsWith($repo + '\', [StringComparison]::OrdinalIgnoreCase)) { $textFiles += $DescriptionFile } + else { $problems += "The description file $DescriptionFile is not in the repo, so it cannot be committed." } + } + if (-not $DescriptionOnly) { $textFiles += 'CHANGELOG.md' } + if ($textFiles) { + # --ignored: an ignored description file never reaches the repo either. + $dirty = @(Invoke-Git (@('status', '--porcelain', '--ignored', '--') + $textFiles)) + if ($LASTEXITCODE -ne 0) { $problems += "git status failed for $($textFiles -join ', ')." } + elseif ($dirty) { $problems += "Uncommitted changes in the description or changelog:`n$($dirty -join "`n")" } + } + if (-not $DescriptionOnly) { + if (-not (Test-Path -LiteralPath $previewFile)) { $problems += 'About\Preview.png is missing; Steam shows it as the item picture.' } + elseif ((Get-Item -LiteralPath $previewFile).Length -gt 1MB) { $problems += ('About\Preview.png is {0:N0} KB; Steam takes at most 1 MB.' -f ((Get-Item -LiteralPath $previewFile).Length / 1KB)) } + if ($topVersion -ne $modVersion) { $problems += "CHANGELOG.md's top entry is $topVersion, About.xml says $modVersion." } + $dirty = @(Invoke-Git (@('status', '--porcelain', '--') + $ship)) + if ($LASTEXITCODE -ne 0) { $problems += 'git status failed for the shipped files.' } + elseif ($dirty) { $problems += "Uncommitted changes in shipped files:`n$($dirty -join "`n")" } + # Everything the game loads from the mod. A change to any of it after a test run makes that run stale, + # also when the DLL stays the same (Defs, Patches, Languages, loadAfter or dependencies in About.xml). + $newest = @(foreach ($d in '1.7', 'Defs', 'Patches', 'Languages') { + $p = Join-Path $repo $d + if (Test-Path -LiteralPath $p) { Get-ChildItem -LiteralPath $p -Recurse -File | Where-Object Extension -ne '.pdb' } + }) + @(Get-Item -LiteralPath (Join-Path $repo 'About\About.xml')) | Sort-Object LastWriteTime -Descending | Select-Object -First 1 + # The mod must work with and without DLCs: a passing run with every installed DLC and one with none. + foreach ($set in @(@{ name = 'all'; run = '.\Tests\run-tests.ps1' }, @{ name = 'nodlc'; run = '.\Tests\run-tests.ps1 -NoDlc' })) { + $file = Join-Path $TestResultsDir "${prefix}TestResults.$($set.name).txt" + if (-not (Test-Path -LiteralPath $file)) { $problems += "No test results at $file. Run $($set.run) first."; continue } + $res = Get-Item -LiteralPath $file + $lines = @(Get-Content -LiteralPath $file -Encoding UTF8) + # Errors the mod logs between tests (save and reload, later phases, after the last test) write no FAIL + # line, only MODERR lines and the counts on the SUMMARY line. + $summary = @($lines -match '^SUMMARY ') | Select-Object -Last 1 + $ranFrom = @($lines -match '^REPO ') | Select-Object -First 1 + $last = "The last $($set.run) run" + if (-not ($lines -match '^END$') -or -not $summary) { $problems += "$last did not finish." } + elseif (-not $ranFrom) { $problems += "$last is from a runner that doesn't record which copy of the repo it tested. Run it again." } + elseif ($lines -notcontains "REPO $repo") { $problems += "$last ran from another copy of the repo ($($ranFrom.Substring(5)))." } + elseif ($summary -notmatch '\bfail=0\b' -or ($lines -match '^FAIL ')) { + $failed = if ($summary -match '\bfail=(\d+)') { $Matches[1] } else { 'some' } + $problems += "$last failed $failed test(s)." + } + elseif ($summary -notmatch '\bpass=[1-9]') { $problems += "$last passed no test: $summary" } + elseif ($summary -match '\bstrayModErrors=([1-9]\d*)') { $problems += "$last logged $($Matches[1]) mod error(s) outside the tests (MODERR lines in $file)." } + elseif ($summary -match '\bstrayModWarnings=([1-9]\d*)') { $problems += "$last logged $($Matches[1]) mod warning(s) outside the tests." } + elseif ($newest -and $res.LastWriteTime -lt $newest.LastWriteTime) { + $problems += "$last ($($res.LastWriteTime)) is older than the last change to the shipped files ($($newest.FullName.Substring($repo.Length + 1)), $($newest.LastWriteTime)). Run it again." + } + } + } +} +if ($Publish) { + if ($SkipChecks) { foreach ($p in $imageProblems) { Write-Warning $p } } + elseif ($problems) { throw ("Not publishing:`n- " + ($problems -join "`n- ")) } +} +elseif (-not $Check) { + if ($SkipChecks) { foreach ($p in $imageProblems) { Write-Warning $p } } + else { foreach ($p in $problems) { Write-Warning "-Publish would refuse: $p" } } +} + +if ($create) { $toolArgs = @('--create', '--id-file', $idFile) } else { $toolArgs = @('--item', $itemId) } +if ($DescriptionOnly) { + $toolArgs += @('--description-file', $DescriptionFile) +} +else { + # Clean copy outside the repo: only what players need, no PDBs. TEMP has no spaces in its path. + $root = Join-Path $env:TEMP 'BlaxWorkshopUpload' + $stage = Join-Path $root $packageId + if (Test-Path $stage) { Remove-Item $stage -Recurse -Force } + New-Item -ItemType Directory $stage -Force | Out-Null + foreach ($dir in $ship) { + $src = Join-Path $repo $dir + if (Test-Path $src) { Copy-Item $src (Join-Path $stage $dir) -Recurse } + } + Get-ChildItem $stage -Recurse -File -Filter *.pdb | Remove-Item + $noteFile = Join-Path $root "$packageId.note.txt" + [IO.File]::WriteAllText($noteFile, $note, $utf8) + + $toolArgs += @('--content', $stage, '--note-file', $noteFile, '--tags', ($tags -join ','), '--title', $name) + # The tool refuses a missing preview. A dry run or -Check without one still checks the Steam side; the + # missing preview is listed above. + if ($Publish -or (Test-Path -LiteralPath $previewFile)) { $toolArgs += @('--preview', $previewFile) } + if ($DescriptionFile) { $toolArgs += @('--description-file', $DescriptionFile) } +} +# Steam creates new items Private; a release is meant to be seen, so a new item is Public unless told otherwise. +if (-not $Visibility -and $create) { $Visibility = 'public' } +if ($Visibility) { $toolArgs += @('--visibility', $Visibility) } +if ($Publish) { $toolArgs += '--publish' } + +# steam_api writes status lines to stderr; under 'Stop' PowerShell 5.1 would turn them into errors. +$ErrorActionPreference = 'Continue' +$toolOut = New-Object System.Collections.Generic.List[string] +Push-Location (Split-Path $toolExe) +try { + & $toolExe @toolArgs 2>&1 | ForEach-Object { "$_" } | Where-Object { $_ -notmatch '^(Setting breakpad|SteamInternal_)' } | ForEach-Object { $toolOut.Add($_); $_ } + $code = $LASTEXITCODE +} +finally { Pop-Location } + +if ($Check) { + if ($code -ne 0) { + $last = @($toolOut | Where-Object { $_.Trim() }) | Select-Object -Last 1 + $problems += "The Steam dry run failed (exit code $code): $last" + } + Write-Host '' + if ($problems) { + Write-Host "Release check: $($problems.Count) problem(s) before $name $modVersion can be published:" + foreach ($p in $problems) { Write-Host "- $p" } + exit 1 + } + Write-Host "Release check: no problems. $name $modVersion is ready for .\Tools\workshop-upload.ps1 -Publish." + exit 0 +} +if ($Publish -and -not $DescriptionOnly) { + if ($code -eq 0) { + [IO.File]::WriteAllText($publishedFile, "$topVersion`n", $utf8) + if ($create) { Write-Host "Recorded $topVersion in Tools\workshop-published.txt. Commit it and About\PublishedFileId.txt." } + else { Write-Host "Recorded $topVersion in Tools\workshop-published.txt. Commit it." } + } + elseif ($create -and (Test-Path -LiteralPath $idFile)) { + Write-Host 'The Workshop item exists now (About\PublishedFileId.txt), but the upload did not finish. Commit that file; -Publish again updates the item.' + } +} +exit $code diff --git a/docs/art/blax-oss-banner.png b/docs/art/blax-oss-banner.png new file mode 100644 index 0000000..6385241 Binary files /dev/null and b/docs/art/blax-oss-banner.png differ diff --git a/docs/art/blax-oss-banner.svg b/docs/art/blax-oss-banner.svg new file mode 100644 index 0000000..5796e28 --- /dev/null +++ b/docs/art/blax-oss-banner.svg @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/art/steam/compatibility.png b/docs/art/steam/compatibility.png new file mode 100644 index 0000000..ee61f75 Binary files /dev/null and b/docs/art/steam/compatibility.png differ diff --git a/docs/art/steam/crimes.png b/docs/art/steam/crimes.png new file mode 100644 index 0000000..4ea59b7 Binary files /dev/null and b/docs/art/steam/crimes.png differ diff --git a/docs/art/steam/lawbook.png b/docs/art/steam/lawbook.png new file mode 100644 index 0000000..2acd108 Binary files /dev/null and b/docs/art/steam/lawbook.png differ diff --git a/docs/art/steam/planned.png b/docs/art/steam/planned.png new file mode 100644 index 0000000..9268e9d Binary files /dev/null and b/docs/art/steam/planned.png differ diff --git a/docs/art/steam/punishments.png b/docs/art/steam/punishments.png new file mode 100644 index 0000000..26b70e2 Binary files /dev/null and b/docs/art/steam/punishments.png differ diff --git a/docs/design.md b/docs/design.md index 6973dd5..582bdb0 100644 --- a/docs/design.md +++ b/docs/design.md @@ -2,7 +2,7 @@ Write a lawbook and the colony enforces it. Add "Drug binge, wake-up, planning, subdue" and when a colonist starts a wake-up binge, a warden goes for it at once and beats it down; if it reaches a drug first, that dose counts as "did it" and the did-it law applies. Add "Drug binge, did it, jail 5 days" and the one who already took some is arrested, sits out five days in your prison and walks back to work. The book starts empty. A law's Action is picked from a searchable list the mod builds from the game's own defs, the way you pick what to tailor: every mental break, everything that can be eaten or used, every social interaction, every act the game records and every bill, with DLC and modded content included. Laws only watches what the game already does. Beyond that it covers sentences that give back what jail took, repeat offenders, a court with a judge the colony elects, attorneys who argue with their Social skill, witnesses and trials over several days, and colony votes on the laws themselves. What the mod covers and in which order: `docs/features.md`. -Status: design, no code yet. Checked against the RimWorld 1.7.5021 game code on 2026-11-30; the act catalogue (2026-12-01) was checked against the 1.7.5021 reference assemblies, which have every signature and no method bodies, so its behaviour claims are listed under "To verify" until the decompiled code confirms them. RimWorld 1.7, package id `blax.laws`. From the first release a plain unsubscribe leaves a save that loads: jailed colonists stay vanilla prisoners and the log shows 2 errors. +Status: the first release, 1.0.0, is built (`CHANGELOG.md`); the rest is design. Checked against the RimWorld 1.7.5021 game code on 2026-11-30; the act catalogue (2026-12-01) was checked against the 1.7.5021 reference assemblies, which have every signature and no method bodies, so its behaviour claims are listed under "To verify" until the decompiled code confirms them. RimWorld 1.7, package id `blax.laws`. From the first release a plain unsubscribe leaves a save that loads: jailed colonists stay vanilla prisoners and the log shows 2 errors. Changes on 2026-12-01, Fabian's decisions (`docs/features.md`, "Decided 2026-12-01"): @@ -101,7 +101,7 @@ Change if you disagree. - Children (Biotech) are never beaten: Subdue on a child becomes Jail when the row has days, otherwise Warn. - Player orders are exempt: an act done while drafted or on a player-forced job opens no case (setting). - Who enforces: the nearest awake free colonist with Warden work active who can do the job (violence for subdue, manipulation for an arrest), then anyone able. Never a slave, a child, the offender, a pawn in a break, a pawn on a player order, a pawn in a party or ritual, or a pawn on a job that must not be dropped: rescuing, carrying or tending someone, fighting a fire, manning a turret, surgery, fleeing. -- Laws starts the enforcer's job at once, interrupting what it does. Law enforcement is urgent; a binge's first dose comes as soon as the pawn reaches a drug, and the binge goes for the closest drug on the map (RimWorld/JobGiver_Binge.cs:17; RimWorld/JobGiver_BingeDrug.cs:83). The one exception is danger: while hostiles threaten the map, nobody is sent, the case waits and the sweep retries after the fight. A colonist in a berserk break counts as such a threat, so cases on its map wait until it ends or is downed. +- Laws starts the enforcer's job at once, interrupting what it does. Law enforcement is urgent; a binge's first dose comes as soon as the pawn reaches a drug, and the binge goes for the closest drug on the map (RimWorld/JobGiver_Binge.cs:17; RimWorld/JobGiver_BingeDrug.cs:83). The one exception is danger: while hostiles threaten the map, nobody is sent, a job already running is called off, the case waits and the sweep retries after the fight. A colonist in a berserk break counts as such a threat, so cases on its map wait until it ends or is downed. - Subdue hits torso and limbs only, never the head or a bionic part, with capped blunt damage that leaves bruises, and stops at downed or once three hits in a row add no pain (go-juice, painkillers). The subdued pawn loses the Catharsis that ending its break would give (setting), so the beating doesn't reward the crime. - Jail convicts through vanilla guilt for the sentence length, renewed right before the arrest. While it lasts the arrest of a free colonist is always accepted. Executing a guilty colonist costs the colony only the -2 "justified execution" thought (ideoligion precepts may change it) plus its family's grief; banishing it costs no colony-wide thought, though banishing it to its death still grieves its family. - A jailed colonist is set to "Maintain only" two ticks after the capture, after any default a prison mod or Blax Castes writes, so no default recruits, enslaves or executes it. When the sentence is served Laws sets "Release" and a warden walks it out; if nobody has after a day, Laws releases it in place. @@ -125,7 +125,7 @@ All state lives in one `GameComponent_BlaxLaws`. Laws are colony policy across e - Saved: - `List laws` (deep) and `nextLawId`. A `Law` holds only names and numbers: id, act key (category plus defName or group id, such as `Ate/WakeUp`, `Ate/@humanMeat`, `Break/FireStartingSpree`, `Special/SetFire`), the entry's label and source mod as they read when the row was written, option (a chemical defName or a drug group, binges only), stage and severity as enum names, punishment defName, days, enabled. - - `List cases` (deep) and `nextCaseId`. A `Case` holds the offender (pawn reference plus name and ThingID), the victim (same), the law's act key and the defName that matched it (which drug, which recipe), mental state defName for planning cases, stage reached, count, note flags, open tick, status (Open, Enforcing, Jailed, Closed), outcome key, enforcer reference (one enforcement at a time), which stages' punishments ran, the last act tick for the cooldown, and for jail the capture tick, whether the Maintain only write is done, the release tick and the bed the pawn owned before the arrest job. + - `List cases` (deep) and `nextCaseId`. A `Case` holds the offender (pawn reference plus name and ThingID), the victim (same), the law's act key and the defName that matched it (which drug, which recipe), mental state defName for planning cases, stage reached, count, note flags, open tick, status (Open, Enforcing, Jailed, Closed), outcome key, enforcer reference (one enforcement at a time), which stages' punishments ran, the last act tick (shown in the log; the cooldown counts from the open tick), and for jail the capture tick, whether the Maintain only write is done, the release tick, the bed the pawn owned before the arrest job and whether "Arrest now" lifted the hold. - A random int token for ids handed to other mods later, as Castes does. - Pawn references: Castes' pattern. `Scribe_References` with `logNullErrors` off; on save and after load, references to Discarded or destroyed pawns become null and the case keeps the name. Closed cases older than the retention setting (60 days) are pruned on save. - Not saved: the watched-act flags and sets, the act catalogue and the enforcement queue (all rebuilt), the instance cache (a weak reference, as in Castes). @@ -147,7 +147,7 @@ All state lives in one `GameComponent_BlaxLaws`. Laws are colony policy across e - Offender filter, shared by every hook: spawned on a map, humanlike, `Faction.IsPlayer`, free colonist or colony slave, not a quest lodger (RimWorld/QuestUtility.cs:524), not a baby, not subhuman. Caravan acts are skipped (Backlog). - Player orders: the offender `Drafted` or its current job `playerForced` (Verse.AI/Job.cs:37) exempts the act while the setting is on. - First-release hooks, all postfixes unless noted, none on a method the JIT may inline: - - A. `MentalStateHandler.TryStartMentalState` (Verse.AI/MentalStateHandler.cs:91), about 110 lines. `PostStart` runs at :162 before `return true` at :202, so the binge chemical and the obsession corpse are already chosen. Break category: opens planning cases. + - A. `MentalStateHandler.TryStartMentalState` (Verse.AI/MentalStateHandler.cs:91), about 110 lines. `PostStart` runs at :162 before `return true` at :202, so the binge chemical and the obsession corpse are already chosen. Break category: opens planning cases. A state another pawn's ability forced on the pawn (otherPawn set and not the pawn: a psycast, Neuroquake; only abilities and the social fight pass one, RimWorld/CompAbilityEffect_GiveMentalState.cs:59, RimWorld/Pawn_InteractionsTracker.cs:379-380) files nothing. For a self-cast state (Berserk trance) a prefix reads the player order before vanilla undrafts the pawn and stops its job (:141-144, :165-172). - C. `Thing.Ingested` (Verse/Thing.cs:2005), prefix and postfix. Called once per meal from `Toils_Ingest` (RimWorld/Toils_Ingest.cs:428), and from doctors and caravans. Ate category, and every binge dose (it reaches `CompDrug.PostIngested` through `ThingWithComps.PostIngested`, Verse/ThingWithComps.cs:767-774, so the old hook D is gone). - E. `Pawn_InteractionsTracker.TryInteractWith` (RimWorld/Pawn_InteractionsTracker.cs:176), about 90 lines, returns true at :268. Interaction category. - F. `Pawn_InteractionsTracker.StartSocialFight` (RimWorld/Pawn_InteractionsTracker.cs:373): a message, two 9-argument `TryStartMentalState` calls and a tale. Special act StartedSocialFight. @@ -165,7 +165,7 @@ All state lives in one `GameComponent_BlaxLaws`. Laws are colony policy across e - `Enforcement` holds a queue of (case, stage) entries. The component's `GameComponentTick` drains it on the tick after a hook filled it, so nothing acts inside a status change, an ingestion or an interaction, as Castes defers its work. The "Maintain only" write waits one tick more (see "Jail for N days"). - Every 250 ticks a sweep walks the open cases only (a handful at a time): closes planning cases whose break ended, re-issues lost subdue jobs, retries arrests that waited for a bed, an enforcer or the end of a fight, and gives the old bed back when an arrest or capture job ended without a prisoner. Every 2500 ticks it checks sentences. Nothing scans all pawns. - Enforcer pick: free colonists on the offender's map, awake, not downed, not in a mental state, not drafted, no player-forced job, no lord (parties, rituals, caravans forming), not the offender, not a child, not a slave. Also skipped: a pawn whose `CurJob.def.casualInterruptible` is false (in Core's JobDefs that covers Rescue, Capture, Arrest, TendPatient, BeatFire, ExtinguishSelf, ManTurret, DeliverToBed and LayDown), a pawn carrying a pawn (`IsCarryingPawn`, RimWorld/PawnUtility.cs:115), a pawn on Flee or FleeAndCower (Core Defs/JobDefs/Jobs_Misc.xml:510, 518) and a pawn on a `DoBill` whose recipe `IsSurgery` (Verse/RecipeDef.cs:362). Wardens (Warden work active) first, then anyone able, nearest by straight distance among those that can reach the offender. Subdue needs a pawn able to do violence, an arrest one with Manipulation. -- Danger: no enforcement starts while `GenHostility.AnyHostileActiveThreatToPlayer(map)` (RimWorld/GenHostility.cs:227) is true on the offender's map or `PawnUtility.EnemiesAreNearby(offender)` (RimWorld/PawnUtility.cs:161). The case waits and the sweep retries. A berserk colonist is hostile to the player faction (`MentalState_Berserk.ForceHostileTo(Faction)` returns true, Verse.AI/MentalState_Berserk.cs:12-15; RimWorld/GenHostility.cs:128-133), enters the attack target cache when the break starts (Verse.AI/MentalStateHandler.cs:175) and passes `IsPotentialThreat` (RimWorld/GenHostility.cs:266-308), so it counts as danger for as long as it rages. That is wanted: a Jail row on a berserk offender waits until the break ends or the pawn is downed, and other cases on that map wait as for a raid. Only "Subdue a pawn that fights back" (Enforcement, step 3) leaves its own offender out of the check. +- Danger: no enforcement starts while `GenHostility.AnyHostileActiveThreatToPlayer(map)` (RimWorld/GenHostility.cs:227) is true on the offender's map or `PawnUtility.EnemiesAreNearby(offender)` (RimWorld/PawnUtility.cs:161). The case waits and the sweep retries. A subdue, arrest or queued capture that is already running when danger comes is called off by the next 250-tick sweep (`SubdueFlow.CallOffInDanger`, `JailFlow.CallOffInDanger`), and the case waits the same way. Laws' jobs are player-forced, so vanilla would never pull the enforcer off them when it is hit (Verse.AI/Pawn_JobTracker.cs:982) or let its hostility response take over (RimWorld/PawnUtility.cs:377-385). An arrest whose enforcer already carries the offender finishes: the carry has made it a prisoner (RimWorld/JobDriver_TakeToBed.cs:121-129). A berserk colonist is hostile to the player faction (`MentalState_Berserk.ForceHostileTo(Faction)` returns true, Verse.AI/MentalState_Berserk.cs:12-15; RimWorld/GenHostility.cs:128-133), enters the attack target cache when the break starts (Verse.AI/MentalStateHandler.cs:175) and passes `IsPotentialThreat` (RimWorld/GenHostility.cs:266-308), so it counts as danger for as long as it rages. That is wanted: a Jail row on a berserk offender waits until the break ends or the pawn is downed, and other cases on that map wait as for a raid. Only "Subdue a pawn that fights back" (Enforcement, step 3) leaves its own offender out of the check and out of the call-off. - Jobs start with `Pawn_JobTracker.StartJob(job, JobCondition.InterruptForced, ..., preToilReservationsCanFail: true)` with `playerForced` set. Before an Arrest or Capture, Laws checks `enforcer.CanReserve(offender)` and `CanReserve(bed)` (Verse.AI/ReservationUtility.cs:63); without that, `StartJob` would log a reservation error and end the job as Errored (Verse.AI/Pawn_JobTracker.cs:336, 373-380), for example when a doctor already reserved the downed offender. On a failed check the case waits for the sweep. Laws never queues its own job; the one job it queues is the vanilla Capture after a subdue (see "Subdue"). - Hook K, a prefix and postfix on `Pawn_GuestTracker.CapturedBy` (RimWorld/Pawn_GuestTracker.cs:561-576, 16 lines with calls, not inlinable). It returns at once unless the pawn has a case in Enforcing with an Arrest or Capture job out. The postfix records the capture tick and queues the "Maintain only" write; the case saves whether that write is done, so a save made in between still gets it after the load. For "Release gives back what jail took" the prefix notes the weapon the pawn still holds, before `SetGuestStatus` drops it (:564; :461), and for "Castes keeps the caste" it sends Castes the `blax.laws.jailed` hint. - Hook L, for the give-back and for Castes, a prefix and postfix on `GenGuest.PrisonerRelease` (RimWorld/GenGuest.cs:8-21). It returns at once unless the pawn serves a Laws sentence. For "Castes keeps the caste" the prefix sends `blax.laws.released`; the postfix queues the give-back for the next tick. Castes reads a hint in its `SetGuestStatus` hook, inside these calls, and drops it at the end of the tick, so the sweep would be too late. @@ -325,7 +325,7 @@ Not specced yet: lawbook templates and "Applies to" (see `docs/features.md`). "A - Records. Hook R: the record def against the watched set; the offender is the tracker's `pawn`. A record goes up for many reasons ("things hauled" every haul), and the cooldown keeps one case a day per pawn and row. - Bills. Hook B: the recipe of the doer's current job against the watched set, the doer as offender. Bills are standing player orders but not forced jobs, so the exemption doesn't cover them: a row on "make yayo" files on the cook who made it, which is the row's point. - Each category worker opens a case or moves an open break case to did it, increments the count, and queues the punishment of the most specific enabled matching row (see "Defaults I picked") once per stage. An act that is the linked did-it of an open break case goes to that case and opens no other case; when it also matches a row of its own, the row with the higher severity decides, the break's row on a tie (see "Defaults I picked"). - - The cooldown setting applies to every act outside a break. Inside the window a further act by the same offender under the same law raises the count on that case, open or closed, and files nothing new. An insult that sparks a fight files two cases: the insult for the insulter, the fight for the one who swings. + - The cooldown setting applies to every act outside a break. Inside the window a further act by the same offender under the same law raises the count on that case, open or closed, and files nothing new. While that case is still open (a jail case waiting for "Arrest now" or a bed) every further act goes to it, whatever its age. An insult that sparks a fight files two cases: the insult for the insulter, the fight for the one who swings. - **Settings:** The cooldown and "Player orders are exempt" from the settings page; per row the option. - **Save and removal:** Cases save in the component. Hooks and the catalogue save nothing. - **Overlaps:** Insult System (3783191560, 86 subs) and Grudges! (3491693870, 27.5k, 1.6, unmaintained) add social conflict; Laws only reads vanilla interactions. Pawn Rules (Continued) (3024243615, 6.7k) prevents meat eating per pawn; Laws punishes it afterwards. Snap Out! (1319782555, 636k, no 1.7) talks a pawn out of a break; Laws' "Talk down" (Enforcement, step 1, New) covers that for colonists on 1.7. @@ -338,6 +338,8 @@ Not specced yet: lawbook templates and "Applies to" (see `docs/features.md`). "A - Fight: `recipient.interactions.StartSocialFight(initiator)` files the case on the recipient, not the initiator. - Insult: `TryInteractWith(target, Insult)` files on the initiator. A Slight only with the option. A second insult within a day files nothing; with the cooldown at 0 it files a second case. - Ate: raw meat, a simple meal with meat and human meat against the meat groups; a row on the Simple meal def catches the simple meal and not the raw meat; a drafted pawn eating opens nothing; a doctor administering a drug to a patient opens nothing for either pawn; a beer drunk on social relax files under "Ate: beer"; a player-forced eat job opens nothing while the setting is on and a case when it is off. 60 colonists eating meat for a day under an "any meat, warn" law produce at most 60 cases and 60 messages. + - Breaks caused by others: a tantrum that another pawn's psycast starts on a colonist opens nothing; a drafted colonist's self-cast break opens nothing while player orders are exempt and a case when the setting is off, and a drafted colonist's own mood break opens a case. + - Offender filter: a colonist made a quest lodger (an ongoing quest's QuestPart_ExtraFaction names another home faction, RimWorld/QuestUtility.cs:524) opens nothing for a meat meal or an insult, and the same pawn files both once the quest is removed. A visitor (guest of the colony) eating a meat meal opens nothing. - Catalogue: every `MentalBreakDef`'s state, every ingestible ThingDef, every `InteractionDef`, every Int or Float `RecordDef` and every `RecipeDef` of the loaded game has an entry; no Time record and no excluded state has one. The test mod's own defs (a test drug ThingDef, a test InteractionDef, a test RecipeDef, a test mental state reusing `MentalState_FireStartingSpree`) appear with the test mod as source, and the test break offers Did it through the link. In a `-NoDlc` run no DLC entry appears and the starter lawbook still adds 7 rows. - Used: a colonist using a healer mech serum on its own job files on it; a doctor-administered healer serum files nothing for either pawn; a `UsedBy` call that `CanBeUsedBy` refuses files nothing. Interactions: a forced `Chitchat` with a Chitchat row files on the initiator. Records: `pawn.records.Increment(RecordDefOf.BodiesStripped)` with a row files one case, a second increment the same day raises the count. Recorded acts: an `ExecutedPrisoner` event with a doer files on the doer, the same event without a doer files nothing (skipped without Ideology if vanilla records it only there). Bills: a finished "make simple meal" iteration files on the cook; a surgery files on the doctor; a mech gestator bill files on the mechanitor who finishes it (skipped: needs Biotech). - Jailbreaker: a forced Jailbreaker break opens planning, the `SparkJailbreak` interaction moves it to did it. A Berserk row offers Warn, Guilty and Jail; a Tantrum or MurderousRage row also offers Subdue. @@ -411,7 +413,7 @@ Not specced yet: "anything the colony's ideoligion forbids" and "left the colony - A warden tending a patient, beating a fire, carrying a downed colonist or doing surgery is never picked; the next candidate is. - During a raid a binge case waits and nobody is sent; after the raid the sweep enforces it. - A downed offender a doctor has already reserved for a rescue: no arrest starts, no reservation error or warning is logged, and the sweep arrests it once the reservation is gone. - - Hand-over: the drug lies next to the binger, starter rows active. One enforcer acts, the pawn ends as a prisoner, never in a medical bed, and the case log shows one did-it outcome. + - Hand-over: the drug lies next to the binger, starter rows active, the warden sent from far enough off that the binger doses first, and a second warden free beside the binger once the first is on its way. One enforcer acts, the one sent to subdue, the pawn ends as a prisoner, never in a medical bed, and the case log shows one did-it outcome. (A warden that arrives first wins every time: each hit re-thinks the binger's job, and with the drug in its hands the binge finds none on the map and wanders off, Verse.AI/Pawn_JobTracker.cs:974-990, RimWorld/JobGiver_BingeDrug.cs:83. That path is the subdue tests'.) - "Enforce laws" off: cases open and close, nothing is enforced. - A forced berserk with a Jail row: nobody is sent while it rages; once the break ends, or the test downs the pawn, it is arrested or captured. A raid still blocks every case as before. @@ -438,11 +440,11 @@ Not specced yet: "anything the colony's ideoligion forbids" and "left the colony - **Players get:** For a pawn caught planning (or still in its break after the act), a warden walks over and beats it down with fists: bruises on torso and limbs, never the head, never a bionic part, never a lost part, never a scar. The break ends when the pawn goes down. Doctors carry it to bed, and the bruises heal in a few days. The pawn remembers who hit it (-15 opinion for 10 days, vanilla's "harmed me"). The enforcer is not marked guilty, and the beaten pawn doesn't fight back. - **How:** - `JobDriver_Subdue`: fail on the target despawned, dead, or no longer in the break its case recorded. One toil, `Toils_Combat.FollowAndMeleeAttack(TargetIndex.A, hit)` (Verse.AI/Toils_Combat.cs:115-178), which follows the target, calls `hit` while adjacent and ends when the target is downed (:165-167) or unreachable (:132-134). The toil runs as a `tickIntervalAction` (:123), which `Thing.DoTick` calls every 1 to 15 ticks depending on how often the camera updates the pawn (Verse/Thing.cs:726-735, bounds :604-606), so counting calls would make the beating up to 15 times slower off screen. The driver keeps a `lastHitTick` field instead (the job is never saved, so the field needs no save) and hits when `Find.TickManager.TicksGame - lastHitTick >= 90`. - - The hit: a random body part of the target that isn't missing, has depth Outside, isn't solid, isn't in the head group (torso, shoulders, arms, legs) and doesn't carry or sit below an added part (`hediffSet.PartOrAnyAncestorHasDirectlyAddedParts`, Verse/HediffSet.cs:1225): an injury there gives no pain (Verse/Hediff_Injury.cs:132-135) and only damages the implant. Damage 4 to 8, divided by the target's `IncomingDamageFactor`, which vanilla multiplies in even with armour ignored (Verse/DamageWorker_AddInjury.cs:164-167; Tough is 0.5, Core Defs/TraitDefs/Traits_Singular.xml:532), so the injury itself is 4 to 8. A factor of 0 ends the job as below. The injury is capped so the part keeps at least half its HP. `new DamageInfo(DamageDefOf.Blunt, amount, 0, -1, enforcer, part, null, SourceCategory.ThingOrUnknown, target, instigatorGuilty: false)` (Verse/DamageInfo.cs:144), with `SetAllowDamagePropagation(false)` (:260) and `SetIgnoreArmor(true)` (:214) so power armour doesn't make it endless, then `TakeDamage`. Then `enforcer.Drawer.Notify_MeleeAttackOn(target)` (Verse/Pawn_DrawTracker.cs:128), a punch sound and Melee XP. + - The hit: a random body part of the target that isn't missing, has depth Outside, isn't solid, isn't in the head group (torso, shoulders, arms, legs) and doesn't carry or sit below an added part (`hediffSet.PartOrAnyAncestorHasDirectlyAddedParts`, Verse/HediffSet.cs:1225): an injury there gives no pain (Verse/Hediff_Injury.cs:132-135) and only damages the implant. Damage 4 to 8, divided by every factor vanilla multiplies in on the way to the injury: the race's damage multiplier (Verse/Thing.cs:1487-1497, which rounds the amount), the genes' and hediffs' damage factors (Verse/Pawn.cs:1919-1927) and `IncomingDamageFactor`, which applies even with armour ignored (Verse/DamageWorker_AddInjury.cs:164-167; Tough is 0.5, Core Defs/TraitDefs/Traits_Singular.xml:532), so the injury itself is 4 to 8. A factor of 0 ends the job as below. The injury is capped so the part keeps at least half its HP, counted unrounded (`GetPartHealth` rounds to a whole point, Verse/HediffSet.cs:581-605), and so the pawn's injuries, old scars included, stay at nine tenths of the sum vanilla kills at (150 times the health scale, Verse/Pawn_HealthTracker.cs:73, 705-719): the part caps alone add up to about 235 on a human. Nine tenths leaves room for a pawn whose pain is halved (Biotech's reduced pain gene) to go down, at about 128 points. A rounding or another mod's factor that still overshoots a cap is healed back on the hit's bruise (`Hediff_Injury.Heal`, Verse/Hediff_Injury.cs:201-212). `new DamageInfo(DamageDefOf.Blunt, amount, 0, -1, enforcer, part, null, SourceCategory.ThingOrUnknown, target, instigatorGuilty: false)` (Verse/DamageInfo.cs:144), with `SetAllowDamagePropagation(false)` (:260) and `SetIgnoreArmor(true)` (:214) so power armour doesn't make it endless, then `TakeDamage`. Then `enforcer.Drawer.Notify_MeleeAttackOn(target)` (Verse/Pawn_DrawTracker.cs:128), a punch sound and Melee XP. - Blunt on a non-solid part makes a Bruise: no bleeding, pain 0.0125 per point (Core Defs/HediffDefs/Hediffs_Local_Injuries.xml:383-400). A pawn goes down when pain reaches its pain shock threshold (Verse/Pawn_HealthTracker.cs:101), 0.8 for a normal adult, so about 64 points or 11 hits. - `instigatorGuilty: false` skips vanilla's guilt for harming a player pawn (Verse/Pawn_HealthTracker.cs:321-329). Calling `TakeDamage` directly sets no `meleeThreat`, which a vanilla melee verb would (RimWorld/Verb_MeleeAttack.cs:33-37), so the target doesn't turn on the enforcer. The target does get `HarmedMe` toward the enforcer (Verse/Pawn_HealthTracker.cs:379-382). - Going down runs `RecoverFromState` (Verse/Pawn_HealthTracker.cs:850-853), which gives the break's `moodRecoveryThought`, Catharsis for the six watched breaks (MentalStates_Mood.xml:76, 103, 413, 539), when the break was mood-caused (Verse.AI/MentalState.cs:92-95). The driver reads that thought def before the hit and, if the hit downed the pawn, removes the memory gained this tick. - - The job ends with a message once three hits in a row haven't raised `hediffSet.PainTotal` (Verse/HediffSet.cs:57, which multiplies in pain factors at :1351-1353): go-juice, painkillers, or every reachable part at its cap. A hard ceiling of 40 hits backs that up. A "subdue then jail" row arrests instead, which works on a pawn in any break that isn't hostile to the arrester (Verse.AI/GenAI.cs:73-103, the check at :83). + - The job ends with a message once three hits in a row haven't raised `hediffSet.PainTotal` (Verse/HediffSet.cs:57, which multiplies in pain factors at :1351-1353): go-juice, painkillers, every reachable part at its cap, or the pawn at the total cap (a normal adult goes down at about 64 points, one with halved pain at about 128). A hard ceiling of 40 hits backs that up. A "subdue then jail" row arrests instead, which works on a pawn in any break that isn't hostile to the arrester (Verse.AI/GenAI.cs:73-103, the check at :83). - Aggressive breaks that aren't hostile (tantrums, murderous and sadistic rage, slaughterer) can be subdued: their state targets things, a named victim, prisoners or animals, never the enforcer, and the direct `TakeDamage` gives them no melee threat to answer. The enforcer pick skips the victim a murderous rage names (`MentalState_MurderousRage.target`). - "Subdue then jail": in the tick the hit downs the target, the driver puts vanilla `JobDefOf.Capture` to a prisoner bed at the front of the enforcer's job queue (`jobQueue.EnqueueFirst`, Verse.AI/JobQueue.cs:40) and ends its toil, so the capture is the enforcer's next job, ahead of a doctor's rescue (RimWorld/WorkGiver_RescueDowned.cs:38-60). A queued job fails its reservations silently (`fromQueue`, Verse.AI/Pawn_JobTracker.cs:336, 373-375), and a queued vanilla Capture is safe in a save. Guilt is renewed before the job is queued, as for any capture (see "Jail for N days"), since a downed colonist can be captured only while guilty (Verse.AI/GenAI.cs:39-67). - Downing drops the pawn's weapon and inventory forbidden (Verse/Pawn_HealthTracker.cs:856-859), as any downing does. @@ -454,8 +456,9 @@ Not specced yet: "anything the colony's ideoligion forbids" and "left the colony - **Replaces:** Arresting your own colonist mid-break by hand, the workaround Arrest and Release (2593514063, 4.6k, no 1.7) exists for. - **Effort:** S plus S. - **Tests:** - - A binge planning case with a subdue row: within 2500 ticks the offender is downed, has only Bruise injuries, every part at 50% HP or more, no head injury, no Catharsis memory (and has it with the setting off), the enforcer isn't guilty and the offender's `meleeThreat` is null. The same run with the camera on another map: still downed within 2500 ticks. + - A binge planning case with a subdue row: within 2500 ticks the offender is downed (a colonist with normal pain; one with halved pain needs twice the hits), has only Bruise injuries, every part at 50% HP or more, no head injury, no Catharsis memory (and has it with the setting off), the enforcer isn't guilty and the offender's `meleeThreat` is null. The same run with the camera on another map: still downed within 2500 ticks. - A Tough colonist and a colonist with two bionic arms both go down; the bionic arms take no injury. + - Hits until nothing is left to hit, on a plain colonist, a Tough one, one with bionic arms and legs and through a race's rounded blunt multiplier: the pawn lives, its injuries add up to nine tenths of the lethal sum or less, and every hit part keeps half its HP or more, counted unrounded. - A go-juice offender: the job ends after three hits without new pain, with one message. - A child offender with a subdue row is warned, and with a subdue then jail row is jailed without a beating (skipped: needs Biotech). - Save while the job runs: the .rws contains no "BlaxLaws_Subdue"; after the reload the enforcer runs another job and the sweep starts a new subdue within 250 ticks. Start `Vomit` with `resumeCurJobAfterwards` on the enforcer mid-subdue, then save: the .rws contains no "BlaxLaws_Subdue" and the enforcer's queue holds no subdue job. @@ -530,18 +533,18 @@ New: the outline below; the full spec comes before the step is built. - Slaves: without "Jail for slaves" Laws never jails a slave. Releasing an imprisoned slave sends it back to its old faction and off the map (RimWorld/GenGuest.cs:14-19; Pawn_GuestTracker.cs:479-482), so slave jail waits for that feature's re-enslave. A slave's jail row falls back to subdue while it is in its break, else to warn. - **Settings:** "Letters for jailings" (on). Days per row. - **Save and removal:** The sentence lives in the case. After removal a jailed colonist stays a vanilla prisoner of the colony; its guilt runs out on its own. -- **Overlaps:** Prisoner Sentencing (3736998871, 1.3k, 1.7) has a Temporary sentence that lets a former colonist rejoin; Prison Expanded (3827258534, 3.3k, 1.7) has its own sentences and parole. Both may release the same pawn: Laws notices the early release and closes its sentence instead of fighting them. Prisoner Realism (3760196312, 23.9k) institutionalises prisoners after about 10 days in jail and has its own "Arrest here", which Laws' jobs don't need. Custom Prisoner Interactions (2841231775, 51.2k) skips colonists on capture. +- **Overlaps:** Prisoner Sentencing (3736998871, 1.3k, 1.7) has a Temporary sentence that lets a former colonist rejoin; Prison Expanded (3827258534, 3.3k, 1.7) has its own sentences and parole. Both may release the same pawn: Laws notices the early release and closes its sentence instead of fighting them. Prisoner Realism (3760196312, 23.9k) institutionalises prisoners after about 10 days in jail and has its own "Arrest here", which Laws' jobs don't need. Custom Prisoner Interactions (2841231775, 51.2k) skips colonists on capture. Prison Labor (1899474310): while its "Force to work" option is on (its default for every new prisoner), its JobGiver_Labor runs `WorkSettings.InitWorkSettings`, which disables each work type its settings bar prisoners from (`WorkSettings.WorkDisabled`, `Pawn_WorkSettings.Disable`); those priorities stay at 0 after the release. Laws leaves that toggle and the priorities alone: turn the option off on a jailed colonist to keep them. - **Replaces:** The manual arrest-and-release cycle. - **Effort:** S plus S plus S, hook K included. - **Tests:** - A did-it binge case with "jail 3 days": within 2500 ticks the offender is `IsPrisonerOfColony`, its mental state is null, it has no Catharsis, `TicksUntilInnocent` is at least 240000 minus the ticks since the arrest started, and two ticks after the capture its mode is MaintainOnly (also with Prison Labor in `-Compat`). Skip to the release tick: the mode is Release; a warden releases it; the pawn is a free colonist with `WasImprisoned` and the same work priorities as before the arrest. - Mode order: Laws' component moved before Castes' in `Game.components`, and an Enslave mode written at capture plus 1 (by the test now, by Castes' prisoner caste once it exists): the mode is MaintainOnly at capture plus 2 (Enslave skipped: needs Ideology; the core run uses ReduceResistance). - - Prison Labor in `-Compat`, once with its non-exclusive "Force to work" (`PrisonLabor_workOption`) off and once on: the same work priorities as before the arrest after the release. Its 1.7 PrisonLabor.dll has `Patches_WorkSettings`, `LaborWorkSettings` and `InitWorkSettings`; if priorities change, Overlaps and the README say so. + - Prison Labor in `-Compat`, once with its non-exclusive "Force to work" (`PrisonLabor_workOption`) off and once on: with it off the same work priorities as before the arrest after the release; with it on only the work types Prison Labor bars prisoners from (`WorkSettings.WorkDisabled`) may read 0 afterwards (Overlaps and the README say so). The 3-day jail test allows the same when the option was on at the capture. - With Castes in `-Compat`: the caste after the release matches the old one, read through reflection on `GameComponent_BlaxCastes.CasteOf(Pawn)`, so the test mod needs no reference to Castes; once Castes ships its read-only API, through `CastesApi.CasteIdOf` (API version 1). Skipped without Castes. - - The old bed: an arrest interrupted after its first toil leaves the colonist owning its old bed by the next sweep. A bed someone else claimed meanwhile stays theirs. + - The old bed: an arrest interrupted after its first toil leaves the colonist owning its old bed by the next sweep. A bed someone else claimed meanwhile stays theirs. Other colonists get beds of their own first: a bedless one that goes to sleep before the sweep takes the freed bed (RimWorld/RestUtility.cs:294-324), which is the second case. - Late arrest: a 5-day row with no prisoner bed for 6 days, then one is built: the arrest is accepted against a Social 0 arrester, and the release comes 5 days after the capture. - No prisoner bed: one letter, no arrest; building one leads to the arrest at the next sweep. - - Holds and fallbacks, each skipped with "skipped: needs ": a role holder (Ideology) and a mechanitor with a mech (Biotech) get no arrest and one letter, and "Arrest now" arrests; a slave in a binge with a jail row is subdued, and the same row outside a break warns (Ideology). In the DLC-off runs no hold or fallback logs anything. + - Holds and fallbacks, each skipped with "skipped: needs ": a role holder (Ideology) and a mechanitor with a mech (Biotech) get no arrest and one letter, and "Arrest now" arrests; a pawn that gets a role or a mech while its case waits for a bed is held, not arrested; "Arrest now" survives phase 2, and a failed arrest after the reload retries without a second hold; a slave in a binge with a jail row is subdued, and the same row outside a break warns (Ideology). In the DLC-off runs no hold or fallback logs anything. - Recruiting the jailed pawn closes the sentence as "released early". The fallback releases a pawn no warden can reach. - **Risks:** Arrest needs a prisoner bed (FloatMenuOptionProvider_Arrest.cs:41-49). Release unclaims bed, grave, throne and casket (RimWorld/GenGuest.cs:47); without "Release gives back what jail took" the pawn picks a free bed again; with it the old one comes back. Jailed colonists can break out (base MTB 60 days, Verse/PawnKindDef.cs:129; RimWorld/PrisonBreakUtility.cs:42-110); the early-end rule closes the sentence. Prisoner Realism's institutionalisation starts around 10 days, so the starter rows stay at 5 and 10. @@ -817,7 +820,7 @@ Not specced yet: the jury (see `docs/features.md`). Needs court sessions and the - An arrest is vanilla `CapturedBy`, so Castes 1.0 already moves the jailed colonist to the new-prisoner row and a release within `formerCasteDays` (60) back to its old caste. Laws' 50-day limit on days keeps every sentence, the fallback day included, inside that window; "Add days" stops at 50 days in total until the API version 2 hint keeps the record. Castes' planned `CapturedBy` scope never moves an arrest to the captured row: a pawn of the player's faction gets its "arrested" reason, which keeps the new-prisoner row (Castes `docs/features.md`, area 2, step 1). Laws' hint ("Castes keeps the caste") adds only the former-caste record that outlives `formerCasteDays`. - The one write into Castes' area: the Maintain only and Release modes for pawns Laws jailed, in every version of both mods. With Castes' join API (API version 2), Laws' "Castes keeps the caste" sends `blax.laws.jailed` from hook K and `blax.laws.released` from hook L through `HintJoinReason`; Castes' prisoner caste then sets no mode on the hinted pawn, and Laws still writes Maintain only two ticks after the capture. -- Laws never writes a policy, a schedule, medical care or a work priority. Jail keeps priorities because prisoners have no disabled work types; the `-Compat` run checks that Prison Labor doesn't change them. +- Laws never writes a policy, a schedule, medical care or a work priority. Jail keeps priorities because prisoners have no disabled work types; with Prison Labor's "Force to work" on, that mod disables the work types it bars prisoners from (see "Jail for N days", Overlaps), and the `-Compat` run checks that nothing else changes. - "Confinement for N days" (Sentences, step 2, New) is a sentence: Laws asks Castes to put a convict into a caste the player picks for sentences and back through `blax.laws.released`. That needs a timed caste assignment in Castes' join API. Castes builds it as "Sentence caste for Blax Laws" (its area 5, step 5) after its join API, and its spec decides whether a third Laws reason sent through `NotifyJoined` is enough. - Castes' read-only API (version 1) lists Laws' caste checks as waiting on it: that is "Applies to" (Lawbook, step 2), which reads `CastesApi.CasteIdOf`. diff --git a/docs/features.md b/docs/features.md index b321fa8..f31764b 100644 --- a/docs/features.md +++ b/docs/features.md @@ -2,7 +2,7 @@ Write the colony's lawbook from every act the game knows, and the colony enforces it: a warden stops a binge before the first dose, a murderer sits out its sentence and walks back to its own bed and role, and a colonist who keeps doing it gets more each time. Grave cases go to a court with a judge the colony elects, attorneys who argue with Social, witnesses and a jury, and the colony votes on the laws themselves. Laws only watches what the game already does: no new crime events, no new mental breaks. -Status: design only, nothing built. Planned 2026-12-01 and reviewed against the decompiled game the same day. This file is the plan of record for what the mod covers and in which order the parts come. `docs/design.md` holds the spec of every designed feature. +Status: item 1 of "Order" is built as release 1.0.0 (`CHANGELOG.md`); the rest is design. Planned 2026-12-01 and reviewed against the decompiled game the same day. This file is the plan of record for what the mod covers and in which order the parts come. `docs/design.md` holds the spec of every designed feature. ## How this plan is cut @@ -76,7 +76,7 @@ When a law is broken the colony acts at once, safely, and the punishment fits th Step 1: -- **Enforcement.** One enforcer per case, wardens first; nobody is pulled off a rescue, a tending, a fire, a turret or a surgery, and nobody is sent while hostiles threaten the map, a berserk colonist included. Waiting cases retry by themselves. Designed: [Enforcement and cases](design.md#enforcement-and-cases). +- **Enforcement.** One enforcer per case, wardens first; nobody is pulled off a rescue, a tending, a fire, a turret or a surgery, and nobody is sent while hostiles threaten the map, a berserk colonist included; one already sent is called back. Waiting cases retry by themselves. Designed: [Enforcement and cases](design.md#enforcement-and-cases). - **Warn and guilty.** A record and a message, or vanilla guilt for N days: certain arrest, a mild execution thought, no colony-wide banishment thought. Designed: [Warn and guilty](design.md#warn-and-guilty). - **Subdue.** A capped fistfight that ends a break that isn't hostile to the colony, tantrums and murderous or sadistic rage included: torso and limbs only, never a bionic part, no catharsis for the offender, children never. Designed: [Subdue](design.md#subdue). - **Jail and subdue then jail.** The arrest; on a berserk pawn the jail waits until the break ends or you down it. Serving the sentence is area 4. Designed: [Jail for N days](design.md#jail-for-n-days), [Subdue](design.md#subdue). diff --git a/docs/workshop-description.txt b/docs/workshop-description.txt new file mode 100644 index 0000000..8ffbf22 --- /dev/null +++ b/docs/workshop-description.txt @@ -0,0 +1,76 @@ +[b]Write your colony's laws.[/b] Pick any act the game knows as a crime, the way you pick what to tailor, and your wardens enforce it. With the starter lawbook, a warden goes for a colonist the moment it starts a wake-up binge and beats it down, and one who already took some sits out five days in your prison and walks back to work. + +โœ… RimWorld 1.7 ๐Ÿ”ง Needs [url=https://steamcommunity.com/sharedfiles/filedetails/?id=2009463077]Harmony[/url] ๐Ÿงฉ Works with any DLC combination ๐Ÿ’พ Safe to add to a running save + +[img]https://cdn.blax.at/blax-gaming/laws/lawbook.png[/img] +[list] +[*]๐Ÿ“– [b]Laws tab.[/b] "Laws" sits in the bottom bar. Each law is a row of Action, Stage, Severity, Punishment and Days, and each dropdown offers only what fits. The book starts empty, and until you add a law Blax Laws watches nothing. +[*]๐Ÿ”Ž [b]Pick any act.[/b] A searchable tree like a tailoring bill's filter, built from the game's own defs, so DLC and modded breaks, drugs and recipes show up with no patch, each labelled with its mod. +[*]๐Ÿ“ [b]Starter lawbook.[/b] One click adds seven laws: subdue drug binges, fire-starting sprees and corpse obsession as they start, jail for binges and fires already done, a warning for fights and insults. +[*]๐ŸŽฏ [b]The most specific law wins:[/b] "wake-up" over "hard drugs" over "any drug", "human meat" over "any meat". +[*]๐ŸŽš๏ธ [b]Planning and did it.[/b] Planning is the moment a mental break starts; did it is the act the break is about, such as the first dose of a binge. +[*]๐Ÿ“‹ [b]Cases.[/b] Who, what, when, the punishment and how it ended, with a jump to the pawn and "Arrest now" for cases that wait. +[*]๐Ÿงฉ [b]Missing entries wait.[/b] A law whose DLC or mod is gone shows "Needs " or "Missing: " and works again when it is back. +[/list] + +[img]https://cdn.blax.at/blax-gaming/laws/crimes.png[/img] +[list] +[*]๐Ÿง  [b]Mental breaks.[/b] Every break a colonist can have, plus any drug binge, any tantrum, any insulting spree, any aggressive break. +[*]๐Ÿ– [b]Ate.[/b] Any food or drug, or a group: any, hard, social or medical drugs, any meat (meals with meat included), raw meat or corpses, human meat, insect meat, any meal. A doctor's dose doesn't count. +[*]๐Ÿ’‰ [b]Used.[/b] Psytrainers, neurotrainers, mech serums. +[*]๐Ÿ—ฏ๏ธ [b]Social interactions.[/b] Insults, slights, romance attempts, breakups. The one who starts it is the offender. +[*]๐Ÿงพ [b]Recorded acts, records and bills.[/b] Cut a tree or butchered a human (most recorded acts need Ideology), kills, bodies stripped, made a human leather duster, any surgery. +[*]๐Ÿ”ฅ [b]Special acts.[/b] Set a fire, displayed a corpse ("on a table", "dug up from a grave"), started a social fight (the one who swings first). +[*]๐Ÿ”— [b]Breaks lead to their act.[/b] A binge's "did it" is a dose or a meal, a fire-starting spree's a fire, a corpse obsession's the displayed corpse, an insulting spree's an insult, a jailbreaker's jailbreak talk. A modded break built on one of these gets the link too. +[*]๐Ÿงฎ [b]No flood.[/b] Acts outside a break open at most one case per colonist and law a day. +[*]๐Ÿ‘€ No new crime events, no new mental breaks: Laws only watches what the game already does. +[/list] + +[img]https://cdn.blax.at/blax-gaming/laws/punishments.png[/img] +[list] +[*]โœ‹ [b]Warn.[/b] A record and a message. +[*]โš–๏ธ [b]Guilty for N days.[/b] Vanilla guilt: its arrest is always accepted, and executing or banishing it costs the colony the mildest thoughts. +[*]๐Ÿ›‘ [b]Subdue.[/b] A warden beats the offender down with fists to end its break: bruises on torso and limbs, never the head or a bionic part. The offender doesn't fight back and gets no catharsis from the break. Children are never beaten. +[*]๐Ÿ”’ [b]Jail for N days.[/b] Arrested into a prisoner bed on "Maintain only", so no prison mod recruits or enslaves your colonist, then released by a warden and back to work with its work priorities intact. +[*]โ›“๏ธ [b]Subdue then jail.[/b] Beaten down and carried straight to a cell. +[*]๐Ÿš‘ [b]Safe enforcement.[/b] Wardens first. Nobody is pulled off a rescue, a patient, a fire or a surgery, and nobody is sent while hostiles threaten the map, or left out there when a raid arrives. +[*]๐Ÿ˜ก [b]Berserk colonists fight back,[/b] so their jail waits until the break ends or you down them. +[*]โธ๏ธ [b]Role holders and mechanitors wait[/b] for your "Arrest now", since an arrest would take the role or shut the mechs down. +[/list] + +Free colonists, children and colony slaves are covered, never guests or prisoners. Acts while drafted or on a job you ordered open no case. + +โš™๏ธ The mod settings: "Enforce laws" (off keeps the cases and carries out nothing), the Laws tab, messages and letters, wardens first or wardens only, catharsis after a subdue, player orders, days between cases and how long closed cases stay. + +๐Ÿ’พ [b]Safe to add and remove.[/b] The lawbook and cases live in Blax Laws' own save data. After you unsubscribe the save loads with two errors in the log, and jailed colonists stay prisoners you release by hand. + +๐Ÿงฉ [b]Any DLC combination works,[/b] core only included. With Ideology, slaves are covered and most recorded acts fire; with Biotech, children are never beaten. + +[img]https://cdn.blax.at/blax-gaming/laws/planned.png[/img] +Not in this version yet. Planned for the next releases: +[list] +[*]๐Ÿ”ช Violence: assault, manslaughter, murder, slaughterers, drugs the policy doesn't allow. +[*]๐Ÿ›๏ธ Release gives back bed, role, throne, mech work modes and the dropped weapon, so role holders and mechanitors no longer wait. Pardon, reprimand, banish and execute. +[*]๐Ÿ›๏ธ Court: Ideology's trial, then court sessions on the core game with a judge, attorneys and witnesses. +[*]๐Ÿ—ณ๏ธ Colony votes on the laws and an elected judge. +[*]๐Ÿ“ˆ Repeat offenders: a criminal record, harsher punishments, probation. +[*]๐Ÿ’ฌ Talk a colonist down, decide a case yourself, laws for one group (slaves, children or a caste), lawbook templates. +[*]๐Ÿค With Blax Castes and Blax Slaves: a convict keeps its caste, and a jailed slave comes back a slave. +[/list] + +[img]https://cdn.blax.at/blax-gaming/laws/compatibility.png[/img] +[list] +[*]โœ”๏ธ Prison Labor, Prisoner Realism and Custom Prisoner Interactions: a jailed colonist is a vanilla prisoner, so their features apply. +[*]โœ”๏ธ Prisoner Sentencing and Prison Expanded: when one releases a colonist Laws jailed, Laws closes its sentence. +[*]โœ”๏ธ Hospitality: guests are never offenders. +[*]โœ”๏ธ Blax Zones: arrests use any prisoner bed, zone beds included. +[*]โŒ Multiplayer: not supported. +[/list] + +๐Ÿ“ฆ Load after Harmony and the other Blax mods. ๐Ÿ› Source code and issues: [url=https://forgejo.blax.at/blax-software/rimworld-blax-laws]forgejo.blax.at/blax-software/rimworld-blax-laws[/url] + +๐ŸŽฎ [b]More Blax Gaming mods:[/b] [url=https://steamcommunity.com/sharedfiles/filedetails/?id=3847282171]Blax Slaves[/url] (slavers, brands and runaways), [url=https://steamcommunity.com/sharedfiles/filedetails/?id=3848261054]Blax Castes[/url] (policy bundles and join defaults), [url=https://steamcommunity.com/sharedfiles/filedetails/?id=3848261160]Blax Zones[/url] (delivery zones and caravan camps), [url=https://steamcommunity.com/sharedfiles/filedetails/?id=3848261264]Blax Defaults[/url] (starting settings for storage and bills). Each works on its own and with the others. + +[hr][/hr] +[url=https://www.blax.at][img]https://cdn.blax.at/blax-gaming/blax-oss-banner.png[/img][/url] +๐Ÿ› ๏ธ [b]Blax Gaming is a project of Blax Software[/b], 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? ๐Ÿ‘‰ [url=https://www.blax.at]www.blax.at[/url] diff --git a/docs/workshop-media.md b/docs/workshop-media.md new file mode 100644 index 0000000..07072de --- /dev/null +++ b/docs/workshop-media.md @@ -0,0 +1,23 @@ +# In-game clips for the Workshop page + +The Steam description shows GIFs inline (`[img]`), the same way as the section headers. These are the clips worth having, in order. Each is 4 to 8 seconds of a real game with Blax Laws on, cropped to the part of the screen that matters. None is recorded yet. + +| File | Shows | How to set it up | +|---|---|---| +| `lawbook-tab.png` | The Laws tab after "Starter lawbook": the seven rows with Action, Stage, Severity, Punishment and Days | Any colony; press "Starter lawbook" | +| `act-picker.gif` | "Add law", type "wake" in the search: Wake-up under Ate and the wake-up bill under Bills; open Mental breaks and scroll past a modded break labelled with its mod | Any colony, ideally with a mod that adds a mental break or a drug | +| `subdue.gif` | A colonist starts a wake-up binge, a warden walks over and beats it down before it reaches the drug, a doctor carries it to bed | Starter lawbook, a warden, wake-up on a shelf across the base; dev mode can start "Binging_DrugExtreme" on a colonist addicted to wake-up, which makes wake-up its binge drug | +| `jail.gif` | The binger reaches the drug first: the warden arrests it into a prisoner bed, the Cases tab shows "Jailed" with the days counting down | The same setup with the drug next to the binger and a prisoner bed in the base | +| `release.gif` | The sentence is served: a warden walks the colonist out of the cell and it goes back to work | Continue the jail clip; dev mode can skip time | +| `cases.png` | The Cases tab with a few cases: a warned insult, a subdued binge, a jailed fire-starter, one role holder waiting with "Arrest now" | A colony that has played a few days with the starter lawbook (the role holder needs Ideology) | +| `corpse-on-table.png` | A corpse obsession case with the notes "on a table" and "dug up from a grave" next to the corpse on a dining table | A pawn with low mood and a grave; dev mode can start "CorpseObsession" | + +Recording: Windows Game Bar (Win+Alt+R) records the game window as MP4 without extra software. Put the raw recordings in `docs/media/raw/` (git-ignored). + +Converting to a GIF needs ffmpeg. 640 px wide at 15 fps keeps a 6-second clip around 2 to 4 MB: + +```sh +ffmpeg -i raw/subdue.mp4 -vf "fps=15,scale=640:-1:flags=lanczos,split[a][b];[a]palettegen[p];[b][p]paletteuse" subdue.gif +``` + +The GIFs and screenshots go to `docs/media/` and onto the CDN next to the header art (`cdn.blax.at/blax-gaming/laws/`, see `Source/Art/README.md`), then into `docs/workshop-description.txt` under the matching header as `[img]https://cdn.blax.at/blax-gaming/laws/[/img]`. Forgejo raw URLs don't work on Steam (no cross-origin header). Each `[img]` line adds about 60 bytes to the description, which must stay under Steam's 8000-byte limit.