diff --git a/1.7/Assemblies/BlaxDefaults.dll b/1.7/Assemblies/BlaxDefaults.dll index e72e05b..27f8160 100644 Binary files a/1.7/Assemblies/BlaxDefaults.dll and b/1.7/Assemblies/BlaxDefaults.dll differ diff --git a/1.7/Assemblies/BlaxDefaults.pdb b/1.7/Assemblies/BlaxDefaults.pdb index 16faccb..472a061 100644 Binary files a/1.7/Assemblies/BlaxDefaults.pdb and b/1.7/Assemblies/BlaxDefaults.pdb differ diff --git a/About/About.xml b/About/About.xml index c92c7a5..0e8b708 100644 --- a/About/About.xml +++ b/About/About.xml @@ -3,7 +3,7 @@ Blax Defaults Blax Gaming blax.defaults - 1.0.0 + 1.1.0
  • 1.7
  • @@ -18,7 +18,7 @@
  • brrainz.harmony
  • - Your own starting settings for new stockpiles, shelves and bills. Set up one shelf, click "Make default for new shelves", and every new shelf starts like it. Nothing changes until you save a default, and the things you already have keep their settings. Works with any DLC combination, core only included; 1.0 needs no DLC. Colonists, slaves and prisoners: Blax Castes. + Your own starting settings for new stockpiles, shelves and bills, and rules for what stays forbidden when pawns go down, die or are stripped. Set up one shelf, click "Make default for new shelves", and every new shelf starts like it. Nothing changes until you save a default or turn a rule on, and the things you already have keep their settings. Works with any DLC combination, core only included; no feature needs a DLC. Colonists, slaves and prisoners: Blax Castes. <color=#19C63C>Storage</color> - New stockpiles and dumping stockpiles start with the filter and priority you saved for that type. @@ -31,13 +31,20 @@ - Values for every new bill: repeat mode, count and target, pause when satisfied and resume at, ingredient radius, allowed skill range, where products go (best stockpile or drop on floor), and the counting options. - Only the values you change are applied. Surgery, mech gestation, pasted bills and the bills you already have are left alone. +<color=#19C63C>Forbid rules</color> +- Gear rules for your colony and for enemies: when a pawn goes down or dies, what the game forbids is allowed again if it matches your filter, with hit points and quality ranges. For example enemy weapons only at 50 to 100% and Normal or better, their food, medicine, drugs and silver always. The rest stays forbidden. +- Allowed things wait until no enemy that can still fight is on the map. A downed colonist's own weapon stays forbidden while the colonist lies where it fell, so it picks the weapon up again. +- Stripping can forbid what doesn't match, such as a Poor tuque. Butchering stays as it is. +- Animal, enemy and other corpses outside the home area can stay allowed. +- Every rule ships off. Ticking a rule uses a suggested setup you can edit. What neutral visitors, traders and quest lodgers drop keeps the game's flags. + <color=#19C63C>Your defaults stay</color> - Defaults live in their own file in the game's Config folder, shared by every save. Nothing goes into your save, so you can add or remove the mod in a running colony. - Each write is checked before it replaces the file, with a backup that a broken file never overwrites. - Items from a mod you removed are skipped, not lost, and work again when the mod comes back. -- The settings page lists every default with Edit and Forget, and names mods that set the same things. +- The settings page lists every default with Edit and Forget, and names mods that do the same things. -Planned for later releases: rules for what stays forbidden when pawns go down or die (1.1), more storage, recipe and workbench bills (1.2), animals (1.3), crops and building settings (1.4), mech work modes (1.5, needs Biotech). +Planned for later releases: more storage, recipe and workbench bills (1.2), animals (1.3), crops and building settings (1.4), mech work modes (1.5, needs Biotech). Multiplayer: not supported yet. diff --git a/CHANGELOG.md b/CHANGELOG.md index d556f1e..0ce7940 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## 1.1.0 + +- Forbid rules, a new section on the settings page. Every rule ships off, so nothing changes until you turn one on. +- Gear rules for your colony and for enemies: when one of the group's pawns goes down or dies, what the game forbids is allowed again if it matches the rule's filter, the vanilla item filter with hit points and quality ranges and the special filters (tainted, biocoded, rotten, smeltable). What doesn't match stays forbidden, and a rule never forbids a dropped thing the game left allowed. Your colony is colonists, slaves, colony mechs, colony animals and prisoners, also while they break out or rebel; enemies are everyone else hostile to you. Neutral visitors, traders and quest lodgers keep the game's rules. +- Each rule has Edit, Forget (which asks first and turns the rule off), "Where" (anywhere, or only inside the home area) and "Use the suggested setup" (which asks first). Ticking a rule that has no filter yet saves its suggested setup and says so. Suggested for enemies: every item, but hit points 50 to 100% and Normal or better, stripping on, so a Poor rifle or one below 50% stays forbidden while food, medicine, drugs and silver are allowed. Suggested for your colony: every item, any hit points and quality, stripping off. +- Wait until the fight is over: what a rule allows waits while an enemy that can still fight is on the map, and is allowed once none is left. Changing a waiting thing's flag yourself takes it off the list. A save and reload forgets the list, so things still waiting stay forbidden. +- A downed colonist's own weapon stays forbidden while the colonist lies where it fell, so it picks the weapon up after getting up, as in vanilla. Once the colonist is rescued, carried off or dies, the rule decides. +- "Stripping forbids what doesn't match", per rule: stripping one of the group's pawns or corpses forbids each dropped thing the filter refuses. Butchering strips too, but what a butcher strips stays allowed. +- Three corpse switches: animal, enemy and other corpses outside the home area stay allowed. Manhunters and predators count as animals. They wait for the fight to end like the gear rules. +- The filters live in the defaults file next to your other defaults; the switches are mod settings. Nothing goes into your save. +- Overlap warnings also name KilledEnemyAutoAllowed (Continued), Allow Everything, Non uno Pinata and Allow Dead Animals, and now say "do some of the same things" instead of "set the same starting settings". +- With Hospitality, a downed colonist doesn't remember its weapon (Hospitality drops it without that), so the colony rule decides the weapon once the fight is over instead of waiting for the colonist. + ## 1.0.0 - Stockpile defaults: drag a stockpile or a dumping stockpile and it starts with the filter and priority you saved for that type. A modded stockpile designator that builds on the vanilla one is a type of its own. An Expand drag that grows a zone leaves its filter alone. diff --git a/Languages/English/Keyed/BlaxDefaults_forbid.xml b/Languages/English/Keyed/BlaxDefaults_forbid.xml new file mode 100644 index 0000000..5bbbdc9 --- /dev/null +++ b/Languages/English/Keyed/BlaxDefaults_forbid.xml @@ -0,0 +1,63 @@ + + + + + + + Forbid rules + Forbid rules act when pawns go down, die or are stripped + Off: dropped gear, stripped things and corpses keep the game's forbidden flags. The rules and filters below stay saved. + + + Gear your colony drops + When a colonist, slave, colony mech, colony animal or prisoner goes down or dies, what the game forbids is allowed again when the filter allows it, once the fight is over. The rest stays forbidden. A downed colonist's own weapon stays forbidden while the colonist lies where it fell, so it picks the weapon up after getting up. Ticking the rule before it has a filter uses the suggested setup. + Gear enemies drop + When anyone hostile to you goes down or dies, what the game forbids is allowed again when the filter allows it, once the fight is over. The rest stays forbidden. Ticking the rule before it has a filter uses the suggested setup. + No filter yet. Ticking the rule saves the suggested setup; Edit makes your own. + The rule is on, but its filter is not loaded (the defaults file could not be read), so it acts as off. + Where + Anywhere + Only inside the home area + Where a dropped or stripped thing must lie for the rule to act. Inside the home area the game already leaves dropped food and medicine allowed and forbids only weapons and what enemies carried. + Stripping forbids what doesn't match + Stripping one of the group's pawns or corpses forbids each dropped thing the filter refuses; the rest stays allowed. Butchering strips too, but what a butcher strips stays allowed. + Tick the rule or edit its filter first. + Use the suggested setup + Replace the filter of "{0}" with the suggested setup? {1} + Every item, any hit points and quality, anywhere, stripping off. + Every item, but hit points 50 to 100% and Normal or better, anywhere, stripping on. A Poor rifle or one below 50% stays forbidden; food, medicine, drugs and silver are allowed. + Using the suggested setup for "{0}": {1}. Edit changes it. + Forget the filter of "{0}"? The rule and its strip switch turn off, and dropped gear keeps the game's flags again. + What neutral visitors, traders and quest lodgers drop keeps the game's flags. + + + all items + no items + allows {0} of {1} items + hit points {0} to {1}% + {0} or better + up to {0} + only {0} + {0} to {1} + refuses: {0} + + + Filter: {0} + Items the filter lists neither as allowed nor as refused, such as items a mod adds later. "Refuse them" leaves them forbidden; "allow them" lets the hit points and quality ranges decide. + + + The game forbids new corpses outside the home area. These switches leave them allowed, once the fight is over: + Animal corpses outside the home area are allowed + Any animal: wild ones, yours, manhunters and predators. + Enemy corpses outside the home area are allowed + Anyone hostile to you that is not an animal: raiders, hostile mechs and the like. + Other corpses outside the home area are allowed + Everyone else: your own colonists and mechs, neutral visitors, traders. + + + Leaves everything pawns drop when they go down or die allowed, corpses too + Allows the items on the map, also what a forbid rule leaves forbidden + Keeps gear on pawns that go down or die, so little drops for the forbid rules to sort + Allows animal corpses, like the animal corpse switch + + diff --git a/Languages/English/Keyed/BlaxDefaults_page.xml b/Languages/English/Keyed/BlaxDefaults_page.xml index e926f3c..935c565 100644 --- a/Languages/English/Keyed/BlaxDefaults_page.xml +++ b/Languages/English/Keyed/BlaxDefaults_page.xml @@ -5,7 +5,7 @@ Apply saved defaults to new things - Off: nothing new gets a default, and every new stockpile, storage building and bill starts with the game's settings. Your saved defaults stay in the file. + Off: nothing new gets a default, every new stockpile, storage building and bill starts with the game's settings, and the forbid rules act on nothing. Your saved defaults stay in the file. No defaults saved yet. 1 default. {0} defaults. diff --git a/Languages/English/Keyed/BlaxDefaults_setup.xml b/Languages/English/Keyed/BlaxDefaults_setup.xml index 3286cff..daa8cb5 100644 --- a/Languages/English/Keyed/BlaxDefaults_setup.xml +++ b/Languages/English/Keyed/BlaxDefaults_setup.xml @@ -18,17 +18,17 @@ Saved {0} empty defaults. - Warn about mods that set the same defaults + Warn about mods that do the same things Names them here and shows one window on the first game you load in a session. "Don't remind me" in that window hides a mod from the window, not from this page. - These active mods set some of the same starting settings: + These active mods do some of the same things as Blax Defaults: {MOD}: {WHAT} - Set each of these in one mod only, or the two overwrite each other. - Mods that set the same defaults - {MODS} set some of the same starting settings as Blax Defaults. Set each of these in one mod only, or the two overwrite each other. The Blax Defaults settings page lists them too. + Use each of these features in one mod only, or the two work against each other. + Mods that do the same things + Blax Defaults does some of the same things as {MODS}. Use each of those features in one mod only, or the two work against each other. The Blax Defaults settings page lists them too. Don't remind me Not shown again - + Starting settings for stockpiles, storage buildings and bills Shelves start empty at Normal Its "No Default Storage Settings" option empties the starting filter of storage buildings diff --git a/README.md b/README.md index 9e39c0d..a94e8b7 100644 --- a/README.md +++ b/README.md @@ -6,9 +6,9 @@ [![Steam Workshop](https://img.shields.io/badge/Steam_Workshop-subscribe-1b2838?logo=steam)](https://steamcommunity.com/sharedfiles/filedetails/?id=3848261264) [![Needs Harmony](https://img.shields.io/badge/needs-Harmony-050805)](https://steamcommunity.com/sharedfiles/filedetails/?id=2009463077) [![Any DLC combination](https://img.shields.io/badge/DLCs-any_combination-5a6b5d)](#dlc-support) -[![Status: 1.0](https://img.shields.io/badge/status-1.0-CDCDCD)](CHANGELOG.md) +[![Status: 1.1](https://img.shields.io/badge/status-1.1-CDCDCD)](CHANGELOG.md) -RimWorld mod (1.7) from Blax Gaming: your own starting settings for new stockpiles, shelves and bills. Set up one shelf, click "Make default for new shelves", and every new shelf starts like it. Nothing changes until you save a default, the things you already have keep their settings, and nothing goes into your save, so the mod can be added to or removed from a running colony. Needs Harmony. Works with any DLC combination, core only included. Colonists, slaves and prisoners are Blax Castes' job; Blax Defaults never changes a pawn. +RimWorld mod (1.7) from Blax Gaming: your own starting settings for new stockpiles, shelves and bills, and rules for what stays forbidden when pawns go down, die or are stripped. Set up one shelf, click "Make default for new shelves", and every new shelf starts like it. Nothing changes until you save a default or turn a rule on, the things you already have keep their settings, and nothing goes into your save, so the mod can be added to or removed from a running colony. Needs Harmony. Works with any DLC combination, core only included. Colonists, slaves and prisoners are Blax Castes' job; Blax Defaults never changes a pawn. ## Features @@ -25,18 +25,29 @@ RimWorld mod (1.7) from Blax Gaming: your own starting settings for new stockpil - ๐Ÿ“œ **Values for every new bill:** repeat mode, count, target, pause when satisfied and resume at, ingredient radius, allowed skill range, where products go (best stockpile or drop on floor), count equipped, count tainted, and the hit points and quality ranges used for counting. Each value starts at "Game's default", and only values you change are applied. "Do until you have X" falls back to "do X times" where the bill can't count its products. `Source/BlaxDefaults/BillDefaults.cs` - ๐Ÿฉบ Surgery, mech gestation, mech resurrection and forming bills, pasted bills and loaded bills are never touched. +### Forbid rules + +A "Forbid rules" section on the settings page. Every rule ships off. `Source/BlaxDefaults/ForbidRules.cs`, `ForbidHooks.cs`, `ForbidRulesSection.cs` + +- ๐Ÿ›ก๏ธ **Gear rules for your colony and for enemies.** When one of the group's pawns goes down or dies, what the game forbids is allowed again if it matches the rule's filter: the vanilla item filter with the hit points and quality ranges stockpiles have and the special filters (tainted, biocoded, rotten, smeltable). What doesn't match stays forbidden, and a rule never forbids a dropped thing the game left allowed. Your colony is colonists, slaves, colony mechs, colony animals and prisoners, also while they break out or rebel; enemies are everyone else hostile to you. Neutral visitors, traders and quest lodgers keep the game's rules. +- Each rule has Edit, Forget (asks first, turns the rule off), "Where" (anywhere, or only inside the home area) and "Use the suggested setup" (asks first). Ticking a rule that has no filter yet saves its suggested setup. Enemies: every item, but hit points 50 to 100% and Normal or better, stripping on, so a Poor rifle or one below 50% stays forbidden while food, medicine, drugs and silver are allowed. Your colony: every item, any hit points and quality, stripping off. +- โš”๏ธ **Once the fight is over.** What a rule allows waits while an enemy that can still fight is on the map. Changing a waiting thing's flag yourself takes it off the list; a save and reload forgets the list, so things still waiting stay forbidden. +- ๐Ÿ”ซ **A downed colonist's own weapon** stays forbidden while the colonist lies where it fell, so it picks the weapon up after getting up, as in vanilla. Once the colonist is rescued, carried off or dies, the rule decides. +- ๐Ÿ‘• **Stripping forbids what doesn't match**, a switch per rule: stripping one of the group's pawns or corpses forbids each dropped thing the filter refuses. This is how the rules reach apparel. Butchering strips too, but what a butcher strips stays allowed. +- ๐Ÿฆด **Corpses outside the home area stay allowed**, with one switch each for animals (manhunters and predators included), enemies and everyone else. They wait for the fight to end too. +- Not reached: trading a pawn away, capturing it, and anything other mods forbid after the game's own drop. + ### Your defaults stay - ๐Ÿ“ **One file for every save.** Defaults live in `Config/BlaxDefaults/Defaults.xml` in the game's save data folder, shared by every save, never in a save or in the mod settings. Every write goes to a temporary file first, is read back and checked, and only then replaces the file, with the previous version kept as `Defaults.xml.bak`. A file that fails to load is kept as a broken copy under its own name and never rotated into the backup; the backup loads instead, and the settings page says so. A file from a newer version is read but never overwritten. `Source/BlaxDefaults/DefaultsFile.cs` - ๐Ÿ”Œ **Removed a mod?** Names from a mod or DLC that is not active stay in the file, are skipped and counted on the settings page, and work again when the mod comes back. -- ๐Ÿ“‹ **Settings page** (Mod settings > Blax Defaults): the master switch "Apply saved defaults to new things", a status line, and the sections Stockpiles, Storage buildings and Every new bill, each with its own switch. Every saved default has a row saying what it sets, with Edit and Forget; Forget asks first. Edit opens the item filter with the priority and the rule for unlisted items. It all works from the main menu. `Source/BlaxDefaults/SettingsPage.cs` -- โš ๏ธ **Overlap warnings.** The settings page names active mods that set the same starting settings, and the first game loaded in a session opens a window listing them, with "Don't remind me" per mod. `Source/BlaxDefaults/OverlapWarnings.cs` +- ๐Ÿ“‹ **Settings page** (Mod settings > Blax Defaults): the master switch "Apply saved defaults to new things", a status line, and the sections Stockpiles, Storage buildings, Every new bill and Forbid rules, each with its own switch. Every saved default has a row saying what it sets, with Edit and Forget; Forget asks first. Edit opens the item filter with the priority and the rule for unlisted items. It all works from the main menu. `Source/BlaxDefaults/SettingsPage.cs` +- โš ๏ธ **Overlap warnings.** The settings page names active mods that do some of the same things, and the first game loaded in a session opens a window listing them, with "Don't remind me" per mod. `Source/BlaxDefaults/OverlapWarnings.cs` ### Planned Designed, not built yet (details and the release table in `docs/design.md`): -- 1.1: forbid rules. When your colonists, slaves, prisoners or enemies go down or die, what the game forbids is allowed again if it matches a filter with hit points and quality ranges, once the fight is over. For example enemy weapons and apparel only at 50 to 100% and Normal or better, their food, medicine, drugs and silver always. Stripping can forbid what doesn't match. Corpses outside the home area can stay allowed. Every rule ships off; neutral visitors and traders keep the game's rules. - 1.2: graves, sarcophagi, mortars, growth vats (Biotech), biosculpter pods (Ideology) and other storage; defaults per recipe from the bill window; the bills a new workbench comes with. - 1.3: animals per species (area, follow flags, training), born animals copy their mother, auto-slaughter limits; auto-repair for new mechs (Biotech). - 1.4: crops for new growing zones and hydroponics basins; settings for new doors, tables, traps, heaters, coolers and lamps. @@ -44,7 +55,7 @@ Designed, not built yet (details and the release table in `docs/design.md`): ### DLC support -Blax Defaults works with any combination of DLCs, core only included, and lists none as a dependency. 1.0 needs no DLC for any feature. +Blax Defaults works with any combination of DLCs, core only included, and lists none as a dependency. No feature needs a DLC. The forbid rules count slaves (Ideology) and colony mechs (Biotech) with your colony when that DLC is loaded; mechs destroy their weapon instead of dropping it in any DLC set. - The defaults file is shared by every DLC set. A DLC item inside a default, such as wastepack in a dumping stockpile default saved with Biotech, is skipped while that DLC is off, counted with the names from inactive mods, and works again when the DLC is back. - A save made with a DLC loads without it: Blax Defaults keeps nothing in the save, and the vanilla fields it wrote are the game's to load. @@ -56,12 +67,16 @@ Replaces, so you can unsubscribe them (the settings page names them while they a - โ™ป๏ธ [FSF] No Default Shelf Storage: the quick setup empties new shelves per kind and leaves hoppers and single-purpose storage alone. - โ™ป๏ธ Default Ingredient Radius and Default Bill Ingredient Radius: "Ingredient radius" under Every new bill. +- โ™ป๏ธ KilledEnemyAutoAllowed (Continued): both gear rules with every item, anywhere, and the corpse switches on. Neutral pawns' drops stay vanilla. +- โ™ป๏ธ Allow Dead Animals: the animal corpse switch. +- โ™ป๏ธ Allow Everything, for what pawns drop when they go down or die: both gear rules with every item. Everything else keeps the flag the player or the game gave it. Overlaps, named by the overlap warning: -- โš ๏ธ 1trickPwnyta's Defaults and Set my Defaults set starting settings for stockpiles and shelves too, and 1trickPwnyta's sets values for every new bill. Blax Defaults 1.0 covers those, so set each in one mod. Their bill lists per recipe or per workbench are not in 1.0 (planned for 1.1), so keep those mods for that and for their other defaults. The unofficial Defaults 1.7 repack is not detected yet. +- โš ๏ธ 1trickPwnyta's Defaults and Set my Defaults set starting settings for stockpiles and shelves too, and 1trickPwnyta's sets values for every new bill. Blax Defaults covers those, so set each in one mod. Their bill lists per recipe or per workbench are not in Blax Defaults yet (planned for 1.2), so keep those mods for that and for their other defaults. The unofficial Defaults 1.7 repack is not detected yet. - โš ๏ธ [FSF] FrozenSnowFox Tweaks: its "No Default Storage Settings" option empties the starting filter of storage buildings, like the quick setup. Use one of the two. - โš ๏ธ Better Workbench Management sets where the products of new bills go. Set that in one mod only. +- โš ๏ธ Non uno Pinata keeps gear on pawns that go down or die, so little drops for the forbid rules to sort. Works next to: @@ -69,6 +84,8 @@ Works next to: - โœ”๏ธ RimFridge (no 1.7 build yet, loads its 1.6 files): its fridges are covered storage kinds. The quick setup leaves them unticked, because RimFridge makes fridges act as hoppers. - โœ”๏ธ Replace Stuff: replacing a shelf's material keeps its settings. - โœ”๏ธ Preset Filtered Zones: its zones keep their preset filters and show no Defaults button. +- โœ”๏ธ Hospitality: guests keep the game's rules, and with its option to keep friendly pawns' gear on them a downed visitor drops nothing. Hospitality drops a downed pawn's weapon without remembering it, so with Hospitality a downed colonist doesn't go back for its weapon and the colony rule decides it once the fight is over. +- โœ”๏ธ Pick Up And Haul: what a forbid rule allows gets hauled like anything else. - ๐Ÿงฉ Other Blax mods: Blax Castes handles colonists, slaves and prisoners. Blax Slaves and Blax Zones don't overlap with Blax Defaults; Zones' delivery zones keep their own tab and get no Defaults button. Load order between them doesn't matter. - โŒ Multiplayer: not supported yet (the defaults file differs per player). @@ -99,7 +116,7 @@ dotnet build Source\BlaxDefaults\BlaxDefaults.csproj -c Release .\Tests\run-tests.ps1 -Compat ``` -A release runs all 8 combinations of Royalty, Ideology and Biotech. Each run also leaves a copy of the results per DLC set next to the results file: `BlaxDefaultsTestResults.all.txt` (every installed DLC), `.nodlc.txt` or `.dlc-.txt`. The Workshop upload checks the `all` and `nodlc` copies. `-Compat` also loads the installed mods Blax Defaults is tested next to (the list is at the top of `run-tests.ps1`). Exit code 0 means all passed, 1 failures, 2 the run didn't finish. +A release runs all 8 combinations of Royalty, Ideology and Biotech. Each run also leaves a copy of the results per DLC set next to the results file: `BlaxDefaultsTestResults.all.txt` (every installed DLC), `.nodlc.txt` or `.dlc-.txt`. The Workshop upload checks the `all` and `nodlc` copies. `-Compat` also loads the installed mods Blax Defaults is tested next to (the list is at the top of `run-tests.ps1`). Exit code 0 means all passed, 1 failures or errors the mod logged between tests, 2 the run didn't finish. ### Workshop art @@ -120,7 +137,7 @@ Without `About/PublishedFileId.txt`, `-Publish` creates a new item. It writes th It stages only what players need (About, 1.7, Defs, Patches, Languages, Textures, Sounds) in `%TEMP%`, sets the tags the game would (Mod plus the supported versions), and writes every CHANGELOG.md entry since the version in `Tools/workshop-published.txt` as the change note. The title is About.xml's name and the preview is `About/Preview.png`, set on every upload like the in-game uploader does. `-Publish` refuses unless the shipped files are committed and pushed, the top CHANGELOG entry matches `modVersion`, `About/Preview.png` is under 1 MB, and two test runs passed after the last build: one with every installed DLC and one with `-NoDlc` (the `all` and `nodlc` result copies, see Tests). `-Check` runs every `-Publish` check and the dry run and lists each problem; exit code 0 means none. The in-game route still works: `Tools/workshop-stage.ps1` swaps the junction for a clean copy, upload from Mods > Blax Defaults > Advanced... > Upload to Steam Workshop (dev mode), then `workshop-stage.ps1 -Done` copies `About/PublishedFileId.txt` back into the repo. -The Workshop description is `docs/workshop-description.txt` (Steam BBCode, at most 8000 bytes); `-DescriptionOnly -DescriptionFile docs\workshop-description.txt` replaces just the text, with no build, no content upload and no change note. Steam loads description images as cross-origin requests, so every `[img]` host must send an `Access-Control-Allow-Origin` header or the image shows broken; the script checks each one and `-Publish` refuses otherwise. Forgejo's raw URLs send no such header, so the Steam images are served from `cdn.blax.at/blax-gaming/`, which does. The section headers must be on `cdn.blax.at/blax-gaming/defaults/` before `-Publish` passes. Every forgejo.blax.at link in the description must also open without a login, so the repo has to be public first. `Source/Art/README.md` has the render commands. +The Workshop description is `docs/workshop-description.txt` (Steam BBCode, at most 8000 bytes). Once something was published from here, an update replaces the description only when `-DescriptionFile docs\workshop-description.txt` is passed, so pass it on every release that changed the file. `-DescriptionOnly -DescriptionFile docs\workshop-description.txt` replaces just the text, with no build, no content upload and no change note. Steam loads description images as cross-origin requests, so every `[img]` host must send an `Access-Control-Allow-Origin` header or the image shows broken; the script checks each one and `-Publish` refuses otherwise. Forgejo's raw URLs send no such header, so the Steam images are served from `cdn.blax.at/blax-gaming/`, which does. The section headers must be on `cdn.blax.at/blax-gaming/defaults/` before `-Publish` passes. Every forgejo.blax.at link in the description must also open without a login, so the repo has to be public first. `Source/Art/README.md` has the render commands. --- diff --git a/Source/Art/README.md b/Source/Art/README.md index f909a83..180bdf7 100644 --- a/Source/Art/README.md +++ b/Source/Art/README.md @@ -30,6 +30,7 @@ The Steam description (`docs/workshop-description.txt`) shows one header per sec & $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\storage.png" "file:///$here/header.html?t=Storage&s=New%20stockpiles%20and%20shelves%20start%20from%20your%20default&i=warehouse" | 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\bills.png" "file:///$here/header.html?t=Bills&s=Values%20every%20new%20bill%20starts%20with&i=scroll-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\forbid.png" "file:///$here/header.html?t=Forbid%20rules&s=What%20stays%20forbidden%20when%20pawns%20go%20down%2C%20die%20or%20are%20stripped&i=sliders" | 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\file.png" "file:///$here/header.html?t=Your%20defaults%20stay&s=Their%20own%20file%2C%20a%20backup%20and%20a%20settings%20page&i=save" | 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\replaces.png" "file:///$here/header.html?t=Replaces&s=Mods%20you%20can%20unsubscribe&i=replace" | Out-Null @@ -40,6 +41,7 @@ The Steam description (`docs/workshop-description.txt`) shows one header per sec |---|---|---|---| | `storage.png` | Storage | New stockpiles and shelves start from your default | warehouse | | `bills.png` | Bills | Values every new bill starts with | scroll-text | +| `forbid.png` | Forbid rules | What stays forbidden when pawns go down, die or are stripped | sliders | | `file.png` | Your defaults stay | Their own file, a backup and a settings page | save | | `planned.png` | Planned | Coming in later releases | milestone | | `replaces.png` | Replaces | Mods you can unsubscribe | replace | diff --git a/Source/BlaxDefaults/BlaxDefaultsMod.cs b/Source/BlaxDefaults/BlaxDefaultsMod.cs index 4806123..0567c7e 100644 --- a/Source/BlaxDefaults/BlaxDefaultsMod.cs +++ b/Source/BlaxDefaults/BlaxDefaultsMod.cs @@ -24,6 +24,9 @@ namespace BlaxDefaults /// New production bills get the values of "Every new bill". public static bool BillsOn => Enabled && (Settings == null || Settings.billDefaults); + /// The forbid rules may act (each rule still needs its own switch and filter). + public static bool ForbidOn => Enabled && (Settings == null || Settings.forbidRules); + public override string SettingsCategory() => "Blax Defaults"; public override void DoSettingsWindowContents(Rect inRect) => SettingsPage.Draw(inRect); diff --git a/Source/BlaxDefaults/BlaxDefaultsSettings.cs b/Source/BlaxDefaults/BlaxDefaultsSettings.cs index 3161c4c..1247831 100644 --- a/Source/BlaxDefaults/BlaxDefaultsSettings.cs +++ b/Source/BlaxDefaults/BlaxDefaultsSettings.cs @@ -18,7 +18,27 @@ namespace BlaxDefaults public bool storageDefaults = true; /// New production bills get the values of "Every new bill". public bool billDefaults = true; - /// The settings page and one message per session name active mods that set the same defaults. + /// The forbid rules as a category: off, no gear rule, strip switch or corpse switch acts. + public bool forbidRules = true; + /// "Gear your colony drops". Acts only with a saved filter under forbid:colony. + public bool colonyGearRule; + /// The colony rule's "Where": anywhere (true) or only inside the home area. + public bool colonyGearAnywhere = true; + /// "Gear enemies drop". Acts only with a saved filter under forbid:enemies. + public bool enemyGearRule; + /// The enemy rule's "Where": anywhere (true) or only inside the home area. + public bool enemyGearAnywhere = true; + /// Stripping one of your colony's pawns or corpses forbids what the colony filter refuses. + public bool colonyStripRule; + /// Stripping an enemy or an enemy corpse forbids what the enemy filter refuses. + public bool enemyStripRule; + /// Animal corpses outside the home area are allowed. + public bool animalCorpsesAllowed; + /// Enemy corpses outside the home area are allowed. + public bool enemyCorpsesAllowed; + /// Other corpses outside the home area are allowed. + public bool otherCorpsesAllowed; + /// The settings page and one message per session name active mods that do some of the same things. public bool warnOverlaps = true; /// Package ids whose overlap message the player dismissed with "Don't remind me". public List dismissedOverlaps = new List(); @@ -30,6 +50,16 @@ namespace BlaxDefaults Scribe_Values.Look(ref stockpileDefaults, "stockpileDefaults", true); Scribe_Values.Look(ref storageDefaults, "storageDefaults", true); Scribe_Values.Look(ref billDefaults, "billDefaults", true); + Scribe_Values.Look(ref forbidRules, "forbidRules", true); + Scribe_Values.Look(ref colonyGearRule, "colonyGearRule", false); + Scribe_Values.Look(ref colonyGearAnywhere, "colonyGearAnywhere", true); + Scribe_Values.Look(ref enemyGearRule, "enemyGearRule", false); + Scribe_Values.Look(ref enemyGearAnywhere, "enemyGearAnywhere", true); + Scribe_Values.Look(ref colonyStripRule, "colonyStripRule", false); + Scribe_Values.Look(ref enemyStripRule, "enemyStripRule", false); + Scribe_Values.Look(ref animalCorpsesAllowed, "animalCorpsesAllowed", false); + Scribe_Values.Look(ref enemyCorpsesAllowed, "enemyCorpsesAllowed", false); + Scribe_Values.Look(ref otherCorpsesAllowed, "otherCorpsesAllowed", false); Scribe_Values.Look(ref warnOverlaps, "warnOverlaps", true); Scribe_Collections.Look(ref dismissedOverlaps, "dismissedOverlaps", LookMode.Value); if (Scribe.mode == LoadSaveMode.PostLoadInit || Scribe.mode == LoadSaveMode.LoadingVars) @@ -44,6 +74,16 @@ namespace BlaxDefaults stockpileDefaults = d.stockpileDefaults; storageDefaults = d.storageDefaults; billDefaults = d.billDefaults; + forbidRules = d.forbidRules; + colonyGearRule = d.colonyGearRule; + colonyGearAnywhere = d.colonyGearAnywhere; + enemyGearRule = d.enemyGearRule; + enemyGearAnywhere = d.enemyGearAnywhere; + colonyStripRule = d.colonyStripRule; + enemyStripRule = d.enemyStripRule; + animalCorpsesAllowed = d.animalCorpsesAllowed; + enemyCorpsesAllowed = d.enemyCorpsesAllowed; + otherCorpsesAllowed = d.otherCorpsesAllowed; warnOverlaps = d.warnOverlaps; dismissedOverlaps = new List(); } diff --git a/Source/BlaxDefaults/DefaultsEntry.cs b/Source/BlaxDefaults/DefaultsEntry.cs index 45f0727..2843250 100644 --- a/Source/BlaxDefaults/DefaultsEntry.cs +++ b/Source/BlaxDefaults/DefaultsEntry.cs @@ -52,7 +52,8 @@ namespace BlaxDefaults /// /// The library keys. One default per kind: "stockpile:Stockpile", "stockpile:Dumping", - /// "stockpile:<designator type name>", "storage:<ThingDef>" and "bill:*" in 1.0. Later releases + /// "stockpile:<designator type name>", "storage:<ThingDef>" and "bill:*" in 1.0, "forbid:colony" and + /// "forbid:enemies" (the forbid rules' filters) in 1.1. Later releases /// add their own prefixes (bill:<RecipeDef>, bench:, animal:, slaughter:, mech:, grower:, building:). /// public static class DefaultsKeys @@ -60,6 +61,12 @@ namespace BlaxDefaults public const string StockpilePrefix = "stockpile:"; public const string StoragePrefix = "storage:"; public const string BillPrefix = "bill:"; + public const string ForbidPrefix = "forbid:"; + + /// The filter of "Gear your colony drops" (1.1). + public const string ForbidColony = "forbid:colony"; + /// The filter of "Gear enemies drop" (1.1). + public const string ForbidEnemies = "forbid:enemies"; /// The vanilla stockpile (DefaultStockpile preset): Designator_ZoneAddStockpile_Resources and _Expand. public const string Stockpile = "stockpile:Stockpile"; @@ -81,6 +88,8 @@ namespace BlaxDefaults public static bool IsBill(string key) => key != null && key.StartsWith(BillPrefix, StringComparison.Ordinal); + public static bool IsForbid(string key) => key != null && key.StartsWith(ForbidPrefix, StringComparison.Ordinal); + /// The part after the prefix: "Shelf" for "storage:Shelf". public static string NameOf(string key) { diff --git a/Source/BlaxDefaults/Dialog_EditStorageTemplate.cs b/Source/BlaxDefaults/Dialog_EditStorageTemplate.cs index 34602f5..6ee8729 100644 --- a/Source/BlaxDefaults/Dialog_EditStorageTemplate.cs +++ b/Source/BlaxDefaults/Dialog_EditStorageTemplate.cs @@ -18,6 +18,9 @@ namespace BlaxDefaults /// template that don't resolve now (so nothing from an inactive mod is lost), and stores it with /// DefaultsLibrary.Set. Needs defs only, not a running game: the places where the vanilla filter reads /// the game are bridged by Patch_Listing_TreeThingFilter_MainMenu below. + /// + /// For a forbid rule's filter (1.1, StorageKind.IsForbid) the same window has no priority, and the unlisted + /// rule offers only "refuse them" (stays forbidden) and "allow them". /// public class Dialog_EditStorageTemplate : Window { @@ -40,7 +43,9 @@ namespace BlaxDefaults Original = template?.CloneTemplate(); Scratch = new StorageSettings(); kind.LoadDefault(Scratch, template); - Unlisted = template?.unlisted ?? UnlistedRule.Game; + Unlisted = template?.unlisted ?? (kind.IsForbid ? UnlistedRule.Allow : UnlistedRule.Game); + if (kind.IsForbid && Unlisted == UnlistedRule.Game) + Unlisted = UnlistedRule.Allow; doCloseX = true; forcePause = true; absorbInputAroundWindow = true; @@ -53,14 +58,18 @@ namespace BlaxDefaults public override void DoWindowContents(Rect inRect) { Text.Font = GameFont.Medium; - Widgets.Label(new Rect(0f, 0f, inRect.width - 30f, TitleHeight), "BlaxDefaults_PageEditTitle".Translate(Kind.LabelPlural)); + string title = Kind.IsForbid ? "BlaxDefaults_ForbidEditTitle".Translate(Kind.Label) : "BlaxDefaults_PageEditTitle".Translate(Kind.LabelPlural); + Widgets.Label(new Rect(0f, 0f, inRect.width - 30f, TitleHeight), title); Text.Font = GameFont.Small; float y = TitleHeight + 4f; - var priorityRect = new Rect(0f, y, Mathf.Min(220f, inRect.width), RowHeight); - if (Widgets.ButtonText(priorityRect, "BlaxDefaults_PagePriority".Translate(Scratch.Priority.Label().CapitalizeFirst()))) - Find.WindowStack.Add(new FloatMenu(PriorityOptions())); - y += RowHeight + Gap; + if (!Kind.IsForbid) + { + var priorityRect = new Rect(0f, y, Mathf.Min(220f, inRect.width), RowHeight); + if (Widgets.ButtonText(priorityRect, "BlaxDefaults_PagePriority".Translate(Scratch.Priority.Label().CapitalizeFirst()))) + Find.WindowStack.Add(new FloatMenu(PriorityOptions())); + y += RowHeight + Gap; + } float bottomHeight = RowHeight + Gap + RowHeight; var filterRect = new Rect(0f, y, inRect.width, inRect.height - y - Gap - bottomHeight); @@ -80,7 +89,9 @@ namespace BlaxDefaults var unlistedRect = new Rect(0f, y, inRect.width, RowHeight); if (Widgets.ButtonText(unlistedRect, "BlaxDefaults_PageUnlisted".Translate(Unlisted.Label()))) Find.WindowStack.Add(new FloatMenu(UnlistedOptions())); - TooltipHandler.TipRegion(unlistedRect, "BlaxDefaults_PageUnlistedTip".Translate(Kind.LabelPlural).Resolve()); + TooltipHandler.TipRegion(unlistedRect, Kind.IsForbid + ? "BlaxDefaults_ForbidUnlistedTip".Translate().Resolve() + : "BlaxDefaults_PageUnlistedTip".Translate(Kind.LabelPlural).Resolve()); y += RowHeight + Gap; float half = (inRect.width - Gap) / 2f; @@ -108,6 +119,8 @@ namespace BlaxDefaults var list = new List(); foreach (UnlistedRule r in Enum.GetValues(typeof(UnlistedRule))) { + if (Kind.IsForbid && r == UnlistedRule.Game) + continue; UnlistedRule local = r; list.Add(new FloatMenuOption(local.Label().CapitalizeFirst(), () => Unlisted = local)); } diff --git a/Source/BlaxDefaults/ForbidHooks.cs b/Source/BlaxDefaults/ForbidHooks.cs new file mode 100644 index 0000000..9636f12 --- /dev/null +++ b/Source/BlaxDefaults/ForbidHooks.cs @@ -0,0 +1,513 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using HarmonyLib; +using RimWorld; +using Verse; +using Verse.AI; + +namespace BlaxDefaults +{ + /// + /// One downing or death in progress: the pawn, its group read while it was alive, and every thing the game + /// forbade inside the call (allowed before, forbidden after). Never saved. + /// + public sealed class ForbidScope + { + public readonly Pawn Pawn; + public readonly ForbidGroup Group; + /// True for Pawn_HealthTracker.MakeDowned, false for Pawn.Kill. + public readonly bool Downing; + public readonly List Recorded = new List(); + + public ForbidScope(Pawn pawn, ForbidGroup group, bool downing) + { + Pawn = pawn; + Group = group; + Downing = downing; + } + } + + /// + /// The forbid rules' hooks. Work package "forbid" (design.md, 1.1 "Gear rules for your colony and for + /// enemies", "Stripping forbids what doesn't match", "Corpses outside the home area stay allowed"). + /// + /// Scopes: prefixes on Pawn.Kill(DamageInfo?, Hediff) and the private Pawn_HealthTracker.MakeDowned(DamageInfo?, + /// Hediff) push the pawn and its group onto a [ThreadStatic] stack while the game is playing, no map is being + /// made and a rule or corpse switch could act; a finalizer pops it, even on an exception. Recorder: a prefix and + /// a postfix on the CompForbiddable.Forbidden setter add a thing that went from allowed to forbidden to the + /// innermost scope. So a scope holds exactly what the game forbade in that call. Apply, in the postfixes of + /// Kill and MakeDowned: a corpse goes to the corpse switches, any other thing is allowed when its group's rule + /// acts, its cell passes "Where" and the filter allows it: at once when the map has no active threat, else + /// through ForbidWaitList. A downed colonist's remembered weapon always waits (ForbidWaitList keeps it while + /// the colonist still remembers it). Strip: a prefix records what the pawn wears, holds and carries, and the + /// postfix forbids each of those now on a map, inside "Where", that the filter refuses; nothing while + /// butchering's ingredient step (Toils_Recipe.CalculateIngredients) runs. Never patched: + /// ForbidUtility.SetForbidden, which player designators use, and SetForbiddenIfOutsideHomeArea, five lines + /// the JIT may inline. + /// + public static class ForbidHooks + { + [ThreadStatic] private static List stack; + [ThreadStatic] private static int butchering; + + /// True while a downing or death scope is open on this thread. + public static bool ScopeOpen + { + get + { + List s = stack; + return s != null && s.Count > 0; + } + } + + /// True while butchering's ingredient step runs on this thread: stripping stays vanilla then. + public static bool Butchering => butchering > 0; + + /// A scope opens while the game plays, no map is being made, and a rule or corpse switch could act. + public static bool ShouldOpen => + Current.ProgramState == ProgramState.Playing && MapGenerator.mapBeingGenerated == null && ForbidRules.AnyDropRuleOn; + + public static ForbidScope Push(Pawn pawn, bool downing) + { + var scope = new ForbidScope(pawn, ForbidRules.GroupOf(pawn), downing); + (stack ??= new List()).Add(scope); + return scope; + } + + public static void Pop(ForbidScope scope) + { + List s = stack; + if (s == null || scope == null) + return; + int i = s.LastIndexOf(scope); + if (i >= 0) + s.RemoveAt(i); + } + + /// The recorder: a thing the game just forbade inside a scope goes to the innermost one. + public static void Record(Thing t) + { + List s = stack; + if (t == null || s == null || s.Count == 0) + return; + List recorded = s[s.Count - 1].Recorded; + if (!recorded.Contains(t)) + recorded.Add(t); + } + + internal static void EnterButchering() => butchering++; + + internal static void LeaveButchering() + { + if (butchering > 0) + butchering--; + } + + /// + /// What the postfix of Kill or MakeDowned does with the things its scope recorded. A thing no longer + /// spawned or no longer forbidden is skipped; a corpse goes to the corpse switches; any other thing to its + /// group's rule. A downed colonist's remembered weapon goes on the wait list with its owner. + /// + public static void Apply(ForbidScope scope) + { + if (scope == null || scope.Recorded.Count == 0) + return; + ForbidRule rule = ForbidRules.For(scope.Group); + Thing remembered = scope.Downing && scope.Group == ForbidGroup.Colony ? scope.Pawn?.mindState?.droppedWeapon : null; + foreach (Thing thing in scope.Recorded.ToList()) + { + if (thing == null || thing.Destroyed || !thing.Spawned || !ForbidRules.IsForbiddenFlag(thing)) + continue; + if (thing is Corpse corpse) + { + ApplyCorpse(corpse, scope); + continue; + } + if (rule == null || !rule.Active) + continue; + if (thing == remembered) + { + ForbidWaitList.Add(thing, rule, null, scope.Pawn); + continue; + } + if (rule.InsideWhere(thing) && rule.Allows(thing)) + AllowOrWait(thing, rule, null); + } + } + + private static void ApplyCorpse(Corpse corpse, ForbidScope scope) + { + Map map = corpse.Map; + if (map == null || map.areaManager.Home[corpse.Position]) + return; + Pawn inner = corpse.InnerPawn; + CorpseKind kind = inner == scope.Pawn + ? ForbidRules.CorpseKindOf(inner, scope.Group) + : ForbidRules.CorpseKindOf(inner, ForbidRules.GroupOfDead(inner)); + if (ForbidRules.CorpseSwitch(kind)) + AllowOrWait(corpse, null, kind); + } + + /// Allows the thing now when its map has no active threat, else puts it on the wait list. + private static void AllowOrWait(Thing thing, ForbidRule rule, CorpseKind? corpse) + { + if (GenHostility.AnyHostileActiveThreatToPlayer(thing.Map)) + ForbidWaitList.Add(thing, rule, corpse, null); + else + thing.SetForbidden(false, warnOnFail: false); + } + + /// What the strip prefix recorded: the rule of the stripped pawn's group and what it had. + public sealed class StripRecord + { + public ForbidRule Rule; + public List Things; + } + + /// The strip prefix: null when the pawn's group has no strip switch acting. + public static StripRecord BeforeStrip(Pawn pawn) + { + if (pawn == null || Butchering || Current.ProgramState != ProgramState.Playing || !ForbidRules.On) + return null; + if (!ForbidRules.Colony.StripActive && !ForbidRules.Enemies.StripActive) + return null; + ForbidGroup group = pawn.Dead ? ForbidRules.GroupOfDead(pawn) : ForbidRules.GroupOf(pawn); + ForbidRule rule = ForbidRules.For(group); + if (rule == null || !rule.StripActive) + return null; + var things = new List(); + if (pawn.equipment != null) + things.AddRange(pawn.equipment.AllEquipmentListForReading); + if (pawn.apparel != null) + things.AddRange(pawn.apparel.WornApparel); + if (pawn.inventory != null) + things.AddRange(pawn.inventory.innerContainer); + return things.Count == 0 ? null : new StripRecord { Rule = rule, Things = things }; + } + + /// The strip postfix: forbids each recorded thing now on a map, inside "Where", that the filter refuses. + public static void AfterStrip(StripRecord record) + { + if (record?.Rule == null || !record.Rule.StripActive) + return; + foreach (Thing t in record.Things) + { + if (t == null || t.Destroyed || !t.Spawned || ForbidRules.IsForbiddenFlag(t)) + continue; + if (record.Rule.InsideWhere(t) && !record.Rule.Allows(t)) + t.SetForbidden(true, warnOnFail: false); + } + } + } + + /// + /// Things a rule allows wait here while an enemy that can still fight is on their map. Work package "forbid" + /// (design.md, 1.1 "Wait until the fight is over"). An unsaved list of thing, rule (or corpse switch) and, for + /// a remembered weapon, its owner, with the Game it belongs to: a different Current.Game clears it, so a save + /// and reload forgets it and things still waiting stay forbidden, as in vanilla. + /// + /// Every 250 ticks, per map with entries (Map.MapPostTick postfix, which returns at once while the list is + /// empty): an entry whose thing is no longer spawned on that map leaves; a remembered weapon stays while + /// owner.mindState.droppedWeapon is still that weapon; if any other entry is left and + /// GenHostility.AnyHostileActiveThreatToPlayer(map) is false, each whose rule still acts, that is still + /// forbidden, inside "Where" and allowed by the current filter is allowed, and all of them leave the list. + /// Changing a waiting thing's flag outside a scope (the player, a mod) takes it off the list. + /// + public static class ForbidWaitList + { + public const int CheckInterval = 250; + + public sealed class Entry + { + public Thing Thing; + /// The gear rule, or null for a corpse. + public ForbidRule Rule; + /// The corpse switch, for a corpse. + public CorpseKind? Corpse; + /// The colonist that remembers this weapon, or null. + public Pawn Owner; + public Map Map; + } + + private static readonly List entries = new List(); + private static Game game; + + /// No entries: the tick postfix returns at once. + public static bool IsEmpty => entries.Count == 0; + + public static int Count + { + get + { + CheckGame(); + return entries.Count; + } + } + + /// True while the thing waits. + public static bool Contains(Thing t) + { + CheckGame(); + return t != null && entries.Any(e => e.Thing == t); + } + + /// The waiting entry of the thing, or null. + public static Entry EntryOf(Thing t) + { + CheckGame(); + return t == null ? null : entries.FirstOrDefault(e => e.Thing == t); + } + + public static void Add(Thing thing, ForbidRule rule, CorpseKind? corpse, Pawn owner) + { + if (thing == null || thing.Map == null) + return; + CheckGame(); + game = Current.Game; + entries.RemoveAll(e => e.Thing == thing); + entries.Add(new Entry { Thing = thing, Rule = rule, Corpse = corpse, Owner = owner, Map = thing.Map }); + } + + public static void Remove(Thing thing) + { + if (thing == null || entries.Count == 0) + return; + entries.RemoveAll(e => e.Thing == thing); + } + + /// Empties the list. Tests only (and a game change). + public static void Clear() + { + entries.Clear(); + game = null; + } + + private static void CheckGame() + { + if (entries.Count > 0 && game != Current.Game) + Clear(); + } + + /// The tick postfix: every CheckInterval ticks, the check for this map. + public static void MapTick(Map map) + { + if (entries.Count == 0 || map == null) + return; + CheckGame(); + if (entries.Count == 0 || Find.TickManager.TicksGame % CheckInterval != 0) + return; + Check(map); + } + + /// The check for one map, as described above. + public static void Check(Map map) + { + CheckGame(); + List maps = Find.Maps; + entries.RemoveAll(e => e.Map == null || !maps.Contains(e.Map)); + var ready = new List(); + foreach (Entry e in entries.Where(x => x.Map == map).ToList()) + { + if (e.Thing == null || e.Thing.Destroyed || !e.Thing.Spawned || e.Thing.Map != map) + { + entries.Remove(e); + continue; + } + if (e.Owner != null && e.Owner.mindState != null && e.Owner.mindState.droppedWeapon == e.Thing) + continue; + ready.Add(e); + } + if (ready.Count == 0 || GenHostility.AnyHostileActiveThreatToPlayer(map)) + return; + foreach (Entry e in ready) + { + entries.Remove(e); + if (ShouldAllow(e)) + e.Thing.SetForbidden(false, warnOnFail: false); + } + } + + private static bool ShouldAllow(Entry e) + { + if (!ForbidRules.IsForbiddenFlag(e.Thing)) + return false; + if (e.Corpse.HasValue) + return ForbidRules.CorpseSwitch(e.Corpse.Value); + ForbidRule rule = e.Rule; + return rule != null && rule.Active && rule.InsideWhere(e.Thing) && rule.Allows(e.Thing); + } + } + + // ---- patches --------------------------------------------------------------------- + + [HarmonyPatch(typeof(Pawn), nameof(Pawn.Kill), new[] { typeof(DamageInfo?), typeof(Hediff) })] + public static class Patch_Pawn_Kill + { + public static void Prefix(Pawn __instance, out ForbidScope __state) + { + __state = null; + try + { + if (ForbidHooks.ShouldOpen) + __state = ForbidHooks.Push(__instance, downing: false); + } + catch (Exception e) + { + HookGuard.Report("Pawn.Kill prefix", e); + } + } + + public static void Postfix(ForbidScope __state) + { + if (__state == null) + return; + try + { + ForbidHooks.Apply(__state); + } + catch (Exception e) + { + HookGuard.Report("Pawn.Kill", e); + } + } + + public static void Finalizer(ForbidScope __state) + { + if (__state != null) + ForbidHooks.Pop(__state); + } + } + + [HarmonyPatch(typeof(Pawn_HealthTracker), "MakeDowned", new[] { typeof(DamageInfo?), typeof(Hediff) })] + public static class Patch_Pawn_HealthTracker_MakeDowned + { + public static void Prefix(Pawn ___pawn, out ForbidScope __state) + { + __state = null; + try + { + if (ForbidHooks.ShouldOpen) + __state = ForbidHooks.Push(___pawn, downing: true); + } + catch (Exception e) + { + HookGuard.Report("Pawn_HealthTracker.MakeDowned prefix", e); + } + } + + public static void Postfix(ForbidScope __state) + { + if (__state == null) + return; + try + { + ForbidHooks.Apply(__state); + } + catch (Exception e) + { + HookGuard.Report("Pawn_HealthTracker.MakeDowned", e); + } + } + + public static void Finalizer(ForbidScope __state) + { + if (__state != null) + ForbidHooks.Pop(__state); + } + } + + /// The recorder. It never changes a flag: it only reads the old value and notes the change. + [HarmonyPatch(typeof(CompForbiddable), nameof(CompForbiddable.Forbidden), MethodType.Setter)] + public static class Patch_CompForbiddable_Forbidden + { + public static void Prefix(CompForbiddable __instance, out bool __state) + { + __state = false; + if (!ForbidHooks.ScopeOpen && ForbidWaitList.IsEmpty) + return; + __state = __instance.Forbidden; + } + + public static void Postfix(CompForbiddable __instance, bool __state) + { + if (!ForbidHooks.ScopeOpen && ForbidWaitList.IsEmpty) + return; + try + { + bool now = __instance.Forbidden; + if (ForbidHooks.ScopeOpen) + { + if (!__state && now) + ForbidHooks.Record(__instance.parent); + } + else if (__state != now) + { + ForbidWaitList.Remove(__instance.parent); + } + } + catch (Exception e) + { + HookGuard.Report("CompForbiddable.Forbidden", e); + } + } + } + + [HarmonyPatch(typeof(Pawn), nameof(Pawn.Strip))] + public static class Patch_Pawn_Strip + { + public static void Prefix(Pawn __instance, out ForbidHooks.StripRecord __state) + { + __state = null; + try + { + __state = ForbidHooks.BeforeStrip(__instance); + } + catch (Exception e) + { + HookGuard.Report("Pawn.Strip prefix", e); + } + } + + public static void Postfix(ForbidHooks.StripRecord __state) + { + if (__state == null) + return; + try + { + ForbidHooks.AfterStrip(__state); + } + catch (Exception e) + { + HookGuard.Report("Pawn.Strip", e); + } + } + } + + /// Butchering's ingredient step strips corpses (autoStripCorpses); the strip switch leaves that vanilla. + [HarmonyPatch(typeof(Toils_Recipe), "CalculateIngredients")] + public static class Patch_Toils_Recipe_CalculateIngredients + { + public static void Prefix() => ForbidHooks.EnterButchering(); + + public static void Finalizer() => ForbidHooks.LeaveButchering(); + } + + [HarmonyPatch(typeof(Map), nameof(Map.MapPostTick))] + public static class Patch_Map_MapPostTick + { + public static void Postfix(Map __instance) + { + if (ForbidWaitList.IsEmpty) + return; + try + { + ForbidWaitList.MapTick(__instance); + } + catch (Exception e) + { + HookGuard.Report("Map.MapPostTick", e); + } + } + } +} diff --git a/Source/BlaxDefaults/ForbidRules.cs b/Source/BlaxDefaults/ForbidRules.cs new file mode 100644 index 0000000..64a58ea --- /dev/null +++ b/Source/BlaxDefaults/ForbidRules.cs @@ -0,0 +1,382 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RimWorld; +using Verse; + +namespace BlaxDefaults +{ + /// Who a pawn that goes down, dies or is stripped belongs to, for the forbid rules. + public enum ForbidGroup + { + /// Neutral visitors, traders, quest lodgers and anyone else: the game's rules. + None, + /// Colonists, slaves, colony mechs, colony animals and prisoners, breaking out or rebelling included. + Colony, + /// Everyone else hostile to the player. + Enemies, + } + + /// Which corpse switch a corpse falls under; the first kind that fits decides. + public enum CorpseKind + { + Animal, + Enemy, + Other, + } + + /// + /// One forbid rule: "Gear your colony drops" or "Gear enemies drop". Work package "forbid" (design.md, 1.1 + /// "Gear rules for your colony and for enemies"). Its filter is a StorageTemplate in the defaults library under + /// forbid:colony or forbid:enemies (priority unused, unlisted Refuse or Allow); its switches live in mod + /// settings. The rule acts only when it is ticked and has a filter: a ticked rule whose filter is missing (the + /// defaults file failed to load) acts as off, and the settings page says why. + /// + public sealed class ForbidRule + { + public readonly ForbidGroup Group; + public readonly string Key; + + private StorageTemplate filterFor; + private ThingFilter filter; + + public ForbidRule(ForbidGroup group, string key) + { + Group = group; + Key = key; + } + + private static BlaxDefaultsSettings S => BlaxDefaultsMod.Settings; + + /// The rule's checkbox: colonyGearRule or enemyGearRule. + public bool Ticked + { + get => S != null && (Group == ForbidGroup.Colony ? S.colonyGearRule : S.enemyGearRule); + set + { + if (S == null) return; + if (Group == ForbidGroup.Colony) S.colonyGearRule = value; + else S.enemyGearRule = value; + } + } + + /// "Where": true for anywhere (the default), false for only inside the home area. + public bool Anywhere + { + get => S == null || (Group == ForbidGroup.Colony ? S.colonyGearAnywhere : S.enemyGearAnywhere); + set + { + if (S == null) return; + if (Group == ForbidGroup.Colony) S.colonyGearAnywhere = value; + else S.enemyGearAnywhere = value; + } + } + + /// "Stripping forbids what doesn't match": colonyStripRule or enemyStripRule. + public bool StripTicked + { + get => S != null && (Group == ForbidGroup.Colony ? S.colonyStripRule : S.enemyStripRule); + set + { + if (S == null) return; + if (Group == ForbidGroup.Colony) S.colonyStripRule = value; + else S.enemyStripRule = value; + } + } + + /// The saved filter, or null. + public StorageTemplate Template => DefaultsLibrary.Get(Key); + + public bool HasFilter => Template != null; + + /// The gear rule acts: the forbid rules are on, the rule is ticked and it has a filter. + public bool Active => ForbidRules.On && Ticked && HasFilter; + + /// The strip switch acts: the forbid rules are on, the switch is ticked and the rule has a filter. + public bool StripActive => ForbidRules.On && StripTicked && HasFilter; + + /// "Gear your colony drops" or "Gear enemies drop". + public string Label => (Group == ForbidGroup.Colony ? "BlaxDefaults_ForbidColonyRule" : "BlaxDefaults_ForbidEnemyRule").Translate(); + + /// + /// The filter built from the saved template, kept until the template changes (the library replaces an entry + /// on every change, so the reference tells). Null without a saved template. + /// + public ThingFilter Filter + { + get + { + StorageTemplate t = Template; + if (t == null) + { + filterFor = null; + filter = null; + return null; + } + if (!ReferenceEquals(t, filterFor) || filter == null) + { + filter = ForbidRules.BuildFilter(t); + filterFor = t; + } + return filter; + } + } + + /// The filter allows the thing (def, hit points, quality, special filters). False without a filter. + public bool Allows(Thing t) + { + ThingFilter f = Filter; + return f != null && t != null && f.Allows(t); + } + + /// The thing's cell passes "Where": anywhere, or inside the home area of its map. + public bool InsideWhere(Thing t) + { + if (Anywhere) + return true; + Map map = t?.MapHeld; + if (map == null) + return false; + IntVec3 c = t.PositionHeld; + return c.InBounds(map) && map.areaManager.Home[c]; + } + + /// + /// The suggested setup, applied only when the player asks (or ticks a rule without a filter). Enemies: + /// every item, hit points 50 to 100%, Normal or better, stripping on. Your colony: every item, full ranges, + /// stripping off. Both anywhere, with unlisted items allowed, so items a mod adds later follow the ranges. + /// + public StorageTemplate Suggested() + { + var t = new StorageTemplate(Key) { unlisted = UnlistedRule.Allow }; + if (Group == ForbidGroup.Enemies) + { + t.hitPoints = new FloatRange(0.5f, 1f); + t.quality = new QualityRange(QualityCategory.Normal, QualityCategory.Legendary); + } + return t; + } + + /// The strip switch the suggested setup sets. + public bool SuggestedStrip => Group == ForbidGroup.Enemies; + + /// + /// Saves the suggested setup as the filter and sets "Where" to anywhere and the strip switch as the setup + /// says. Leaves the rule's checkbox as it is. Returns whether the defaults file was written. + /// + public bool UseSuggested() + { + bool ok = DefaultsLibrary.Set(Suggested()); + Anywhere = true; + StripTicked = SuggestedStrip; + return ok; + } + + /// + /// Ticks or unticks the rule from the settings page. Ticking a rule that has no filter yet saves the + /// suggested setup first (strip switch included) and returns true, so the page can say so (decided + /// 2026-11-30, design.md "Defaults I picked"). + /// + public bool SetTicked(bool on) + { + bool usedSuggested = false; + if (on && !HasFilter) + { + UseSuggested(); + usedSuggested = true; + } + Ticked = on; + return usedSuggested; + } + + /// Forget: deletes the filter and turns the rule and its strip switch off. + public void Forget() + { + DefaultsLibrary.Forget(Key); + Ticked = false; + StripTicked = false; + } + + public override string ToString() => Key; + } + + /// + /// The two forbid rules, the corpse switches and the shared pieces: groups, the parent filter, filters built + /// from templates and the row summary. Work package "forbid" (design.md, 1.1 Forbid rules). + /// + public static class ForbidRules + { + public static readonly ForbidRule Colony = new ForbidRule(ForbidGroup.Colony, DefaultsKeys.ForbidColony); + public static readonly ForbidRule Enemies = new ForbidRule(ForbidGroup.Enemies, DefaultsKeys.ForbidEnemies); + + public static readonly ForbidRule[] All = { Colony, Enemies }; + + private static ThingFilter parentFilter; + + /// The forbid rules category is on (and the master switch). + public static bool On => BlaxDefaultsMod.ForbidOn; + + public static ForbidRule For(ForbidGroup group) => + group == ForbidGroup.Colony ? Colony : group == ForbidGroup.Enemies ? Enemies : null; + + public static ForbidRule ForKey(string key) => All.FirstOrDefault(r => r.Key == key); + + /// Anything a downing or a death could change: a gear rule acting or a corpse switch on. + public static bool AnyDropRuleOn => + On && (Colony.Active || Enemies.Active || CorpseSwitch(CorpseKind.Animal) || CorpseSwitch(CorpseKind.Enemy) || CorpseSwitch(CorpseKind.Other)); + + /// + /// The group of a living pawn: your colony when its faction is the player's and it is not a quest lodger, + /// or it is a prisoner of the colony (a prison break leaves it one); otherwise enemies when it is hostile + /// to the player; otherwise none. Read before death: HostileTo is false for anything destroyed. + /// + public static ForbidGroup GroupOf(Pawn p) + { + Faction player = Faction.OfPlayerSilentFail; + if (p == null || player == null) + return ForbidGroup.None; + if (p.Faction == player && !p.IsQuestLodger()) + return ForbidGroup.Colony; + if (p.IsPrisonerOfColony) + return ForbidGroup.Colony; + if (p.HostileTo(player)) + return ForbidGroup.Enemies; + return ForbidGroup.None; + } + + /// + /// The group of a dead pawn, from its faction alone: your faction (not a lodger) is your colony, a faction + /// hostile to yours is enemies. A dead prisoner counts by the faction it came from. + /// + public static ForbidGroup GroupOfDead(Pawn p) + { + Faction player = Faction.OfPlayerSilentFail; + if (p == null || player == null || p.Faction == null) + return ForbidGroup.None; + if (p.Faction == player) + return p.IsQuestLodger() ? ForbidGroup.None : ForbidGroup.Colony; + return p.Faction.HostileTo(player) ? ForbidGroup.Enemies : ForbidGroup.None; + } + + /// + /// The corpse switch a pawn's corpse falls under: animal (any RaceProps.Animal), then enemy (the group read + /// while it was alive), then other. + /// + public static CorpseKind CorpseKindOf(Pawn p, ForbidGroup group) + { + if (p?.RaceProps != null && p.RaceProps.Animal) + return CorpseKind.Animal; + return group == ForbidGroup.Enemies ? CorpseKind.Enemy : CorpseKind.Other; + } + + /// The corpse switch for this kind is on (and the forbid rules). + public static bool CorpseSwitch(CorpseKind kind) + { + BlaxDefaultsSettings s = BlaxDefaultsMod.Settings; + if (s == null || !On) + return false; + switch (kind) + { + case CorpseKind.Animal: return s.animalCorpsesAllowed; + case CorpseKind.Enemy: return s.enemyCorpsesAllowed; + default: return s.otherCorpsesAllowed; + } + } + + /// + /// What a forbid filter may ever allow: every storable item (StorageSettings.EverStorableFixedSettings) + /// without the Corpses category, which the corpse switches cover. Built once. + /// + public static ThingFilter ParentFilter + { + get + { + if (parentFilter == null) + { + var f = new ThingFilter(); + f.CopyAllowancesFrom(StorageSettings.EverStorableFixedSettings().filter); + if (ThingCategoryDefOf.Corpses != null) + f.SetAllow(ThingCategoryDefOf.Corpses, false); + f.RecalculateDisplayRootCategory(); + parentFilter = f; + } + return parentFilter; + } + } + + /// + /// A base the template goes on: every item of the parent filter, every special filter, full ranges. The + /// edit window's "game's default" for a forbid rule. + /// + public static StorageSettings BaseSettings() + { + var s = new StorageSettings(); + s.filter.SetAllowAll(ParentFilter); + s.filter.AllowedHitPointsPercents = FloatRange.ZeroToOne; + s.filter.AllowedQualityLevels = QualityRange.All; + s.Priority = StoragePriority.Normal; + return s; + } + + /// The ThingFilter a template stands for: the base with the template applied on top. + public static ThingFilter BuildFilter(StorageTemplate t) + { + StorageSettings s = BaseSettings(); + t?.ApplyTo(s, ParentFilter); + return s.filter; + } + + /// + /// What a rule's row says: "all items, hit points 50 to 100%, Normal or better", "allows 120 of 1,903 items, + /// refuses tainted apparel". Counts only names that resolve. + /// + public static string Summary(StorageTemplate t) + { + if (t == null) + return null; + ThingFilter f = BuildFilter(t); + List storable = StorageKinds.StorableDefs(ParentFilter).ToList(); + int allows = storable.Count(d => f.Allows(d)); + var parts = new List(); + if (allows == storable.Count) + parts.Add("BlaxDefaults_ForbidSummaryAll".Translate()); + else if (allows == 0) + parts.Add("BlaxDefaults_ForbidSummaryNone".Translate()); + else + parts.Add("BlaxDefaults_ForbidSummarySome".Translate(allows.ToString("N0", System.Globalization.CultureInfo.InvariantCulture), + storable.Count.ToString("N0", System.Globalization.CultureInfo.InvariantCulture))); + if (t.hitPoints != FloatRange.ZeroToOne) + parts.Add("BlaxDefaults_ForbidSummaryHitPoints".Translate(Percent(t.hitPoints.min), Percent(t.hitPoints.max))); + string quality = QualityText(t.quality); + if (quality != null) + parts.Add(quality); + List refusedSpecial = t.refusedSpecial + .Select(n => DefDatabase.GetNamedSilentFail(n)) + .Where(sf => sf != null && sf.configurable) + .Select(sf => sf.label) + .ToList(); + if (refusedSpecial.Count > 0) + parts.Add("BlaxDefaults_ForbidSummaryRefuses".Translate(string.Join(", ", refusedSpecial))); + return string.Join(", ", parts); + } + + private static string Percent(float f) => UnityEngine.Mathf.RoundToInt(f * 100f).ToString(System.Globalization.CultureInfo.InvariantCulture); + + /// "Normal or better", "up to Normal", "Normal to Excellent", or null for every quality. + public static string QualityText(QualityRange q) + { + if (q == QualityRange.All) + return null; + if (q.max == QualityCategory.Legendary) + return "BlaxDefaults_ForbidSummaryQualityMin".Translate(q.min.GetLabel().CapitalizeFirst()); + if (q.min == QualityCategory.Awful) + return "BlaxDefaults_ForbidSummaryQualityMax".Translate(q.max.GetLabel().CapitalizeFirst()); + if (q.min == q.max) + return "BlaxDefaults_ForbidSummaryQualityOnly".Translate(q.min.GetLabel().CapitalizeFirst()); + return "BlaxDefaults_ForbidSummaryQualityRange".Translate(q.min.GetLabel().CapitalizeFirst(), q.max.GetLabel().CapitalizeFirst()); + } + + /// The thing's forbidden flag, false for things that can't be forbidden. + public static bool IsForbiddenFlag(Thing t) => t is ThingWithComps twc && twc.GetComp() is CompForbiddable c && c.Forbidden; + } +} diff --git a/Source/BlaxDefaults/ForbidRulesSection.cs b/Source/BlaxDefaults/ForbidRulesSection.cs new file mode 100644 index 0000000..f32dcd7 --- /dev/null +++ b/Source/BlaxDefaults/ForbidRulesSection.cs @@ -0,0 +1,153 @@ +using System.Collections.Generic; +using RimWorld; +using UnityEngine; +using Verse; + +namespace BlaxDefaults +{ + /// + /// The "Forbid rules" section of the settings page. Work package "forbid" (design.md, 1.1). Order: the + /// category toggle (forbidRules); per rule its checkbox ("Gear your colony drops", "Gear enemies drop"), a row + /// saying what its filter allows with Edit and Forget (Forget asks first), "Where", the strip switch (disabled + /// until the rule has a filter) and "Use the suggested setup" (asks first); a line saying what neutral pawns drop keeps + /// the game's flags; the three corpse switches. Ticking a rule without a filter saves its suggested setup and + /// says so in a message. Works from the main menu: nothing here needs a running game. + /// + public static class ForbidRulesSection + { + private const float ButtonWidth = 90f; + private const float ButtonHeight = 28f; + private const float RowPad = 4f; + + /// The summary row per rule, cached by template reference (library entries are replaced, never edited). + private static readonly Dictionary summaries = + new Dictionary(); + + public static void Draw(Listing_Standard l) + { + BlaxDefaultsSettings s = BlaxDefaultsMod.Settings; + if (s == null) + return; + l.CheckboxLabeled("BlaxDefaults_ForbidToggle".Translate(), ref s.forbidRules, "BlaxDefaults_ForbidToggleTip".Translate()); + foreach (ForbidRule rule in ForbidRules.All) + DrawRule(l, rule); + using (new TextBlock(Color.gray)) + l.Label("BlaxDefaults_ForbidNeutral".Translate()); + + l.Gap(6f); + l.Label("BlaxDefaults_ForbidCorpsesHeader".Translate()); + l.CheckboxLabeled("BlaxDefaults_ForbidCorpsesAnimal".Translate(), ref s.animalCorpsesAllowed, "BlaxDefaults_ForbidCorpsesAnimalTip".Translate()); + l.CheckboxLabeled("BlaxDefaults_ForbidCorpsesEnemy".Translate(), ref s.enemyCorpsesAllowed, "BlaxDefaults_ForbidCorpsesEnemyTip".Translate()); + l.CheckboxLabeled("BlaxDefaults_ForbidCorpsesOther".Translate(), ref s.otherCorpsesAllowed, "BlaxDefaults_ForbidCorpsesOtherTip".Translate()); + } + + private static void DrawRule(Listing_Standard l, ForbidRule rule) + { + l.Gap(6f); + bool ticked = rule.Ticked; + bool was = ticked; + l.CheckboxLabeled(rule.Label, ref ticked, (rule.Group == ForbidGroup.Colony ? "BlaxDefaults_ForbidColonyRuleTip" : "BlaxDefaults_ForbidEnemyRuleTip").Translate()); + if (ticked != was) + Tick(rule, ticked); + + DrawFilterRow(l, rule); + + string where = rule.Anywhere ? "BlaxDefaults_ForbidWhereAnywhere".Translate() : "BlaxDefaults_ForbidWhereHome".Translate(); + if (l.ButtonTextLabeledPct("BlaxDefaults_ForbidWhere".Translate(), where, 0.6f, tooltip: "BlaxDefaults_ForbidWhereTip".Translate())) + { + Find.WindowStack.Add(new FloatMenu(new List + { + new FloatMenuOption("BlaxDefaults_ForbidWhereAnywhere".Translate(), () => rule.Anywhere = true), + new FloatMenuOption("BlaxDefaults_ForbidWhereHome".Translate(), () => rule.Anywhere = false), + })); + } + + bool strip = rule.StripTicked; + Rect stripRect = l.GetRect(Text.LineHeight); + bool hasFilter = rule.HasFilter; + Widgets.CheckboxLabeled(stripRect, "BlaxDefaults_ForbidStrip".Translate(), ref strip, disabled: !hasFilter); + TooltipHandler.TipRegion(stripRect, hasFilter ? "BlaxDefaults_ForbidStripTip".Translate() : "BlaxDefaults_ForbidStripNeedsFilter".Translate()); + if (hasFilter) + rule.StripTicked = strip; + l.Gap(2f); + + if (l.ButtonText("BlaxDefaults_ForbidUseSuggested".Translate(), widthPct: 0.6f)) + ConfirmSuggested(rule); + } + + /// The checkbox: ticking a rule without a filter saves the suggested setup and says so. + public static void Tick(ForbidRule rule, bool on) + { + if (rule.SetTicked(on)) + Messages.Message("BlaxDefaults_ForbidUsedSuggested".Translate(rule.Label, ForbidRules.Summary(rule.Template) ?? ""), MessageTypeDefOf.NeutralEvent, historical: false); + } + + private static void DrawFilterRow(Listing_Standard l, ForbidRule rule) + { + StorageTemplate t = rule.Template; + string text; + Color color = Color.white; + if (t != null) + { + text = Summary(rule, t); + } + else if (rule.Ticked && ForbidRules.On) + { + text = "BlaxDefaults_ForbidFilterMissing".Translate(); + color = ColorLibrary.RedReadable; + } + else + { + text = "BlaxDefaults_ForbidNoFilter".Translate(); + color = Color.gray; + } + + float textWidth = l.ColumnWidth - 2f * ButtonWidth - 3f * 6f; + float height = Mathf.Max(ButtonHeight + 2f * RowPad, Text.CalcHeight(text, textWidth) + 2f * RowPad); + Rect row = l.GetRect(height); + Widgets.DrawHighlightIfMouseover(row); + using (new TextBlock(color)) + Widgets.Label(new Rect(row.x + 6f, row.y + RowPad, textWidth, height - 2f * RowPad), text); + + float buttonY = row.y + (height - ButtonHeight) / 2f; + var forgetRect = new Rect(row.xMax - ButtonWidth, buttonY, ButtonWidth, ButtonHeight); + var editRect = new Rect(forgetRect.x - 6f - ButtonWidth, buttonY, ButtonWidth, ButtonHeight); + if (Widgets.ButtonText(editRect, "BlaxDefaults_PageEdit".Translate())) + OpenEditor(rule); + if (t != null && Widgets.ButtonText(forgetRect, "BlaxDefaults_PageForget".Translate())) + ConfirmForget(rule); + l.Gap(2f); + } + + private static string Summary(ForbidRule rule, StorageTemplate t) + { + if (summaries.TryGetValue(rule, out var cached) && ReferenceEquals(cached.template, t)) + return cached.summary; + string summary = ForbidRules.Summary(t); + summaries[rule] = (t, summary); + return summary; + } + + /// Edit: the storage editor on the saved filter, or on the suggested setup when there is none yet. + public static Dialog_EditStorageTemplate Editor(ForbidRule rule) => + new Dialog_EditStorageTemplate(StorageKinds.ForForbid(rule), (rule.Template ?? rule.Suggested()).CloneTemplate()); + + private static void OpenEditor(ForbidRule rule) => Find.WindowStack.Add(Editor(rule)); + + private static void ConfirmForget(ForbidRule rule) + { + Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation( + "BlaxDefaults_ForbidForgetConfirm".Translate(rule.Label), + rule.Forget, + destructive: true)); + } + + private static void ConfirmSuggested(ForbidRule rule) + { + Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation( + "BlaxDefaults_ForbidUseSuggestedConfirm".Translate(rule.Label, + (rule.Group == ForbidGroup.Colony ? "BlaxDefaults_ForbidSuggestedColony" : "BlaxDefaults_ForbidSuggestedEnemies").Translate()), + () => rule.UseSuggested())); + } + } +} diff --git a/Source/BlaxDefaults/OverlapWarnings.cs b/Source/BlaxDefaults/OverlapWarnings.cs index 3ce0c98..3db32e9 100644 --- a/Source/BlaxDefaults/OverlapWarnings.cs +++ b/Source/BlaxDefaults/OverlapWarnings.cs @@ -9,7 +9,7 @@ using Verse; namespace BlaxDefaults { - /// A mod that sets the same defaults: its package id, name and a keyed string naming what it sets. + /// A mod that does some of the same things: its package id, name and a keyed string naming what it does. public sealed class OverlapMod { public readonly string PackageId; @@ -29,12 +29,14 @@ namespace BlaxDefaults } /// - /// Names active mods that set the same defaults. Work package "setup" (design.md: "Overlap warnings"). + /// Names active mods that do some of the same things. Work package "setup" (design.md: "Overlap warnings"). /// Detection only, through Compat.IsActive; no patches against those mods. 1.0 detects for storage /// 1trickPwnyta's Defaults (defaults.1trickPwnyta), the unofficial Defaults 1.7 repack, Set my Defaults, /// [FSF] No Default Shelf Storage, [FSF] FrozenSnowFox Tweaks and Default Normal Empty Storage, and for the /// bill values Better Workbench Management, Default Ingredient Radius, Default Bill Ingredient Radius and - /// Default Until X. Dismissed ids live in BlaxDefaultsSettings.dismissedOverlaps, never in a save. + /// Default Until X. 1.1 adds, for the forbid rules, KilledEnemyAutoAllowed (Continued), Allow Everything and + /// Non uno Pinata, and for the corpse switches Allow Dead Animals. Dismissed ids live in + /// BlaxDefaultsSettings.dismissedOverlaps, never in a save. /// /// Package ids, each read from the mod's own About/About.xml in its public source repository, with its /// About/PublishedFileId.txt matching the Workshop item (checked 2026-11-29): @@ -47,11 +49,21 @@ namespace BlaxDefaults /// mod-structure/About/About.xml. /// - Default Ingredient Radius (2909706985): github.com/emipa606/DefaultIngredientRadius, branch main. /// - Default Bill Ingredient Radius (3789671048): github.com/benpbmith/DefaultBillIngredientRadius, branch main. + /// - KilledEnemyAutoAllowed (Continued) (2159090973): github.com/emipa606/KilledEnemyAutoAllowed, branch main + /// (read 2026-11-30). + /// - Allow Everything (2592726874): github.com/andrew-raphael-lukasik/rimworld-mod_allow-everything, branch + /// master (read 2026-11-30). + /// - Allow Dead Animals (2403873031): github.com/andrew-raphael-lukasik/rimworld-mod_allow-dead-animals, branch + /// master (read 2026-11-30). + /// - Non uno Pinata (1778821244): github.com/catgirlfighter/RimWorld_NonUnoPinata, branch master, the source its + /// Workshop page links (it has no PublishedFileId.txt; read 2026-11-30). /// Not listed yet, because no public About.xml could be read; add each once its id is read from the mod files: /// - the unofficial Defaults 1.7 repack (3836680679): its Workshop description says its packageId differs /// from the original's, without naming it (what: BlaxDefaults_OverlapWhatDefaults). /// - Default Normal Empty Storage (3779351608): no public source; Nexus mod 758 (BlaxDefaults_OverlapWhatEmptyStorage). /// - Default Until X (3554414830): no public source (BlaxDefaults_OverlapWhatRepeat). + /// Not listed at all: KilledEnemyAutoAllowed's 1.0 original (1858219355). It supports RimWorld 1.0 only, whose + /// About.xml had no packageId, and the id the game makes up for such a mod hashes its description. /// None of these mods is installed on the test machine, so detection is tested with a simulated id. /// public static class OverlapWarnings @@ -63,8 +75,12 @@ namespace BlaxDefaults public const string BetterWorkbenchManagement = "falconne.BWM"; public const string DefaultIngredientRadius = "Mlie.DefaultIngredientRadius"; public const string DefaultBillIngredientRadius = "pkthxbai.defaultbillingredientradius"; + public const string KilledEnemyAutoAllowed = "Mlie.KilledEnemyAutoAllowed"; + public const string AllowEverything = "AndrewRaphaelLukasik.AllowEverything"; + public const string NonUnoPinata = "avilmask.NonUnoPinata"; + public const string AllowDeadAnimals = "AndrewRaphaelLukasik.AllowDeadAnimals"; - /// Every overlapping mod Defaults knows, in the order the page lists them: storage, then bills. + /// Every overlapping mod Defaults knows, in the order the page lists them: storage, bills, forbid rules. public static readonly OverlapMod[] Mods = { new OverlapMod(Defaults1trickPwnyta, "1trickPwnyta's Defaults", "BlaxDefaults_OverlapWhatDefaults"), @@ -74,6 +90,10 @@ namespace BlaxDefaults new OverlapMod(BetterWorkbenchManagement, "Better Workbench Management", "BlaxDefaults_OverlapWhatStoreMode"), new OverlapMod(DefaultIngredientRadius, "Default Ingredient Radius", "BlaxDefaults_OverlapWhatRadius"), new OverlapMod(DefaultBillIngredientRadius, "Default Bill Ingredient Radius", "BlaxDefaults_OverlapWhatRadius"), + new OverlapMod(KilledEnemyAutoAllowed, "KilledEnemyAutoAllowed (Continued)", "BlaxDefaults_OverlapWhatForbid"), + new OverlapMod(AllowEverything, "Allow Everything", "BlaxDefaults_OverlapWhatAllowEverything"), + new OverlapMod(NonUnoPinata, "Non uno Pinata", "BlaxDefaults_OverlapWhatPinata"), + new OverlapMod(AllowDeadAnimals, "Allow Dead Animals", "BlaxDefaults_OverlapWhatDeadAnimals"), }; /// Package ids treated as active on top of the real mod list. For tests only. @@ -198,8 +218,8 @@ namespace BlaxDefaults } /// - /// The window on the first game loaded in a session: which active mods set the same defaults, each with - /// what it sets and "Don't remind me". Work package "setup". + /// The window on the first game loaded in a session: which active mods do some of the same things, each with + /// what it does and "Don't remind me". Work package "setup". /// public class Dialog_OverlapWarnings : Window { diff --git a/Source/BlaxDefaults/SettingsPage.cs b/Source/BlaxDefaults/SettingsPage.cs index f9b413e..6c32e17 100644 --- a/Source/BlaxDefaults/SettingsPage.cs +++ b/Source/BlaxDefaults/SettingsPage.cs @@ -17,7 +17,8 @@ namespace BlaxDefaults /// from inactive mods); the red BrokenFilesLine when the startup load found broken files; then one section /// per category, each with its toggle: Stockpiles (stockpileDefaults, one row per stockpile entry), /// Storage buildings (storageDefaults, one row per storage entry, then QuickSetup.DrawButton), Every new - /// bill (billDefaults, then BillValuesSection.Draw); last OverlapWarnings.DrawSettings. Each storage row + /// bill (billDefaults, then BillValuesSection.Draw), Forbid rules (ForbidRulesSection.Draw, 1.1: the + /// forbid:colony and forbid:enemies rows live there); last OverlapWarnings.DrawSettings. Each storage row /// shows RowSummary with Edit (Dialog_EditStorageTemplate) and Forget (asks first). A row whose kind /// needs a DLC that is off is drawn disabled with DisabledReason; a row whose kind is not loaded for /// another reason (a removed mod) shows its inactive names and can't be edited. It all works from the @@ -105,6 +106,10 @@ namespace BlaxDefaults l.CheckboxLabeled("BlaxDefaults_PageBillsToggle".Translate(), ref s.billDefaults, "BlaxDefaults_PageBillsToggleTip".Translate()); Guarded("BillValuesSection.Draw", () => BillValuesSection.Draw(l)); + // Forbid rules + SectionHeader(l, "BlaxDefaults_ForbidSection".Translate()); + Guarded("ForbidRulesSection.Draw", () => ForbidRulesSection.Draw(l)); + l.GapLine(); Guarded("OverlapWarnings.DrawSettings", () => OverlapWarnings.DrawSettings(l)); } @@ -273,6 +278,9 @@ namespace BlaxDefaults return null; if (entry.key == DefaultsKeys.EveryBill) return "BlaxDefaults_PageSectionBills".Translate(); + ForbidRule rule = ForbidRules.ForKey(entry.key); + if (rule != null) + return rule.Label; StorageKind kind = StorageKinds.ForKey(entry.key); string label = kind?.Label; return label.NullOrEmpty() ? DefaultsKeys.NameOf(entry.key) : label.CapitalizeFirst(); diff --git a/Source/BlaxDefaults/StorageKinds.cs b/Source/BlaxDefaults/StorageKinds.cs index 9a881b7..e3f1e76 100644 --- a/Source/BlaxDefaults/StorageKinds.cs +++ b/Source/BlaxDefaults/StorageKinds.cs @@ -55,8 +55,9 @@ namespace BlaxDefaults } /// - /// One kind that has its own storage default: a stockpile type or a storage building def. Knows its - /// key, label, parent filter and the game's default, and loads a default onto settings. + /// One kind that has its own storage default: a stockpile type, a storage building def, or (1.1) a forbid + /// rule, whose filter is a template too. Knows its key, label, parent filter and the game's default, and + /// loads a default onto settings. /// public sealed class StorageKind { @@ -65,6 +66,8 @@ namespace BlaxDefaults public readonly ThingDef Def; /// The stockpile type, or null for a building. public readonly StockpileType Stockpile; + /// The forbid rule whose filter this is, or null for storage. + public readonly ForbidRule Forbid; public StorageKind(ThingDef def) { @@ -78,10 +81,19 @@ namespace BlaxDefaults Key = stockpile.Key; } + public StorageKind(ForbidRule rule) + { + Forbid = rule; + Key = rule.Key; + } + public bool IsStockpile => Stockpile != null; - /// "shelf", "stockpile". - public string Label => Def != null ? Def.label : Stockpile.Label; + /// A forbid rule's filter: no priority, the unlisted rule is Refuse or Allow. + public bool IsForbid => Forbid != null; + + /// "shelf", "stockpile", "gear enemies drop". + public string Label => Def != null ? Def.label : Forbid != null ? Forbid.Label : Stockpile.Label; /// /// "shelves", "stockpiles". A key BlaxDefaults_Plural_<defName> in the active language wins over @@ -91,6 +103,8 @@ namespace BlaxDefaults { get { + if (Forbid != null) + return Forbid.Label; if (Def == null) return Stockpile.LabelPlural; string key = "BlaxDefaults_Plural_" + Def.defName; @@ -99,13 +113,15 @@ namespace BlaxDefaults } /// What settings of this kind may ever allow: the building's fixedStorageSettings, else every storable item. - public ThingFilter ParentFilter => Def != null ? StorageKinds.ParentFilterFor(Def) : StorageKinds.StockpileParentFilter; + public ThingFilter ParentFilter => + Def != null ? StorageKinds.ParentFilterFor(Def) : Forbid != null ? ForbidRules.ParentFilter : StorageKinds.StockpileParentFilter; /// The saved default, or null. public StorageTemplate Saved => DefaultsLibrary.Get(Key); /// A fresh scratch StorageSettings holding the game's default for this kind. - public StorageSettings GameDefault() => Def != null ? StorageKinds.GameDefaultFor(Def) : StorageKinds.GameDefaultFor(Stockpile); + public StorageSettings GameDefault() => + Def != null ? StorageKinds.GameDefaultFor(Def) : Forbid != null ? ForbidRules.BaseSettings() : StorageKinds.GameDefaultFor(Stockpile); /// Replaces the target's priority, filter, special filters and ranges with the game's default. public void LoadGameDefault(StorageSettings target) => target.CopyFrom(GameDefault()); @@ -261,6 +277,8 @@ namespace BlaxDefaults public static StorageKind ForStockpile(StockpileType type) => type == null ? null : new StorageKind(type); + public static StorageKind ForForbid(ForbidRule rule) => rule == null ? null : new StorageKind(rule); + /// The kind for a library key, or null when its def or designator is not loaded. public static StorageKind ForKey(string key) { @@ -268,6 +286,8 @@ namespace BlaxDefaults return ForDef(DefDatabase.GetNamedSilentFail(DefaultsKeys.NameOf(key))); if (DefaultsKeys.IsStockpile(key)) return ForStockpile(StockpileTypeForKey(key)); + if (DefaultsKeys.IsForbid(key)) + return ForForbid(ForbidRules.ForKey(key)); return null; } diff --git a/Tests/BlaxDefaultsTests/Source/Fixtures.cs b/Tests/BlaxDefaultsTests/Source/Fixtures.cs index 6f779e9..24f14aa 100644 --- a/Tests/BlaxDefaultsTests/Source/Fixtures.cs +++ b/Tests/BlaxDefaultsTests/Source/Fixtures.cs @@ -1,15 +1,17 @@ +using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using BlaxDefaults; using RimWorld; +using RimWorld.Planet; using Verse; namespace BlaxDefaultsTests { /// - /// Shared helpers for tests. Things, zones and areas made here are removed after each test unless passed - /// to Keep() or KeepZone(). Mod settings and the defaults library are restored after each test (the + /// Shared helpers for tests. Things, pawns, zones and areas made here are removed after each test unless + /// passed to Keep() or KeepZone(). Mod settings and the defaults library are restored after each test (the /// library in memory only, the file is not rewritten), so tests may change them freely. Feature-specific /// helpers belong in the feature's own test file. /// @@ -20,6 +22,8 @@ namespace BlaxDefaultsTests private static readonly List madeZones = new List(); private static readonly HashSet keptZones = new HashSet(); private static readonly List areas = new List(); + private static readonly List madePawns = new List(); + private static readonly List afterTest = new List(); private static List librarySnapshot; private static bool keepLibrary; @@ -79,13 +83,17 @@ namespace BlaxDefaultsTests /// /// A free area of this size near the map centre: in bounds, away from the edge, unfogged, standable, - /// heavy-supporting terrain, no zone, nothing but grass or filth, which is removed. Tracked: buildings, - /// blueprints, frames, items and zones in it are removed after the test (kept ones stay). + /// inside a district (pawns spawned there can walk and work as in vanilla; the map centre can be rock), heavy-supporting + /// terrain, no zone, nothing but grass or filth, which is removed. Searches 40 cells around the centre, + /// then the whole map by distance. Tracked: buildings, blueprints, frames, items and zones in it are + /// removed after the test (kept ones stay). /// public static CellRect EmptyArea(int width, int height) { Map map = Map; - foreach (IntVec3 origin in GenRadial.RadialCellsAround(map.Center, 40f, useCenter: true)) + IEnumerable near = GenRadial.RadialCellsAround(map.Center, 40f, useCenter: true); + IEnumerable rest = map.AllCells.OrderBy(c => (c - map.Center).LengthHorizontalSquared); + foreach (IntVec3 origin in near.Concat(rest)) { var rect = new CellRect(origin.x, origin.z, width, height); if (rect.Cells.All(c => Free(c, map))) @@ -97,12 +105,12 @@ namespace BlaxDefaultsTests return rect; } } - T.Fail("no empty " + width + "x" + height + " area near the map centre"); + T.Fail("no empty " + width + "x" + height + " area on the map"); return default; } private static bool Free(IntVec3 c, Map map) => - c.InBounds(map) && !c.CloseToEdge(map, 5) && !c.Fogged(map) && c.Standable(map) + c.InBounds(map) && !c.CloseToEdge(map, 5) && !c.Fogged(map) && c.Standable(map) && c.GetDistrict(map) != null && c.SupportsStructureType(map, TerrainAffordanceDefOf.Heavy) && c.GetZone(map) == null && map.thingGrid.ThingsListAt(c).All(t => (t is Plant plant && !plant.def.plant.IsTree) || t is Filth) && !areas.Any(r => r.Contains(c)); @@ -133,6 +141,31 @@ namespace BlaxDefaultsTests return zone; } + /// Destroys the pawn (or its corpse) after the test unless kept. + public static Pawn TrackPawn(Pawn p) + { + if (p != null) madePawns.Add(p); + return p; + } + + /// Runs after the test, last added first, before the things and zones are removed (restore a value the test changed). + public static void AfterTest(Action undo) + { + if (undo != null) afterTest.Add(undo); + } + + /// A visible, non-player, humanlike faction that is not hostile to the player, or null. + 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, or null. + 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(); + /// A spawned free colonist of the quick-test colony, to complete frames with. public static Pawn Worker() { @@ -201,6 +234,27 @@ namespace BlaxDefaultsTests public static void Cleanup() { + for (int i = afterTest.Count - 1; i >= 0; i--) + { + try { afterTest[i](); } + catch (Exception e) { T.Info("after-test step threw: " + e.Message); } + } + afterTest.Clear(); + + foreach (Pawn p in madePawns) + { + if (p == null || kept.Contains(p)) continue; + if (p.Corpse != null && !kept.Contains(p.Corpse) && !p.Corpse.Destroyed) + p.Corpse.Destroy(DestroyMode.Vanish); + else if (p.Spawned) + p.Destroy(DestroyMode.Vanish); + else if (!p.Destroyed && p.ParentHolder is Pawn_CarryTracker carrier) + carrier.innerContainer.Remove(p); + if (!p.Destroyed && !p.Spawned && p.IsWorldPawn()) + Find.WorldPawns.RemoveAndDiscardPawnViaGC(p); + } + madePawns.Clear(); + foreach (Thing t in made) { if (t != null && !kept.Contains(t) && !t.Destroyed && t.Spawned) diff --git a/Tests/BlaxDefaultsTests/Source/ForbidTests.cs b/Tests/BlaxDefaultsTests/Source/ForbidTests.cs new file mode 100644 index 0000000..5c03580 --- /dev/null +++ b/Tests/BlaxDefaultsTests/Source/ForbidTests.cs @@ -0,0 +1,1263 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using BlaxDefaults; +using HarmonyLib; +using RimWorld; +using RimWorld.Planet; +using UnityEngine; +using Verse; +using Verse.AI; +using Verse.AI.Group; + +namespace BlaxDefaultsTests +{ + /// + /// Work package "forbid". The tests of design.md, 1.1: Gear rules for your colony and for enemies; Wait until + /// the fight is over; Stripping forbids what doesn't match; Corpses outside the home area stay allowed. + /// No hostile pawn stands on the test map unless a test says so (Begin checks). Pawns are downed with an + /// anesthetic (HealthUtility.TryAnesthetize), which goes through Pawn_HealthTracker.MakeDowned without the + /// death roll, and killed with Pawn.Kill. Every test area is 9x9 with the pawn in its centre, and its cells are + /// set inside or outside the home area (restored after the test), so every drop lands on the side the test names. + /// + public static class ForbidTests + { + private const string KeptAllowedKey = "forbid.keptAllowed"; + private const string KeptForbiddenKey = "forbid.keptForbidden"; + private const string WaitingRifleKey = "forbid.waitingRifle"; + private const string WaitingThreatKey = "forbid.waitingThreat"; + + private static Map Map => Fixtures.Map; + + // ---- setup helpers --------------------------------------------------------------- + + /// Clears the wait list before and after the test and checks the map has no active threat. + private static void Begin() + { + ForbidWaitList.Clear(); + Fixtures.AfterTest(ForbidWaitList.Clear); + if (GenHostility.AnyHostileActiveThreatTo(Map, Faction.OfPlayer, out IAttackTarget threat)) + T.Fail("setup: a hostile threat is on the test map: " + threat?.Thing); + } + + /// A 9x9 area, inside or outside the home area. + private static CellRect Area(bool home) + { + CellRect r = Fixtures.EmptyArea(9, 9); + SetHome(r, home); + return r; + } + + private static void SetHome(CellRect r, bool home) + { + Area_Home area = Map.areaManager.Home; + var old = r.Cells.Select(c => (c, area[c])).ToList(); + foreach (IntVec3 c in r.Cells) + area[c] = home; + Fixtures.AfterTest(() => + { + foreach (var (c, v) in old) + area[c] = v; + }); + } + + private static Pawn Generate(PawnKindDef kind, Faction faction) + { + var req = new PawnGenerationRequest(kind, faction, PawnGenerationContext.NonPlayer, + forceGenerateNewPawn: true, canGeneratePawnRelations: false, + colonistRelationChanceFactor: 0f, developmentalStages: DevelopmentalStage.Adult); + Pawn p = Fixtures.TrackPawn(PawnGenerator.GeneratePawn(req)); + p.equipment?.DestroyAllEquipment(); + p.inventory?.DestroyAll(); + return p; + } + + private static Pawn Spawn(Pawn p, IntVec3 at) + { + GenSpawn.Spawn(p, at, Map); + if (p.needs?.food != null) p.needs.food.CurLevel = p.needs.food.MaxLevel; + if (p.needs?.rest != null) p.needs.rest.CurLevel = 1f; + if (p.needs?.joy != null) p.needs.joy.CurLevel = 1f; + return p; + } + + private static Pawn Colonist(IntVec3 at, bool canFight = false) + { + for (int i = 0; ; i++) + { + Pawn p = Generate(PawnKindDefOf.Colonist, Faction.OfPlayer); + if (!canFight || !p.WorkTagIsDisabled(WorkTags.Violent) || i >= 20) + { + if (canFight && p.WorkTagIsDisabled(WorkTags.Violent)) + T.Fail("setup: 20 generated colonists were all incapable of violence"); + return Spawn(p, at); + } + p.Destroy(DestroyMode.Vanish); + } + } + + private static Faction Hostile() + { + Faction f = Fixtures.HostileFaction(); + if (f == null) + T.Skip("setup: no hostile humanlike faction in this world"); + return f; + } + + private static Faction Friendly() + { + Faction f = Fixtures.FriendlyFaction(); + if (f == null) + T.Skip("setup: no friendly humanlike faction in this world"); + return f; + } + + private static PawnKindDef MemberKind(Faction f) => f.def.basicMemberKind ?? PawnKindDefOf.Villager; + + /// A spawned raider of a hostile faction, without weapon or inventory: an active threat until downed or killed. + private static Pawn Raider(IntVec3 at) + { + Faction f = Hostile(); + return Spawn(Generate(MemberKind(f), f), at); + } + + private static ThingWithComps Weapon(string defName, QualityCategory quality, float hitPoints) + { + ThingDef def = Fixtures.Thing(defName); + var t = (ThingWithComps)ThingMaker.MakeThing(def, def.MadeFromStuff ? GenStuff.DefaultStuffFor(def) : null); + t.TryGetComp()?.SetQuality(quality, ArtGenerationContext.Outsider); + t.HitPoints = Mathf.RoundToInt(t.MaxHitPoints * hitPoints); + return Fixtures.Track(t); + } + + private static Apparel Wear(Pawn p, string defName, QualityCategory quality, float hitPoints) + { + var a = (Apparel)Weapon(defName, quality, hitPoints); + p.apparel.Wear(a, dropReplacedApparel: false); + T.Check(p.apparel.WornApparel.Contains(a), "setup: " + p + " is not wearing " + a); + return a; + } + + private static Thing Stack(string defName, int count) + { + Thing t = ThingMaker.MakeThing(Fixtures.Thing(defName)); + t.stackCount = count; + return Fixtures.Track(t); + } + + private static Thing Give(Pawn p, string defName, int count) + { + Thing t = Stack(defName, count); + T.Check(p.inventory.innerContainer.TryAdd(t), "setup: could not put " + defName + " into " + p + "'s inventory"); + return t; + } + + private static ThingWithComps Arm(Pawn p, string defName, QualityCategory quality, float hitPoints) + { + ThingWithComps w = Weapon(defName, quality, hitPoints); + p.equipment.AddEquipment(w); + return w; + } + + private static void Down(Pawn p) + { + T.Check(HealthUtility.TryAnesthetize(p), "setup: " + p + " can't be anesthetized"); + T.Check(p.Downed, "setup: " + p + " did not go down"); + } + + private static bool Forbidden(Thing t) => t.TryGetComp()?.Forbidden ?? false; + + private const string Hospitality = "Orion.Hospitality"; + + /// + /// Hospitality's MakeDowned transpiler calls DropAndForbidEverything without rememberPrimary (its + /// Source/Patches/Pawn_HealthTracker_MakeDowned_Patch.cs), so with it a downed pawn never remembers its + /// weapon, and its "disable friendly gear drops" option keeps a downed visitor's things on it. Skips the + /// rest of a test about the remembered weapon when that happened. + /// + private static void NeedRememberedWeapon(Pawn p, Thing weapon) + { + if (p.mindState.droppedWeapon == weapon) + return; + if (Compat.IsActive(Hospitality)) + T.Skip("Hospitality drops a downed pawn's weapon without remembering it, so there is no remembered weapon to wait for"); + T.Fail("the weapon is not the downed pawn's droppedWeapon"); + } + + private static void ColonyRule(bool anywhere = true) + { + ForbidRules.Colony.UseSuggested(); + ForbidRules.Colony.Ticked = true; + ForbidRules.Colony.Anywhere = anywhere; + } + + private static void EnemyRule(bool anywhere = true) + { + ForbidRules.Enemies.UseSuggested(); + ForbidRules.Enemies.Ticked = true; + ForbidRules.Enemies.Anywhere = anywhere; + } + + /// Saves a filter for the rule: every item but these defs, full ranges, unlisted allowed. + private static void FilterRefusing(ForbidRule rule, params string[] refused) + { + StorageKind kind = StorageKinds.ForForbid(rule); + StorageSettings s = kind.GameDefault(); + foreach (string name in refused) + s.filter.SetAllow(Fixtures.Thing(name), false); + StorageTemplate t = kind.Capture(s); + t.unlisted = UnlistedRule.Allow; + Fixtures.Save(t); + } + + /// A raider killed in the area's centre with the enemy rule's usual kit. + private sealed class RaiderKit + { + public Pawn Raider; + public ThingWithComps Good; // Normal at 80%: allowed by the suggested setup + public ThingWithComps Poor; // Poor at 80% + public ThingWithComps Damaged; // Normal at 40% + public Thing GoJuice; + public Thing Medicine; + } + + private static RaiderKit KitRaider(IntVec3 at) + { + var k = new RaiderKit { Raider = Raider(at) }; + k.Good = Arm(k.Raider, "Gun_AssaultRifle", QualityCategory.Normal, 0.8f); + k.Poor = Weapon("Gun_AssaultRifle", QualityCategory.Poor, 0.8f); + k.Damaged = Weapon("Gun_AssaultRifle", QualityCategory.Normal, 0.4f); + T.Check(k.Raider.inventory.innerContainer.TryAdd(k.Poor) && k.Raider.inventory.innerContainer.TryAdd(k.Damaged), "setup: rifles into the inventory"); + k.GoJuice = Give(k.Raider, "GoJuice", 2); + k.Medicine = Give(k.Raider, "MedicineIndustrial", 3); + return k; + } + + /// A spawned hostile pawn that stands on the map as an active threat until Down() takes it out. + private static Pawn Threat(CellRect area) + { + Pawn p = Raider(area.Corners.First()); + T.Check(GenHostility.AnyHostileActiveThreatToPlayer(Map), "setup: the hostile test pawn is not an active threat"); + return p; + } + + // ---- the rules on the settings page ---------------------------------------------- + + [BlaxTest("forbid rules: everything ships off, and the parent filter has no corpses")] + public static void ShipsOff() + { + var fresh = new BlaxDefaultsSettings(); + T.Check(fresh.forbidRules, "forbidRules is off in fresh settings"); + T.Check(!fresh.colonyGearRule && !fresh.enemyGearRule && !fresh.colonyStripRule && !fresh.enemyStripRule, "a gear rule or strip switch is on in fresh settings"); + T.Check(!fresh.animalCorpsesAllowed && !fresh.enemyCorpsesAllowed && !fresh.otherCorpsesAllowed, "a corpse switch is on in fresh settings"); + T.Check(fresh.colonyGearAnywhere && fresh.enemyGearAnywhere, "\"Where\" does not default to anywhere"); + ThingFilter parent = ForbidRules.ParentFilter; + T.Check(!parent.Allows(ThingDefOf.Human.race.corpseDef), "the forbid parent filter allows human corpses"); + T.Check(parent.Allows(Fixtures.Thing("Gun_AssaultRifle")) && parent.Allows(ThingDefOf.MedicineIndustrial) && parent.Allows(ThingDefOf.Silver), + "the forbid parent filter refuses a rifle, medicine or silver"); + T.Equal(DefaultsKeys.ForbidColony, ForbidRules.Colony.Key, "colony key"); + T.Equal(DefaultsKeys.ForbidEnemies, ForbidRules.Enemies.Key, "enemy key"); + } + + private static readonly string[] Keys = + { + "BlaxDefaults_ForbidColonyRule", "BlaxDefaults_ForbidColonyRuleTip", "BlaxDefaults_ForbidCorpsesAnimal", "BlaxDefaults_ForbidCorpsesAnimalTip", "BlaxDefaults_ForbidCorpsesEnemy", "BlaxDefaults_ForbidCorpsesEnemyTip", "BlaxDefaults_ForbidCorpsesHeader", "BlaxDefaults_ForbidCorpsesOther", "BlaxDefaults_ForbidCorpsesOtherTip", "BlaxDefaults_ForbidEditTitle", "BlaxDefaults_ForbidEnemyRule", "BlaxDefaults_ForbidEnemyRuleTip", "BlaxDefaults_ForbidFilterMissing", "BlaxDefaults_ForbidForgetConfirm", "BlaxDefaults_ForbidNeutral", "BlaxDefaults_ForbidNoFilter", "BlaxDefaults_ForbidSection", "BlaxDefaults_ForbidStrip", "BlaxDefaults_ForbidStripNeedsFilter", "BlaxDefaults_ForbidStripTip", "BlaxDefaults_ForbidSuggestedColony", "BlaxDefaults_ForbidSuggestedEnemies", "BlaxDefaults_ForbidSummaryAll", "BlaxDefaults_ForbidSummaryHitPoints", "BlaxDefaults_ForbidSummaryNone", "BlaxDefaults_ForbidSummaryQualityMax", "BlaxDefaults_ForbidSummaryQualityMin", "BlaxDefaults_ForbidSummaryQualityOnly", "BlaxDefaults_ForbidSummaryQualityRange", "BlaxDefaults_ForbidSummaryRefuses", "BlaxDefaults_ForbidSummarySome", "BlaxDefaults_ForbidToggle", "BlaxDefaults_ForbidToggleTip", "BlaxDefaults_ForbidUnlistedTip", "BlaxDefaults_ForbidUseSuggested", "BlaxDefaults_ForbidUseSuggestedConfirm", "BlaxDefaults_ForbidUsedSuggested", "BlaxDefaults_ForbidWhere", "BlaxDefaults_ForbidWhereAnywhere", "BlaxDefaults_ForbidWhereHome", "BlaxDefaults_ForbidWhereTip", "BlaxDefaults_OverlapWhatForbid", "BlaxDefaults_OverlapWhatAllowEverything", "BlaxDefaults_OverlapWhatPinata", "BlaxDefaults_OverlapWhatDeadAnimals", + }; + + [BlaxTest("forbid rules: every string of the forbid rules section, its edit window and its overlap line is in Keyed")] + public static void Strings() + { + var missing = Keys.Where(k => !k.CanTranslate()).ToList(); + T.Check(missing.Count == 0, "strings missing from Keyed: " + string.Join(", ", missing)); + } + [BlaxTest("forbid rules: ticking a rule without a filter saves its suggested setup and turns it on")] + public static void TickWithoutFilter() + { + DefaultsLibrary.Forget(DefaultsKeys.ForbidColony); + DefaultsLibrary.Forget(DefaultsKeys.ForbidEnemies); + ForbidRule enemies = ForbidRules.Enemies; + enemies.Anywhere = false; + T.Check(!enemies.HasFilter && !enemies.Active, "setup: the enemy rule has a filter or acts"); + T.Check(enemies.SetTicked(true), "SetTicked(true) without a filter did not report the suggested setup"); + T.Check(enemies.Ticked && enemies.HasFilter && enemies.Active, "the enemy rule is not on with a filter after ticking"); + T.Check(enemies.Template.SameSettingsAs(enemies.Suggested()), "the saved enemy filter is not the suggested setup"); + T.Check(enemies.StripTicked, "the suggested enemy setup did not turn stripping on"); + T.Check(enemies.Anywhere, "the suggested setup did not set \"Where\" to anywhere"); + T.Check(!enemies.SetTicked(true), "ticking a rule that has a filter reported the suggested setup again"); + + ForbidRule colony = ForbidRules.Colony; + T.Check(colony.SetTicked(true), "SetTicked(true) on the colony rule did not report the suggested setup"); + T.Check(colony.Active && !colony.StripTicked, "the colony rule is off, or its stripping is on, after ticking"); + T.Check(colony.Template.SameSettingsAs(colony.Suggested()), "the saved colony filter is not the suggested setup"); + + T.Check(!colony.SetTicked(false) && !colony.Ticked && colony.HasFilter, "unticking changed the filter or did not untick"); + } + + [BlaxTest("forbid rules: Forget on a saved enemy filter turns the rule and its strip switch off")] + public static void ForgetTurnsOff() + { + EnemyRule(); + T.Check(Fixtures.Settings.enemyGearRule && Fixtures.Settings.enemyStripRule, "setup: rule or strip switch off"); + ForbidRules.Enemies.Forget(); + T.Check(!DefaultsLibrary.Has(DefaultsKeys.ForbidEnemies), "the enemy filter is still saved"); + T.Check(!Fixtures.Settings.enemyGearRule, "enemyGearRule is still on after Forget"); + T.Check(!Fixtures.Settings.enemyStripRule, "enemyStripRule is still on after Forget"); + } + + [BlaxTest("forbid rules: a rule ticked in mod settings with an empty library acts as off and logs nothing")] + public static void TickedWithoutFilter() + { + Begin(); + DefaultsLibrary.Forget(DefaultsKeys.ForbidEnemies); + Fixtures.Settings.enemyGearRule = true; + Fixtures.Settings.enemyStripRule = true; + T.Check(!ForbidRules.Enemies.Active && !ForbidRules.Enemies.StripActive, "the enemy rule acts without a filter"); + CellRect r = Area(home: false); + RaiderKit k = KitRaider(r.CenterCell); + k.Raider.Kill(null); + T.Check(Forbidden(k.Good) && Forbidden(k.Medicine), "a raider's drops were allowed by a rule without a filter"); + T.Check(T.ErrorsSoFar().Count == 0, "errors were logged: " + string.Join(" | ", T.ErrorsSoFar().Take(3))); + } + + [BlaxTest("forbid rules: with forbidRules or the master switch off, gear, corpses and stripping keep the game's flags")] + public static void SwitchesOff() + { + Begin(); + EnemyRule(); + Fixtures.Settings.enemyCorpsesAllowed = true; + T.Check(ForbidRules.Enemies.Active && ForbidRules.Enemies.StripActive, "setup: the enemy rule or its strip switch is off"); + + Fixtures.Settings.forbidRules = false; + T.Check(!BlaxDefaultsMod.ForbidOn, "ForbidOn with forbidRules off"); + KillAndStrip("forbidRules off", acts: false); + + // The master switch turns the forbid rules off too (BlaxDefaultsMod.ForbidOn, the PageEnabled tooltip). + Fixtures.Settings.forbidRules = true; + Fixtures.Settings.enabled = false; + T.Check(!BlaxDefaultsMod.ForbidOn, "ForbidOn with the master switch off"); + KillAndStrip("the master switch off", acts: false); + + Fixtures.Settings.enabled = true; + KillAndStrip("both on again", acts: true); + } + + /// A raider with a Normal rifle at 80% and a Poor tuque, killed outside the home area, its corpse stripped. + private static void KillAndStrip(string when, bool acts) + { + CellRect r = Area(home: false); + Pawn raider = Raider(r.CenterCell); + raider.apparel.DestroyAll(); + Apparel tuque = Wear(raider, "Apparel_Tuque", QualityCategory.Poor, 0.9f); + ThingWithComps rifle = Arm(raider, "Gun_AssaultRifle", QualityCategory.Normal, 0.8f); + Corpse corpse = KillKeepingHitPoints(raider, tuque); + T.Check(rifle.Spawned, "setup: the rifle is not on the ground with " + when); + T.Equal(!acts, Forbidden(rifle), "the Normal rifle at 80% forbidden with " + when); + T.Equal(!acts, Forbidden(corpse), "the raider's corpse forbidden with " + when); + corpse.Strip(); + T.Check(tuque.Spawned, "setup: the tuque is not on the ground with " + when); + T.Equal(acts, Forbidden(tuque), "the stripped Poor tuque forbidden with " + when); + } + + [BlaxTest("forbid rules: the row says what the suggested filters allow")] + public static void RowSummary() + { + T.Equal("all items, hit points 50 to 100%, Normal or better", ForbidRules.Summary(ForbidRules.Enemies.Suggested()), "enemy row"); + T.Equal("all items", ForbidRules.Summary(ForbidRules.Colony.Suggested()), "colony row"); + } + + [BlaxTest("forbid rules: the edit window saves a forbid filter with no priority and unlisted Refuse or Allow")] + public static void EditWindow() + { + EnemyRule(); + Dialog_EditStorageTemplate dialog = ForbidRulesSection.Editor(ForbidRules.Enemies); + T.Check(dialog.Kind.IsForbid, "the window's kind is not a forbid rule"); + T.Equal(UnlistedRule.Allow, dialog.Unlisted, "unlisted rule of the suggested setup in the window"); + T.Check(dialog.Scratch.filter.AllowedQualityLevels == new QualityRange(QualityCategory.Normal, QualityCategory.Legendary), + "the window's filter lost the quality range"); + ThingDef rifle = Fixtures.Thing("Gun_AssaultRifle"); + dialog.Scratch.filter.SetAllow(rifle, false); + StorageTemplate t = dialog.BuildTemplate(); + T.Equal(DefaultsKeys.ForbidEnemies, t.key, "key of the saved filter"); + T.Check(t.refused.Contains(rifle.defName), "the saved filter does not refuse the rifle"); + T.Check(!t.allowed.Concat(t.refused).Any(n => DefDatabase.GetNamedSilentFail(n)?.IsCorpse ?? false), "the saved filter names a corpse"); + Fixtures.Save(t); + ThingWithComps gun = Weapon("Gun_AssaultRifle", QualityCategory.Legendary, 1f); + T.Check(!ForbidRules.Enemies.Allows(gun), "the rule still allows the rifle after the edit"); + T.Check(ForbidRules.Enemies.Allows(Stack("MedicineIndustrial", 1)), "the rule refuses medicine after the edit"); + } + + // ---- gear rules: your colony ----------------------------------------------------- + + [BlaxTest("forbid gear: a downed colonist's meal and medicine are allowed, its rifle waits until it dies")] + public static void ColonistDowned() + { + Begin(); + ColonyRule(); + CellRect r = Area(home: false); + Pawn c = Colonist(r.CenterCell); + ThingWithComps rifle = Arm(c, "Gun_AssaultRifle", QualityCategory.Normal, 1f); + Thing meal = Give(c, "MealSurvivalPack", 1); + Thing herbal = Give(c, "MedicineHerbal", 2); + Down(c); + T.Check(meal.Spawned && herbal.Spawned && rifle.Spawned, "setup: the drops are not on the ground"); + T.Check(!Forbidden(meal), "the survival meal is forbidden"); + T.Check(!Forbidden(herbal), "the herbal medicine is forbidden"); + if (c.mindState.droppedWeapon != rifle && Compat.IsActive(Hospitality)) + { + // Nothing remembers the rifle, so the colonist never comes back for it: the rule decides at once. + T.Check(!Forbidden(rifle) && !ForbidWaitList.Contains(rifle), "with Hospitality the rifle nobody remembers is still forbidden or waiting"); + T.Info("Hospitality: the downed colonist does not remember its rifle, so the rule allowed it at once"); + return; + } + T.Check(Forbidden(rifle), "the rifle was allowed at once"); + T.Check(c.mindState.droppedWeapon == rifle, "the rifle is not the colonist's droppedWeapon"); + T.Check(ForbidWaitList.Contains(rifle), "the rifle does not wait"); + for (int i = 0; i < 3; i++) + { + Fixtures.Tick(ForbidWaitList.CheckInterval); + T.Check(Forbidden(rifle), "the rifle was allowed while its colonist lies where it fell (check " + (i + 1) + ")"); + } + c.Kill(null); + Fixtures.Tick(ForbidWaitList.CheckInterval); + T.Check(!Forbidden(rifle), "the rifle is still forbidden after its colonist died and a check passed"); + T.Check(!ForbidWaitList.Contains(rifle), "the rifle is still on the wait list"); + } + + [BlaxTest("forbid gear: with the colony rule off, a downed colonist's rifle, meal and medicine stay forbidden")] + public static void ColonistDownedRuleOff() + { + Begin(); + ForbidRules.Colony.UseSuggested(); + ForbidRules.Colony.Ticked = false; + // The enemy rule keeps the downing scope open, so the colony rule's own checkbox is what leaves the drops alone. + EnemyRule(); + T.Check(ForbidHooks.ShouldOpen, "setup: no scope opens"); + CellRect r = Area(home: false); + Pawn c = Colonist(r.CenterCell); + ThingWithComps rifle = Arm(c, "Gun_AssaultRifle", QualityCategory.Normal, 1f); + Thing meal = Give(c, "MealSurvivalPack", 1); + Thing herbal = Give(c, "MedicineHerbal", 2); + Down(c); + T.Check(!ForbidWaitList.Contains(rifle), "the rifle waits with the colony rule off"); + Fixtures.Tick(ForbidWaitList.CheckInterval); + T.Check(Forbidden(rifle) && Forbidden(meal) && Forbidden(herbal), + "with the rule off: rifle " + Forbidden(rifle) + ", meal " + Forbidden(meal) + ", medicine " + Forbidden(herbal) + " (all should be forbidden)"); + } + + [BlaxTest("forbid gear: colony rule only inside the home area: a colonist downed outside keeps its meal and medicine forbidden")] + public static void ColonistDownedOnlyInsideHome() + { + Begin(); + ColonyRule(anywhere: false); + CellRect r = Area(home: false); + Pawn c = Colonist(r.CenterCell); + Thing meal = Give(c, "MealSurvivalPack", 1); + Thing herbal = Give(c, "MedicineHerbal", 2); + Down(c); + Fixtures.Tick(ForbidWaitList.CheckInterval); + T.Check(meal.Spawned && herbal.Spawned, "setup: the drops are not on the ground"); + T.Check(Forbidden(meal) && Forbidden(herbal), + "outside the home area: meal " + Forbidden(meal) + ", medicine " + Forbidden(herbal) + " (both should be forbidden)"); + } + + [BlaxTest("forbid gear: a downed colonist carried off by a rescuer: its rifle is allowed after the next check")] + public static void ColonistRescued() + { + Begin(); + ColonyRule(); + CellRect r = Area(home: false); + Pawn c = Colonist(r.CenterCell); + ThingWithComps rifle = Arm(c, "Gun_AssaultRifle", QualityCategory.Normal, 1f); + Down(c); + NeedRememberedWeapon(c, rifle); + T.Check(Forbidden(rifle) && ForbidWaitList.Contains(rifle), "setup: the rifle is not forbidden and waiting"); + Pawn rescuer = Colonist(r.CenterCell + IntVec3.North * 2); + rescuer.drafter.Drafted = true; + // The rescue job carries the pawn with Toils_Haul.StartCarryThing, which is Pawn_CarryTracker.TryStartCarry. + T.Check(rescuer.carryTracker.TryStartCarry(c, 1, reserve: false) > 0, "setup: the rescuer could not pick the colonist up"); + T.Check(!c.Spawned && c.mindState.droppedWeapon == null, "the carried colonist still remembers its rifle"); + Fixtures.Tick(ForbidWaitList.CheckInterval); + T.Check(!Forbidden(rifle), "the rifle is still forbidden after the rescue and a check"); + if (rescuer.carryTracker.CarriedThing != null) + rescuer.carryTracker.TryDropCarriedThing(rescuer.Position, ThingPlaceMode.Near, out _); + } + + [BlaxTest("forbid gear: a downed colonist healed where it fell equips its still forbidden rifle, which leaves the list")] + public static void ColonistHealed() + { + Begin(); + ColonyRule(); + CellRect r = Area(home: false); + Pawn c = Colonist(r.CenterCell, canFight: true); + ThingWithComps rifle = Arm(c, "Gun_AssaultRifle", QualityCategory.Normal, 1f); + Down(c); + NeedRememberedWeapon(c, rifle); + T.Check(Forbidden(rifle) && ForbidWaitList.Contains(rifle), "setup: the rifle is not forbidden and waiting"); + Hediff anesthetic = c.health.hediffSet.GetFirstHediffOfDef(HediffDefOf.Anesthetic); + T.NotNull(anesthetic, "the anesthetic"); + c.health.RemoveHediff(anesthetic); + T.Check(!c.Downed, "the colonist is still down after the anesthetic was removed"); + int waited = 0; + while (c.equipment.Primary != rifle && waited < 3000) + { + Fixtures.Tick(60); + waited += 60; + } + T.Check(c.equipment.Primary == rifle, "the colonist did not pick its rifle up within 3000 ticks (job: " + c.CurJobDef?.defName + ")"); + T.Info("equipped after " + waited + " ticks"); + Fixtures.Tick(ForbidWaitList.CheckInterval); + T.Check(!ForbidWaitList.Contains(rifle), "the equipped rifle is still on the wait list"); + T.Check(T.ErrorsSoFar().Count == 0, "errors were logged: " + string.Join(" | ", T.ErrorsSoFar().Take(3))); + } + + [BlaxTest("forbid gear: a prisoner breaking out, downed with a knife: it waits, then follows the colony rule once carried")] + public static void PrisonerBreakingOut() + { + Begin(); + ColonyRule(); + CellRect r = Area(home: false); + Pawn p = Spawn(Generate(PawnKindDefOf.Slave, Hostile()), r.CenterCell); + p.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Prisoner); + T.Check(p.IsPrisonerOfColony, "setup: not a prisoner of the colony"); + ThingWithComps knife = Arm(p, "MeleeWeapon_Knife", QualityCategory.Normal, 1f); + LordMaker.MakeNewLord(p.Faction, new LordJob_PrisonBreak(p.Position, p.Position, -1), Map, new[] { p }); + T.Check(PrisonBreakUtility.IsPrisonBreaking(p), "setup: the prisoner is not breaking out"); + T.Check(p.HostileTo(Faction.OfPlayer), "setup: the escaping prisoner is not hostile to the player"); + T.Equal(ForbidGroup.Colony, ForbidRules.GroupOf(p), "group of the escaping prisoner"); + Down(p); + NeedRememberedWeapon(p, knife); + T.Check(Forbidden(knife), "the knife was allowed at once"); + Fixtures.Tick(ForbidWaitList.CheckInterval * 2); + T.Check(Forbidden(knife), "the knife was allowed while the prisoner lies where it fell"); + Pawn carrier = Colonist(r.CenterCell + IntVec3.East * 2); + carrier.drafter.Drafted = true; + T.Check(carrier.carryTracker.TryStartCarry(p, 1, reserve: false) > 0, "setup: the colonist could not pick the prisoner up"); + Fixtures.Tick(ForbidWaitList.CheckInterval); + T.Check(!Forbidden(knife), "the knife is still forbidden after the prisoner was carried off"); + if (carrier.carryTracker.CarriedThing != null) + carrier.carryTracker.TryDropCarriedThing(carrier.Position, ThingPlaceMode.Near, out _); + } + + // ---- gear rules: enemies --------------------------------------------------------- + + [BlaxTest("forbid gear: a raider killed outside the home area, suggested setup: good rifle, drugs and medicine allowed, the rest forbidden")] + public static void RaiderKilled() + { + Begin(); + EnemyRule(); + CellRect r = Area(home: false); + RaiderKit k = KitRaider(r.CenterCell); + Pawn raider = k.Raider; + raider.Kill(null); + T.Check(!Forbidden(k.Good), "the Normal assault rifle at 80% is forbidden"); + T.Check(Forbidden(k.Poor), "the Poor assault rifle at 80% is allowed"); + T.Check(Forbidden(k.Damaged), "the Normal assault rifle at 40% is allowed"); + T.Check(!Forbidden(k.GoJuice), "the go-juice is forbidden"); + T.Check(!Forbidden(k.Medicine), "the medicine is forbidden"); + T.NotNull(raider.Corpse, "the raider's corpse"); + T.Check(Forbidden(raider.Corpse), "the corpse is allowed with the corpse switches off"); + } + + [BlaxTest("forbid gear: a raider downed, not killed: its weapon is allowed; captured afterwards, nothing else changes")] + public static void RaiderDowned() + { + Begin(); + EnemyRule(); + CellRect r = Area(home: false); + RaiderKit k = KitRaider(r.CenterCell); + Down(k.Raider); + T.Check(!Forbidden(k.Good), "the downed raider's Normal rifle at 80% is forbidden"); + T.Check(Forbidden(k.Poor), "the downed raider's Poor rifle is allowed"); + T.Check(!ForbidWaitList.Contains(k.Good), "an enemy's weapon waits like a remembered colony weapon"); + Pawn captor = Colonist(r.CenterCell + IntVec3.West * 2); + k.Raider.guest.CapturedBy(Faction.OfPlayer, captor); + T.Check(k.Raider.IsPrisonerOfColony, "setup: the raider was not captured"); + T.Check(!Forbidden(k.Good) && Forbidden(k.Poor), "capture changed the flags"); + T.Check(T.ErrorsSoFar().Count == 0, "errors were logged: " + string.Join(" | ", T.ErrorsSoFar().Take(3))); + } + + [BlaxTest("forbid gear: \"only inside the home area\": killed outside stays vanilla, killed inside the good rifle is allowed")] + public static void OnlyInsideHome() + { + Begin(); + EnemyRule(anywhere: false); + CellRect outside = Area(home: false); + RaiderKit a = KitRaider(outside.CenterCell); + a.Raider.Kill(null); + T.Check(Forbidden(a.Good) && Forbidden(a.Medicine), "a raider killed outside the home area got its drops allowed"); + + CellRect inside = Area(home: true); + RaiderKit b = KitRaider(inside.CenterCell); + b.Raider.Kill(null); + T.Check(!Forbidden(b.Good), "the Normal rifle at 80% of a raider killed inside the home area is forbidden"); + } + + [BlaxTest("forbid gear: two raiders' medicine merging into one stack outside the home area is allowed; a stack the player forbade stays forbidden")] + public static void MergedStacks() + { + Begin(); + EnemyRule(); + CellRect r = Area(home: false); + ThingDef medicine = ThingDefOf.MedicineIndustrial; + for (int i = 0; i < 2; i++) + { + Pawn raider = Raider(r.CenterCell); + Give(raider, medicine.defName, 5); + raider.Kill(null); + } + List stacks = r.Cells.SelectMany(c => c.GetThingList(Map)).Where(t => t.def == medicine).ToList(); + T.Equal(1, stacks.Count, "medicine stacks in the area"); + T.Equal(10, stacks[0].stackCount, "medicine in the merged stack"); + T.Check(!Forbidden(stacks[0]), "the merged stack of 10 is forbidden"); + + CellRect r2 = Area(home: false); + // The corpse takes the centre cell, so the first cell the drop tries after it is the next one of the radial pattern. + IntVec3 spot = r2.CenterCell + GenRadial.RadialPattern[1]; + Thing mine = GenSpawn.Spawn(Stack(medicine.defName, 10), spot, Map); + mine.SetForbidden(true, warnOnFail: false); + Pawn third = Raider(r2.CenterCell); + Give(third, medicine.defName, 5); + // The corpse fills the centre, and the player's stack is on the first cell a drop near it tries, so the raider's 5 merge into it. + third.Kill(null); + List after = r2.Cells.SelectMany(c => c.GetThingList(Map)).Where(t => t.def == medicine).ToList(); + T.Info("medicine stacks next to the player's: " + string.Join(", ", after.Select(t => t.stackCount + (Forbidden(t) ? " forbidden" : " allowed")))); + T.Check(!mine.Destroyed && mine.stackCount == 15, "the raider's medicine did not merge into the player's stack (" + mine.stackCount + ")"); + T.Check(Forbidden(mine), "the stack the player forbade was allowed"); + } + + [BlaxTest("forbid gear: a raider carrying 200 silver killed inside the home area: allowed with the rule on, forbidden with it off")] + public static void CarriedSilver() + { + Begin(); + EnemyRule(); + // The colony rule keeps the death scope open in the "off" pass, so the enemy rule's own checkbox decides. + ColonyRule(); + foreach (bool on in new[] { true, false }) + { + ForbidRules.Enemies.Ticked = on; + T.Check(ForbidHooks.ShouldOpen, "setup: no scope opens with the enemy rule " + (on ? "on" : "off")); + CellRect r = Area(home: true); + Pawn raider = Raider(r.CenterCell); + Thing silver = Stack("Silver", 200); + T.Check(raider.carryTracker.TryStartCarry(silver), "setup: the raider could not carry the silver"); + raider.Kill(null); + Thing dropped = r.Cells.SelectMany(c => c.GetThingList(Map)).FirstOrDefault(t => t.def == ThingDefOf.Silver); + T.NotNull(dropped, "the silver on the ground"); + T.Equal(!on, Forbidden(dropped), "silver forbidden with the rule " + (on ? "on" : "off")); + } + } + + [BlaxTest("forbid gear: a filter refusing medicine never forbids: a raider killed inside the home area leaves its medicine allowed")] + public static void RefusingNeverForbids() + { + Begin(); + FilterRefusing(ForbidRules.Enemies, "MedicineIndustrial"); + ForbidRules.Enemies.Ticked = true; + CellRect r = Area(home: true); + Pawn raider = Raider(r.CenterCell); + Thing medicine = Give(raider, "MedicineIndustrial", 4); + raider.Kill(null); + T.Check(medicine.Spawned, "setup: the medicine is not on the ground"); + T.Check(!Forbidden(medicine), "the medicine was forbidden"); + } + + [BlaxTest("forbid gear: with both rules on, a downed trader guest's wares and a downed quest lodger's weapon stay forbidden")] + public static void NeutralsStayVanilla() + { + Begin(); + ColonyRule(); + EnemyRule(); + CellRect r = Area(home: false); + Faction friendly = Friendly(); + Pawn trader = Spawn(Generate(MemberKind(friendly), friendly), r.CenterCell); + Thing wares = Give(trader, "Silver", 50); + Thing cloth = Give(trader, "Cloth", 20); + T.Equal(ForbidGroup.None, ForbidRules.GroupOf(trader), "group of the trader"); + Down(trader); + Fixtures.Tick(ForbidWaitList.CheckInterval); + // With Hospitality's "disable friendly gear drops" a downed visitor keeps its things; what does drop stays forbidden. + if (!Compat.IsActive(Hospitality)) + T.Check(wares.Spawned && cloth.Spawned, "setup: the downed trader's wares are not on the ground"); + else if (!wares.Spawned && !cloth.Spawned) + T.Info("the downed trader kept its wares (Hospitality keeps a friendly pawn's gear on it)"); + T.Check((!wares.Spawned || Forbidden(wares)) && (!cloth.Spawned || Forbidden(cloth)), "the trader's dropped wares were allowed"); + + Pawn lodger = Spawn(Generate(PawnKindDefOf.Colonist, Faction.OfPlayer), r.CenterCell + IntVec3.North * 3); + Quest quest = Quest.MakeRaw(); + quest.hidden = true; + quest.acceptanceTick = Find.TickManager.TicksGame; + var part = new QuestPart_ExtraFaction { extraFaction = new ExtraFaction(friendly, ExtraFactionType.HomeFaction) }; + part.affectedPawns.Add(lodger); + quest.AddPart(part); + Find.QuestManager.Add(quest); + try + { + T.Check(lodger.IsQuestLodger(), "setup: the pawn is not a quest lodger"); + T.Equal(ForbidGroup.None, ForbidRules.GroupOf(lodger), "group of the quest lodger"); + ThingWithComps weapon = Arm(lodger, "Gun_AssaultRifle", QualityCategory.Normal, 1f); + Down(lodger); + T.Check(Forbidden(weapon), "the lodger's weapon was allowed"); + T.Check(!ForbidWaitList.Contains(weapon), "the lodger's weapon waits on the list"); + } + finally + { + if (Find.QuestManager.QuestsListForReading.Contains(quest)) + Find.QuestManager.Remove(quest); + } + } + + [BlaxTest("forbid gear: a downed slave's meal outside the home area follows the colony rule (Ideology)")] + public static void SlaveDowned() + { + Fixtures.NeedDlc(DlcSupport.Ideology); + Begin(); + ColonyRule(); + CellRect r = Area(home: false); + Pawn slave = Spawn(Generate(PawnKindDefOf.Slave, Friendly()), r.CenterCell); + slave.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Slave); + T.Check(slave.IsSlaveOfColony, "setup: not a slave of the colony"); + T.Equal(ForbidGroup.Colony, ForbidRules.GroupOf(slave), "group of the slave"); + Thing meal = Give(slave, "MealSurvivalPack", 1); + Down(slave); + T.Check(meal.Spawned && !Forbidden(meal), "the slave's meal is forbidden or not on the ground"); + } + + [BlaxTest("forbid gear: a colony mech hauling forbidden steel goes down and the steel keeps its flag; a hostile Lancer's weapon is destroyed, not dropped (Biotech)")] + public static void Mechs() + { + Fixtures.NeedDlc(DlcSupport.Biotech); + Begin(); + ColonyRule(); + EnemyRule(); + CellRect r = Area(home: false); + PawnKindDef lifterKind = DefDatabase.GetNamedSilentFail("Mech_Lifter"); + Fixtures.NeedDef(lifterKind, "PawnKindDef Mech_Lifter"); + Pawn lifter = Spawn(Fixtures.TrackPawn(PawnGenerator.GeneratePawn(lifterKind, Faction.OfPlayer)), r.CenterCell); + T.Check(lifter.IsColonyMech, "setup: the lifter is not a colony mech"); + // Forbidden before the haul: the colony's suggested filter allows every item, so a rule that allowed + // what the game never forbade in the downing would show here. + Thing steel = Stack("Steel", 30); + steel.SetForbidden(true, warnOnFail: false); + T.Check(lifter.carryTracker.TryStartCarry(steel), "setup: the lifter could not carry steel"); + HealthUtility.DamageUntilDowned(lifter, allowBleedingWounds: false); + T.Check(lifter.Downed && !lifter.Dead, "setup: the lifter is not down (dead: " + lifter.Dead + ")"); + Thing dropped = r.Cells.SelectMany(c => c.GetThingList(Map)).FirstOrDefault(t => t.def == ThingDefOf.Steel); + T.NotNull(dropped, "the steel on the ground"); + T.Check(Forbidden(dropped), "the forbidden steel the colony mech carried was allowed"); + + CellRect r2 = Area(home: false); + T.NotNull(Faction.OfMechanoids, "setup: the mechanoid faction"); + PawnKindDef lancerKind = Fixtures.NeedDef(DefDatabase.GetNamedSilentFail("Mech_Lancer"), "PawnKindDef Mech_Lancer"); + Pawn lancer = Spawn(Fixtures.TrackPawn(PawnGenerator.GeneratePawn(lancerKind, Faction.OfMechanoids)), r2.CenterCell); + T.Equal(ForbidGroup.Enemies, ForbidRules.GroupOf(lancer), "group of the hostile Lancer"); + ThingWithComps weapon = lancer.equipment?.Primary; + T.NotNull(weapon, "setup: the Lancer's weapon"); + lancer.Kill(null); + T.Check(weapon.Destroyed, "the Lancer's weapon was not destroyed"); + T.Check(!r2.Cells.SelectMany(c => c.GetThingList(Map)).Any(t => t.def.IsWeapon), "a weapon lies next to the dead Lancer"); + T.Check(T.ErrorsSoFar().Count == 0, "errors were logged: " + string.Join(" | ", T.ErrorsSoFar().Take(3))); + } + + [BlaxTest("forbid gear: with Hospitality, a downed guest's weapon stays forbidden (-Compat)")] + public static void HospitalityGuest() + { + if (!Compat.IsActive("Orion.Hospitality")) + T.Skip("needs Hospitality (-Compat)"); + Begin(); + ColonyRule(); + EnemyRule(); + CellRect r = Area(home: false); + Faction friendly = Friendly(); + Pawn guest = Spawn(Generate(MemberKind(friendly), friendly), r.CenterCell); + guest.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Guest); + ThingWithComps weapon = Arm(guest, "Gun_AssaultRifle", QualityCategory.Normal, 1f); + Down(guest); + Fixtures.Tick(ForbidWaitList.CheckInterval); + if (!weapon.Spawned) + T.Info("the downed guest kept its weapon (Hospitality's option to keep a friendly pawn's gear on it)"); + T.Check(!weapon.Spawned || Forbidden(weapon), "the guest's dropped weapon was allowed"); + T.Check(!ForbidWaitList.Contains(weapon), "the guest's weapon waits on the list"); + } + + [BlaxTest("forbid gear: with Pick Up And Haul, an allowed rifle is listed for hauling and gets a haul job (-Compat)")] + public static void PickUpAndHaul() + { + if (!Compat.IsActive("Mehni.PickUpAndHaul")) + T.Skip("needs Pick Up And Haul (-Compat)"); + Begin(); + EnemyRule(); + CellRect r = Area(home: false); + RaiderKit k = KitRaider(r.CenterCell); + k.Raider.Kill(null); + T.Check(!Forbidden(k.Good), "setup: the good rifle is forbidden"); + + CellRect pile = Fixtures.EmptyArea(3, 3); + var zone = new Zone_Stockpile(StorageSettingsPreset.DefaultStockpile, Map.zoneManager); + Map.zoneManager.RegisterZone(zone); + Fixtures.TrackZone(zone); + foreach (IntVec3 c in pile.Cells) + zone.AddCell(c); + T.Check(zone.settings.AllowedToAccept(k.Good), "setup: the stockpile refuses the rifle"); + + T.Check(Map.listerHaulables.ThingsPotentiallyNeedingHauling().Contains(k.Good), "the allowed rifle is not listed for hauling"); + Pawn hauler = Colonist(r.CenterCell + IntVec3.South * 3); + T.Check(HaulAIUtility.PawnCanAutomaticallyHaulFast(hauler, k.Good, forced: false), "a colonist can't haul the allowed rifle"); + WorkGiverDef puah = DefDatabase.AllDefsListForReading.FirstOrDefault(w => w.giverClass?.FullName == "PickUpAndHaul.WorkGiver_HaulToInventory"); + T.NotNull(puah, "Pick Up And Haul's work giver"); + Job job = (puah.Worker as WorkGiver_Scanner)?.JobOnThing(hauler, k.Good, forced: false); + T.Check(job != null, "Pick Up And Haul gave no job for the allowed rifle"); + T.Info("Pick Up And Haul job: " + job.def.defName); + } + + [BlaxTest("forbid gear: kept drops for the phase-2 check, and a rifle still waiting at save time")] + public static void KeepForPhase2() + { + Begin(); + EnemyRule(); + CellRect r = Area(home: false); + RaiderKit k = KitRaider(r.CenterCell); + k.Raider.Kill(null); + T.Check(!Forbidden(k.Good) && Forbidden(k.Poor), "setup: flags after the kill"); + Fixtures.Keep(k.Good); + Fixtures.Keep(k.Poor); + T.Carry[KeptAllowedKey] = k.Good.ThingID; + T.Carry[KeptForbiddenKey] = k.Poor.ThingID; + // Right before the save, after every other phase-1 test: a hostile pawn stands on the map and a raider + // killed then leaves its rifle on the wait list. Nothing here is tracked, so no cleanup removes it. + T.CarryAtSave(WaitingRifleKey, WaitingRifleAtSave); + } + + private static string WaitingRifleAtSave() + { + BlaxDefaultsSettings s = BlaxDefaultsMod.Settings; + List library = DefaultsLibrary.Snapshot(); + bool rule = s.enemyGearRule, strip = s.enemyStripRule, anywhere = s.enemyGearAnywhere; + try + { + ForbidRules.Enemies.UseSuggested(); + ForbidRules.Enemies.Ticked = true; + Map map = Map; + Faction hostile = Fixtures.HostileFaction(); + IntVec3 cell = map.AllCells + .Where(c => !c.CloseToEdge(map, 8) && c.Standable(map) && !c.Fogged(map) && c.GetDistrict(map) != null + && !map.areaManager.Home[c] && c.GetThingList(map).Count == 0) + .OrderBy(c => (c - map.Center).LengthHorizontalSquared) + .First(); + Pawn threat = PawnGenerator.GeneratePawn(new PawnGenerationRequest(MemberKind(hostile), hostile, forceGenerateNewPawn: true)); + threat.equipment?.DestroyAllEquipment(); + GenSpawn.Spawn(threat, cell, map); + Pawn raider = PawnGenerator.GeneratePawn(new PawnGenerationRequest(MemberKind(hostile), hostile, forceGenerateNewPawn: true)); + raider.equipment?.DestroyAllEquipment(); + raider.inventory?.DestroyAll(); + var rifle = (ThingWithComps)ThingMaker.MakeThing(Fixtures.Thing("Gun_AssaultRifle")); + rifle.TryGetComp()?.SetQuality(QualityCategory.Normal, ArtGenerationContext.Outsider); + raider.equipment.AddEquipment(rifle); + GenSpawn.Spawn(raider, cell, map); + raider.Kill(null); + T.Carry[WaitingThreatKey] = threat.ThingID; + return Forbidden(rifle) && ForbidWaitList.Contains(rifle) ? rifle.ThingID : "not waiting: forbidden " + Forbidden(rifle) + ", on the list " + ForbidWaitList.Contains(rifle); + } + finally + { + s.enemyGearRule = rule; + s.enemyStripRule = strip; + s.enemyGearAnywhere = anywhere; + DefaultsLibrary.RestoreForTests(library); + } + } + + [BlaxTest("forbid gear: the flags persist; a rifle waiting at save time stays forbidden after the load and nothing logs", phase: 2)] + public static void Phase2() + { + Thing allowed = FindAnywhere(T.Carry.TryGetValue(KeptAllowedKey, out string a) ? a : null); + Thing forbidden = FindAnywhere(T.Carry.TryGetValue(KeptForbiddenKey, out string f) ? f : null); + T.NotNull(allowed, "the kept allowed rifle"); + T.NotNull(forbidden, "the kept forbidden rifle"); + T.Check(!Forbidden(allowed), "the allowed rifle is forbidden after the load"); + T.Check(Forbidden(forbidden), "the forbidden rifle is allowed after the load"); + + T.Carry.TryGetValue(WaitingRifleKey, out string rifleId); + Thing rifle = FindAnywhere(rifleId); + T.NotNull(rifle, "the rifle waiting at save time (" + rifleId + ")"); + Pawn threat = FindAnywhere(T.Carry.TryGetValue(WaitingThreatKey, out string th) ? th : null) as Pawn; + if (threat != null && threat.Spawned) + threat.Destroy(DestroyMode.Vanish); + EnemyRule(); + T.Check(!GenHostility.AnyHostileActiveThreatToPlayer(Map), "a hostile threat is still on the map"); + T.Equal(0, ForbidWaitList.Count, "wait list entries after the load"); + Fixtures.Tick(ForbidWaitList.CheckInterval); + T.Check(Forbidden(rifle), "the rifle that waited at save time was allowed after the load"); + T.Check(T.ErrorsSoFar().Count == 0, "errors were logged: " + string.Join(" | ", T.ErrorsSoFar().Take(3))); + if (rifle.Spawned) + rifle.Destroy(DestroyMode.Vanish); + } + + private static Thing FindAnywhere(string thingId) + { + if (thingId == null) + return null; + Thing t = Fixtures.FindThingById(thingId); + if (t != null) + return t; + foreach (Map m in Find.Maps) + { + foreach (Pawn p in m.mapPawns.AllPawnsSpawned) + { + IEnumerable held = (p.carryTracker?.innerContainer ?? Enumerable.Empty()) + .Concat(p.inventory?.innerContainer ?? Enumerable.Empty()) + .Concat(p.equipment?.AllEquipmentListForReading ?? Enumerable.Empty()); + foreach (Thing h in held) + if (h.ThingID == thingId) return h; + } + } + return null; + } + + // ---- wait until the fight is over ------------------------------------------------ + + [BlaxTest("forbid wait: with a hostile pawn standing, a killed raider's rifle waits; once it is downed and 250 ticks pass, it is allowed")] + public static void WaitForThreat() + { + Begin(); + EnemyRule(); + CellRect r = Area(home: false); + Pawn threat = Threat(r); + RaiderKit k = KitRaider(r.CenterCell); + k.Raider.Kill(null); + T.Check(Forbidden(k.Good), "the rifle was allowed while a hostile pawn stands on the map"); + T.Check(ForbidWaitList.Contains(k.Good), "the rifle does not wait"); + Down(threat); + T.Check(!GenHostility.AnyHostileActiveThreatToPlayer(Map), "the downed hostile pawn is still an active threat"); + Fixtures.Tick(ForbidWaitList.CheckInterval); + T.Check(!Forbidden(k.Good), "the rifle is still forbidden after the fight and a check"); + T.Check(!Forbidden(k.Medicine), "the medicine is still forbidden after the fight and a check"); + T.Check(Forbidden(k.Poor), "the Poor rifle was allowed after the fight"); + T.Equal(0, ForbidWaitList.Count, "entries left on the wait list"); + } + + [BlaxTest("forbid wait: a waiting rifle the player allows and forbids again stays forbidden")] + public static void WaitPlayerChange() + { + Begin(); + EnemyRule(); + CellRect r = Area(home: false); + Pawn threat = Threat(r); + RaiderKit k = KitRaider(r.CenterCell); + k.Raider.Kill(null); + T.Check(ForbidWaitList.Contains(k.Good), "setup: the rifle does not wait"); + k.Good.SetForbidden(false); + k.Good.SetForbidden(true); + T.Check(!ForbidWaitList.Contains(k.Good), "the rifle still waits after the player changed its flag"); + Down(threat); + Fixtures.Tick(ForbidWaitList.CheckInterval); + T.Check(Forbidden(k.Good), "the rifle the player forbade again was allowed"); + } + + [BlaxTest("forbid wait: a waiting rifle a pawn picks up leaves the list without a log line")] + public static void WaitPickedUp() + { + Begin(); + EnemyRule(); + CellRect r = Area(home: false); + Threat(r); + RaiderKit k = KitRaider(r.CenterCell); + k.Raider.Kill(null); + T.Check(ForbidWaitList.Contains(k.Good), "setup: the rifle does not wait"); + Pawn c = Colonist(r.CenterCell + IntVec3.South * 2); + c.drafter.Drafted = true; + T.Check(c.carryTracker.TryStartCarry(k.Good, 1, reserve: false) > 0, "setup: the colonist could not pick the rifle up"); + Fixtures.Tick(ForbidWaitList.CheckInterval); + T.Check(!ForbidWaitList.Contains(k.Good), "the picked-up rifle is still on the wait list"); + T.Check(T.ErrorsSoFar().Count == 0, "errors were logged: " + string.Join(" | ", T.ErrorsSoFar().Take(3))); + if (c.carryTracker.CarriedThing != null) + c.carryTracker.TryDropCarriedThing(c.Position, ThingPlaceMode.Near, out _); + } + + [BlaxTest("forbid wait: a waiting rifle the filter no longer allows stays forbidden")] + public static void WaitFilterChanged() + { + Begin(); + EnemyRule(); + CellRect r = Area(home: false); + Pawn threat = Threat(r); + RaiderKit k = KitRaider(r.CenterCell); + k.Raider.Kill(null); + T.Check(ForbidWaitList.Contains(k.Good), "setup: the rifle does not wait"); + FilterRefusing(ForbidRules.Enemies, "Gun_AssaultRifle"); + Down(threat); + Fixtures.Tick(ForbidWaitList.CheckInterval); + T.Check(Forbidden(k.Good), "the rifle the filter now refuses was allowed"); + T.Check(!Forbidden(k.Medicine), "the medicine the filter still allows is forbidden"); + } + + // ---- stripping --------------------------------------------------------------------- + + private static Pawn DressedRaider(IntVec3 at, out Apparel duster, out Apparel tuque) + { + Pawn p = Raider(at); + p.apparel.DestroyAll(); + duster = Wear(p, "Apparel_Duster", QualityCategory.Normal, 0.8f); + tuque = Wear(p, "Apparel_Tuque", QualityCategory.Poor, 0.9f); + return p; + } + + /// Kills the pawn and puts its apparel's hit points back where the test set them. + private static Corpse KillKeepingHitPoints(Pawn p, params Apparel[] apparel) + { + int[] hp = apparel.Select(a => a.HitPoints).ToArray(); + p.Kill(null); + for (int i = 0; i < apparel.Length; i++) + apparel[i].HitPoints = hp[i]; + T.NotNull(p.Corpse, "the corpse of " + p); + return p.Corpse; + } + + [BlaxTest("forbid strip: a raider corpse stripped with the enemy switch on: Normal duster at 80% allowed, Poor tuque forbidden; switch off: both allowed")] + public static void StripRaiderCorpse() + { + Begin(); + EnemyRule(); + foreach (bool on in new[] { true, false }) + { + ForbidRules.Enemies.StripTicked = on; + CellRect r = Area(home: false); + Pawn p = DressedRaider(r.CenterCell, out Apparel duster, out Apparel tuque); + Corpse corpse = KillKeepingHitPoints(p, duster, tuque); + corpse.Strip(); + T.Check(duster.Spawned && tuque.Spawned, "setup: the apparel is not on the ground"); + T.Check(!Forbidden(duster), "the Normal duster at 80% is forbidden (switch " + (on ? "on" : "off") + ")"); + T.Equal(on, Forbidden(tuque), "Poor tuque forbidden with the switch " + (on ? "on" : "off")); + } + } + + [BlaxTest("forbid strip: the strip in butchering's ingredient step leaves both allowed with the switch on")] + public static void StripButchering() + { + Begin(); + EnemyRule(); + T.Check(ForbidRules.Enemies.StripActive, "setup: the enemy strip switch is off"); + CellRect r = Area(home: false); + Pawn p = DressedRaider(r.CenterCell, out Apparel duster, out Apparel tuque); + Corpse corpse = KillKeepingHitPoints(p, duster, tuque); + RecipeDef butcher = Fixtures.NeedDef(DefDatabase.GetNamedSilentFail("ButcherCorpseFlesh"), "RecipeDef ButcherCorpseFlesh"); + T.Check(butcher.autoStripCorpses, "setup: butchering does not strip corpses"); + Pawn butcherPawn = Colonist(r.CenterCell + IntVec3.East * 2); + Job job = JobMaker.MakeJob(JobDefOf.DoBill, butcherPawn); + job.bill = new Bill_Production(butcher); + job.placedThings = new List { new ThingCountClass(corpse, 1) }; + // The private static ingredient step of the butcher's bill job (Verse.AI/Toils_Recipe.cs:301), as the + // finish toil calls it: it strips the corpse because the recipe has autoStripCorpses. + AccessTools.Method(typeof(Toils_Recipe), "CalculateIngredients").Invoke(null, new object[] { job, butcherPawn }); + T.Check(duster.Spawned && tuque.Spawned, "the butchering step did not strip the corpse"); + T.Check(!Forbidden(duster) && !Forbidden(tuque), "butchering forbade stripped apparel (duster " + Forbidden(duster) + ", tuque " + Forbidden(tuque) + ")"); + T.Check(!ForbidHooks.Butchering, "the butchering flag is still set"); + } + + [BlaxTest("forbid strip: a colonist's corpse stripped with only the enemy switch on: both allowed; with only the colony switch on, the colony filter decides")] + public static void StripColonistCorpse() + { + Begin(); + EnemyRule(); + foreach (bool colonySwitch in new[] { false, true }) + { + if (colonySwitch) + { + // The colony filter refuses the Normal duster and allows the Poor tuque, the opposite of the + // enemy filter, so the colony switch and the colony filter are both what decides. + FilterRefusing(ForbidRules.Colony, "Apparel_Duster"); + ForbidRules.Colony.StripTicked = true; + ForbidRules.Enemies.StripTicked = false; + T.Check(ForbidRules.Colony.StripActive && !ForbidRules.Enemies.StripActive, "setup: strip switches"); + } + string pass = colonySwitch ? "only the colony switch on" : "only the enemy switch on"; + CellRect r = Area(home: false); + Pawn c = Colonist(r.CenterCell); + c.apparel.DestroyAll(); + Apparel duster = Wear(c, "Apparel_Duster", QualityCategory.Normal, 0.8f); + Apparel tuque = Wear(c, "Apparel_Tuque", QualityCategory.Poor, 0.9f); + Corpse corpse = KillKeepingHitPoints(c, duster, tuque); + corpse.Strip(); + T.Check(duster.Spawned && tuque.Spawned, "setup: the apparel is not on the ground (" + pass + ")"); + T.Equal(colonySwitch, Forbidden(duster), "the colonist's Normal duster forbidden with " + pass); + T.Check(!Forbidden(tuque), "the colonist's Poor tuque was forbidden with " + pass); + } + } + + [BlaxTest("forbid strip: a raider stripped while down: its Poor shirt isn't tainted and is forbidden, its Normal duster allowed")] + public static void StripDownedRaider() + { + Begin(); + EnemyRule(); + CellRect r = Area(home: false); + Pawn p = Raider(r.CenterCell); + p.apparel.DestroyAll(); + Apparel shirt = Wear(p, "Apparel_BasicShirt", QualityCategory.Poor, 1f); + Apparel duster = Wear(p, "Apparel_Duster", QualityCategory.Normal, 1f); + Down(p); + T.Equal(ForbidGroup.Enemies, ForbidRules.GroupOf(p), "group of the downed raider"); + p.Strip(); + T.Check(shirt.Spawned && duster.Spawned, "setup: the apparel is not on the ground"); + T.Check(!shirt.WornByCorpse, "the shirt stripped from a living raider is tainted"); + T.Check(Forbidden(shirt), "the Poor shirt was allowed"); + T.Check(!Forbidden(duster), "the Normal duster was forbidden"); + } + + [BlaxTest("forbid strip: a strip inside a caravan logs nothing")] + public static void StripInCaravan() + { + Begin(); + FilterRefusing(ForbidRules.Colony, "Apparel_Tuque"); + ForbidRules.Colony.StripTicked = true; + T.Check(ForbidRules.Colony.StripActive, "setup: the colony strip switch is off"); + Pawn colonist = Generate(PawnKindDefOf.Colonist, Faction.OfPlayer); + Pawn prisoner = Generate(PawnKindDefOf.Slave, Hostile()); + prisoner.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Prisoner); + prisoner.apparel.DestroyAll(); + Apparel tuque = Wear(prisoner, "Apparel_Tuque", QualityCategory.Normal, 1f); + Caravan caravan = CaravanMaker.MakeCaravan(new[] { colonist, prisoner }, Faction.OfPlayer, Map.Tile, addToWorldPawnsIfNotAlready: true); + try + { + T.Check(prisoner.GetCaravan() == caravan, "setup: the prisoner is not in the caravan"); + prisoner.Strip(); + T.Check(!tuque.Spawned, "the tuque landed on a map"); + T.Check(!prisoner.apparel.WornApparel.Contains(tuque), "the tuque was not stripped"); + T.Check(T.ErrorsSoFar().Count == 0, "errors were logged: " + string.Join(" | ", T.ErrorsSoFar().Take(3))); + } + finally + { + caravan.RemoveAllPawns(); + if (!caravan.Destroyed) + caravan.Destroy(); + foreach (Pawn p in new[] { colonist, prisoner }) + { + if (!p.Destroyed && p.IsWorldPawn()) + Find.WorldPawns.RemoveAndDiscardPawnViaGC(p); + } + } + } + + // ---- corpses ----------------------------------------------------------------------- + + private static Pawn Animal(string kindName, IntVec3 at) + { + PawnKindDef kind = Fixtures.NeedDef(DefDatabase.GetNamedSilentFail(kindName), "PawnKindDef " + kindName); + return Spawn(Fixtures.TrackPawn(PawnGenerator.GeneratePawn(kind, null)), at); + } + + [BlaxTest("forbid corpses: a wild animal killed outside the home area: allowed with the animal switch, forbidden without; a hunter's kill is unchanged")] + public static void AnimalCorpses() + { + Begin(); + foreach (bool on in new[] { true, false }) + { + Fixtures.Settings.animalCorpsesAllowed = on; + CellRect r = Area(home: false); + Pawn muffalo = Animal("Muffalo", r.CenterCell); + muffalo.Kill(null); + T.NotNull(muffalo.Corpse, "the muffalo's corpse"); + T.Equal(!on, Forbidden(muffalo.Corpse), "muffalo corpse forbidden with the animal switch " + (on ? "on" : "off")); + } + + Fixtures.Settings.animalCorpsesAllowed = false; + CellRect h = Area(home: false); + Pawn prey = Animal("Muffalo", h.CenterCell); + Pawn hunter = Colonist(h.CenterCell + IntVec3.West * 3, canFight: true); + Arm(hunter, "Gun_AssaultRifle", QualityCategory.Normal, 1f); + Job hunt = JobMaker.MakeJob(JobDefOf.Hunt, prey); + // A hunt job without the Hunt designation, so the game's own "designated for hunting" exception doesn't apply. + hunt.ignoreDesignations = true; + hunter.jobs.StartJob(hunt, JobCondition.InterruptForced); + T.Check(hunter.jobs.curDriver is JobDriver_Hunt, "setup: the hunter is not hunting"); + prey.Kill(new DamageInfo(DamageDefOf.Bullet, 10f, instigator: hunter)); + T.NotNull(prey.Corpse, "the hunted muffalo's corpse"); + T.Check(!Forbidden(prey.Corpse), "the corpse the hunter reserved was forbidden"); + hunter.jobs.EndCurrentJob(JobCondition.InterruptForced); + } + + [BlaxTest("forbid corpses: a raider killed outside the home area with the enemy switch on is allowed")] + public static void EnemyCorpse() + { + Begin(); + Fixtures.Settings.enemyCorpsesAllowed = true; + CellRect r = Area(home: false); + Pawn raider = Raider(r.CenterCell); + raider.Kill(null); + T.NotNull(raider.Corpse, "the raider's corpse"); + T.Check(!Forbidden(raider.Corpse), "the raider's corpse is forbidden with the enemy switch on"); + } + + [BlaxTest("forbid corpses: a manhunter husky killed outside the home area follows the animal switch, not the enemy switch")] + public static void ManhunterCorpse() + { + Begin(); + foreach (bool animal in new[] { true, false }) + { + Fixtures.Settings.animalCorpsesAllowed = animal; + Fixtures.Settings.enemyCorpsesAllowed = !animal; + CellRect r = Area(home: false); + Pawn husky = Animal("Husky", r.CenterCell); + T.Check(husky.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Manhunter, forced: true), "setup: the husky did not turn manhunter"); + T.Equal(ForbidGroup.Enemies, ForbidRules.GroupOf(husky), "group of the manhunter"); + husky.Kill(null); + T.NotNull(husky.Corpse, "the husky's corpse"); + T.Equal(!animal, Forbidden(husky.Corpse), "manhunter corpse forbidden with only the " + (animal ? "animal" : "enemy") + " switch on"); + } + } + + [BlaxTest("forbid corpses: the other switch allows a colonist's and a friendly visitor's corpse outside the home area; the animal and enemy switches don't")] + public static void OtherCorpses() + { + Begin(); + Faction friendly = Friendly(); + foreach (bool other in new[] { true, false }) + { + Fixtures.Settings.otherCorpsesAllowed = other; + Fixtures.Settings.animalCorpsesAllowed = !other; + Fixtures.Settings.enemyCorpsesAllowed = !other; + string pass = other ? "only the other switch on" : "only the animal and enemy switches on"; + CellRect r = Area(home: false); + Pawn colonist = Colonist(r.CenterCell); + Pawn visitor = Spawn(Generate(MemberKind(friendly), friendly), r.CenterCell + IntVec3.North * 3); + T.Equal(ForbidGroup.None, ForbidRules.GroupOf(visitor), "group of the visitor"); + colonist.Kill(null); + visitor.Kill(null); + T.NotNull(colonist.Corpse, "the colonist's corpse"); + T.NotNull(visitor.Corpse, "the visitor's corpse"); + T.Equal(!other, Forbidden(colonist.Corpse), "the colonist's corpse forbidden with " + pass); + T.Equal(!other, Forbidden(visitor.Corpse), "the visitor's corpse forbidden with " + pass); + } + } + + [BlaxTest("forbid corpses: a corpse inside the home area is never touched")] + public static void CorpseInsideHome() + { + Begin(); + Fixtures.Settings.animalCorpsesAllowed = true; + Fixtures.Settings.enemyCorpsesAllowed = true; + Fixtures.Settings.otherCorpsesAllowed = true; + CellRect r = Area(home: true); + Pawn raider = Raider(r.CenterCell); + raider.Kill(null); + T.NotNull(raider.Corpse, "the raider's corpse"); + T.Check(!Forbidden(raider.Corpse), "a corpse inside the home area is forbidden"); + T.Check(!ForbidWaitList.Contains(raider.Corpse), "a corpse inside the home area waits"); + } + + [BlaxTest("forbid corpses: with a hostile pawn on the map, an enemy corpse waits and is allowed once the hostile pawn is downed")] + public static void CorpseWaits() + { + Begin(); + Fixtures.Settings.enemyCorpsesAllowed = true; + CellRect r = Area(home: false); + Pawn threat = Threat(r); + Pawn raider = Raider(r.CenterCell); + raider.Kill(null); + Corpse corpse = raider.Corpse; + T.NotNull(corpse, "the raider's corpse"); + T.Check(Forbidden(corpse) && ForbidWaitList.Contains(corpse), "the corpse was allowed during the fight, or does not wait"); + Down(threat); + Fixtures.Tick(ForbidWaitList.CheckInterval); + T.Check(!Forbidden(corpse), "the corpse is still forbidden after the fight"); + } + } +} diff --git a/Tests/run-tests.ps1 b/Tests/run-tests.ps1 index 47d8733..e37f6c4 100644 --- a/Tests/run-tests.ps1 +++ b/Tests/run-tests.ps1 @@ -1,7 +1,9 @@ <# 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, settings and defaults file stay untouched. Needs Steam -running and the Harmony mod from the Workshop. Exit code: 0 all passed, 1 failures, 2 the run didn't finish. +running and the Harmony mod from the Workshop. Exit code: 0 all passed, 1 failures or errors the mod logged +between tests (MODERR lines, strayModErrors on the SUMMARY line; the Workshop upload refuses those too), +2 the run didn't finish. .\Tests\run-tests.ps1 Harmony, the installed DLCs, Blax Defaults .\Tests\run-tests.ps1 -Compat also the installed mods Defaults is tested next to: RimFridge, Weapon Racks, @@ -214,4 +216,7 @@ $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 logged between tests (a reload, a hook running while the game settles) fail no single test. +$summary = @($lines -match '^SUMMARY ') | Select-Object -Last 1 +if ($summary -match '\bstrayModErrors=([1-9]\d*)') { Write-Host "Blax Defaults logged $($Matches[1]) error(s) between tests (MODERR lines)."; exit 1 } exit 0 diff --git a/docs/art/steam/forbid.png b/docs/art/steam/forbid.png new file mode 100644 index 0000000..ee6e0f4 Binary files /dev/null and b/docs/art/steam/forbid.png differ diff --git a/docs/workshop-description.txt b/docs/workshop-description.txt index d8f49cc..74d5b1d 100644 --- a/docs/workshop-description.txt +++ b/docs/workshop-description.txt @@ -1,4 +1,4 @@ -[b]Your own starting settings for new stockpiles, shelves and bills.[/b] Set up one shelf, click "Make default for new shelves", and every new shelf starts like it. Nothing changes until you save a default, and the things you already have keep their settings. Colonists, slaves and prisoners are not part of this mod: that is the job of [url=https://steamcommunity.com/sharedfiles/filedetails/?id=3848261054]Blax Castes[/url]. +[b]Your own starting settings for new stockpiles, shelves and bills, and rules for what stays forbidden when pawns go down or die.[/b] Set up one shelf, click "Make default for new shelves", and every new shelf starts like it. Nothing changes until you save a default or turn a rule on, and the things you already have keep their settings. Colonists, slaves and prisoners are not part of this mod: that is the job of [url=https://steamcommunity.com/sharedfiles/filedetails/?id=3848261054]Blax Castes[/url]. โœ… RimWorld 1.7 ๐Ÿ”ง Needs [url=https://steamcommunity.com/sharedfiles/filedetails/?id=2009463077]Harmony[/url] ๐Ÿงฉ Works with any DLC combination ๐Ÿ’พ Nothing goes into your save @@ -6,7 +6,7 @@ [list] [*]๐Ÿ“ฆ [b]New stockpiles start from your default.[/b] Drag a stockpile or a dumping stockpile and it gets the filter and priority you saved for that type. Growing an existing stockpile leaves its filter alone. [*]๐Ÿ—„๏ธ [b]New storage buildings too.[/b] Shelves, small shelves, bookcases and hoppers start with your default from the moment you place the blueprint, and so does modded storage built the same way, such as the racks from Weapon Racks. Changes you make on the blueprint still win, and a shelf that auto-rebuild puts back keeps its old settings. -[*]๐Ÿ”˜ [b]A "Defaults" button in the storage tab[/b] with "Make default for new shelves", "Load your default", "Load the game's default" and "Forget the default for new shelves", which asks first. On a stockpile you pick the stockpile type. The tooltip tells you whether new ones start from your default. +[*]๐Ÿ”˜ [b]A "Defaults" button in the storage tab[/b] with "Make default for new shelves", "Load your default", "Load the game's default" and "Forget the default for new shelves", which asks first. On a stockpile you pick the stockpile type. [*]๐Ÿงน [b]New shelves start empty.[/b] The settings page button "New shelves start empty at Normal" lists your storage buildings with general-purpose shelves ticked, and Confirm saves an empty default at Normal for each ticked one. Hoppers start unticked so the nutrient paste dispenser keeps its food, and so do bookcases, storage for one kind of item and kinds that already have a default. These defaults also refuse items that mods add later. [*]๐Ÿš๏ธ [b]Only what you build.[/b] Ruins, map generation and trader stock keep the game's settings, and a default never makes a building take items it can't hold. [/list] @@ -18,21 +18,28 @@ [*]๐Ÿฉบ [b]Left alone:[/b] surgery, mech gestation, pasted bills and the bills you already have. [/list] +[img]https://cdn.blax.at/blax-gaming/defaults/forbid.png[/img] +[list] +[*]๐Ÿ›ก๏ธ [b]Gear rules for your colony and for enemies.[/b] When a pawn goes down or dies, what the game forbids is allowed again if it matches your filter, with hit points and quality ranges. Say enemy weapons only at 50 to 100% and Normal or better, food and medicine always. +[*]โš”๏ธ [b]Once the fight is over,[/b] so no hauler walks into one. A downed colonist's weapon stays forbidden while the colonist lies there, so it picks it up again. +[*]๐Ÿ‘• [b]Stripping can forbid what doesn't match,[/b] such as a Poor tuque. Butchering stays as it is. +[*]๐Ÿฆด [b]Corpses outside the home area[/b] can stay allowed: animals, enemies, the rest. +[*]โš™๏ธ Every rule ships off; ticking one uses a suggested setup you can edit. What visitors, traders and quest lodgers drop stays vanilla. +[/list] [img]https://cdn.blax.at/blax-gaming/defaults/file.png[/img] [list] [*]๐Ÿ“ [b]One file for every save.[/b] Your defaults live in their own file in the game's Config folder (BlaxDefaults/Defaults.xml), shared by every save and never written into one. Add or remove the mod in a running colony. [*]๐Ÿ›Ÿ [b]Hard to lose.[/b] Each write is read back and checked before it replaces the file, the previous version stays as a backup, and a broken file is kept under its own name instead of overwriting the backup. [*]๐Ÿ”Œ [b]Removed a mod?[/b] Its items stay in your defaults, are skipped while it is gone, and work again when it is back. [*]๐Ÿ“‹ [b]Settings page[/b] (Mod settings > Blax Defaults): every default with what it sets, Edit and Forget, and a switch per section. It works from the main menu. -[*]โš ๏ธ [b]Overlap warnings.[/b] Mods that set the same starting settings are named on the settings page and in one window on the first game you load, with "Don't remind me". +[*]โš ๏ธ [b]Overlap warnings.[/b] Mods that do the same things are named on the settings page and in one window on the first game you load, with "Don't remind me". [/list] -๐Ÿงฉ [b]Any DLC combination works,[/b] core only included, and 1.0 needs no DLC for anything. Items from a DLC in a default, such as wastepack in a dumping stockpile, are skipped while that DLC is off and work again when it is back. Anomaly's corpse stockpile and Odyssey's fishing zones are not covered. +๐Ÿงฉ [b]Any DLC combination works,[/b] core only included, and no feature needs a DLC. Items from a DLC in a default, such as wastepack in a dumping stockpile, are skipped while that DLC is off and work again when it is back. Anomaly's corpse stockpile and Odyssey's fishing zones are not covered. [img]https://cdn.blax.at/blax-gaming/defaults/planned.png[/img] -Not in this version yet. Planned for the next releases: +Planned for the next releases: [list] -[*]๐Ÿ›ก๏ธ Forbid rules: when your colonists, slaves, prisoners or enemies go down or die, dropped gear that matches your filter is allowed again once the fight is over. For example enemy weapons and apparel only at 50% hit points or more and Normal quality or better, their food and medicine always. [*]๐Ÿชฆ Graves, sarcophagi, mortars and other storage, defaults per recipe and the bills a new workbench comes with. [*]๐Ÿ„ Animals: area, follow flags and training per species, auto-slaughter limits. [*]๐ŸŒฑ Crops for new growing zones, settings for new doors, lamps, heaters and coolers. @@ -43,13 +50,15 @@ Not in this version yet. Planned for the next releases: Blax Defaults does what these mods do, so you can unsubscribe them. While one is active, the settings page names it. [list] [*]โ™ป๏ธ [FSF] No Default Shelf Storage (the quick setup empties new shelves per kind and leaves hoppers alone) -[*]โ™ป๏ธ Default Ingredient Radius -[*]โ™ป๏ธ Default Bill Ingredient Radius +[*]โ™ป๏ธ Default Ingredient Radius and Default Bill Ingredient Radius +[*]โ™ป๏ธ KilledEnemyAutoAllowed (Continued) (gear rules with every item, corpse switches on) +[*]โ™ป๏ธ Allow Dead Animals (the animal corpse switch) +[*]โ™ป๏ธ Allow Everything (for what downed and dead pawns drop) [/list] [img]https://cdn.blax.at/blax-gaming/defaults/compatibility.png[/img] [list] -[*]โš ๏ธ 1trickPwnyta's Defaults and Set my Defaults set starting settings for stockpiles and shelves too, and 1trickPwnyta's sets values for every new bill. Blax Defaults 1.0 covers those, so set each in one mod. Their bill lists per recipe or per workbench are not in 1.0 (planned for 1.1), so keep those mods for that and for their other defaults. The overlap warning doesn't detect the unofficial Defaults 1.7 repack yet. +[*]โš ๏ธ 1trickPwnyta's Defaults and Set my Defaults set starting settings for stockpiles and shelves too, and 1trickPwnyta's sets values for every new bill. Set each of those in one mod. Their bill lists per recipe or per workbench come in 1.2, so keep those mods for that and their other defaults. The overlap warning doesn't detect the unofficial Defaults 1.7 repack yet. [*]โš ๏ธ [FSF] FrozenSnowFox Tweaks: its "No Default Storage Settings" option does what the quick setup does. Use one of the two. [*]โš ๏ธ Better Workbench Management also sets where the products of new bills go. Set that in one mod only. [*]โœ”๏ธ Replace Stuff: replacing a shelf's material keeps its settings.