feat: slaver requests, brand fixes, Workshop art and in-game tests (1.1)
- Allied outlanders and tribes send a slaver caravan on request at the comms console; vanilla marks slavers as not requestable. - Branding now slows suppression loss (vanilla's suppression stat ignored the brand's factor) and a slave can't be branded twice. - Workshop preview and mod icon in the blax.at CI, with their HTML sources. - Headless in-game test suite (Tests/run-tests.ps1) that saves, reloads and checks every feature without touching the player's mods or saves. - Tools/workshop-stage.ps1 stages a clean copy for Workshop uploads. - Roadmap in docs/roadmap.md.
This commit is contained in:
parent
d331075649
commit
fffa1db866
|
|
@ -2,3 +2,6 @@ Source/**/bin/
|
||||||
Source/**/obj/
|
Source/**/obj/
|
||||||
.vs/
|
.vs/
|
||||||
*.user
|
*.user
|
||||||
|
Tests/**/1.7/
|
||||||
|
Tests/**/bin/
|
||||||
|
Tests/**/obj/
|
||||||
|
|
|
||||||
Binary file not shown.
Binary file not shown.
|
|
@ -21,6 +21,7 @@
|
||||||
<description>Slavery as an everyday part of the rim. Needs Ideology for slaves.
|
<description>Slavery as an everyday part of the rim. Needs Ideology for slaves.
|
||||||
|
|
||||||
- Slavers (caravans and orbital slave ships) show up far more often and bring more slaves.
|
- Slavers (caravans and orbital slave ships) show up far more often and bring more slaves.
|
||||||
|
- Allied outlanders and tribes send a slaver caravan on request (comms console).
|
||||||
- Every caravan and orbital trader may have a slave or two for sale, and settlements keep more.
|
- Every caravan and orbital trader may have a slave or two for sale, and settlements keep more.
|
||||||
- Brand your slaves: a burn mark that shows who owns them. Branded slaves' suppression falls slower.
|
- Brand your slaves: a burn mark that shows who owns them. Branded slaves' suppression falls slower.
|
||||||
- Branded runaways come back: a non-hostile faction that finds one returns them after a few days. Hostile factions keep them.
|
- Branded runaways come back: a non-hostile faction that finds one returns them after a few days. Hostile factions keep them.
|
||||||
|
|
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 11 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 85 KiB |
|
|
@ -0,0 +1 @@
|
||||||
|
3847282171
|
||||||
|
|
@ -19,6 +19,16 @@
|
||||||
</value>
|
</value>
|
||||||
</Operation>
|
</Operation>
|
||||||
|
|
||||||
|
<!-- Vanilla hides the slaver caravans from the comms console's "request trade caravan" (requestable false).
|
||||||
|
Allied outlanders and tribes can now send one. No faction lists the orbital slave ship, so it stays unrequestable. -->
|
||||||
|
<Operation Class="PatchOperationReplace">
|
||||||
|
<success>Always</success>
|
||||||
|
<xpath>Defs/TraderKindDef[defName="Caravan_Outlander_PirateMerchant" or defName="Caravan_Neolithic_Slaver"]/requestable</xpath>
|
||||||
|
<value>
|
||||||
|
<requestable>true</requestable>
|
||||||
|
</value>
|
||||||
|
</Operation>
|
||||||
|
|
||||||
<!-- Vanilla: (0.2, 0) (1, 1) (2, 3), so a big colony never sees slavers. Keep at least half weight. -->
|
<!-- Vanilla: (0.2, 0) (1, 1) (2, 3), so a big colony never sees slavers. Keep at least half weight. -->
|
||||||
<Operation Class="PatchOperationReplace">
|
<Operation Class="PatchOperationReplace">
|
||||||
<success>Always</success>
|
<success>Always</success>
|
||||||
|
|
|
||||||
16
README.md
16
README.md
|
|
@ -4,7 +4,7 @@ RimWorld mod (1.7) that makes slavery an everyday part of the rim. First mod und
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- **Slavers are common.** The three vanilla slavers (outlander "slaver" caravan, tribal "slaver" caravan, orbital "slave ship") get commonality 2 instead of 1, and big colonies keep seeing them at half weight instead of zero. They carry more: outlander 5~9, tribal 4~7, slave ship 6~10 (vanilla 2~4). Every other caravan and orbital trader has a ~50% chance of 1~2 slaves, settlements stock 1~4. `Patches/BlaxSlaves_Traders.xml`
|
- **Slavers are common.** The three vanilla slavers (outlander "slaver" caravan, tribal "slaver" caravan, orbital "slave ship") get commonality 2 instead of 1, and big colonies keep seeing them at half weight instead of zero. They carry more: outlander 5~9, tribal 4~7, slave ship 6~10 (vanilla 2~4). Allied outlanders and tribes send a slaver caravan on request (vanilla hides slavers from the comms console request). Every other caravan and orbital trader has a ~50% chance of 1~2 slaves, settlements stock 1~4. `Patches/BlaxSlaves_Traders.xml`
|
||||||
- **Branding.** "Brand" surgery for colony slaves (adults, Medicine 2, never fails). The brand remembers its owner (shown as "slave brand (Owner)"), slows suppression loss by 15%, gives the slave a -3 "branded" mood and a fresh torso burn. "Rebrand" burns your mark over another owner's. `Defs/BlaxSlaves_Brand.xml`, `Source/BlaxSlaves/Brand.cs`
|
- **Branding.** "Brand" surgery for colony slaves (adults, Medicine 2, never fails). The brand remembers its owner (shown as "slave brand (Owner)"), slows suppression loss by 15%, gives the slave a -3 "branded" mood and a fresh torso burn. "Rebrand" burns your mark over another owner's. `Defs/BlaxSlaves_Brand.xml`, `Source/BlaxSlaves/Brand.cs`
|
||||||
- **Trader slaves come branded.** 35% of adult slaves in trader stock carry the trader faction's brand (orbital ships: a random faction).
|
- **Trader slaves come branded.** 35% of adult slaves in trader stock carry the trader faction's brand (orbital ships: a random faction).
|
||||||
- **Runaways come back.** A slave with your brand who escapes (slave rebellion, or a caravan whose last free member dies) is tracked. If the faction they end up with is hostile, they keep them. Otherwise, after 3~10 days (80% chance) a non-hostile faction returns them as your slave, walking in (tribal/medieval) or by drop pod. `Source/BlaxSlaves/Runaways.cs`
|
- **Runaways come back.** A slave with your brand who escapes (slave rebellion, or a caravan whose last free member dies) is tracked. If the faction they end up with is hostile, they keep them. Otherwise, after 3~10 days (80% chance) a non-hostile faction returns them as your slave, walking in (tribal/medieval) or by drop pod. `Source/BlaxSlaves/Runaways.cs`
|
||||||
|
|
@ -38,6 +38,18 @@ RimWorld 1.7 no longer runs on Unity/Mono. It runs on .NET 10 (CoreCLR) with Lud
|
||||||
- In game, the Harmony mod swaps in a Waylith method-body backend (`HarmonyMod.RuntimeIL.dll`). Check `Player.log` for `[Blax Slaves] N patches applied` and Harmony's `runtime-body provider` line.
|
- In game, the Harmony mod swaps in a Waylith method-body backend (`HarmonyMod.RuntimeIL.dll`). Check `Player.log` for `[Blax Slaves] N patches applied` and Harmony's `runtime-body provider` line.
|
||||||
- Patches are applied from a `[StaticConstructorOnStartup]` class, one class at a time, so one broken target can't disable the rest.
|
- Patches are applied from a `[StaticConstructorOnStartup]` class, one class at a time, so one broken target can't disable the rest.
|
||||||
|
|
||||||
Quick test map: `RimWorld.exe -quicktest`. Dev mode: spawn a slaver caravan, enslave a prisoner, brand them, then trigger a slave rebellion from the debug actions.
|
### Tests
|
||||||
|
|
||||||
|
`Tests/BlaxSlavesTests` is a separate test mod. `Tests/run-tests.ps1` builds both projects, links the test mod into the game's Mods folder for the run, and starts RimWorld headless (`-headless -quicktest -blaxslavestests`, no window) with its own save data folder in `%TEMP%\BlaxSlavesTest`, so your mod list, saves and settings stay untouched. The suite runs in a quick-test colony, saves and reloads the game, runs the persistence tests, writes `BlaxSlavesTestResults.txt` and quits. It takes about a minute and needs Steam running.
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.\Tests\run-tests.ps1
|
||||||
|
```
|
||||||
|
|
||||||
|
`-Compat` also loads the installed mods Blax Slaves has compat code for (Hospitality, Harvest Organs Post Mortem, War Crimes Expanded 2, SYR More Slaves, Everybody Buys Slaves). Exit code 0 means all passed, 1 failures, 2 the run didn't finish (see `game.log` in the data folder).
|
||||||
|
|
||||||
|
Tests are `public static void` methods marked `[BlaxTest("area: what", phase: 1)]`, using `T` for assertions and `Fixtures` for pawns, ticks and memories. Phase 2 runs after the save and reload; carry ThingIDs through `T.Carry`.
|
||||||
|
|
||||||
|
Useful 1.7 switches for manual runs: `-quicktest` (straight into a generated colony), `-headless`, `-savedatafolder=<dir>`, `-QuitAfterBoot`, `-NoFileLog`.
|
||||||
|
|
||||||
A decompiled copy of the 1.7 game code for reference lives outside the repo in `..\rimworld-src-1.7` (never commit or publish it).
|
A decompiled copy of the 1.7 game code for reference lives outside the repo in `..\rimworld-src-1.7` (never commit or publish it).
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,12 @@
|
||||||
|
# Preview art
|
||||||
|
|
||||||
|
`preview.html` renders `About/Preview.png` (1280x720) and `icon.html` renders `About/ModIcon.png` (256x256), in the Blax CI from https://www.blax.at/ui-ci: Blax black `#050805`, Blax green `#19C63C`, logo gray `#CDCDCD`, Geist for headings, Inter for body, Rajdhani only for the "Blax Gaming" wordmark. Fonts are the woff2 files blax.at self-hosts (all SIL Open Font License); icons are lucide.
|
||||||
|
|
||||||
|
Render with Edge headless from this folder:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$edge = 'C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe'
|
||||||
|
$here = (Get-Location).Path -replace '\','/'
|
||||||
|
& $edge --headless=new --disable-gpu --hide-scrollbars --virtual-time-budget=3000 --window-size=1280,720 --screenshot="$PWD\preview.png" "file:///$here/preview.html"
|
||||||
|
& $edge --headless=new --disable-gpu --hide-scrollbars --virtual-time-budget=2000 --window-size=256,256 --default-background-color=00000000 --screenshot="$PWD\icon.png" "file:///$here/icon.html"
|
||||||
|
```
|
||||||
|
|
@ -0,0 +1,16 @@
|
||||||
|
<svg width="980" height="980" viewBox="0 0 980 980" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||||
|
<g clip-path="url(#clip0_477_24)">
|
||||||
|
<circle cx="474.5" cy="474.5" r="474.5" fill="#CDCDCD"/>
|
||||||
|
<circle cx="475" cy="474" r="352" stroke="black" stroke-width="96"/>
|
||||||
|
<path d="M475 226L405 651.616L474.5 778L545 651.616L475 226Z" fill="black"/>
|
||||||
|
<path d="M385 226L475 306L565 226H385Z" fill="black"/>
|
||||||
|
<path d="M875 226H99L131.5 179.542L169.5 139.031L253.5 84.0246L475 45L715 98.1478L875 226Z" fill="#CDCDCD"/>
|
||||||
|
<rect x="287" y="226" width="13" height="13" fill="#CDCDCD"/>
|
||||||
|
<rect x="650" y="226" width="13" height="13" fill="#CDCDCD"/>
|
||||||
|
</g>
|
||||||
|
<defs>
|
||||||
|
<clipPath id="clip0_477_24">
|
||||||
|
<rect width="980" height="980" fill="white"/>
|
||||||
|
</clipPath>
|
||||||
|
</defs>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 740 B |
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
|
@ -0,0 +1,6 @@
|
||||||
|
<!doctype html>
|
||||||
|
<html><head><meta charset="utf-8"><style>
|
||||||
|
html, body { margin: 0; width: 256px; height: 256px; background: transparent; overflow: hidden; }
|
||||||
|
img { display: block; width: 256px; height: 256px; }
|
||||||
|
</style></head>
|
||||||
|
<body><img src="monogram-centered.svg" alt=""></body></html>
|
||||||
|
|
@ -0,0 +1,16 @@
|
||||||
|
<svg width="256" height="256" viewBox="0 0 949 949" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||||
|
<g clip-path="url(#clip0_477_24)">
|
||||||
|
<circle cx="474.5" cy="474.5" r="474.5" fill="#CDCDCD"/>
|
||||||
|
<circle cx="475" cy="474" r="352" stroke="black" stroke-width="96"/>
|
||||||
|
<path d="M475 226L405 651.616L474.5 778L545 651.616L475 226Z" fill="black"/>
|
||||||
|
<path d="M385 226L475 306L565 226H385Z" fill="black"/>
|
||||||
|
<path d="M875 226H99L131.5 179.542L169.5 139.031L253.5 84.0246L475 45L715 98.1478L875 226Z" fill="#CDCDCD"/>
|
||||||
|
<rect x="287" y="226" width="13" height="13" fill="#CDCDCD"/>
|
||||||
|
<rect x="650" y="226" width="13" height="13" fill="#CDCDCD"/>
|
||||||
|
</g>
|
||||||
|
<defs>
|
||||||
|
<clipPath id="clip0_477_24">
|
||||||
|
<rect width="980" height="980" fill="white"/>
|
||||||
|
</clipPath>
|
||||||
|
</defs>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 740 B |
|
|
@ -0,0 +1,74 @@
|
||||||
|
<!doctype html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<style>
|
||||||
|
@font-face { font-family: Geist; src: url(fonts/geist.woff2) format("woff2"); font-weight: 100 900; }
|
||||||
|
@font-face { font-family: Inter; src: url(fonts/inter.woff2) format("woff2"); font-weight: 100 900; }
|
||||||
|
@font-face { font-family: Rajdhani; src: url(fonts/rajdhani-700.woff2) format("woff2"); font-weight: 700; }
|
||||||
|
:root {
|
||||||
|
--background: #050805; /* Blax black */
|
||||||
|
--accent: #19C63C; /* Blax green */
|
||||||
|
--logo-gray: #CDCDCD;
|
||||||
|
--heading: oklch(98% .008 145);
|
||||||
|
--foreground: oklch(97% .01 145);
|
||||||
|
--muted-foreground: oklch(75% .015 145);
|
||||||
|
--border: oklch(30% .016 145);
|
||||||
|
}
|
||||||
|
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||||
|
html, body { width: 1280px; height: 720px; background: var(--background); overflow: hidden; }
|
||||||
|
body { font-family: Inter, sans-serif; color: var(--foreground); position: relative; }
|
||||||
|
|
||||||
|
.top { position: absolute; left: 72px; right: 72px; top: 52px; display: flex; align-items: center; justify-content: space-between; }
|
||||||
|
.brand { display: flex; align-items: center; gap: 16px; }
|
||||||
|
.brand img { width: 56px; height: 56px; }
|
||||||
|
.wordmark { font-family: Rajdhani, sans-serif; font-weight: 700; font-size: 40px; line-height: 1; letter-spacing: -0.01em; color: var(--heading); }
|
||||||
|
.wordmark span { color: var(--accent); }
|
||||||
|
|
||||||
|
.hero { position: absolute; left: 72px; top: 158px; width: 640px; }
|
||||||
|
h1 { font-family: Geist, sans-serif; font-weight: 600; font-size: 178px; line-height: .9; letter-spacing: -0.045em; color: var(--heading); }
|
||||||
|
.sub { margin-top: 26px; font-family: Geist, sans-serif; font-weight: 600; font-size: 46px; line-height: 1; letter-spacing: -0.03em; color: var(--accent); }
|
||||||
|
.lede { margin-top: 18px; font-size: 23px; line-height: 1.4; color: var(--muted-foreground); max-width: 560px; }
|
||||||
|
|
||||||
|
.features { position: absolute; left: 760px; right: 72px; top: 150px; bottom: 56px; display: flex; flex-direction: column; border-left: 1px solid var(--border); }
|
||||||
|
.feature { flex: 1; display: flex; align-items: center; gap: 24px; padding-left: 40px; border-top: 1px solid var(--border); }
|
||||||
|
.feature:first-child { border-top: 0; }
|
||||||
|
.feature svg { width: 40px; height: 40px; flex: none; color: var(--accent); }
|
||||||
|
.feature h2 { font-family: Geist, sans-serif; font-weight: 600; font-size: 31px; line-height: 1.05; letter-spacing: -0.03em; color: var(--heading); }
|
||||||
|
.feature p { margin-top: 6px; font-size: 19px; line-height: 1.35; color: var(--muted-foreground); }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="top">
|
||||||
|
<div class="brand">
|
||||||
|
<img src="blax-monogram.svg" alt="">
|
||||||
|
<div class="wordmark">Blax <span>Gaming</span></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="hero">
|
||||||
|
<h1>Blax<br>Slaves</h1>
|
||||||
|
<div class="sub">for RimWorld 1.7</div>
|
||||||
|
<p class="lede">Slavers, brands and runaways that come back.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="features">
|
||||||
|
<div class="feature">
|
||||||
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M13.744 17.736a6 6 0 1 1-7.48-7.48M15 6h1v4"/><path d="m6.134 14.768l.866-.5l2 3.464"/><circle cx="16" cy="8" r="6"/></svg>
|
||||||
|
<div><h2>More slavers</h2><p>Slave caravans and ships visit often.</p></div>
|
||||||
|
</div>
|
||||||
|
<div class="feature">
|
||||||
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3q1 4 4 6.5t3 5.5a1 1 0 0 1-14 0a5 5 0 0 1 1-3a1 1 0 0 0 5 0c0-2-1.5-3-1.5-5q0-2 2.5-4"/></svg>
|
||||||
|
<div><h2>Branding</h2><p>Mark every slave with your faction.</p></div>
|
||||||
|
</div>
|
||||||
|
<div class="feature">
|
||||||
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 14L4 9l5-5"/><path d="M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11"/></svg>
|
||||||
|
<div><h2>Runaways return</h2><p>Friendly factions bring them back.</p></div>
|
||||||
|
</div>
|
||||||
|
<div class="feature">
|
||||||
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M8 14s1.5 2 4 2s4-2 4-2M9 9h.01M15 9h.01"/></svg>
|
||||||
|
<div><h2>Calm colonists</h2><p>No mood hit, unless they're pacifists.</p></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
|
@ -63,6 +63,20 @@ namespace BlaxSlaves
|
||||||
public static HediffComp_BrandOwner BrandOf(Pawn pawn) =>
|
public static HediffComp_BrandOwner BrandOf(Pawn pawn) =>
|
||||||
pawn?.health?.hediffSet?.GetFirstHediffOfDef(BlaxDefOf.BlaxSlaves_SlaveBrand)?.TryGetComp<HediffComp_BrandOwner>();
|
pawn?.health?.hediffSet?.GetFirstHediffOfDef(BlaxDefOf.BlaxSlaves_SlaveBrand)?.TryGetComp<HediffComp_BrandOwner>();
|
||||||
|
|
||||||
|
/// <summary>The brand stage's SlaveSuppressionFallRate factor (from the def), 1 without a brand.</summary>
|
||||||
|
public static float SuppressionFallFactor(Pawn pawn, out Hediff brand)
|
||||||
|
{
|
||||||
|
brand = pawn?.health?.hediffSet?.GetFirstHediffOfDef(BlaxDefOf.BlaxSlaves_SlaveBrand);
|
||||||
|
List<StatModifier> factors = brand?.CurStage?.statFactors;
|
||||||
|
if (factors == null || StatDefOf.SlaveSuppressionFallRate == null)
|
||||||
|
return 1f;
|
||||||
|
float f = 1f;
|
||||||
|
foreach (StatModifier m in factors)
|
||||||
|
if (m.stat == StatDefOf.SlaveSuppressionFallRate)
|
||||||
|
f *= m.value;
|
||||||
|
return f;
|
||||||
|
}
|
||||||
|
|
||||||
public static bool IsBrandedByPlayer(Pawn pawn)
|
public static bool IsBrandedByPlayer(Pawn pawn)
|
||||||
{
|
{
|
||||||
HediffComp_BrandOwner brand = BrandOf(pawn);
|
HediffComp_BrandOwner brand = BrandOf(pawn);
|
||||||
|
|
@ -112,8 +126,17 @@ namespace BlaxSlaves
|
||||||
public override bool AvailableOnNow(Thing thing, BodyPartRecord part = null) =>
|
public override bool AvailableOnNow(Thing thing, BodyPartRecord part = null) =>
|
||||||
thing is Pawn pawn && pawn.IsSlaveOfColony && base.AvailableOnNow(thing, part);
|
thing is Pawn pawn && pawn.IsSlaveOfColony && base.AvailableOnNow(thing, part);
|
||||||
|
|
||||||
|
// A bill queued before the slave got branded (bought back, handed over) must not stack a second
|
||||||
|
// brand on top; taking over someone else's brand is the rebrand surgery.
|
||||||
public override bool CompletableEver(Pawn surgeryTarget) =>
|
public override bool CompletableEver(Pawn surgeryTarget) =>
|
||||||
base.CompletableEver(surgeryTarget) && surgeryTarget.IsSlaveOfColony;
|
base.CompletableEver(surgeryTarget) && surgeryTarget.IsSlaveOfColony && !BrandUtility.IsBranded(surgeryTarget);
|
||||||
|
|
||||||
|
public override void ApplyOnPawn(Pawn pawn, BodyPartRecord part, Pawn billDoer, List<Thing> ingredients, Bill bill)
|
||||||
|
{
|
||||||
|
if (BrandUtility.IsBranded(pawn))
|
||||||
|
return;
|
||||||
|
base.ApplyOnPawn(pawn, part, billDoer, ingredients, bill);
|
||||||
|
}
|
||||||
|
|
||||||
protected override void OnSurgerySuccess(Pawn pawn, BodyPartRecord part, Pawn billDoer, List<Thing> ingredients, Bill bill)
|
protected override void OnSurgerySuccess(Pawn pawn, BodyPartRecord part, Pawn billDoer, List<Thing> ingredients, Bill bill)
|
||||||
{
|
{
|
||||||
|
|
@ -197,3 +220,40 @@ namespace BlaxSlaves
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
namespace BlaxSlaves
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// StatWorker_SuppressionFallRate overrides GetValueUnfinalized without the hediff stat factors the
|
||||||
|
/// base worker applies, so the brand stage's SlaveSuppressionFallRate factor would do nothing.
|
||||||
|
/// Applies the brand's factor (and only that one, so other mods' hediffs keep vanilla behaviour).
|
||||||
|
/// </summary>
|
||||||
|
[HarmonyPatch(typeof(StatWorker_SuppressionFallRate), nameof(StatWorker_SuppressionFallRate.GetValueUnfinalized))]
|
||||||
|
public static class Patch_BrandSuppressionFallRate
|
||||||
|
{
|
||||||
|
public static void Postfix(StatRequest req, ref float __result)
|
||||||
|
{
|
||||||
|
float f = BrandUtility.SuppressionFallFactor(req.Thing as Pawn, out _);
|
||||||
|
if (f != 1f)
|
||||||
|
__result *= f;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Shows the brand's factor in the stat breakdown and the suppression tooltip.</summary>
|
||||||
|
[HarmonyPatch]
|
||||||
|
public static class Patch_BrandSuppressionFallRateExplanation
|
||||||
|
{
|
||||||
|
public static IEnumerable<System.Reflection.MethodBase> TargetMethods()
|
||||||
|
{
|
||||||
|
yield return AccessTools.Method(typeof(StatWorker_SuppressionFallRate), nameof(StatWorker_SuppressionFallRate.GetExplanationUnfinalized));
|
||||||
|
yield return AccessTools.Method(typeof(StatWorker_SuppressionFallRate), nameof(StatWorker_SuppressionFallRate.GetExplanationForTooltip));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void Postfix(StatRequest req, ref string __result)
|
||||||
|
{
|
||||||
|
float f = BrandUtility.SuppressionFallFactor(req.Thing as Pawn, out Hediff brand);
|
||||||
|
if (f != 1f && brand != null)
|
||||||
|
__result = __result.TrimEnd() + "\n " + brand.LabelBaseCap + ": x" + f.ToStringPercent();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,19 @@
|
||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<ModMetaData>
|
||||||
|
<name>Blax Slaves Tests</name>
|
||||||
|
<author>Blax Gaming</author>
|
||||||
|
<packageId>blax.slaves.tests</packageId>
|
||||||
|
<supportedVersions>
|
||||||
|
<li>1.7</li>
|
||||||
|
</supportedVersions>
|
||||||
|
<modDependencies>
|
||||||
|
<li>
|
||||||
|
<packageId>blax.slaves</packageId>
|
||||||
|
<displayName>Blax Slaves</displayName>
|
||||||
|
</li>
|
||||||
|
</modDependencies>
|
||||||
|
<loadAfter>
|
||||||
|
<li>blax.slaves</li>
|
||||||
|
</loadAfter>
|
||||||
|
<description>In-game test suite for Blax Slaves. Does nothing unless the game is started with -blaxslavestests (see Tests/run-tests.ps1). Not for players.</description>
|
||||||
|
</ModMetaData>
|
||||||
|
|
@ -0,0 +1,45 @@
|
||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<!-- In-game test suite. Built and run by Tests/run-tests.ps1; the DLL is not committed. -->
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<AssemblyName>BlaxSlavesTests</AssemblyName>
|
||||||
|
<RootNamespace>BlaxSlavesTests</RootNamespace>
|
||||||
|
<LangVersion>latest</LangVersion>
|
||||||
|
<Nullable>disable</Nullable>
|
||||||
|
<ImplicitUsings>disable</ImplicitUsings>
|
||||||
|
<OutputPath>..\1.7\Assemblies\</OutputPath>
|
||||||
|
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
|
||||||
|
<AppendRuntimeIdentifierToOutputPath>false</AppendRuntimeIdentifierToOutputPath>
|
||||||
|
<GenerateDependencyFile>false</GenerateDependencyFile>
|
||||||
|
<CopyLocalLockFileAssemblies>false</CopyLocalLockFileAssemblies>
|
||||||
|
<DebugType>portable</DebugType>
|
||||||
|
<PathMap>$(MSBuildProjectDirectory)=Tests/BlaxSlavesTests/Source</PathMap>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<RimWorldDir Condition="'$(RimWorldDir)' == ''">E:\SteamLibrary\steamapps\common\RimWorld</RimWorldDir>
|
||||||
|
<HarmonyDir Condition="'$(HarmonyDir)' == ''">E:\SteamLibrary\steamapps\workshop\content\294100\2009463077\1.7\Assemblies</HarmonyDir>
|
||||||
|
<BlaxSlavesDir Condition="'$(BlaxSlavesDir)' == ''">$(MSBuildProjectDirectory)\..\..\..\1.7\Assemblies</BlaxSlavesDir>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Reference Include="Assembly-CSharp">
|
||||||
|
<HintPath>$(RimWorldDir)\Assembly-CSharp.dll</HintPath>
|
||||||
|
<Private>false</Private>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="UnityStubs">
|
||||||
|
<HintPath>$(RimWorldDir)\UnityStubs.dll</HintPath>
|
||||||
|
<Private>false</Private>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="0Harmony">
|
||||||
|
<HintPath>$(HarmonyDir)\0Harmony.dll</HintPath>
|
||||||
|
<Private>false</Private>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="BlaxSlaves">
|
||||||
|
<HintPath>$(BlaxSlavesDir)\BlaxSlaves.dll</HintPath>
|
||||||
|
<Private>false</Private>
|
||||||
|
</Reference>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
|
|
@ -0,0 +1,622 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using BlaxSlaves;
|
||||||
|
using HarmonyLib;
|
||||||
|
using RimWorld;
|
||||||
|
using Verse;
|
||||||
|
|
||||||
|
namespace BlaxSlavesTests
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Branding and rebranding surgeries, the brand hediff, its owner comp, the Branded mood and
|
||||||
|
/// the suppression factor, plus persistence of the owner over save and reload.
|
||||||
|
/// Surgeries run the way a doctor's bill finishes: a Bill_Medical queued through
|
||||||
|
/// HealthCardUtility.CreateSurgeryBill, then Bill_Medical.Notify_IterationCompleted (what
|
||||||
|
/// Toils_Recipe.FinishRecipeAndStartStoringProduct calls), which checks CompletableEver and calls
|
||||||
|
/// the recipe worker's ApplyOnPawn with the doctor and an empty ingredient list.
|
||||||
|
/// </summary>
|
||||||
|
public static class BrandTests
|
||||||
|
{
|
||||||
|
private const string GoneOwnerName = "Blax Vanished Masters";
|
||||||
|
|
||||||
|
// ---- availability ----------------------------------------------------------------
|
||||||
|
|
||||||
|
[BlaxTest("brand: surgery offered for colony slaves only, and only once")]
|
||||||
|
public static void BrandAvailability()
|
||||||
|
{
|
||||||
|
RecipeDef recipe = BrandRecipe;
|
||||||
|
T.Check(recipe.AvailableNow, "BlaxSlaves_BrandSlave.AvailableNow is false (research/meme prerequisite?), so the operations tab never lists it");
|
||||||
|
var worker = recipe.Worker as Recipe_BrandSlave;
|
||||||
|
T.NotNull(worker, "BlaxSlaves_BrandSlave worker as Recipe_BrandSlave (got " + recipe.Worker?.GetType().Name + ")");
|
||||||
|
|
||||||
|
Pawn slave = Fixtures.ColonySlave();
|
||||||
|
T.Check(slave.IsSlaveOfColony, "fixture slave is not a slave of the colony");
|
||||||
|
T.Check(Offered(recipe, slave), "brand surgery not offered for an unbranded colony slave");
|
||||||
|
T.Check(worker.CompletableEver(slave), "Recipe_BrandSlave.CompletableEver is false for an unbranded colony slave");
|
||||||
|
|
||||||
|
Pawn colonist = Fixtures.Colonist();
|
||||||
|
T.Check(!Offered(recipe, colonist), "brand surgery offered for a free colonist");
|
||||||
|
T.Check(!worker.CompletableEver(colonist), "Recipe_BrandSlave.CompletableEver is true for a free colonist");
|
||||||
|
|
||||||
|
Pawn prisoner = Prisoner();
|
||||||
|
T.Check(prisoner.IsPrisonerOfColony, "prisoner fixture is not a prisoner of the colony");
|
||||||
|
T.Check(!Offered(recipe, prisoner), "brand surgery offered for a prisoner");
|
||||||
|
T.Check(!worker.CompletableEver(prisoner), "Recipe_BrandSlave.CompletableEver is true for a prisoner");
|
||||||
|
|
||||||
|
Pawn ours = Fixtures.ColonySlave();
|
||||||
|
BrandUtility.Brand(ours, Faction.OfPlayer);
|
||||||
|
T.Check(!Offered(recipe, ours), "brand surgery offered again for a slave that already carries our brand");
|
||||||
|
|
||||||
|
Pawn foreign = Fixtures.ColonySlave();
|
||||||
|
Faction other = OtherFaction(foreign.SlaveFaction);
|
||||||
|
if (other != null)
|
||||||
|
{
|
||||||
|
BrandUtility.Brand(foreign, other);
|
||||||
|
T.Check(!Offered(recipe, foreign), "brand surgery offered for a slave branded by " + other.Name + " (that's the rebrand's job)");
|
||||||
|
}
|
||||||
|
else T.Info("no second non-player faction; skipped the foreign-brand case");
|
||||||
|
|
||||||
|
T.Check(!recipe.CompatibleWithHediff(BlaxDefOf.BlaxSlaves_SlaveBrand),
|
||||||
|
"BlaxSlaves_BrandSlave is compatible with the brand hediff: incompatibleWithHediffTags no longer matches the BlaxSlaves_Brand tag");
|
||||||
|
|
||||||
|
QueueBill(slave, recipe);
|
||||||
|
T.Check(!Offered(recipe, slave), "brand surgery offered a second time while a brand bill is already queued");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("brand: stale brand bill can't complete on a slave branded meanwhile")]
|
||||||
|
public static void StaleBrandBillOnBrandedSlave()
|
||||||
|
{
|
||||||
|
Pawn doctor = Fixtures.Colonist();
|
||||||
|
Pawn slave = Fixtures.ColonySlave();
|
||||||
|
Faction other = OtherFaction(slave.SlaveFaction);
|
||||||
|
if (other == null) T.Skip("no second non-player faction to brand the slave with");
|
||||||
|
|
||||||
|
Bill_Medical bill = QueueBill(slave, BrandRecipe);
|
||||||
|
BrandUtility.Brand(slave, other);
|
||||||
|
Hediff brand = BrandHediff(slave);
|
||||||
|
T.NotNull(brand, "brand hediff after BrandUtility.Brand");
|
||||||
|
float severityBefore = brand.Severity;
|
||||||
|
|
||||||
|
bool completable = ((Recipe_BrandSlave)BrandRecipe.Worker).CompletableEver(slave);
|
||||||
|
bool billCompletable = bill.CompletableEver;
|
||||||
|
FinishBill(bill, doctor, 51002);
|
||||||
|
|
||||||
|
HediffComp_BrandOwner comp = BrandUtility.BrandOf(slave);
|
||||||
|
int count = BrandCount(slave);
|
||||||
|
float severityAfter = BrandHediff(slave)?.Severity ?? -1f;
|
||||||
|
bool untouched = comp != null && comp.owner == other && count == 1 && Math.Abs(severityAfter - severityBefore) < 0.001f;
|
||||||
|
T.Check(!completable && !billCompletable && untouched,
|
||||||
|
$"slave already branded by {other.Name}: Recipe_BrandSlave.CompletableEver={completable}, Bill_Medical.CompletableEver={billCompletable} (expected both false). " +
|
||||||
|
$"Finishing the stale brand bill left owner={comp?.OwnerName ?? "no brand"}, brand hediffs={count}, brand severity {severityBefore}->{severityAfter}; " +
|
||||||
|
"expected the brand untouched (taking over someone else's brand is the rebrand surgery)");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("rebrand: offered only for another owner's brand, and only once")]
|
||||||
|
public static void RebrandAvailability()
|
||||||
|
{
|
||||||
|
RecipeDef recipe = RebrandRecipe;
|
||||||
|
T.Check(recipe.AvailableNow, "BlaxSlaves_RebrandSlave.AvailableNow is false, so the operations tab never lists it");
|
||||||
|
var worker = recipe.Worker as Recipe_RebrandSlave;
|
||||||
|
T.NotNull(worker, "BlaxSlaves_RebrandSlave worker as Recipe_RebrandSlave (got " + recipe.Worker?.GetType().Name + ")");
|
||||||
|
|
||||||
|
Pawn foreign = Fixtures.ColonySlave();
|
||||||
|
Faction other = OtherFaction(foreign.SlaveFaction);
|
||||||
|
if (other == null) T.Skip("no second non-player faction to brand the slave with");
|
||||||
|
BrandUtility.Brand(foreign, other);
|
||||||
|
T.Check(Offered(recipe, foreign), "rebrand not offered for a colony slave branded by " + other.Name);
|
||||||
|
T.Check(worker.CompletableEver(foreign), "Recipe_RebrandSlave.CompletableEver is false for a colony slave branded by " + other.Name);
|
||||||
|
|
||||||
|
Pawn ours = Fixtures.ColonySlave();
|
||||||
|
BrandUtility.Brand(ours, Faction.OfPlayer);
|
||||||
|
T.Check(!Offered(recipe, ours), "rebrand offered for a slave that already carries our brand");
|
||||||
|
T.Check(!worker.CompletableEver(ours), "Recipe_RebrandSlave.CompletableEver is true for a slave with our brand");
|
||||||
|
|
||||||
|
Pawn plain = Fixtures.ColonySlave();
|
||||||
|
T.Check(!Offered(recipe, plain), "rebrand offered for an unbranded slave");
|
||||||
|
T.Check(!worker.CompletableEver(plain), "Recipe_RebrandSlave.CompletableEver is true for an unbranded slave");
|
||||||
|
|
||||||
|
Pawn freeBranded = Fixtures.Colonist();
|
||||||
|
BrandUtility.Brand(freeBranded, other);
|
||||||
|
T.Check(!Offered(recipe, freeBranded), "rebrand offered for a free colonist carrying " + other.Name + "'s brand");
|
||||||
|
T.Check(!worker.CompletableEver(freeBranded), "Recipe_RebrandSlave.CompletableEver is true for a free colonist");
|
||||||
|
|
||||||
|
// Owner faction gone: after a reload the reference is null and only the name is cached.
|
||||||
|
Pawn orphan = Fixtures.ColonySlave();
|
||||||
|
BrandUtility.Brand(orphan, other);
|
||||||
|
BrandUtility.BrandOf(orphan).owner = null;
|
||||||
|
T.Check(Offered(recipe, orphan), "rebrand not offered for a slave whose brand owner faction is gone (owner null)");
|
||||||
|
T.Check(worker.CompletableEver(orphan), "Recipe_RebrandSlave.CompletableEver is false for a slave whose brand owner faction is gone (owner null)");
|
||||||
|
|
||||||
|
QueueBill(foreign, recipe);
|
||||||
|
T.Check(!Offered(recipe, foreign), "rebrand offered a second time while a rebrand bill is already queued");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- performing the surgeries ----------------------------------------------------
|
||||||
|
|
||||||
|
[BlaxTest("brand: surgery marks a colony slave as ours with a clean fresh burn")]
|
||||||
|
public static void BrandSurgeryOutcome()
|
||||||
|
{
|
||||||
|
RecipeDef recipe = BrandRecipe;
|
||||||
|
T.Check(recipe.surgeryOutcomeEffect == null,
|
||||||
|
"BlaxSlaves_BrandSlave.surgeryOutcomeEffect is " + recipe.surgeryOutcomeEffect +
|
||||||
|
"; Recipe_Surgery.CheckSurgeryFail only skips the failure roll when it is null, so branding can fail");
|
||||||
|
|
||||||
|
Pawn doctor = Fixtures.Colonist();
|
||||||
|
Pawn slave = Fixtures.ColonySlave();
|
||||||
|
ClearInjuries(slave);
|
||||||
|
T.Check(!BrandUtility.IsBranded(slave), "fresh fixture slave is already branded");
|
||||||
|
|
||||||
|
PerformSurgery(slave, recipe, doctor, 51001);
|
||||||
|
|
||||||
|
Hediff brand = BrandHediff(slave);
|
||||||
|
T.NotNull(brand, "hediff BlaxSlaves_SlaveBrand after the brand bill finished");
|
||||||
|
T.Equal(1, BrandCount(slave), "brand hediffs on the slave");
|
||||||
|
HediffComp_BrandOwner comp = brand.TryGetComp<HediffComp_BrandOwner>();
|
||||||
|
T.NotNull(comp, "HediffComp_BrandOwner on the brand");
|
||||||
|
T.Check(comp.owner == Faction.OfPlayer, "brand owner after the surgery: expected the player faction, got " + (comp.owner?.Name ?? "null"));
|
||||||
|
T.Equal(Faction.OfPlayer.Name, comp.ownerName, "cached owner name after the surgery");
|
||||||
|
T.Check(BrandUtility.IsBrandedByPlayer(slave), "BrandUtility.IsBrandedByPlayer is false right after our surgery");
|
||||||
|
T.Check(slave.IsSlaveOfColony, "slave lost slave status during the surgery");
|
||||||
|
|
||||||
|
CheckFreshBurn(slave, "after branding");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("rebrand: finishing the bill makes another owner's brand ours")]
|
||||||
|
public static void RebrandSurgeryOutcome()
|
||||||
|
{
|
||||||
|
RecipeDef recipe = RebrandRecipe;
|
||||||
|
T.Check(recipe.surgeryOutcomeEffect == null, "BlaxSlaves_RebrandSlave.surgeryOutcomeEffect is " + recipe.surgeryOutcomeEffect + " (should be cleared like the brand's)");
|
||||||
|
|
||||||
|
Pawn doctor = Fixtures.Colonist();
|
||||||
|
Pawn slave = Fixtures.ColonySlave();
|
||||||
|
Faction other = OtherFaction(slave.SlaveFaction);
|
||||||
|
if (other == null) T.Skip("no second non-player faction to brand the slave with");
|
||||||
|
ClearInjuries(slave);
|
||||||
|
BrandUtility.Brand(slave, other);
|
||||||
|
T.Check(BrandUtility.BrandOf(slave)?.owner == other, "setup: brand owner is not " + other.Name);
|
||||||
|
|
||||||
|
PerformSurgery(slave, recipe, doctor, 51003);
|
||||||
|
|
||||||
|
HediffComp_BrandOwner comp = BrandUtility.BrandOf(slave);
|
||||||
|
T.NotNull(comp, "brand owner comp after the rebrand");
|
||||||
|
T.Check(comp.owner == Faction.OfPlayer, $"brand owner after the rebrand: expected the player faction, got {comp.owner?.Name ?? "null"} (was {other.Name})");
|
||||||
|
T.Equal(Faction.OfPlayer.Name, comp.ownerName, "cached owner name after the rebrand");
|
||||||
|
T.Equal(1, BrandCount(slave), "brand hediffs after the rebrand (it should reuse the existing brand)");
|
||||||
|
CheckFreshBurn(slave, "after rebranding");
|
||||||
|
T.Check(!Offered(recipe, slave), "rebrand still offered once the brand is ours");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- mood and suppression --------------------------------------------------------
|
||||||
|
|
||||||
|
[BlaxTest("brand: Branded mood while a slave, gone once emancipated")]
|
||||||
|
public static void BrandedThoughtFollowsSlaveStatus()
|
||||||
|
{
|
||||||
|
ThoughtDef thought = BrandedThought;
|
||||||
|
T.Check(thought.Worker is ThoughtWorker_Branded, "BlaxSlaves_Branded worker is " + thought.Worker?.GetType().Name + ", not ThoughtWorker_Branded");
|
||||||
|
|
||||||
|
Pawn doctor = Fixtures.Colonist();
|
||||||
|
// An enslaved colonist: their home faction is ours, so vanilla emancipation frees them on
|
||||||
|
// the spot instead of sending them off the map while still a slave.
|
||||||
|
Pawn slave = Fixtures.Colonist();
|
||||||
|
slave.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Slave);
|
||||||
|
T.Check(slave.IsSlaveOfColony, "setup: enslaved colonist is not a slave of the colony");
|
||||||
|
T.Check(!thought.Worker.CurrentState(slave).Active, "unbranded slave already has the Branded thought");
|
||||||
|
|
||||||
|
PerformSurgery(slave, BrandRecipe, doctor, 51004);
|
||||||
|
T.Check(BrandUtility.IsBranded(slave), "slave not branded after the brand bill finished");
|
||||||
|
|
||||||
|
T.Check(thought.Worker.CurrentState(slave).Active, "BlaxSlaves_Branded inactive for a branded slave");
|
||||||
|
T.Check(HasMoodThought(slave, thought), "BlaxSlaves_Branded worker is active but the thought is not among the slave's mood thoughts");
|
||||||
|
|
||||||
|
GenGuest.EmancipateSlave(doctor, slave);
|
||||||
|
if (slave.IsSlave)
|
||||||
|
T.Skip("vanilla GenGuest.EmancipateSlave left the pawn a slave (home faction " + slave.HomeFaction?.Name + "); can't check the freed state");
|
||||||
|
|
||||||
|
T.Check(BrandUtility.IsBranded(slave), "the brand disappeared on emancipation; the scar should stay");
|
||||||
|
// Control: a plain ThoughtWorker_Hediff for the same def must still fire for the freed pawn.
|
||||||
|
// Otherwise the thought is off for another reason (CanGetThought, missing hediff) and the
|
||||||
|
// check below would pass without the slave gate doing anything.
|
||||||
|
var plain = new ThoughtWorker_Hediff { def = thought };
|
||||||
|
if (!plain.CurrentState(slave).Active)
|
||||||
|
T.Skip("control: a plain ThoughtWorker_Hediff for BlaxSlaves_Branded is inactive for the freed, still branded pawn; can't attribute the freed state to ThoughtWorker_Branded");
|
||||||
|
T.Check(!thought.Worker.CurrentState(slave).Active, "BlaxSlaves_Branded still active after the slave was emancipated");
|
||||||
|
T.Check(!HasMoodThought(slave, thought), "BlaxSlaves_Branded still among the mood thoughts after emancipation");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("brand: slave suppression falls slower with the brand")]
|
||||||
|
public static void BrandSlowsSuppressionFall()
|
||||||
|
{
|
||||||
|
if (!ModsConfig.IdeologyActive) T.Skip("Ideology inactive: no suppression");
|
||||||
|
StatDef stat = StatDefOf.SlaveSuppressionFallRate;
|
||||||
|
T.NotNull(stat, "StatDefOf.SlaveSuppressionFallRate");
|
||||||
|
|
||||||
|
Pawn doctor = Fixtures.Colonist();
|
||||||
|
Pawn slave = Fixtures.ColonySlave();
|
||||||
|
ClearInjuries(slave);
|
||||||
|
// Worn gear's SlaveSuppressionOffset is subtracted by a stat part and the stat clamps at 0
|
||||||
|
// (a collar plus a head cover would zero it), so measure without random generated apparel.
|
||||||
|
slave.apparel?.DestroyAll();
|
||||||
|
Need_Suppression need = slave.needs?.TryGetNeed<Need_Suppression>();
|
||||||
|
T.NotNull(need, "suppression need of the colony slave");
|
||||||
|
|
||||||
|
// The real path: Pawn_NeedsTracker calls Need_Suppression.NeedInterval every 150 ticks,
|
||||||
|
// which lowers CurLevel by 0.0025 x SlaveSuppressionFallRate. Measured at a fixed 50%.
|
||||||
|
float dropBefore = SuppressionDrop(need);
|
||||||
|
PerformSurgery(slave, BrandRecipe, doctor, 51005);
|
||||||
|
Hediff brand = BrandHediff(slave);
|
||||||
|
T.NotNull(brand, "brand hediff after the brand bill finished");
|
||||||
|
|
||||||
|
float dropBranded = SuppressionDrop(need);
|
||||||
|
need.CurLevelPercentage = 0.5f;
|
||||||
|
float statBranded = slave.GetStatValue(stat);
|
||||||
|
// Take the brand alone off again (the fresh burn stays), so the brand is the only difference.
|
||||||
|
slave.health.RemoveHediff(brand);
|
||||||
|
float dropRemoved = SuppressionDrop(need);
|
||||||
|
need.CurLevelPercentage = 0.5f;
|
||||||
|
float statRemoved = slave.GetStatValue(stat);
|
||||||
|
T.Info($"suppression drop per NeedInterval at 50%: unbranded {dropBefore:F6}, branded {dropBranded:F6}, brand removed {dropRemoved:F6}; " +
|
||||||
|
$"SlaveSuppressionFallRate branded {statBranded}, brand removed {statRemoved}");
|
||||||
|
|
||||||
|
if (dropRemoved <= 0f)
|
||||||
|
T.Skip($"suppression did not fall in Need_Suppression.NeedInterval without the brand (drop {dropRemoved}; need frozen or fall rate 0); nothing for the brand to slow");
|
||||||
|
T.Check(dropBranded < dropRemoved - 1e-6f,
|
||||||
|
$"suppression fell by {dropBranded:F6} per NeedInterval with the brand and by {dropRemoved:F6} without it " +
|
||||||
|
$"(SlaveSuppressionFallRate {statBranded} vs {statRemoved}); expected the brand stage's x0.85 to slow it. " +
|
||||||
|
"StatWorker_SuppressionFallRate overrides GetValueUnfinalized without applying hediff statFactors");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Suppression lost in one vanilla Need_Suppression.NeedInterval call, starting from 50%.</summary>
|
||||||
|
private static float SuppressionDrop(Need_Suppression need)
|
||||||
|
{
|
||||||
|
need.CurLevelPercentage = 0.5f;
|
||||||
|
float before = need.CurLevel;
|
||||||
|
need.NeedInterval();
|
||||||
|
float drop = before - need.CurLevel;
|
||||||
|
need.CurLevelPercentage = 0.5f;
|
||||||
|
return drop;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- owner name ------------------------------------------------------------------
|
||||||
|
|
||||||
|
[BlaxTest("brand: owner name in label and tooltip, cached name once the faction is gone")]
|
||||||
|
public static void BrandOwnerNameShown()
|
||||||
|
{
|
||||||
|
Pawn doctor = Fixtures.Colonist();
|
||||||
|
Pawn ours = Fixtures.ColonySlave();
|
||||||
|
PerformSurgery(ours, BrandRecipe, doctor, 51006);
|
||||||
|
CheckNameShown(ours, Faction.OfPlayer.Name, "our brand");
|
||||||
|
|
||||||
|
Pawn foreign = Fixtures.ColonySlave();
|
||||||
|
Faction other = OtherFaction(foreign.SlaveFaction);
|
||||||
|
if (other != null)
|
||||||
|
{
|
||||||
|
BrandUtility.Brand(foreign, other);
|
||||||
|
CheckNameShown(foreign, other.Name, other.Name + "'s brand");
|
||||||
|
}
|
||||||
|
else T.Info("no second non-player faction; skipped the foreign-brand case");
|
||||||
|
|
||||||
|
// A faction that is not in the world any more. After a reload CompExposeData leaves the
|
||||||
|
// reference null and only the cached name; the phase-2 test covers that real save.
|
||||||
|
Pawn orphan = Fixtures.ColonySlave();
|
||||||
|
BrandUtility.Brand(orphan, GoneFaction(GoneOwnerName));
|
||||||
|
HediffComp_BrandOwner comp = BrandUtility.BrandOf(orphan);
|
||||||
|
T.NotNull(comp, "brand owner comp of the orphan slave");
|
||||||
|
T.Equal(GoneOwnerName, comp.ownerName, "cached owner name right after branding");
|
||||||
|
comp.owner = null;
|
||||||
|
T.Equal(GoneOwnerName, comp.OwnerName, "OwnerName with the owner faction gone");
|
||||||
|
CheckNameShown(orphan, GoneOwnerName, "brand whose owner faction is gone");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- persistence -----------------------------------------------------------------
|
||||||
|
|
||||||
|
[BlaxTest("brand: set up branded slaves for reload")]
|
||||||
|
public static void SetupForReload()
|
||||||
|
{
|
||||||
|
Pawn doctor = Fixtures.Colonist();
|
||||||
|
|
||||||
|
Pawn ours = Fixtures.Keep(Fixtures.ColonySlave());
|
||||||
|
ClearInjuries(ours);
|
||||||
|
PerformSurgery(ours, BrandRecipe, doctor, 51007);
|
||||||
|
T.Check(BrandUtility.IsBrandedByPlayer(ours), "setup: our slave is not branded by the player");
|
||||||
|
Calm(ours);
|
||||||
|
T.Carry["brand.ours"] = ours.ThingID;
|
||||||
|
T.Carry["brand.ours.name"] = Faction.OfPlayer.Name;
|
||||||
|
|
||||||
|
Pawn orphan = Fixtures.Keep(Fixtures.ColonySlave());
|
||||||
|
Faction gone = GoneFaction(GoneOwnerName);
|
||||||
|
BrandUtility.Brand(orphan, gone);
|
||||||
|
T.Check(BrandUtility.BrandOf(orphan)?.owner == gone, "setup: orphan brand owner is not the gone faction");
|
||||||
|
Calm(orphan);
|
||||||
|
T.Carry["brand.gone"] = orphan.ThingID;
|
||||||
|
T.Carry["brand.gone.name"] = GoneOwnerName;
|
||||||
|
T.Carry["brand.gone.faction"] = gone.GetUniqueLoadID();
|
||||||
|
|
||||||
|
Faction origin = Fixtures.FriendlyFaction();
|
||||||
|
Faction other = OtherFaction(origin);
|
||||||
|
if (other == null) T.Skip("no second non-player faction; the foreign-brand reload case is not set up");
|
||||||
|
Pawn foreign = Fixtures.Keep(Fixtures.ColonySlave(origin));
|
||||||
|
BrandUtility.Brand(foreign, other);
|
||||||
|
T.Check(BrandUtility.BrandOf(foreign)?.owner == other, "setup: foreign brand owner is not " + other.Name);
|
||||||
|
Calm(foreign);
|
||||||
|
T.Carry["brand.foreign"] = foreign.ThingID;
|
||||||
|
T.Carry["brand.foreign.faction"] = other.GetUniqueLoadID();
|
||||||
|
T.Carry["brand.foreign.name"] = other.Name;
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("brand (reload): our brand and owner survive save and load", phase: 2)]
|
||||||
|
public static void ReloadKeepsOurBrand()
|
||||||
|
{
|
||||||
|
Pawn pawn = CarriedPawn("brand.ours");
|
||||||
|
string name = T.Carry["brand.ours.name"];
|
||||||
|
HediffComp_BrandOwner comp = ReloadedBrand(pawn);
|
||||||
|
T.Check(comp.owner == Faction.OfPlayer, "brand owner after reload: expected the player faction, got " + (comp.owner?.Name ?? "null"));
|
||||||
|
T.Equal(name, comp.ownerName, "cached owner name after reload");
|
||||||
|
T.Check(BrandUtility.IsBrandedByPlayer(pawn), "BrandUtility.IsBrandedByPlayer is false after reload");
|
||||||
|
CheckNameShown(pawn, Faction.OfPlayer.Name, "our brand after reload");
|
||||||
|
|
||||||
|
if (pawn.IsSlave)
|
||||||
|
T.Check(BrandedThought.Worker.CurrentState(pawn).Active, "BlaxSlaves_Branded inactive for the branded slave after reload");
|
||||||
|
else
|
||||||
|
T.Info("pawn is no longer a slave after reload (a later phase-1 test may have freed it); skipped the mood check");
|
||||||
|
|
||||||
|
// The brand burn had its infecter removed. After a reload vanilla recreates the comp from
|
||||||
|
// the def; with nothing saved it must load as "will not infect".
|
||||||
|
BodyPartRecord core = pawn.RaceProps.body.corePart;
|
||||||
|
var burns = pawn.health.hediffSet.hediffs.OfType<Hediff_Injury>()
|
||||||
|
.Where(h => h.def == DamageDefOf.Burn.hediff && h.Part == core && !h.IsPermanent()).ToList();
|
||||||
|
if (burns.Count == 0) T.Info("brand burn already healed before the reload; skipped the infection check");
|
||||||
|
foreach (Hediff_Injury burn in burns)
|
||||||
|
{
|
||||||
|
HediffComp_Infecter infecter = burn.TryGetComp<HediffComp_Infecter>();
|
||||||
|
if (infecter == null) continue;
|
||||||
|
int ticks = Traverse.Create(infecter).Field("ticksUntilInfect").GetValue<int>();
|
||||||
|
T.Check(ticks <= 0, $"reloaded brand burn (severity {burn.Severity:F1}) has an infection timer of {ticks} ticks; it should never get infected");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("brand (reload): another faction's brand and owner survive save and load", phase: 2)]
|
||||||
|
public static void ReloadKeepsForeignBrand()
|
||||||
|
{
|
||||||
|
Pawn pawn = CarriedPawn("brand.foreign");
|
||||||
|
string factionId = T.Carry["brand.foreign.faction"];
|
||||||
|
string name = T.Carry["brand.foreign.name"];
|
||||||
|
HediffComp_BrandOwner comp = ReloadedBrand(pawn);
|
||||||
|
T.NotNull(comp.owner, "brand owner after reload (expected " + name + ", " + factionId + ")");
|
||||||
|
T.Equal(factionId, comp.owner.GetUniqueLoadID(), "brand owner faction id after reload");
|
||||||
|
T.Check(Find.FactionManager.AllFactionsListForReading.Contains(comp.owner), "reloaded brand owner " + comp.owner.Name + " is not a faction of the loaded world");
|
||||||
|
T.Equal(name, comp.owner.Name, "brand owner name after reload");
|
||||||
|
T.Equal(name, comp.ownerName, "cached owner name after reload");
|
||||||
|
T.Check(!BrandUtility.IsBrandedByPlayer(pawn), "a slave branded by " + name + " counts as branded by the player after reload");
|
||||||
|
CheckNameShown(pawn, name, name + "'s brand after reload");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("brand (reload): cached owner name kept when the owner faction is gone", phase: 2)]
|
||||||
|
public static void ReloadKeepsGoneOwnerName()
|
||||||
|
{
|
||||||
|
Pawn pawn = CarriedPawn("brand.gone");
|
||||||
|
string name = T.Carry["brand.gone.name"];
|
||||||
|
HediffComp_BrandOwner comp = ReloadedBrand(pawn);
|
||||||
|
T.Check(comp.owner == null,
|
||||||
|
$"brand owner after reload: expected null (the faction was never in the world), got {comp.owner?.Name} ({comp.owner?.GetUniqueLoadID()})");
|
||||||
|
T.Equal(name, comp.ownerName, "cached owner name after reload");
|
||||||
|
T.Equal(name, comp.OwnerName, "OwnerName after reload");
|
||||||
|
CheckNameShown(pawn, name, "brand with a gone owner after reload");
|
||||||
|
|
||||||
|
// owner == null alone doesn't prove the save guard: without it the reference is still
|
||||||
|
// written, and loading fails to resolve it to null too, just with a warning. Vanilla
|
||||||
|
// warns "Could not resolve reference to object with loadID Faction_N" on load (always)
|
||||||
|
// and "Object with load ID Faction_N is referenced ... but is not deep-saved" on save (dev mode).
|
||||||
|
if (!T.Carry.TryGetValue("brand.gone.faction", out string goneId))
|
||||||
|
{
|
||||||
|
T.Info("gone faction load ID not carried; skipped the save-guard log check");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
List<LogMessage> log = Log.Messages.ToList();
|
||||||
|
bool covered = log.Any(m => m.text != null && m.text.Contains("[BlaxTest] STAGE save+reload"));
|
||||||
|
if (!covered)
|
||||||
|
{
|
||||||
|
T.Info("the log no longer holds the save+reload stage (rolled over or logging stopped); skipped the save-guard log check");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
var idPattern = new Regex(@"\b" + Regex.Escape(goneId) + @"\b");
|
||||||
|
var hits = log.Where(m => m.text != null && idPattern.IsMatch(m.text)).Select(m => m.type + ": " + m.text).ToList();
|
||||||
|
T.Check(hits.Count == 0,
|
||||||
|
$"saving or loading logged a reference to the gone owner faction {goneId}; HediffComp_BrandOwner.CompExposeData should drop an owner " +
|
||||||
|
"that is not in the FactionManager before Scribe_References saves it: " + string.Join(" | ", hits.Take(2)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- helpers ---------------------------------------------------------------------
|
||||||
|
|
||||||
|
private static RecipeDef BrandRecipe => DefDatabase<RecipeDef>.GetNamed("BlaxSlaves_BrandSlave");
|
||||||
|
|
||||||
|
private static RecipeDef RebrandRecipe => DefDatabase<RecipeDef>.GetNamed("BlaxSlaves_RebrandSlave");
|
||||||
|
|
||||||
|
private static ThoughtDef BrandedThought => DefDatabase<ThoughtDef>.GetNamed("BlaxSlaves_Branded");
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// What the operations tab asks before listing a recipe (HealthCardUtility.DrawMedOperationsTab
|
||||||
|
/// walks pawn.def.AllRecipes and lists a non-part recipe when Worker.AvailableReport accepts).
|
||||||
|
/// </summary>
|
||||||
|
private static bool Offered(RecipeDef recipe, Pawn pawn)
|
||||||
|
{
|
||||||
|
if (!pawn.def.AllRecipes.Contains(recipe))
|
||||||
|
T.Fail($"{recipe.defName} is not in {pawn.def.defName}.AllRecipes (recipeUsers), so the operations tab never lists it for {pawn.LabelShort}");
|
||||||
|
bool available = recipe.AvailableOnNow(pawn);
|
||||||
|
bool report = recipe.Worker.AvailableReport(pawn).Accepted;
|
||||||
|
if (available != report)
|
||||||
|
T.Fail($"{recipe.defName}: AvailableOnNow={available} but AvailableReport={report} for {pawn.LabelShort}");
|
||||||
|
return available;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Bill_Medical QueueBill(Pawn patient, RecipeDef recipe)
|
||||||
|
{
|
||||||
|
Bill_Medical bill = HealthCardUtility.CreateSurgeryBill(patient, recipe, null, null, sendMessages: false);
|
||||||
|
T.Check(patient.BillStack.Bills.Contains(bill), recipe.defName + " bill not in the patient's bill stack after queuing");
|
||||||
|
return bill;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void FinishBill(Bill_Medical bill, Pawn doctor, int seed)
|
||||||
|
{
|
||||||
|
Rand.PushState(seed);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
bill.Notify_IterationCompleted(doctor, new List<Thing>());
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Rand.PopState();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Queue the bill and finish it as the doctor would; fails when the bill is not completable.
|
||||||
|
/// Failure is made impossible here even if the def gained a surgery outcome (the outcome
|
||||||
|
/// tests assert that separately), so the other checks still say something.
|
||||||
|
/// </summary>
|
||||||
|
private static void PerformSurgery(Pawn patient, RecipeDef recipe, Pawn doctor, int seed)
|
||||||
|
{
|
||||||
|
Bill_Medical bill = QueueBill(patient, recipe);
|
||||||
|
T.Check(bill.CompletableEver, $"{recipe.defName} bill on {patient.LabelShort} is not completable (Bill_Medical.CompletableEver false)");
|
||||||
|
SurgeryOutcomeEffectDef outcome = recipe.surgeryOutcomeEffect;
|
||||||
|
if (outcome != null)
|
||||||
|
{
|
||||||
|
T.Info($"{recipe.defName} has surgeryOutcomeEffect {outcome.defName}; cleared for this surgery so it can't fail");
|
||||||
|
recipe.surgeryOutcomeEffect = null;
|
||||||
|
}
|
||||||
|
try
|
||||||
|
{
|
||||||
|
FinishBill(bill, doctor, seed);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
recipe.surgeryOutcomeEffect = outcome;
|
||||||
|
}
|
||||||
|
T.Check(!patient.BillStack.Bills.Contains(bill), recipe.defName + " bill still queued after it finished");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Hediff BrandHediff(Pawn pawn) =>
|
||||||
|
pawn.health.hediffSet.GetFirstHediffOfDef(BlaxDefOf.BlaxSlaves_SlaveBrand);
|
||||||
|
|
||||||
|
private static int BrandCount(Pawn pawn) =>
|
||||||
|
pawn.health.hediffSet.hediffs.Count(h => h.def == BlaxDefOf.BlaxSlaves_SlaveBrand);
|
||||||
|
|
||||||
|
/// <summary>Removes old injuries so a new brand burn can't merge into one (burns have canMerge).</summary>
|
||||||
|
private static void ClearInjuries(Pawn pawn)
|
||||||
|
{
|
||||||
|
foreach (Hediff h in pawn.health.hediffSet.hediffs.Where(h => h is Hediff_Injury).ToList())
|
||||||
|
pawn.health.RemoveHediff(h);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void CheckFreshBurn(Pawn pawn, string when)
|
||||||
|
{
|
||||||
|
HediffDef burnDef = DamageDefOf.Burn.hediff;
|
||||||
|
BodyPartRecord core = pawn.RaceProps.body.corePart;
|
||||||
|
List<Hediff_Injury> burns = pawn.health.hediffSet.hediffs.OfType<Hediff_Injury>()
|
||||||
|
.Where(h => h.def == burnDef && h.Part == core).ToList();
|
||||||
|
T.Check(burns.Count == 1, $"{when}: expected one burn on the {core.Label}, found {burns.Count}");
|
||||||
|
Hediff_Injury burn = burns[0];
|
||||||
|
T.Check(Math.Abs(burn.Severity - BrandUtility.FreshBurnSeverity) < 0.01f,
|
||||||
|
$"{when}: burn severity {burn.Severity}, expected {BrandUtility.FreshBurnSeverity}");
|
||||||
|
T.Check(!burn.IsPermanent(), when + ": the brand burn is already a permanent scar, expected a fresh injury");
|
||||||
|
T.Check(burn.ageTicks < 60, $"{when}: burn is {burn.ageTicks} ticks old, expected a fresh one");
|
||||||
|
T.Check(burn.TryGetComp<HediffComp_Infecter>() == null, when + ": the brand burn has an infection comp (HediffComp_Infecter); it should never get infected");
|
||||||
|
bool defInfects = burnDef.comps != null && burnDef.comps.Any(c => c.compClass != null && typeof(HediffComp_Infecter).IsAssignableFrom(c.compClass));
|
||||||
|
if (!defInfects) T.Info("the vanilla burn def has no infecter comp, so the no-infection check proves little");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void CheckNameShown(Pawn pawn, string name, string what)
|
||||||
|
{
|
||||||
|
Hediff brand = BrandHediff(pawn);
|
||||||
|
T.NotNull(brand, what + ": brand hediff");
|
||||||
|
T.Check(!name.NullOrEmpty(), what + ": expected owner name is empty");
|
||||||
|
string label = brand.Label;
|
||||||
|
T.Check(label != null && label.Contains(name), $"{what}: label \"{label}\" does not name the owner \"{name}\"");
|
||||||
|
// The tooltip starts with LabelCap, which already holds the name in brackets, so a plain
|
||||||
|
// Contains(name) would pass without the comp's tooltip line. Look for that line itself.
|
||||||
|
T.Check("BlaxSlaves_BrandOwnerTip".CanTranslate(), "language key BlaxSlaves_BrandOwnerTip is missing");
|
||||||
|
string ownerLine = "BlaxSlaves_BrandOwnerTip".Translate(name);
|
||||||
|
string tip = brand.GetTooltip(pawn, false);
|
||||||
|
T.Check(tip != null && tip.Contains(ownerLine), $"{what}: tooltip lacks the owner line \"{ownerLine}\": {tip}");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool HasMoodThought(Pawn pawn, ThoughtDef def)
|
||||||
|
{
|
||||||
|
var thoughts = new List<Thought>();
|
||||||
|
pawn.needs.mood.thoughts.situational.Notify_SituationalThoughtsDirty();
|
||||||
|
pawn.needs.mood.thoughts.GetAllMoodThoughts(thoughts);
|
||||||
|
return thoughts.Any(t => t.def == def);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Pawn Prisoner()
|
||||||
|
{
|
||||||
|
Faction from = Fixtures.HostileFaction() ?? Fixtures.FriendlyFaction();
|
||||||
|
Pawn p = Fixtures.Spawn(Fixtures.Generate(PawnKindDefOf.Slave, from));
|
||||||
|
p.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Prisoner);
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A visible humanlike faction other than the player and the given ones, hostile first.</summary>
|
||||||
|
private static Faction OtherFaction(params Faction[] exclude) =>
|
||||||
|
Find.FactionManager.AllFactionsVisible
|
||||||
|
.Where(f => !f.IsPlayer && !f.defeated && !f.temporary && f.def.humanlikeFaction && !exclude.Contains(f))
|
||||||
|
.OrderByDescending(f => f.HostileTo(Faction.OfPlayer))
|
||||||
|
.ThenBy(f => f.loadID)
|
||||||
|
.FirstOrDefault();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A faction object that is not part of the world, like a removed temporary faction:
|
||||||
|
/// never added to the FactionManager, so saving must drop the reference.
|
||||||
|
/// </summary>
|
||||||
|
private static Faction GoneFaction(string name)
|
||||||
|
{
|
||||||
|
Faction template = Fixtures.FriendlyFaction() ?? OtherFaction();
|
||||||
|
T.NotNull(template, "a faction def to model the gone faction on");
|
||||||
|
Faction gone;
|
||||||
|
Rand.PushState(51099);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
gone = new Faction
|
||||||
|
{
|
||||||
|
def = template.def,
|
||||||
|
loadID = Find.UniqueIDsManager.GetNextFactionID(),
|
||||||
|
temporary = true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Rand.PopState();
|
||||||
|
}
|
||||||
|
gone.Name = name;
|
||||||
|
return gone;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Full suppression so a kept slave is unlikely to rebel during later phase-1 tests.</summary>
|
||||||
|
private static void Calm(Pawn slave)
|
||||||
|
{
|
||||||
|
Need_Suppression need = slave.needs?.TryGetNeed<Need_Suppression>();
|
||||||
|
if (need != null) need.CurLevelPercentage = 1f;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Pawn CarriedPawn(string key)
|
||||||
|
{
|
||||||
|
if (!T.Carry.TryGetValue(key, out string id))
|
||||||
|
T.Skip("phase-1 setup did not carry '" + key + "' (setup failed or skipped)");
|
||||||
|
Pawn pawn = Fixtures.FindPawnById(id);
|
||||||
|
T.NotNull(pawn, $"pawn {id} ({key}) after reload (destroyed, or made to leave by a later phase-1 test?)");
|
||||||
|
T.Info($"{key}: {pawn.LabelShort}, spawned={pawn.Spawned}, slave of colony={pawn.IsSlaveOfColony}");
|
||||||
|
return pawn;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static HediffComp_BrandOwner ReloadedBrand(Pawn pawn)
|
||||||
|
{
|
||||||
|
Hediff brand = BrandHediff(pawn);
|
||||||
|
T.NotNull(brand, "brand hediff on " + pawn.LabelShort + " after reload");
|
||||||
|
T.Equal(1, BrandCount(pawn), "brand hediffs on " + pawn.LabelShort + " after reload");
|
||||||
|
HediffComp_BrandOwner comp = brand.TryGetComp<HediffComp_BrandOwner>();
|
||||||
|
T.NotNull(comp, "HediffComp_BrandOwner on the reloaded brand");
|
||||||
|
return comp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,167 @@
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Reflection;
|
||||||
|
using BlaxSlaves;
|
||||||
|
using RimWorld;
|
||||||
|
using RimWorld.Planet;
|
||||||
|
using Verse;
|
||||||
|
|
||||||
|
namespace BlaxSlavesTests
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Shared helpers for tests. Pawns made here are destroyed after each test unless passed to
|
||||||
|
/// Keep(). Mod settings are restored after each test, so tests may change them freely.
|
||||||
|
/// </summary>
|
||||||
|
public static class Fixtures
|
||||||
|
{
|
||||||
|
private static readonly List<Pawn> made = new List<Pawn>();
|
||||||
|
private static readonly HashSet<Pawn> kept = new HashSet<Pawn>();
|
||||||
|
|
||||||
|
public static Map Map => Find.CurrentMap;
|
||||||
|
|
||||||
|
public static BlaxSlavesSettings Settings => BlaxSlavesMod.Settings;
|
||||||
|
|
||||||
|
// ---- factions --------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// <summary>A visible, non-player, humanlike faction that is not hostile to the player.</summary>
|
||||||
|
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();
|
||||||
|
|
||||||
|
/// <summary>A visible, non-player, humanlike faction hostile to the player.</summary>
|
||||||
|
public static Faction HostileFaction() =>
|
||||||
|
Find.FactionManager.AllFactionsVisible
|
||||||
|
.Where(f => !f.IsPlayer && !f.defeated && f.def.humanlikeFaction && f.HostileTo(Faction.OfPlayer))
|
||||||
|
.OrderBy(f => f.loadID).FirstOrDefault();
|
||||||
|
|
||||||
|
// ---- pawns -----------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// <summary>A fresh adult pawn, not spawned. Relations off so no accidental family ties.</summary>
|
||||||
|
public 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 = PawnGenerator.GeneratePawn(req);
|
||||||
|
made.Add(p);
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Pawn Spawn(Pawn p)
|
||||||
|
{
|
||||||
|
IntVec3 cell = CellFinder.RandomClosewalkCellNear(Map.Center, Map, 12);
|
||||||
|
GenSpawn.Spawn(p, cell, Map);
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A spawned free colonist. pacifist = has the Kind trait; otherwise Kind is removed.</summary>
|
||||||
|
public static Pawn Colonist(bool pacifist = false)
|
||||||
|
{
|
||||||
|
Pawn p = Generate(PawnKindDefOf.Colonist, Faction.OfPlayer);
|
||||||
|
Trait kind = p.story.traits.GetTrait(TraitDefOf.Kind);
|
||||||
|
if (pacifist && kind == null) p.story.traits.GainTrait(new Trait(TraitDefOf.Kind));
|
||||||
|
if (!pacifist && kind != null) p.story.traits.RemoveTrait(kind);
|
||||||
|
return Spawn(p);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A spawned slave of the colony, enslaved from origin (default: a friendly faction).</summary>
|
||||||
|
public static Pawn ColonySlave(Faction origin = null)
|
||||||
|
{
|
||||||
|
Pawn p = Generate(PawnKindDefOf.Slave, origin ?? FriendlyFaction());
|
||||||
|
Spawn(p);
|
||||||
|
p.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Slave);
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Exclude a pawn from the per-test cleanup (phase-1 setup for phase-2 checks).</summary>
|
||||||
|
public static Pawn Keep(Pawn p)
|
||||||
|
{
|
||||||
|
kept.Add(p);
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Pawn FindPawnById(string thingId)
|
||||||
|
{
|
||||||
|
if (thingId == null) return null;
|
||||||
|
foreach (Map m in Find.Maps)
|
||||||
|
foreach (Pawn p in m.mapPawns.AllPawns)
|
||||||
|
if (p.ThingID == thingId) return p;
|
||||||
|
foreach (Pawn p in Find.WorldPawns.AllPawnsAliveOrDead)
|
||||||
|
if (p.ThingID == thingId) return p;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- time ------------------------------------------------------------------------
|
||||||
|
|
||||||
|
public static void Tick(int ticks)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < ticks; i++) Find.TickManager.DoSingleTick();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void QuietStoryteller()
|
||||||
|
{
|
||||||
|
Find.Storyteller.incidentQueue.Clear();
|
||||||
|
Find.Storyteller.storytellerComps.Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- thoughts --------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// <summary>Snapshot of a pawn's memories with their age, to spot new or renewed ones.</summary>
|
||||||
|
public static Dictionary<Thought_Memory, int> Memories(Pawn p)
|
||||||
|
{
|
||||||
|
var d = new Dictionary<Thought_Memory, int>();
|
||||||
|
var list = p.needs?.mood?.thoughts?.memories?.Memories;
|
||||||
|
if (list != null) foreach (Thought_Memory m in list) d[m] = m.age;
|
||||||
|
return d;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Memories added or renewed since the snapshot that lower mood or opinion.</summary>
|
||||||
|
public static List<Thought_Memory> NewBadMemories(Pawn p, Dictionary<Thought_Memory, int> before)
|
||||||
|
{
|
||||||
|
var result = new List<Thought_Memory>();
|
||||||
|
var list = p.needs?.mood?.thoughts?.memories?.Memories;
|
||||||
|
if (list == null) return result;
|
||||||
|
foreach (Thought_Memory m in list)
|
||||||
|
{
|
||||||
|
bool fresh = !before.TryGetValue(m, out int oldAge) || m.age < oldAge;
|
||||||
|
if (!fresh) continue;
|
||||||
|
bool bad = m.MoodOffset() < 0f || (m is ISocialThought s && s.OpinionOffset() < 0f);
|
||||||
|
if (bad) result.Add(m);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string Describe(IEnumerable<Thought_Memory> memories) =>
|
||||||
|
string.Join(", ", memories.Select(m => m.def.defName + (m.otherPawn != null ? "(" + m.otherPawn.LabelShort + ")" : "")));
|
||||||
|
|
||||||
|
// ---- settings and cleanup (used by the runner) -----------------------------------
|
||||||
|
|
||||||
|
public static Dictionary<FieldInfo, object> SnapshotSettings()
|
||||||
|
{
|
||||||
|
var d = new Dictionary<FieldInfo, object>();
|
||||||
|
if (Settings == null) return d;
|
||||||
|
foreach (FieldInfo f in typeof(BlaxSlavesSettings).GetFields(BindingFlags.Public | BindingFlags.Instance))
|
||||||
|
d[f] = f.GetValue(Settings);
|
||||||
|
return d;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void RestoreSettings(Dictionary<FieldInfo, object> snapshot)
|
||||||
|
{
|
||||||
|
if (Settings == null) return;
|
||||||
|
foreach (var kv in snapshot) kv.Key.SetValue(Settings, kv.Value);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void Cleanup()
|
||||||
|
{
|
||||||
|
foreach (Pawn p in made)
|
||||||
|
{
|
||||||
|
if (p == null || kept.Contains(p)) continue;
|
||||||
|
if (p.Corpse != null && p.Corpse.Spawned) p.Corpse.Destroy(DestroyMode.Vanish);
|
||||||
|
else if (p.Spawned) p.Destroy(DestroyMode.Vanish);
|
||||||
|
else if (p.IsWorldPawn()) Find.WorldPawns.RemoveAndDiscardPawnViaGC(p);
|
||||||
|
}
|
||||||
|
made.Clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,252 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Reflection;
|
||||||
|
using RimWorld;
|
||||||
|
using UnityEngine;
|
||||||
|
using Verse;
|
||||||
|
|
||||||
|
namespace BlaxSlavesTests
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Marks a public static void method without parameters as a test. Phase 1 runs in a fresh
|
||||||
|
/// quick-test colony. Phase 2 runs after the runner saved that game and loaded it again.
|
||||||
|
/// </summary>
|
||||||
|
[AttributeUsage(AttributeTargets.Method)]
|
||||||
|
public sealed class BlaxTestAttribute : Attribute
|
||||||
|
{
|
||||||
|
public readonly string Name;
|
||||||
|
public readonly int Phase;
|
||||||
|
|
||||||
|
public BlaxTestAttribute(string name, int phase = 1)
|
||||||
|
{
|
||||||
|
Name = name;
|
||||||
|
Phase = phase;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public class TestFailure : Exception
|
||||||
|
{
|
||||||
|
public TestFailure(string message) : base(message) { }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class TestSkipped : Exception
|
||||||
|
{
|
||||||
|
public TestSkipped(string message) : base(message) { }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Assertions and notes for test bodies.</summary>
|
||||||
|
public static class T
|
||||||
|
{
|
||||||
|
/// <summary>Values carried from phase 1 into phase 2. Store ThingIDs or def names, never objects.</summary>
|
||||||
|
public static readonly Dictionary<string, string> Carry = new Dictionary<string, string>();
|
||||||
|
|
||||||
|
public static void Check(bool condition, string message)
|
||||||
|
{
|
||||||
|
if (!condition) throw new TestFailure(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void Equal<TV>(TV expected, TV actual, string what)
|
||||||
|
{
|
||||||
|
if (!EqualityComparer<TV>.Default.Equals(expected, actual))
|
||||||
|
throw new TestFailure($"{what}: expected {Show(expected)}, got {Show(actual)}");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void NotNull(object value, string what)
|
||||||
|
{
|
||||||
|
if (value == null) throw new TestFailure(what + " is null");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void Fail(string message) => throw new TestFailure(message);
|
||||||
|
|
||||||
|
public static void Skip(string reason) => throw new TestSkipped(reason);
|
||||||
|
|
||||||
|
/// <summary>Adds an INFO line under the current test in the results file.</summary>
|
||||||
|
public static void Info(string message) => TestRunner.Note(message);
|
||||||
|
|
||||||
|
private static string Show(object o) => o == null ? "null" : o.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Drives the suite when the game runs with -quicktest -blaxslavestests: phase 1, save, load,
|
||||||
|
/// phase 2, then writes BlaxSlavesTestResults.txt into the save data folder and quits.
|
||||||
|
/// </summary>
|
||||||
|
public class TestRunner : GameComponent
|
||||||
|
{
|
||||||
|
public const string SaveName = "BlaxSlavesTest";
|
||||||
|
public const string ResultFile = "BlaxSlavesTestResults.txt";
|
||||||
|
|
||||||
|
private static int stage; // 0 waiting, 1 phase 1 done + reload queued, 2 finished
|
||||||
|
private static bool reloaded;
|
||||||
|
private static int pass, fail, skip;
|
||||||
|
private static string currentTest;
|
||||||
|
private static readonly List<string> modErrors = new List<string>();
|
||||||
|
private static readonly List<string> otherErrors = new List<string>();
|
||||||
|
private static bool hooked;
|
||||||
|
private int settleFrames;
|
||||||
|
|
||||||
|
public static bool Enabled => GenCommandLine.CommandLineArgPassed("blaxslavestests");
|
||||||
|
|
||||||
|
public static string ResultPath => Path.Combine(GenFilePaths.SaveDataFolderPath, ResultFile);
|
||||||
|
|
||||||
|
public TestRunner(Game game) { }
|
||||||
|
|
||||||
|
public override void LoadedGame()
|
||||||
|
{
|
||||||
|
if (Enabled && stage == 1) reloaded = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void GameComponentUpdate()
|
||||||
|
{
|
||||||
|
if (!Enabled || stage == 2) return;
|
||||||
|
if (LongEventHandler.AnyEventNowOrWaiting || Find.CurrentMap == null) return;
|
||||||
|
if (++settleFrames < 30) return;
|
||||||
|
|
||||||
|
if (stage == 0)
|
||||||
|
{
|
||||||
|
stage = 1;
|
||||||
|
Begin();
|
||||||
|
RunPhase(1);
|
||||||
|
Line("STAGE save+reload");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
GameDataSaveLoader.SaveGame(SaveName);
|
||||||
|
GameDataSaveLoader.LoadGame(SaveName);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
Record("FAIL", "save and reload", e.ToString());
|
||||||
|
Finish();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (stage == 1 && reloaded)
|
||||||
|
{
|
||||||
|
stage = 2;
|
||||||
|
Line("STAGE phase 2 (after reload)");
|
||||||
|
RunPhase(2);
|
||||||
|
Finish();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Begin()
|
||||||
|
{
|
||||||
|
try { File.Delete(ResultPath); } catch { }
|
||||||
|
HookLog();
|
||||||
|
Line("BEGIN Blax Slaves in-game tests, RimWorld " + VersionControl.CurrentVersionStringWithRev);
|
||||||
|
Fixtures.QuietStoryteller();
|
||||||
|
Find.TickManager.CurTimeSpeed = TimeSpeed.Paused;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void HookLog()
|
||||||
|
{
|
||||||
|
if (hooked) return;
|
||||||
|
hooked = true;
|
||||||
|
Application.logMessageReceivedThreaded += (text, stack, type) =>
|
||||||
|
{
|
||||||
|
if (type != LogType.Error && type != LogType.Exception) return;
|
||||||
|
string where = currentTest ?? "(between tests)";
|
||||||
|
string entry = where + ": " + OneLine(text);
|
||||||
|
bool ours = (text != null && text.Contains("BlaxSlaves")) || (stack != null && stack.Contains("BlaxSlaves"));
|
||||||
|
lock (modErrors) (ours ? modErrors : otherErrors).Add(entry);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void RunPhase(int phase)
|
||||||
|
{
|
||||||
|
var tests = typeof(TestRunner).Assembly.GetTypes()
|
||||||
|
.SelectMany(t => t.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static))
|
||||||
|
.Select(m => (method: m, attr: m.GetCustomAttribute<BlaxTestAttribute>()))
|
||||||
|
.Where(x => x.attr != null && x.attr.Phase == phase)
|
||||||
|
.OrderBy(x => x.method.DeclaringType.FullName)
|
||||||
|
.ThenBy(x => x.method.MetadataToken)
|
||||||
|
.ToList();
|
||||||
|
foreach (var (method, attr) in tests) RunOne(attr.Name, method);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void RunOne(string name, MethodInfo method)
|
||||||
|
{
|
||||||
|
currentTest = name;
|
||||||
|
int modErrorsBefore, otherErrorsBefore;
|
||||||
|
lock (modErrors) { modErrorsBefore = modErrors.Count; otherErrorsBefore = otherErrors.Count; }
|
||||||
|
var settings = Fixtures.SnapshotSettings();
|
||||||
|
string status = "PASS", detail = "";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Find.TickManager.CurTimeSpeed = TimeSpeed.Paused;
|
||||||
|
method.Invoke(null, null);
|
||||||
|
}
|
||||||
|
catch (TargetInvocationException tie) when (tie.InnerException is TestSkipped s)
|
||||||
|
{
|
||||||
|
status = "SKIP"; detail = s.Message;
|
||||||
|
}
|
||||||
|
catch (TargetInvocationException tie) when (tie.InnerException is TestFailure f)
|
||||||
|
{
|
||||||
|
status = "FAIL"; detail = f.Message;
|
||||||
|
}
|
||||||
|
catch (TargetInvocationException tie)
|
||||||
|
{
|
||||||
|
status = "FAIL"; detail = "exception: " + tie.InnerException;
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
status = "FAIL"; detail = "runner exception: " + e;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Fixtures.RestoreSettings(settings);
|
||||||
|
try { Fixtures.Cleanup(); } catch (Exception e) { Note("cleanup threw: " + OneLine(e.Message)); }
|
||||||
|
}
|
||||||
|
|
||||||
|
List<string> newModErrors, newOtherErrors;
|
||||||
|
lock (modErrors)
|
||||||
|
{
|
||||||
|
newModErrors = modErrors.Skip(modErrorsBefore).ToList();
|
||||||
|
newOtherErrors = otherErrors.Skip(otherErrorsBefore).ToList();
|
||||||
|
}
|
||||||
|
if (status == "PASS" && newModErrors.Count > 0)
|
||||||
|
{
|
||||||
|
status = "FAIL";
|
||||||
|
detail = "Blax Slaves logged errors: " + string.Join(" | ", newModErrors.Take(3));
|
||||||
|
}
|
||||||
|
Record(status, name, detail);
|
||||||
|
foreach (string e in newOtherErrors.Take(5)) Line(" LOGERR " + e);
|
||||||
|
currentTest = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Finish()
|
||||||
|
{
|
||||||
|
stage = 2;
|
||||||
|
List<string> stray;
|
||||||
|
lock (modErrors) stray = modErrors.Where(e => e.StartsWith("(between tests)")).ToList();
|
||||||
|
foreach (string e in stray.Take(10)) Line(" MODERR " + e);
|
||||||
|
Line($"SUMMARY pass={pass} fail={fail} skip={skip} strayModErrors={stray.Count}");
|
||||||
|
Line("END");
|
||||||
|
Log.Message($"[BlaxTest] finished: pass={pass} fail={fail} skip={skip}");
|
||||||
|
Root.Shutdown();
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static void Note(string message) => Line(" INFO " + OneLine(message));
|
||||||
|
|
||||||
|
private static void Record(string status, string name, string detail)
|
||||||
|
{
|
||||||
|
if (status == "PASS") pass++;
|
||||||
|
else if (status == "FAIL") fail++;
|
||||||
|
else skip++;
|
||||||
|
Line(string.IsNullOrEmpty(detail) ? $"{status} {name}" : $"{status} {name}: {OneLine(detail)}");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Line(string text)
|
||||||
|
{
|
||||||
|
Log.Message("[BlaxTest] " + text);
|
||||||
|
try { File.AppendAllText(ResultPath, text + Environment.NewLine); } catch { }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string OneLine(string s)
|
||||||
|
{
|
||||||
|
if (s == null) return "";
|
||||||
|
s = s.Replace("\r", " ").Replace("\n", " ⏎ ");
|
||||||
|
return s.Length > 1500 ? s.Substring(0, 1500) + "…" : s;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,817 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using BlaxSlaves;
|
||||||
|
using RimWorld;
|
||||||
|
using Verse;
|
||||||
|
|
||||||
|
namespace BlaxSlavesTests
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// SlaveHarm: free, non-pacifist colonists take no bad memories when the colony harms its slaves
|
||||||
|
/// (or branded pawns who aren't free members). Each test drives the vanilla path the player
|
||||||
|
/// triggers with observer colonists present, then repeats it on fresh pawns as a control.
|
||||||
|
///
|
||||||
|
/// Which execution, organ and slave-trade thoughts vanilla gives depends on the quick-test colony's
|
||||||
|
/// random ideoligion, so scenes also use observers whose thoughts don't: a friend of the victim
|
||||||
|
/// (opinion 20+ gives "my friend died") and bystanders who see the death happen.
|
||||||
|
/// </summary>
|
||||||
|
public static class MoodGateTests
|
||||||
|
{
|
||||||
|
private const int Seed = 7331;
|
||||||
|
private const string KeptMainKey = "moodgate.reloadMain";
|
||||||
|
private const string KeptControlKey = "moodgate.reloadControl";
|
||||||
|
|
||||||
|
private static readonly List<(Pawn child, Pawn parent)> madeParents = new List<(Pawn child, Pawn parent)>();
|
||||||
|
|
||||||
|
private static BlaxSlavesSettings Settings => BlaxSlavesMod.Settings;
|
||||||
|
|
||||||
|
// =========================================================================================
|
||||||
|
// harm the gate must suppress
|
||||||
|
// =========================================================================================
|
||||||
|
|
||||||
|
[BlaxTest("mood gate: executing a colony slave")]
|
||||||
|
public static void ExecuteSlave()
|
||||||
|
{
|
||||||
|
ExpectSuppressed("executing a colony slave", () =>
|
||||||
|
{
|
||||||
|
var s = new Scene(Fixtures.ColonySlave());
|
||||||
|
s.Add("executioner", Watcher());
|
||||||
|
Befriend(s.Add("friend", Watcher()), s.victim);
|
||||||
|
s.Add("bystander", Watcher());
|
||||||
|
PlaceAround(s);
|
||||||
|
return s;
|
||||||
|
}, s => ExecuteLikeWarden(s.victim, s["executioner"]));
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("mood gate: harvesting a kidney from a slave")]
|
||||||
|
public static void HarvestKidney()
|
||||||
|
{
|
||||||
|
ExpectSuppressed("harvesting a kidney from a colony slave", () => SurgeryScene(withFriend: false),
|
||||||
|
s => HarvestOrgan(s.victim, s["surgeon"], "Kidney"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("mood gate: harvesting a slave's heart")]
|
||||||
|
public static void HarvestHeart()
|
||||||
|
{
|
||||||
|
ExpectSuppressed("harvesting the heart of a colony slave", () => SurgeryScene(withFriend: true),
|
||||||
|
s => HarvestOrgan(s.victim, s["surgeon"], "Heart"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("mood gate: a colonist kills a slave")]
|
||||||
|
public static void ColonistKillsSlave()
|
||||||
|
{
|
||||||
|
ExpectSuppressed("a colonist killing a colony slave", () =>
|
||||||
|
{
|
||||||
|
var s = new Scene(Fixtures.ColonySlave());
|
||||||
|
s.Add("killer", Watcher());
|
||||||
|
Befriend(s.Add("friend", Watcher()), s.victim);
|
||||||
|
s.Add("bystander", Watcher());
|
||||||
|
PlaceAround(s);
|
||||||
|
RequireWitnesses(s, "bystander");
|
||||||
|
return s;
|
||||||
|
}, s => KillBy(s.victim, s["killer"]));
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("mood gate: banishing a downed slave")]
|
||||||
|
public static void BanishDownedSlave()
|
||||||
|
{
|
||||||
|
ExpectSuppressed("banishing a downed colony slave (left to die)", () =>
|
||||||
|
{
|
||||||
|
var s = new Scene(Fixtures.ColonySlave());
|
||||||
|
Befriend(s.Add("friend", Watcher()), s.victim);
|
||||||
|
s.Add("bystander", Watcher());
|
||||||
|
Down(s.victim);
|
||||||
|
return s;
|
||||||
|
}, s =>
|
||||||
|
{
|
||||||
|
PawnBanishUtility.Banish(s.victim);
|
||||||
|
T.Check(s.victim.Faction != Faction.OfPlayer, "banished slave " + s.victim.LabelShort + " still belongs to the colony");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("mood gate: the banish dialog leaves out thoughts the gate drops")]
|
||||||
|
public static void BanishPreview()
|
||||||
|
{
|
||||||
|
Pawn slave = Fixtures.ColonySlave();
|
||||||
|
Pawn friend = Watcher();
|
||||||
|
Befriend(friend, slave);
|
||||||
|
Down(slave);
|
||||||
|
string allColonistsLine = " - " + ThoughtDefOf.PrisonerBanishedToDie.stages[0].LabelCap;
|
||||||
|
string friendHeader = friend.KindLabel.CapitalizeFirst() + " " + friend.LabelShort + ":";
|
||||||
|
|
||||||
|
Settings.suppressSlaveHarmMood = false;
|
||||||
|
string vanilla = PawnBanishUtility.GetBanishPawnDialogText(slave);
|
||||||
|
Settings.suppressSlaveHarmMood = true;
|
||||||
|
string gated = PawnBanishUtility.GetBanishPawnDialogText(slave);
|
||||||
|
T.Check(SlaveHarm.Top == null, "a SlaveHarm frame was left open after building the banish dialog text");
|
||||||
|
|
||||||
|
T.Info("setting off: " + vanilla);
|
||||||
|
T.Info("setting on: " + gated);
|
||||||
|
if (!vanilla.Contains(allColonistsLine))
|
||||||
|
T.Skip("vanilla gives no thought here in this setup: the banish dialog for a downed slave lists no '" + allColonistsLine.Trim() + "' line even with suppressSlaveHarmMood off");
|
||||||
|
T.Check(!gated.Contains(allColonistsLine), "banish dialog still lists '" + allColonistsLine.Trim() + "' with suppressSlaveHarmMood on");
|
||||||
|
if (vanilla.Contains(friendHeader))
|
||||||
|
T.Check(!gated.Contains(friendHeader), "banish dialog still lists the friend's thoughts ('" + friendHeader + "') with suppressSlaveHarmMood on");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("mood gate: selling a slave to a trader")]
|
||||||
|
public static void SellSlave()
|
||||||
|
{
|
||||||
|
Faction hostile = Fixtures.HostileFaction();
|
||||||
|
if (hostile == null)
|
||||||
|
T.Skip("no hostile humanlike faction: selling a slave from a friendly faction would turn that faction hostile for the rest of the suite");
|
||||||
|
ThoughtDef soldThought = DefDatabase<ThoughtDef>.GetNamedSilentFail("SoldMyLovedOne");
|
||||||
|
|
||||||
|
WithParentsUndone(() =>
|
||||||
|
{
|
||||||
|
Func<Scene> setup = () =>
|
||||||
|
{
|
||||||
|
var s = new Scene(Fixtures.ColonySlave(hostile));
|
||||||
|
s.Add("negotiator", Watcher());
|
||||||
|
s.Add("bystander", Watcher());
|
||||||
|
MakeParent(s.Add("parent", Watcher()), s.victim);
|
||||||
|
return s;
|
||||||
|
};
|
||||||
|
Action<Scene> sell = s => SellToTrader(s.victim, s["negotiator"]);
|
||||||
|
|
||||||
|
Settings.suppressSlaveHarmMood = false;
|
||||||
|
Scene control = Run(setup, sell, "selling a slave (control)");
|
||||||
|
Settings.suppressSlaveHarmMood = true;
|
||||||
|
Settings.keepRelationGrief = true;
|
||||||
|
Scene withGrief = Run(setup, sell, "selling a slave");
|
||||||
|
Settings.keepRelationGrief = false;
|
||||||
|
Scene noGrief = Run(setup, sell, "selling a slave, relation grief off");
|
||||||
|
|
||||||
|
T.Info("control, suppression off: " + control.Report());
|
||||||
|
T.Info("suppression on: " + withGrief.Report());
|
||||||
|
T.Info("suppression on, keepRelationGrief off: " + noGrief.Report());
|
||||||
|
if (!control.AnyBad)
|
||||||
|
T.Skip("vanilla gives no thought here in this setup: selling a slave gave no bad memories even with suppressSlaveHarmMood off. " + IdeoNote());
|
||||||
|
|
||||||
|
foreach (string role in new[] { "negotiator", "bystander" })
|
||||||
|
T.Check(withGrief.Bad(role).Count == 0,
|
||||||
|
"selling a slave: " + role + " took bad memories with suppressSlaveHarmMood on: " + withGrief.Report() + " (control: " + control.Report() + ")");
|
||||||
|
if (control.Has("parent", soldThought))
|
||||||
|
T.Check(withGrief.Has("parent", soldThought),
|
||||||
|
"selling a slave: the slave's parent should keep " + soldThought.defName + " while keepRelationGrief is on, got: " + withGrief.Report());
|
||||||
|
T.Check(!noGrief.AnyBad,
|
||||||
|
"selling a slave with keepRelationGrief off: expected no bad memories on anyone, got: " + noGrief.Report() + " (control: " + control.Report() + ")");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("mood gate: executing a branded prisoner, not an unbranded one")]
|
||||||
|
public static void BrandedPrisoner()
|
||||||
|
{
|
||||||
|
Faction hostile = Fixtures.HostileFaction();
|
||||||
|
if (hostile == null)
|
||||||
|
T.Skip("no hostile humanlike faction to take a prisoner from");
|
||||||
|
Func<bool, Func<Scene>> setup = branded => () =>
|
||||||
|
{
|
||||||
|
Pawn prisoner = Fixtures.Spawn(Fixtures.Generate(PawnKindDefOf.Slave, hostile));
|
||||||
|
prisoner.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Prisoner);
|
||||||
|
if (branded)
|
||||||
|
BrandUtility.Brand(prisoner, Faction.OfPlayer);
|
||||||
|
T.Check(prisoner.IsPrisonerOfColony, "setup: " + prisoner.LabelShort + " is not a prisoner of the colony");
|
||||||
|
T.Check(SlaveHarm.IsProtected(prisoner) == branded,
|
||||||
|
"setup: SlaveHarm.IsProtected(" + (branded ? "branded" : "unbranded") + " prisoner) returned " + SlaveHarm.IsProtected(prisoner));
|
||||||
|
var s = new Scene(prisoner);
|
||||||
|
s.Add("executioner", Watcher());
|
||||||
|
Befriend(s.Add("friend", Watcher()), prisoner);
|
||||||
|
s.Add("bystander", Watcher());
|
||||||
|
PlaceAround(s);
|
||||||
|
return s;
|
||||||
|
};
|
||||||
|
|
||||||
|
Settings.suppressSlaveHarmMood = true;
|
||||||
|
Scene brandedScene = Run(setup(true), s => ExecuteLikeWarden(s.victim, s["executioner"]), "executing a branded prisoner");
|
||||||
|
Scene plainScene = Run(setup(false), s => ExecuteLikeWarden(s.victim, s["executioner"]), "executing an unbranded prisoner");
|
||||||
|
T.Info("branded: " + brandedScene.Report());
|
||||||
|
T.Info("unbranded: " + plainScene.Report());
|
||||||
|
|
||||||
|
T.Check(!brandedScene.AnyBad, "executing a branded prisoner: free colonists took bad memories: " + brandedScene.Report()
|
||||||
|
+ " (unbranded, same setting: " + plainScene.Report() + ")");
|
||||||
|
if (!plainScene.AnyBad)
|
||||||
|
T.Skip("vanilla gives no thought here in this setup: executing an unbranded prisoner gave no bad memories either. " + IdeoNote());
|
||||||
|
T.Check(plainScene.Has("friend", ThoughtDefOf.PawnWithGoodOpinionDied),
|
||||||
|
"executing an unbranded prisoner should not be suppressed: friend expected " + ThoughtDefOf.PawnWithGoodOpinionDied.defName + ", got: " + plainScene.Report());
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("mood gate: a slave's corpse in a gibbet cage")]
|
||||||
|
public static void GibbetCageCorpse()
|
||||||
|
{
|
||||||
|
ThingDef cageDef = DefDatabase<ThingDef>.GetNamedSilentFail("GibbetCage");
|
||||||
|
if (cageDef == null)
|
||||||
|
T.Skip("no GibbetCage def (Ideology inactive?)");
|
||||||
|
Pawn plain = Watcher();
|
||||||
|
Pawn pacifist = Watcher(pacifist: true);
|
||||||
|
if (plain.Ideo != null && plain.Ideo.IdeoApprovesOfSlavery())
|
||||||
|
T.Skip("vanilla gives no thought here in this setup: the colony's ideoligion approves of slavery, so gibbet cages scare no one. " + IdeoNote());
|
||||||
|
|
||||||
|
Pawn victim = Fixtures.ColonySlave();
|
||||||
|
Corpse corpse = null;
|
||||||
|
Building_GibbetCage cage = null;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Seeded(() => victim.Kill(null));
|
||||||
|
corpse = victim.Corpse;
|
||||||
|
T.NotNull(corpse, "corpse of the killed slave");
|
||||||
|
IntVec3 cell = FreeBuildCell(corpse.Position);
|
||||||
|
cage = (Building_GibbetCage)GenSpawn.Spawn(ThingMaker.MakeThing(cageDef, GenStuff.DefaultStuffFor(cageDef)), cell, Fixtures.Map);
|
||||||
|
corpse.DeSpawn();
|
||||||
|
T.Check(cage.GetDirectlyHeldThings().TryAdd(corpse), "could not put the slave's corpse into the gibbet cage");
|
||||||
|
T.Check(cage.Corpse == corpse, "gibbet cage doesn't report the slave's corpse");
|
||||||
|
|
||||||
|
Settings.suppressSlaveHarmMood = false;
|
||||||
|
Thought_Memory control = cage.GiveObservedThought(plain);
|
||||||
|
Settings.suppressSlaveHarmMood = true;
|
||||||
|
Thought_Memory plainThought = cage.GiveObservedThought(plain);
|
||||||
|
Thought_Memory pacifistThought = cage.GiveObservedThought(pacifist);
|
||||||
|
T.Info("setting off: " + (control?.def.defName ?? "null") + "; on, non-pacifist: " + (plainThought?.def.defName ?? "null")
|
||||||
|
+ "; on, pacifist: " + (pacifistThought?.def.defName ?? "null"));
|
||||||
|
|
||||||
|
if (control == null)
|
||||||
|
T.Skip("vanilla gives no thought here in this setup: the gibbet cage gave no observed thought even with suppressSlaveHarmMood off. " + IdeoNote());
|
||||||
|
T.Check(plainThought == null, "gibbet cage with a slave's corpse still gives a non-pacifist colonist " + plainThought?.def.defName);
|
||||||
|
T.Check(pacifistThought != null, "gibbet cage with a slave's corpse gave the pacifist (Kind) observer no thought; pacifists should keep it");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
if (corpse != null && !corpse.Destroyed)
|
||||||
|
corpse.Destroy();
|
||||||
|
if (cage != null && !cage.Destroyed)
|
||||||
|
cage.Destroy();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================================
|
||||||
|
// exceptions: what the gate must let through
|
||||||
|
// =========================================================================================
|
||||||
|
|
||||||
|
[BlaxTest("mood gate: a raider kills a slave (not suppressed)")]
|
||||||
|
public static void RaiderKillsSlave()
|
||||||
|
{
|
||||||
|
Faction hostile = Fixtures.HostileFaction();
|
||||||
|
if (hostile == null)
|
||||||
|
T.Skip("no hostile humanlike faction to send a killer from");
|
||||||
|
ExpectNotSuppressed("a raider killing a colony slave", () =>
|
||||||
|
{
|
||||||
|
var s = new Scene(Fixtures.ColonySlave());
|
||||||
|
Befriend(s.Add("friend", Watcher()), s.victim);
|
||||||
|
s.Add("bystander", Watcher());
|
||||||
|
PlaceAround(s);
|
||||||
|
RequireWitnesses(s, "bystander");
|
||||||
|
s.other = Fixtures.Spawn(Fixtures.Generate(PawnKindDefOf.Slave, hostile));
|
||||||
|
return s;
|
||||||
|
}, s => KillBy(s.victim, s.other));
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("mood gate: harm to a free colonist is never suppressed")]
|
||||||
|
public static void FreeColonistNotSuppressed()
|
||||||
|
{
|
||||||
|
ExpectNotSuppressed("a colonist killing a free colonist", () =>
|
||||||
|
{
|
||||||
|
var s = new Scene(Watcher());
|
||||||
|
s.Add("killer", Watcher());
|
||||||
|
Befriend(s.Add("friend", Watcher()), s.victim);
|
||||||
|
s.Add("bystander", Watcher());
|
||||||
|
PlaceAround(s);
|
||||||
|
RequireWitnesses(s, "bystander");
|
||||||
|
return s;
|
||||||
|
}, s => KillBy(s.victim, s["killer"]));
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("mood gate: a pacifist observer still takes the bad memory")]
|
||||||
|
public static void PacifistKeepsMemory()
|
||||||
|
{
|
||||||
|
Settings.suppressSlaveHarmMood = true;
|
||||||
|
Scene s = Run(() =>
|
||||||
|
{
|
||||||
|
var scene = new Scene(Fixtures.ColonySlave());
|
||||||
|
scene.Add("killer", Watcher());
|
||||||
|
scene.Add("bystander", Watcher());
|
||||||
|
scene.Add("pacifist", Watcher(pacifist: true));
|
||||||
|
PlaceAround(scene);
|
||||||
|
RequireWitnesses(scene, "bystander", "pacifist");
|
||||||
|
return scene;
|
||||||
|
}, scene => KillBy(scene.victim, scene["killer"]), "a colonist killing a slave in front of a pacifist");
|
||||||
|
|
||||||
|
T.Info(s.Report());
|
||||||
|
T.Check(s.Has("pacifist", ThoughtDefOf.WitnessedDeathNonAlly),
|
||||||
|
"pacifist (Kind) observer should still get " + ThoughtDefOf.WitnessedDeathNonAlly.defName + " for a slave killed in sight, got: " + s.Report());
|
||||||
|
T.Check(s.Bad("bystander").Count == 0 && s.Bad("killer").Count == 0,
|
||||||
|
"non-pacifists in the same scene should get no bad memories: " + s.Report());
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("mood gate: family keeps its grief while keepRelationGrief is on")]
|
||||||
|
public static void FamilyKeepsGrief()
|
||||||
|
{
|
||||||
|
WithParentsUndone(() =>
|
||||||
|
{
|
||||||
|
Settings.suppressSlaveHarmMood = true;
|
||||||
|
Settings.keepRelationGrief = true;
|
||||||
|
ThoughtDef grief = null;
|
||||||
|
Scene s = Run(() =>
|
||||||
|
{
|
||||||
|
var scene = new Scene(Fixtures.ColonySlave());
|
||||||
|
scene.Add("killer", Watcher());
|
||||||
|
scene.Add("bystander", Watcher());
|
||||||
|
grief = MakeParent(scene.Add("parent", Watcher()), scene.victim);
|
||||||
|
PlaceAround(scene);
|
||||||
|
return scene;
|
||||||
|
}, scene => KillBy(scene.victim, scene["killer"]), "a colonist killing a slave whose parent watches");
|
||||||
|
|
||||||
|
T.Info(s.Report());
|
||||||
|
T.NotNull(grief, "died thought of the parent's relation to the slave");
|
||||||
|
T.Check(s.Has("parent", grief), "the slave's parent should keep " + grief.defName + " while keepRelationGrief is on, got: " + s.Report());
|
||||||
|
T.Check(s.Bad("bystander").Count == 0 && s.Bad("killer").Count == 0,
|
||||||
|
"unrelated colonists in the same scene should get no bad memories: " + s.Report());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("mood gate: family grief is dropped too with keepRelationGrief off")]
|
||||||
|
public static void FamilyGriefOff()
|
||||||
|
{
|
||||||
|
WithParentsUndone(() =>
|
||||||
|
{
|
||||||
|
Settings.keepRelationGrief = false;
|
||||||
|
ExpectSuppressed("a colonist killing a slave whose parent watches, keepRelationGrief off", () =>
|
||||||
|
{
|
||||||
|
var s = new Scene(Fixtures.ColonySlave());
|
||||||
|
s.Add("killer", Watcher());
|
||||||
|
MakeParent(s.Add("parent", Watcher()), s.victim);
|
||||||
|
PlaceAround(s);
|
||||||
|
return s;
|
||||||
|
}, s => KillBy(s.victim, s["killer"]));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================================
|
||||||
|
// save and reload
|
||||||
|
// =========================================================================================
|
||||||
|
|
||||||
|
[BlaxTest("mood gate: keep two slaves for the reload check")]
|
||||||
|
public static void KeepSlavesForReload()
|
||||||
|
{
|
||||||
|
T.Carry[KeptMainKey] = Fixtures.Keep(Fixtures.ColonySlave()).ThingID;
|
||||||
|
T.Carry[KeptControlKey] = Fixtures.Keep(Fixtures.ColonySlave()).ThingID;
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("mood gate: executing a slave loaded from the save", phase: 2)]
|
||||||
|
public static void ExecuteReloadedSlave()
|
||||||
|
{
|
||||||
|
Pawn main = KeptSlave(KeptMainKey);
|
||||||
|
Pawn control = KeptSlave(KeptControlKey);
|
||||||
|
var victims = new Queue<Pawn>(new[] { main, control });
|
||||||
|
try
|
||||||
|
{
|
||||||
|
ExpectSuppressed("executing a slave loaded from the save", () =>
|
||||||
|
{
|
||||||
|
var s = new Scene(victims.Dequeue());
|
||||||
|
s.Add("executioner", Watcher());
|
||||||
|
Befriend(s.Add("friend", Watcher()), s.victim);
|
||||||
|
s.Add("bystander", Watcher());
|
||||||
|
PlaceAround(s);
|
||||||
|
return s;
|
||||||
|
}, s => ExecuteLikeWarden(s.victim, s["executioner"]));
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
// Kept pawns are not part of the per-test cleanup.
|
||||||
|
foreach (Pawn p in new[] { main, control })
|
||||||
|
if (p.Dead && p.Corpse != null && p.Corpse.Spawned)
|
||||||
|
p.Corpse.Destroy();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================================
|
||||||
|
// runners
|
||||||
|
// =========================================================================================
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The scene with suppression on must leave every observer without new bad memories. The
|
||||||
|
/// same scene on fresh pawns with suppression off must give some, or the test skips.
|
||||||
|
/// </summary>
|
||||||
|
private static void ExpectSuppressed(string what, Func<Scene> setup, Action<Scene> harm)
|
||||||
|
{
|
||||||
|
Settings.suppressSlaveHarmMood = true;
|
||||||
|
Scene main = Run(setup, harm, what);
|
||||||
|
Settings.suppressSlaveHarmMood = false;
|
||||||
|
Scene control = Run(setup, harm, what + " (control)");
|
||||||
|
Settings.suppressSlaveHarmMood = true;
|
||||||
|
|
||||||
|
T.Info("suppression on: " + main.Report());
|
||||||
|
T.Info("control, suppression off: " + control.Report());
|
||||||
|
if (main.AnyBad)
|
||||||
|
T.Fail(what + ": free colonists took bad memories with suppressSlaveHarmMood on: " + main.Report()
|
||||||
|
+ " (control with it off: " + control.Report() + ")");
|
||||||
|
if (!control.AnyBad)
|
||||||
|
T.Skip("vanilla gives no thought here in this setup: " + what + " gave no bad memories even with suppressSlaveHarmMood off. " + IdeoNote());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// For harm the gate must not touch: with suppression on the observers must get what the
|
||||||
|
/// control (suppression off) gave them, at least the thoughts that don't depend on the ideoligion.
|
||||||
|
/// </summary>
|
||||||
|
private static void ExpectNotSuppressed(string what, Func<Scene> setup, Action<Scene> harm)
|
||||||
|
{
|
||||||
|
Settings.suppressSlaveHarmMood = false;
|
||||||
|
Scene control = Run(setup, harm, what + " (control)");
|
||||||
|
Settings.suppressSlaveHarmMood = true;
|
||||||
|
Scene main = Run(setup, harm, what);
|
||||||
|
|
||||||
|
T.Info("control, suppression off: " + control.Report());
|
||||||
|
T.Info("suppression on: " + main.Report());
|
||||||
|
if (!control.AnyBad)
|
||||||
|
T.Skip("vanilla gives no thought here in this setup: " + what + " gave no bad memories even with suppressSlaveHarmMood off. " + IdeoNote());
|
||||||
|
T.Check(main.AnyBad, what + ": expected bad memories with suppressSlaveHarmMood on (nothing to suppress here), got none. Control: " + control.Report());
|
||||||
|
var steady = new[] { ThoughtDefOf.WitnessedDeathNonAlly, ThoughtDefOf.WitnessedDeathAlly, ThoughtDefOf.PawnWithGoodOpinionDied };
|
||||||
|
foreach (string role in control.Roles)
|
||||||
|
foreach (ThoughtDef def in steady)
|
||||||
|
if (control.Has(role, def))
|
||||||
|
T.Check(main.Has(role, def), what + ": " + role + " got " + def.defName + " with suppressSlaveHarmMood off but not with it on. On: "
|
||||||
|
+ main.Report() + "; off: " + control.Report());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Scene Run(Func<Scene> setup, Action<Scene> harm, string what)
|
||||||
|
{
|
||||||
|
Scene s = setup();
|
||||||
|
s.Snapshot();
|
||||||
|
Seeded(() => harm(s));
|
||||||
|
s.Freeze();
|
||||||
|
T.Check(SlaveHarm.Top == null, "a SlaveHarm frame was left open after " + what);
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Seeded(Action action)
|
||||||
|
{
|
||||||
|
Rand.PushState(Seed);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
action();
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Rand.PopState();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void WithParentsUndone(Action body)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
body();
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
foreach ((Pawn child, Pawn parent) in madeParents)
|
||||||
|
child?.relations?.TryRemoveDirectRelation(PawnRelationDefOf.Parent, parent);
|
||||||
|
madeParents.Clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================================
|
||||||
|
// vanilla paths
|
||||||
|
// =========================================================================================
|
||||||
|
|
||||||
|
/// <summary>What the execute toil of JobDriver_ExecuteSlave and JobDriver_Execute does.</summary>
|
||||||
|
private static void ExecuteLikeWarden(Pawn victim, Pawn executioner)
|
||||||
|
{
|
||||||
|
ExecutionUtility.DoExecutionByCut(executioner, victim);
|
||||||
|
ThoughtUtility.GiveThoughtsForPawnExecuted(victim, executioner, PawnExecutionKind.GenericBrutal);
|
||||||
|
T.Check(victim.Dead, "execution by cut left " + victim.LabelShort + " alive");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A lethal cut from the instigator, the way ExecutionUtility applies one.</summary>
|
||||||
|
private static void KillBy(Pawn victim, Thing instigator)
|
||||||
|
{
|
||||||
|
BodyPartRecord neck = ExecutionUtility.ExecuteCutPart(victim);
|
||||||
|
var dinfo = new DamageInfo(DamageDefOf.Cut, 9999f, 999f, -1f, instigator, neck, null,
|
||||||
|
DamageInfo.SourceCategory.ThingOrUnknown, null, instigatorGuilty: false);
|
||||||
|
dinfo.SetIgnoreArmor(true);
|
||||||
|
victim.TakeDamage(dinfo);
|
||||||
|
if (!victim.Dead)
|
||||||
|
victim.Kill(dinfo);
|
||||||
|
T.Check(victim.Dead, "a 9999 cut from " + (instigator?.LabelShort ?? "nobody") + " left " + victim.LabelShort + " alive");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The remove-part recipe worker, as when a surgeon finishes the bill.</summary>
|
||||||
|
private static void HarvestOrgan(Pawn patient, Pawn surgeon, string partDefName)
|
||||||
|
{
|
||||||
|
BodyPartRecord part = patient.health.hediffSet.GetNotMissingParts()
|
||||||
|
.FirstOrDefault(r => r.def.defName == partDefName && MedicalRecipesUtility.IsClean(patient, r));
|
||||||
|
if (part == null)
|
||||||
|
T.Skip("setup: " + patient.LabelShort + " has no clean " + partDefName + " to harvest");
|
||||||
|
bool lethal = part.def == BodyPartDefOf.Heart;
|
||||||
|
Map map = surgeon.Map;
|
||||||
|
ThingDef organDef = part.def.spawnThingOnRemoved;
|
||||||
|
var organsBefore = organDef == null ? new HashSet<Thing>() : new HashSet<Thing>(map.listerThings.ThingsOfDef(organDef));
|
||||||
|
|
||||||
|
// The first random roll in ApplyOnPawn is the surgery success check (quality is capped at 0.98).
|
||||||
|
Rand.PushState(SeedWithFirstRollBelow(0.3f));
|
||||||
|
try
|
||||||
|
{
|
||||||
|
RecipeDefOf.RemoveBodyPart.Worker.ApplyOnPawn(patient, part, surgeon, new List<Thing>(), null);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Rand.PopState();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (organDef != null)
|
||||||
|
foreach (Thing organ in map.listerThings.ThingsOfDef(organDef).ToList())
|
||||||
|
if (!organsBefore.Contains(organ) && !organ.Destroyed)
|
||||||
|
organ.Destroy();
|
||||||
|
|
||||||
|
bool done = lethal ? patient.Dead : patient.health.hediffSet.PartIsMissing(part);
|
||||||
|
if (!done)
|
||||||
|
T.Skip("setup: removing " + partDefName + " from " + patient.LabelShort + " did not "
|
||||||
|
+ (lethal ? "kill the patient (deathless?)" : "remove the part (surgery failed)"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Tradeable_Pawn.ResolveTrade, as when the trade dialog is accepted, selling to an orbital trader.</summary>
|
||||||
|
private static void SellToTrader(Pawn slave, Pawn negotiator)
|
||||||
|
{
|
||||||
|
TraderKindDef kind = DefDatabase<TraderKindDef>.AllDefsListForReading.FirstOrDefault(d => d.orbital);
|
||||||
|
T.NotNull(kind, "an orbital TraderKindDef");
|
||||||
|
var ship = new TradeShip(kind);
|
||||||
|
ITrader oldTrader = TradeSession.trader;
|
||||||
|
Pawn oldNegotiator = TradeSession.playerNegotiator;
|
||||||
|
TradeDeal oldDeal = TradeSession.deal;
|
||||||
|
bool oldGiftMode = TradeSession.giftMode;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
TradeSession.trader = ship;
|
||||||
|
TradeSession.playerNegotiator = negotiator;
|
||||||
|
TradeSession.giftMode = false;
|
||||||
|
var tradeable = new Tradeable_Pawn();
|
||||||
|
tradeable.AddThing(slave, Transactor.Colony);
|
||||||
|
tradeable.ForceToDestination(1);
|
||||||
|
T.Equal(TradeAction.PlayerSells, tradeable.ActionToDo, "trade action for one colony pawn moved to the trader");
|
||||||
|
tradeable.ResolveTrade();
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
TradeSession.trader = oldTrader;
|
||||||
|
TradeSession.playerNegotiator = oldNegotiator;
|
||||||
|
TradeSession.deal = oldDeal;
|
||||||
|
TradeSession.giftMode = oldGiftMode;
|
||||||
|
// What TradeShip.Depart does with its stock: pawns go to the world.
|
||||||
|
ship.GetDirectlyHeldThings().ClearAndDestroyContentsOrPassToWorld();
|
||||||
|
}
|
||||||
|
T.Check(!slave.Spawned && !slave.IsSlave, "sold slave " + slave.LabelShort + " is still a spawned slave");
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================================
|
||||||
|
// setup helpers
|
||||||
|
// =========================================================================================
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A spawned free colonist who can see and has no trait that blanks the death thoughts
|
||||||
|
/// (Psychopath, Bloodlust). Non-pacifist unless asked: no Kind and capable of violence.
|
||||||
|
/// Rejected candidates stay for the per-test cleanup.
|
||||||
|
/// </summary>
|
||||||
|
private static Pawn Watcher(bool pacifist = false)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < 30; i++)
|
||||||
|
{
|
||||||
|
Pawn p = Fixtures.Colonist(pacifist);
|
||||||
|
if (PawnUtility.IsBiologicallyOrArtificiallyBlind(p))
|
||||||
|
continue;
|
||||||
|
DropTrait(p, TraitDefOf.Psychopath);
|
||||||
|
DropTrait(p, TraitDefOf.Bloodlust);
|
||||||
|
if (SlaveHarm.IsPacifist(p) != pacifist)
|
||||||
|
continue;
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
T.Fail("could not generate a seeing " + (pacifist ? "pacifist" : "non-pacifist") + " colonist in 30 tries");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void DropTrait(Pawn p, TraitDef def)
|
||||||
|
{
|
||||||
|
Trait trait = def == null ? null : p.story?.traits?.GetTrait(def);
|
||||||
|
if (trait != null)
|
||||||
|
p.story.traits.RemoveTrait(trait);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Scene SurgeryScene(bool withFriend)
|
||||||
|
{
|
||||||
|
var s = new Scene(Fixtures.ColonySlave());
|
||||||
|
Pawn surgeon = s.Add("surgeon", Watcher());
|
||||||
|
SkillRecord medicine = surgeon.skills?.GetSkill(SkillDefOf.Medicine);
|
||||||
|
if (medicine != null)
|
||||||
|
medicine.Level = 20;
|
||||||
|
if (withFriend)
|
||||||
|
Befriend(s.Add("friend", Watcher()), s.victim);
|
||||||
|
s.Add("bystander", Watcher());
|
||||||
|
PlaceAround(s);
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Positive social memories about the victim until opinion reaches 20+, which gives "my friend
|
||||||
|
/// died" on death. More are added only if the victim's looks or traits pull the opinion down.
|
||||||
|
/// </summary>
|
||||||
|
private static void Befriend(Pawn watcher, Pawn victim)
|
||||||
|
{
|
||||||
|
MemoryThoughtHandler memories = watcher.needs.mood.thoughts.memories;
|
||||||
|
var boosts = new[]
|
||||||
|
{
|
||||||
|
ThoughtDefOf.CrashedTogether, ThoughtDefOf.RescuedMeByOfferingHelp, ThoughtDefOf.RescuedMe,
|
||||||
|
ThoughtDefOf.HoneymoonPhase, ThoughtDefOf.RecruitedMe, ThoughtDefOf.RescuedMe, ThoughtDefOf.RescuedMe,
|
||||||
|
};
|
||||||
|
int opinion = watcher.relations.OpinionOf(victim);
|
||||||
|
for (int i = 0; i < boosts.Length && (i < 3 || opinion < 20); i++)
|
||||||
|
{
|
||||||
|
if (boosts[i] != null)
|
||||||
|
memories.TryGainMemory(boosts[i], victim);
|
||||||
|
opinion = watcher.relations.OpinionOf(victim);
|
||||||
|
}
|
||||||
|
T.Check(opinion >= 20, "setup: " + watcher.LabelShort + "'s opinion of " + victim.LabelShort + " is " + opinion
|
||||||
|
+ " after " + boosts.Length + " positive memories; the friend-died thought needs 20+");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Makes parent the victim's parent. Returns the thought vanilla gives the parent when the child dies.</summary>
|
||||||
|
private static ThoughtDef MakeParent(Pawn parent, Pawn child)
|
||||||
|
{
|
||||||
|
child.relations.AddDirectRelation(PawnRelationDefOf.Parent, parent);
|
||||||
|
madeParents.Add((child, parent));
|
||||||
|
PawnRelationDef relation = parent.GetMostImportantRelation(child);
|
||||||
|
T.NotNull(relation, "setup: relation from " + parent.LabelShort + " to their child " + child.LabelShort);
|
||||||
|
return relation.GetGenderSpecificDiedThought(child);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Down(Pawn p)
|
||||||
|
{
|
||||||
|
p.health.AddHediff(HediffDefOf.Anesthetic);
|
||||||
|
if (!p.Downed)
|
||||||
|
T.Skip("setup: anesthetic did not down " + p.LabelShort);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Moves the watchers onto free cells next to the victim with line of sight, so they see the death.</summary>
|
||||||
|
private static void PlaceAround(Scene s)
|
||||||
|
{
|
||||||
|
Map map = s.victim.Map;
|
||||||
|
IntVec3 at = s.victim.Position;
|
||||||
|
var taken = new HashSet<IntVec3> { at };
|
||||||
|
foreach (Pawn w in s.Watchers)
|
||||||
|
{
|
||||||
|
IntVec3 spot = IntVec3.Invalid;
|
||||||
|
foreach (IntVec3 c in GenRadial.RadialCellsAround(at, 5.9f, false))
|
||||||
|
{
|
||||||
|
if (taken.Contains(c) || !c.InBounds(map) || !c.Standable(map) || c.Fogged(map))
|
||||||
|
continue;
|
||||||
|
Pawn there = c.GetFirstPawn(map);
|
||||||
|
if (there != null && there != w)
|
||||||
|
continue;
|
||||||
|
if (!GenSight.LineOfSight(at, c, map))
|
||||||
|
continue;
|
||||||
|
spot = c;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (!spot.IsValid)
|
||||||
|
T.Skip("setup: no free cell with line of sight near " + at + " for " + w.LabelShort);
|
||||||
|
taken.Add(spot);
|
||||||
|
if (w.Position != spot)
|
||||||
|
{
|
||||||
|
w.Position = spot;
|
||||||
|
w.Notify_Teleported();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void RequireWitnesses(Scene s, params string[] roles)
|
||||||
|
{
|
||||||
|
foreach (string role in roles)
|
||||||
|
if (!ThoughtUtility.Witnessed(s[role], s.victim))
|
||||||
|
T.Skip("setup: " + role + " " + s[role].LabelShort + " can't see " + s.victim.LabelShort + " (asleep, blind or no line of sight)");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IntVec3 FreeBuildCell(IntVec3 near)
|
||||||
|
{
|
||||||
|
Map map = Fixtures.Map;
|
||||||
|
foreach (IntVec3 c in GenRadial.RadialCellsAround(near, 8.9f, false))
|
||||||
|
{
|
||||||
|
if (c.InBounds(map) && c.Standable(map) && !c.Fogged(map) && c.GetEdifice(map) == null
|
||||||
|
&& c.GetFirstItem(map) == null && c.GetFirstPawn(map) == null && c.GetFirstBuilding(map) == null)
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
T.Skip("setup: no free cell for a gibbet cage near " + near);
|
||||||
|
return IntVec3.Invalid;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int SeedWithFirstRollBelow(float limit)
|
||||||
|
{
|
||||||
|
for (int seed = 1; seed < 1000; seed++)
|
||||||
|
{
|
||||||
|
Rand.PushState(seed);
|
||||||
|
float roll = Rand.Value;
|
||||||
|
Rand.PopState();
|
||||||
|
if (roll < limit)
|
||||||
|
return seed;
|
||||||
|
}
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Pawn KeptSlave(string key)
|
||||||
|
{
|
||||||
|
if (!T.Carry.TryGetValue(key, out string id))
|
||||||
|
T.Skip("phase 1 did not store " + key);
|
||||||
|
Pawn p = Fixtures.FindPawnById(id);
|
||||||
|
if (p == null || p.Dead || !p.Spawned || !p.IsSlaveOfColony)
|
||||||
|
T.Skip("kept slave " + id + " is no longer a spawned colony slave after the reload ("
|
||||||
|
+ (p == null ? "not found" : p.Dead ? "dead" : !p.Spawned ? "not spawned" : "not a colony slave") + ")");
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string IdeoNote()
|
||||||
|
{
|
||||||
|
Ideo ideo = Faction.OfPlayer?.ideos?.PrimaryIdeo;
|
||||||
|
if (ideo == null)
|
||||||
|
return "Player ideoligion: none.";
|
||||||
|
IEnumerable<string> precepts = ideo.PreceptsListForReading
|
||||||
|
.Where(p => p?.def?.issue != null && (p.def.issue.defName.Contains("Execution") || p.def.issue.defName.Contains("Organ") || p.def.issue.defName.Contains("Slave")))
|
||||||
|
.Select(p => p.def.defName);
|
||||||
|
return "Player ideoligion " + ideo.name + ": " + string.Join(", ", precepts) + (ideo.IdeoApprovesOfSlavery() ? " (approves of slavery)" : "") + ".";
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================================
|
||||||
|
// scene
|
||||||
|
// =========================================================================================
|
||||||
|
|
||||||
|
/// <summary>A victim and named observer colonists, with a memory snapshot taken just before the harm.</summary>
|
||||||
|
private sealed class Scene
|
||||||
|
{
|
||||||
|
public readonly Pawn victim;
|
||||||
|
public Pawn other;
|
||||||
|
private readonly List<KeyValuePair<string, Pawn>> roles = new List<KeyValuePair<string, Pawn>>();
|
||||||
|
private readonly Dictionary<Pawn, Dictionary<Thought_Memory, int>> before = new Dictionary<Pawn, Dictionary<Thought_Memory, int>>();
|
||||||
|
|
||||||
|
public Scene(Pawn victim)
|
||||||
|
{
|
||||||
|
this.victim = victim;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Pawn this[string role]
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
foreach (KeyValuePair<string, Pawn> r in roles)
|
||||||
|
if (r.Key == role)
|
||||||
|
return r.Value;
|
||||||
|
throw new TestFailure("test bug: no role '" + role + "' in this scene");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public IEnumerable<string> Roles => roles.Select(r => r.Key);
|
||||||
|
|
||||||
|
public IEnumerable<Pawn> Watchers => roles.Select(r => r.Value);
|
||||||
|
|
||||||
|
public Pawn Add(string role, Pawn watcher)
|
||||||
|
{
|
||||||
|
roles.Add(new KeyValuePair<string, Pawn>(role, watcher));
|
||||||
|
return watcher;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Snapshot()
|
||||||
|
{
|
||||||
|
before.Clear();
|
||||||
|
foreach (KeyValuePair<string, Pawn> r in roles)
|
||||||
|
before[r.Value] = Fixtures.Memories(r.Value);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Dictionary<string, List<Thought_Memory>> frozen;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Records what each observer got from this scene's harm. Observers stay alive into the next
|
||||||
|
/// run (the control), whose colony-wide thoughts would otherwise count against this scene.
|
||||||
|
/// </summary>
|
||||||
|
public void Freeze()
|
||||||
|
{
|
||||||
|
frozen = null;
|
||||||
|
var result = new Dictionary<string, List<Thought_Memory>>();
|
||||||
|
foreach (KeyValuePair<string, Pawn> r in roles)
|
||||||
|
result[r.Key] = Bad(r.Key);
|
||||||
|
frozen = result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Thought_Memory> Bad(string role)
|
||||||
|
{
|
||||||
|
if (frozen != null && frozen.TryGetValue(role, out List<Thought_Memory> got))
|
||||||
|
return got;
|
||||||
|
Pawn p = this[role];
|
||||||
|
return before.TryGetValue(p, out Dictionary<Thought_Memory, int> snapshot)
|
||||||
|
? Fixtures.NewBadMemories(p, snapshot)
|
||||||
|
: new List<Thought_Memory>();
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool AnyBad => roles.Any(r => Bad(r.Key).Count > 0);
|
||||||
|
|
||||||
|
public bool Has(string role, ThoughtDef def) => def != null && Bad(role).Any(m => m.def == def);
|
||||||
|
|
||||||
|
public string Report() =>
|
||||||
|
string.Join("; ", roles.Select(r => r.Key + " " + r.Value.LabelShort + " [" + Fixtures.Describe(Bad(r.Key)) + "]"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,670 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Reflection;
|
||||||
|
using BlaxSlaves;
|
||||||
|
using HarmonyLib;
|
||||||
|
using RimWorld;
|
||||||
|
using RimWorld.Planet;
|
||||||
|
using RimWorld.QuestGen;
|
||||||
|
using Verse;
|
||||||
|
using Verse.AI.Group;
|
||||||
|
|
||||||
|
namespace BlaxSlavesTests
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Branded runaways (Runaways.cs). Escapes end the way a vanilla slave rebellion ends: the slave
|
||||||
|
/// is in a LordJob_SlaveRebellion lord and calls Pawn.ExitMap(true, edge) like JobDriver_Goto does
|
||||||
|
/// at the map edge. Vanilla then passes them to the world, where Pawn.Notify_PassedToWorld frees
|
||||||
|
/// them and hands them a random non-colony humanlike faction (hostile ones included), so each
|
||||||
|
/// escape is seeded and retried a bounded number of times until that faction is not hostile
|
||||||
|
/// (and, where the test needs it, not the slave's origin faction either).
|
||||||
|
/// </summary>
|
||||||
|
public static class RunawayTests
|
||||||
|
{
|
||||||
|
// Vanilla weights the freed escapee's faction pick, so a non-hostile faction other than the
|
||||||
|
// origin can come up as rarely as ~1 in 5 (one civil outlander faction as origin, Empire
|
||||||
|
// the only other non-hostile one). 30 seeded tries keep a vacuous skip below ~0.2%.
|
||||||
|
private const int MaxEscapeAttempts = 30;
|
||||||
|
private const int CheckInterval = 250;
|
||||||
|
private const int MaxLandingTicks = 3000;
|
||||||
|
|
||||||
|
private const string CarryPawn = "runaways.pawn";
|
||||||
|
private const string CarryOrigin = "runaways.origin";
|
||||||
|
private const string CarryFinder = "runaways.finder";
|
||||||
|
private const string CarryDueTick = "runaways.dueTick";
|
||||||
|
|
||||||
|
private const string SearchMessageKey = "BlaxSlaves_RunawaySearchMessage";
|
||||||
|
private const string GoneMessageKey = "BlaxSlaves_RunawayGoneMessage";
|
||||||
|
private const string KeptLabelKey = "BlaxSlaves_RunawayKeptLabel";
|
||||||
|
private const string ReturnedLabelKey = "BlaxSlaves_RunawayReturnedLabel";
|
||||||
|
|
||||||
|
/// <summary>Every pawn this class let escape in the current test, forgotten by the mod afterwards.</summary>
|
||||||
|
private static readonly List<Pawn> escapees = new List<Pawn>();
|
||||||
|
|
||||||
|
// ---- registered and returned --------------------------------------------------------
|
||||||
|
|
||||||
|
[BlaxTest("runaways: branded escapee is registered, then returned as our slave")]
|
||||||
|
public static void BrandedEscapeeIsReturned()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
RequireExitMapPatch();
|
||||||
|
BlaxSlavesSettings s = Fixtures.Settings;
|
||||||
|
s.returnRunaways = true;
|
||||||
|
s.returnChance = 1f;
|
||||||
|
s.returnDelayMinDays = 3;
|
||||||
|
s.returnDelayMaxDays = 3;
|
||||||
|
Map map = Fixtures.Map;
|
||||||
|
|
||||||
|
// distinctFinder: if vanilla handed the escapee back to its origin faction, the
|
||||||
|
// SlaveFaction/HomeFaction checks after delivery would pass without the restore.
|
||||||
|
Escapee e = EscapeUntilNonHostileFinder(1100, BrandForPlayerNoInteraction, playerBrand: true, distinctFinder: true);
|
||||||
|
Pawn pawn = e.pawn;
|
||||||
|
|
||||||
|
T.Check(GameComponent_BlaxRunaways.IsPending(pawn),
|
||||||
|
$"{pawn} escaped with the player's brand to non-hostile {pawn.Faction} but GameComponent_BlaxRunaways.IsPending is false (the ExitMap patch did not register it)");
|
||||||
|
T.Check(Find.WorldPawns.ForcefullyKeptPawns.Contains(pawn),
|
||||||
|
$"pending runaway {pawn} is not in Find.WorldPawns.ForcefullyKeptPawns, world pawn GC could discard it");
|
||||||
|
RunawayRecord r = RecordOf(pawn);
|
||||||
|
T.NotNull(r, "runaway record for " + pawn);
|
||||||
|
T.Equal(e.origin, r.origin, "record origin (SlaveFaction before the escape)");
|
||||||
|
T.Equal(pawn.Faction, r.finder, "record finder (the faction vanilla gave the escapee)");
|
||||||
|
T.Equal(map, r.map, "record map");
|
||||||
|
T.Equal(SlaveInteractionModeDefOf.NoInteraction, r.mode, "record slave interaction mode");
|
||||||
|
T.Equal(e.escapeTick + 3 * GenDate.TicksPerDay, r.dueTick, "record dueTick with returnDelayMin/MaxDays = 3");
|
||||||
|
T.Check(r.pinnedByUs, "record.pinnedByUs is false although the pawn was not pinned before");
|
||||||
|
T.Check(HasMessage(e.since, SearchMessageKey, pawn, r.finder), "no 'may bring them back' message for " + pawn);
|
||||||
|
T.Check(!HasMessage(e.since, GoneMessageKey, pawn), "'nobody will bring them back' message sent although returnChance = 1");
|
||||||
|
|
||||||
|
// Not due yet: the 250-tick check has to leave the record alone.
|
||||||
|
Fixtures.Tick(CheckInterval + 10);
|
||||||
|
T.Check(GameComponent_BlaxRunaways.IsPending(pawn) && pawn.IsWorldPawn() && RecordOf(pawn) != null,
|
||||||
|
$"{pawn} left the pending state {CheckInterval + 10} ticks after escaping, 3 days before its dueTick (pending={GameComponent_BlaxRunaways.IsPending(pawn)}, world pawn={pawn.IsWorldPawn()})");
|
||||||
|
|
||||||
|
Faction finder = r.finder;
|
||||||
|
T.Check(finder != e.origin, $"precondition: finder {finder} must differ from origin {e.origin}");
|
||||||
|
SetDecoyMode(pawn, r.mode);
|
||||||
|
DeliverNow(pawn, r, map);
|
||||||
|
AssertReturned(e.since, pawn, e.origin, SlaveInteractionModeDefOf.NoInteraction, finder, map);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
ForgetEscapees();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- not registered -----------------------------------------------------------------
|
||||||
|
|
||||||
|
[BlaxTest("runaways: unbranded escapee is not registered")]
|
||||||
|
public static void UnbrandedEscapeeNotRegistered()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
RequireExitMapPatch();
|
||||||
|
Fixtures.Settings.returnRunaways = true;
|
||||||
|
Fixtures.Settings.returnChance = 1f;
|
||||||
|
|
||||||
|
Escapee e = EscapeUntilNonHostileFinder(1200, p =>
|
||||||
|
{
|
||||||
|
T.Check(!BrandUtility.IsBranded(p), "fixture slave " + p + " is already branded");
|
||||||
|
}, playerBrand: false);
|
||||||
|
|
||||||
|
AssertNotRegistered(e.pawn, "without a brand");
|
||||||
|
AssertNoRunawayMessages(e.since, e.pawn, "without a brand");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
ForgetEscapees();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("runaways: escapee with another faction's brand is not registered")]
|
||||||
|
public static void ForeignBrandedEscapeeNotRegistered()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
RequireExitMapPatch();
|
||||||
|
Fixtures.Settings.returnRunaways = true;
|
||||||
|
Fixtures.Settings.returnChance = 1f;
|
||||||
|
Faction owner = Fixtures.HostileFaction() ?? Fixtures.FriendlyFaction();
|
||||||
|
if (owner == null)
|
||||||
|
T.Skip("no non-player faction to own the brand");
|
||||||
|
|
||||||
|
Escapee e = EscapeUntilNonHostileFinder(1300, p =>
|
||||||
|
{
|
||||||
|
BrandUtility.Brand(p, owner);
|
||||||
|
T.Check(BrandUtility.IsBranded(p) && !BrandUtility.IsBrandedByPlayer(p),
|
||||||
|
$"brand on {p} should belong to {owner}, owner is {BrandUtility.BrandOf(p)?.owner.ToStringSafe()}");
|
||||||
|
}, playerBrand: false);
|
||||||
|
|
||||||
|
T.Equal(owner, BrandUtility.BrandOf(e.pawn)?.owner, "brand owner after the escape");
|
||||||
|
AssertNotRegistered(e.pawn, "carrying " + owner + "'s brand");
|
||||||
|
AssertNoRunawayMessages(e.since, e.pawn, "carrying " + owner + "'s brand");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
ForgetEscapees();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("runaways: returnRunaways off, branded escapee is not registered")]
|
||||||
|
public static void ReturnRunawaysOffNotRegistered()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
RequireExitMapPatch();
|
||||||
|
Fixtures.Settings.returnRunaways = false;
|
||||||
|
Fixtures.Settings.returnChance = 1f;
|
||||||
|
|
||||||
|
Escapee e = EscapeUntilNonHostileFinder(1400, BrandForPlayerNoInteraction, playerBrand: true);
|
||||||
|
|
||||||
|
AssertNotRegistered(e.pawn, "with returnRunaways = false");
|
||||||
|
T.Check(HasMessage(e.since, GoneMessageKey, e.pawn),
|
||||||
|
$"no 'nobody will bring them back' message for {e.pawn}; with returnRunaways = false the escape should still be reported");
|
||||||
|
T.Check(!HasMessage(e.since, SearchMessageKey, e.pawn, e.pawn.Faction), "'may bring them back' message sent although returnRunaways = false");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
ForgetEscapees();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("runaways: returnChance 0, not pinned, only a message")]
|
||||||
|
public static void ReturnChanceZeroOnlyMessage()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
RequireExitMapPatch();
|
||||||
|
Fixtures.Settings.returnRunaways = true;
|
||||||
|
Fixtures.Settings.returnChance = 0f;
|
||||||
|
|
||||||
|
Escapee e = EscapeUntilNonHostileFinder(1500, BrandForPlayerNoInteraction, playerBrand: true);
|
||||||
|
|
||||||
|
AssertNotRegistered(e.pawn, "with returnChance = 0");
|
||||||
|
T.Check(HasMessage(e.since, GoneMessageKey, e.pawn), $"no 'nobody will bring them back' message for {e.pawn} with returnChance = 0");
|
||||||
|
T.Check(!HasMessage(e.since, SearchMessageKey, e.pawn, e.pawn.Faction), "'may bring them back' message sent although returnChance = 0");
|
||||||
|
T.Check(FindLetter(e.since, KeptLabelKey, e.pawn) == null && FindLetter(e.since, ReturnedLabelKey, e.pawn) == null,
|
||||||
|
"a runaway letter was sent for " + e.pawn + " with returnChance = 0; only a message was expected");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
ForgetEscapees();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- blocked from redress and quests --------------------------------------------------
|
||||||
|
|
||||||
|
[BlaxTest("runaways: pending runaway is not redressed or taken by quests")]
|
||||||
|
public static void PendingBlockedFromRedressAndQuests()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Fixtures.Settings.returnRunaways = true;
|
||||||
|
Fixtures.Settings.returnChance = 1f;
|
||||||
|
Fixtures.Settings.returnDelayMinDays = 5;
|
||||||
|
Fixtures.Settings.returnDelayMaxDays = 5;
|
||||||
|
|
||||||
|
Escapee e = EscapeUntilNonHostileFinder(1600, BrandForPlayerNoInteraction, playerBrand: true);
|
||||||
|
Pawn pawn = e.pawn;
|
||||||
|
T.Check(GameComponent_BlaxRunaways.IsPending(pawn), $"{pawn} is not pending after a branded escape, nothing to check");
|
||||||
|
|
||||||
|
MethodInfo redress = AccessTools.Method(typeof(PawnGenerator), "IsValidCandidateToRedress");
|
||||||
|
T.NotNull(redress, "PawnGenerator.IsValidCandidateToRedress");
|
||||||
|
// Loose request (no faction, so no faction-xenotype filter) that vanilla should accept the escapee for.
|
||||||
|
var request = new PawnGenerationRequest(pawn.kindDef, null, PawnGenerationContext.NonPlayer,
|
||||||
|
allowDowned: true, canGeneratePawnRelations: true, allowGay: true, allowPregnant: true,
|
||||||
|
allowAddictions: true, worldPawnFactionDoesntMatter: true, developmentalStages: DevelopmentalStage.Adult);
|
||||||
|
|
||||||
|
MethodInfo goodPawn = AccessTools.Method(typeof(QuestNode_GetPawn), "IsGoodPawn");
|
||||||
|
T.NotNull(goodPawn, "QuestNode_GetPawn.IsGoodPawn");
|
||||||
|
var node = new QuestNode_GetPawn();
|
||||||
|
var slate = new Slate();
|
||||||
|
|
||||||
|
int verified = 0;
|
||||||
|
verified += CheckBlockedWhilePending("PawnGenerator.IsValidCandidateToRedress", pawn,
|
||||||
|
() => (bool)redress.Invoke(null, new object[] { pawn, request }));
|
||||||
|
verified += CheckBlockedWhilePending("QuestNode_GetPawn.IsGoodPawn", pawn,
|
||||||
|
() => (bool)goodPawn.Invoke(node, new object[] { pawn, slate }));
|
||||||
|
if (verified == 0)
|
||||||
|
T.Skip("vanilla rejects the escapee in both methods even when it is not pending, so the patches can't be told apart from vanilla");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
ForgetEscapees();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- save and reload ----------------------------------------------------------------
|
||||||
|
|
||||||
|
[BlaxTest("runaways: set up a pending runaway for the reload check")]
|
||||||
|
public static void SetupPendingRunawayForReload()
|
||||||
|
{
|
||||||
|
Pawn keep = null;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
RequireExitMapPatch();
|
||||||
|
BlaxSlavesSettings s = Fixtures.Settings;
|
||||||
|
s.returnRunaways = true;
|
||||||
|
s.returnChance = 1f;
|
||||||
|
s.returnDelayMinDays = 20;
|
||||||
|
s.returnDelayMaxDays = 20;
|
||||||
|
|
||||||
|
Escapee e = EscapeUntilNonHostileFinder(1700, BrandForPlayerNoInteraction, playerBrand: true, distinctFinder: true);
|
||||||
|
Pawn pawn = e.pawn;
|
||||||
|
T.Check(GameComponent_BlaxRunaways.IsPending(pawn), $"{pawn} is not pending after a branded escape");
|
||||||
|
RunawayRecord r = RecordOf(pawn);
|
||||||
|
T.NotNull(r, "runaway record for " + pawn);
|
||||||
|
T.Equal(e.escapeTick + 20 * GenDate.TicksPerDay, r.dueTick, "record dueTick with a 20-day delay");
|
||||||
|
T.NotNull(r.finder, "record finder");
|
||||||
|
T.Equal(e.origin, r.origin, "record origin");
|
||||||
|
T.Equal(SlaveInteractionModeDefOf.NoInteraction, r.mode, "record slave interaction mode");
|
||||||
|
|
||||||
|
keep = Fixtures.Keep(pawn);
|
||||||
|
T.Carry[CarryPawn] = pawn.ThingID;
|
||||||
|
T.Carry[CarryOrigin] = e.origin.GetUniqueLoadID();
|
||||||
|
T.Carry[CarryFinder] = r.finder.GetUniqueLoadID();
|
||||||
|
T.Carry[CarryDueTick] = r.dueTick.ToString();
|
||||||
|
T.Info($"kept pending runaway {pawn} ({pawn.ThingID}), origin {e.origin}, finder {r.finder}, due tick {r.dueTick}");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
ForgetEscapees(keep);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("runaways: pending runaway survives save and reload, then is returned", phase: 2)]
|
||||||
|
public static void PendingRunawaySurvivesReload()
|
||||||
|
{
|
||||||
|
if (!T.Carry.TryGetValue(CarryPawn, out string id))
|
||||||
|
T.Skip("phase 1 stored no pending runaway; see 'runaways: set up a pending runaway for the reload check'");
|
||||||
|
Pawn pawn = Fixtures.FindPawnById(id);
|
||||||
|
T.NotNull(pawn, "pending runaway " + id + " after reload");
|
||||||
|
// The runner silences the storyteller only before phase 1; loading the save rebuilt its
|
||||||
|
// comps, so a raid could land during the delivery ticks below.
|
||||||
|
Fixtures.QuietStoryteller();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Faction origin = FactionByLoadId(T.Carry[CarryOrigin]);
|
||||||
|
Faction finder = FactionByLoadId(T.Carry[CarryFinder]);
|
||||||
|
T.NotNull(origin, "origin faction " + T.Carry[CarryOrigin] + " after reload");
|
||||||
|
int dueTick = int.Parse(T.Carry[CarryDueTick]);
|
||||||
|
Map map = Fixtures.Map;
|
||||||
|
|
||||||
|
T.Check(pawn.IsWorldPawn() && !pawn.Spawned,
|
||||||
|
$"{pawn} should still be a world pawn after reload: spawned={pawn.Spawned}, world pawn={pawn.IsWorldPawn()}");
|
||||||
|
T.Check(GameComponent_BlaxRunaways.IsPending(pawn),
|
||||||
|
$"{pawn} not pending after reload: the static pending set was not rebuilt from the saved records");
|
||||||
|
RunawayRecord r = RecordOf(pawn);
|
||||||
|
T.NotNull(r, "runaway record for " + pawn + " after reload");
|
||||||
|
T.Equal(origin, r.origin, "record origin after reload");
|
||||||
|
T.Equal(finder, r.finder, "record finder after reload");
|
||||||
|
T.Equal(dueTick, r.dueTick, "record dueTick after reload");
|
||||||
|
T.Equal(map, r.map, "record map after reload");
|
||||||
|
T.Equal(SlaveInteractionModeDefOf.NoInteraction, r.mode, "record mode after reload");
|
||||||
|
T.Check(r.dueTick > Find.TickManager.TicksGame,
|
||||||
|
$"record already due ({r.dueTick} <= {Find.TickManager.TicksGame}) before the test forced it");
|
||||||
|
T.Check(r.pinnedByUs, "record.pinnedByUs lost over save and reload");
|
||||||
|
T.Check(Find.WorldPawns.ForcefullyKeptPawns.Contains(pawn), $"{pawn} not in ForcefullyKeptPawns after reload");
|
||||||
|
T.Check(BrandUtility.IsBrandedByPlayer(pawn), $"{pawn} lost the player's brand over save and reload");
|
||||||
|
|
||||||
|
// Other phase-1 tests may have soured relations; a hostile holder rightly keeps them.
|
||||||
|
if (pawn.Faction != null && pawn.Faction.HostileTo(Faction.OfPlayer))
|
||||||
|
T.Skip($"reload state checked; {pawn}'s faction {pawn.Faction} turned hostile during phase 1, so delivery would rightly be cancelled");
|
||||||
|
|
||||||
|
T.Check(r.finder != origin, $"precondition: finder {r.finder} must differ from origin {origin}");
|
||||||
|
Faction deliverer = r.finder;
|
||||||
|
SetDecoyMode(pawn, r.mode);
|
||||||
|
var since = new Snapshot();
|
||||||
|
DeliverNow(pawn, r, map);
|
||||||
|
AssertReturned(since, pawn, origin, SlaveInteractionModeDefOf.NoInteraction, deliverer, map);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
escapees.Add(pawn);
|
||||||
|
ForgetEscapees();
|
||||||
|
Dispose(pawn);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- escape helpers -----------------------------------------------------------------
|
||||||
|
|
||||||
|
private sealed class Escapee
|
||||||
|
{
|
||||||
|
public Pawn pawn;
|
||||||
|
public Faction origin;
|
||||||
|
public int escapeTick;
|
||||||
|
public Snapshot since; // letters and messages that existed just before the escape
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Letters and archived messages that already exist, so lookups only see newer ones.</summary>
|
||||||
|
private sealed class Snapshot
|
||||||
|
{
|
||||||
|
public readonly HashSet<Letter> letters = new HashSet<Letter>(Find.LetterStack.LettersListForReading);
|
||||||
|
public readonly HashSet<Message> messages = new HashSet<Message>(Find.Archive.ArchivablesListForReading.OfType<Message>());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void BrandForPlayerNoInteraction(Pawn p)
|
||||||
|
{
|
||||||
|
BrandUtility.Brand(p, Faction.OfPlayer);
|
||||||
|
p.guest.slaveInteractionMode = SlaveInteractionModeDefOf.NoInteraction;
|
||||||
|
T.Check(BrandUtility.IsBrandedByPlayer(p), $"BrandUtility.Brand did not mark {p} as the player's");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The live interaction mode never changes between escape and delivery (SetGuestStatus keeps
|
||||||
|
/// it for a pawn that was enslaved before), so checking it after delivery proves nothing
|
||||||
|
/// unless it differs from the record. Set it to something else on the free world pawn: only
|
||||||
|
/// RunawayDelivery copying record.mode back can make the post-delivery check pass.
|
||||||
|
/// </summary>
|
||||||
|
private static void SetDecoyMode(Pawn pawn, SlaveInteractionModeDef recorded)
|
||||||
|
{
|
||||||
|
SlaveInteractionModeDef decoy = recorded == SlaveInteractionModeDefOf.Suppress
|
||||||
|
? SlaveInteractionModeDefOf.NoInteraction
|
||||||
|
: SlaveInteractionModeDefOf.Suppress;
|
||||||
|
pawn.guest.slaveInteractionMode = decoy;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A non-hostile humanlike faction to enslave from. Prefers one vanilla rarely picks for a
|
||||||
|
/// freed escapee (below Medieval: weight 0.1 in TryGetRandomNonColonyHumanlikeFaction), so a
|
||||||
|
/// finder different from the origin comes up more often.
|
||||||
|
/// </summary>
|
||||||
|
private static Faction OriginFaction() =>
|
||||||
|
Find.FactionManager.AllFactionsVisible
|
||||||
|
.Where(f => !f.IsPlayer && !f.defeated && !f.temporary && f.def.humanlikeFaction && !f.HostileTo(Faction.OfPlayer))
|
||||||
|
.OrderBy(f => f.def.techLevel >= TechLevel.Medieval ? 1 : 0)
|
||||||
|
.ThenBy(f => f.loadID)
|
||||||
|
.FirstOrDefault();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Enslaves a pawn from a non-hostile faction, prepares it and lets it escape like vanilla,
|
||||||
|
/// under Rand seed + attempt. Retries while vanilla hands the escapee a hostile faction, or,
|
||||||
|
/// with distinctFinder, the origin faction itself.
|
||||||
|
/// </summary>
|
||||||
|
private static Escapee EscapeUntilNonHostileFinder(int seed, Action<Pawn> prepare, bool playerBrand, bool distinctFinder = false)
|
||||||
|
{
|
||||||
|
Faction origin = OriginFaction();
|
||||||
|
if (origin == null)
|
||||||
|
T.Skip("no visible non-hostile humanlike faction to enslave a pawn from");
|
||||||
|
var hostile = new List<string>();
|
||||||
|
for (int attempt = 0; attempt < MaxEscapeAttempts; attempt++)
|
||||||
|
{
|
||||||
|
Pawn slave;
|
||||||
|
int tick;
|
||||||
|
Snapshot since;
|
||||||
|
Rand.PushState(seed + attempt);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
slave = Fixtures.ColonySlave(origin);
|
||||||
|
escapees.Add(slave);
|
||||||
|
T.Check(slave.IsSlaveOfColony, $"fixture pawn {slave} is not a slave of the colony");
|
||||||
|
T.Equal(origin, slave.SlaveFaction, "SlaveFaction of the fixture slave");
|
||||||
|
prepare?.Invoke(slave);
|
||||||
|
tick = Find.TickManager.TicksGame;
|
||||||
|
since = new Snapshot();
|
||||||
|
EscapeLikeVanilla(slave);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Rand.PopState();
|
||||||
|
}
|
||||||
|
|
||||||
|
T.Check(!slave.Spawned && slave.IsWorldPawn(),
|
||||||
|
$"after ExitMap {slave} should be a world pawn: spawned={slave.Spawned}, world pawn={slave.IsWorldPawn()}, caravan={slave.IsCaravanMember()}");
|
||||||
|
T.Check(!slave.IsSlave && slave.Faction != Faction.OfPlayer,
|
||||||
|
$"vanilla should have freed {slave} on passing to the world: faction={slave.Faction.ToStringSafe()}, slave={slave.IsSlave}");
|
||||||
|
|
||||||
|
Faction got = slave.Faction;
|
||||||
|
if (got == null)
|
||||||
|
T.Skip($"vanilla left escapee {slave} without a faction (no humanlike faction to hand them to)");
|
||||||
|
if (distinctFinder && got == origin && !got.HostileTo(Faction.OfPlayer))
|
||||||
|
{
|
||||||
|
// Back with its origin: useless for the restore checks. Drop it from the mod now.
|
||||||
|
ForgetOne(slave);
|
||||||
|
hostile.Add(got.Name + " (the origin)");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!got.HostileTo(Faction.OfPlayer))
|
||||||
|
{
|
||||||
|
T.Check(Find.WorldPawns.GetSituation(slave) == WorldPawnSituation.Free,
|
||||||
|
$"escapee {slave} has world situation {Find.WorldPawns.GetSituation(slave)}, expected Free");
|
||||||
|
if (attempt > 0)
|
||||||
|
T.Info($"escape attempt {attempt + 1}: {slave} went to non-hostile {got}");
|
||||||
|
return new Escapee { pawn = slave, origin = origin, escapeTick = tick, since = since };
|
||||||
|
}
|
||||||
|
|
||||||
|
// A hostile faction keeps them: never pinned; the player's brand still gets a letter.
|
||||||
|
T.Check(!GameComponent_BlaxRunaways.IsPending(slave), $"{slave} ran to hostile {got} but was registered as pending");
|
||||||
|
T.Check(!Find.WorldPawns.ForcefullyKeptPawns.Contains(slave), $"{slave} ran to hostile {got} but was pinned as a world pawn");
|
||||||
|
bool kept = FindLetter(since, KeptLabelKey, slave) != null;
|
||||||
|
if (playerBrand)
|
||||||
|
T.Check(kept, $"{slave} with the player's brand ran to hostile {got}, expected a 'Runaway kept' letter");
|
||||||
|
else
|
||||||
|
T.Check(!kept, $"'Runaway kept' letter for {slave}, who did not carry the player's brand");
|
||||||
|
hostile.Add(got.Name);
|
||||||
|
}
|
||||||
|
T.Skip($"vanilla gave all {MaxEscapeAttempts} escapees an unusable faction (hostile{(distinctFinder ? " or the origin " + origin : "")}: {string.Join(", ", hostile)}), so this path can't be reached");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The end of a slave rebellion: the slave is in a LordJob_SlaveRebellion lord (as
|
||||||
|
/// SlaveRebellionUtility.StartSlaveRebellion makes it, but for this slave only) and reaches the
|
||||||
|
/// edge, where JobDriver_Goto calls ExitMap(allowedToJoinOrCreateCaravan: true, closest edge).
|
||||||
|
/// </summary>
|
||||||
|
private static void EscapeLikeVanilla(Pawn slave)
|
||||||
|
{
|
||||||
|
Map map = slave.Map;
|
||||||
|
IntVec3 exit = new IntVec3(0, 0, slave.Position.z);
|
||||||
|
LordMaker.MakeNewLord(slave.Faction, new LordJob_SlaveRebellion(slave.Position, exit, -1, passive: true), map, new List<Pawn> { slave });
|
||||||
|
T.Check(SlaveRebellionUtility.IsRebelling(slave), $"{slave} is not rebelling after joining a LordJob_SlaveRebellion lord");
|
||||||
|
slave.ExitMap(allowedToJoinOrCreateCaravan: true, CellRect.WholeMap(map).GetClosestEdge(slave.Position));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void RequireExitMapPatch()
|
||||||
|
{
|
||||||
|
MethodInfo exitMap = AccessTools.Method(typeof(Pawn), nameof(Pawn.ExitMap));
|
||||||
|
HarmonyLib.Patches info = exitMap == null ? null : Harmony.GetPatchInfo(exitMap);
|
||||||
|
bool ok = info != null
|
||||||
|
&& info.Prefixes.Any(p => p.owner == "blax.slaves")
|
||||||
|
&& info.Postfixes.Any(p => p.owner == "blax.slaves");
|
||||||
|
T.Check(ok, "Pawn.ExitMap has no blax.slaves prefix and postfix: Patch_RunawayExitMap did not apply");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Drops this test's escapees from the runaway component (record, pending set, our pin), so
|
||||||
|
/// nothing stale reaches later tests or the save. Never throws: it runs in finally blocks.
|
||||||
|
/// </summary>
|
||||||
|
private static void ForgetEscapees(Pawn keep = null)
|
||||||
|
{
|
||||||
|
foreach (Pawn p in escapees)
|
||||||
|
{
|
||||||
|
if (p == null || p == keep)
|
||||||
|
continue;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
ForgetOne(p);
|
||||||
|
// A failed test can leave a delivered pawn inside a falling drop pod, which
|
||||||
|
// Fixtures.Cleanup does not see (neither spawned nor a world pawn).
|
||||||
|
if (!p.Destroyed && !p.Spawned && !p.IsWorldPawn() && p.SpawnedOrAnyParentSpawned)
|
||||||
|
p.Destroy(DestroyMode.Vanish);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
T.Info("forgetting escapee " + p.ToStringSafe() + " threw: " + ex.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
escapees.Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Removes one pawn's record, pending entry and our pin from the runaway component.</summary>
|
||||||
|
private static void ForgetOne(Pawn p)
|
||||||
|
{
|
||||||
|
GameComponent_BlaxRunaways comp = GameComponent_BlaxRunaways.Instance;
|
||||||
|
var records = comp == null ? null : AccessTools.Field(typeof(GameComponent_BlaxRunaways), "records")?.GetValue(comp) as List<RunawayRecord>;
|
||||||
|
var pending = AccessTools.Field(typeof(GameComponent_BlaxRunaways), "pending")?.GetValue(null) as HashSet<Pawn>;
|
||||||
|
bool pinnedByUs = false;
|
||||||
|
if (records != null)
|
||||||
|
{
|
||||||
|
foreach (RunawayRecord r in records.Where(r => r != null && r.pawn == p).ToList())
|
||||||
|
{
|
||||||
|
pinnedByUs |= r.pinnedByUs;
|
||||||
|
records.Remove(r);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pending?.Remove(p);
|
||||||
|
if (pinnedByUs && Find.WorldPawns.Contains(p))
|
||||||
|
Find.WorldPawns.ForcefullyKeptPawns.Remove(p);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- delivery -----------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// <summary>Makes the record due now, ticks past the 250-tick check, then until the pawn is on the map.</summary>
|
||||||
|
private static void DeliverNow(Pawn pawn, RunawayRecord record, Map map)
|
||||||
|
{
|
||||||
|
record.dueTick = Find.TickManager.TicksGame;
|
||||||
|
int waited = 0;
|
||||||
|
while (GameComponent_BlaxRunaways.IsPending(pawn) && waited < CheckInterval + 10)
|
||||||
|
{
|
||||||
|
Fixtures.Tick(1);
|
||||||
|
waited++;
|
||||||
|
}
|
||||||
|
T.Check(!GameComponent_BlaxRunaways.IsPending(pawn),
|
||||||
|
$"{pawn} still pending {waited} ticks after its record fell due (dueTick now {record.dueTick}; it moves on Retry), world pawn={pawn.IsWorldPawn()}, situation={Find.WorldPawns.GetSituation(pawn)}");
|
||||||
|
T.Check(!pawn.IsWorldPawn(),
|
||||||
|
$"{pawn} left the pending set but is still a world pawn: delivery was cancelled (faction {pawn.Faction.ToStringSafe()}, situation {Find.WorldPawns.GetSituation(pawn)})");
|
||||||
|
|
||||||
|
int landing = 0;
|
||||||
|
while (!(pawn.Spawned && pawn.Map == map) && landing < MaxLandingTicks)
|
||||||
|
{
|
||||||
|
Fixtures.Tick(10);
|
||||||
|
landing += 10;
|
||||||
|
}
|
||||||
|
T.Check(pawn.Spawned && pawn.Map == map,
|
||||||
|
$"{pawn} not on the home map {MaxLandingTicks} ticks after delivery: spawned={pawn.Spawned}, map={pawn.MapHeld.ToStringSafe()}, holder={pawn.ParentHolder.ToStringSafe()}, destroyed={pawn.Destroyed}");
|
||||||
|
T.Info($"{pawn} delivered after {waited} ticks, on the map {landing} ticks later");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void AssertReturned(Snapshot since, Pawn pawn, Faction origin, SlaveInteractionModeDef mode, Faction deliverer, Map map)
|
||||||
|
{
|
||||||
|
T.Check(pawn.Spawned && pawn.Map == map, $"{pawn} is not spawned on the home map");
|
||||||
|
T.Check(pawn.IsSlaveOfColony,
|
||||||
|
$"returned {pawn} is not a slave of the colony: faction={pawn.Faction.ToStringSafe()}, slave={pawn.IsSlave}, prisoner={pawn.IsPrisoner}");
|
||||||
|
T.Equal(origin, pawn.SlaveFaction, "SlaveFaction after the return (origin restored before re-enslaving)");
|
||||||
|
T.Equal(origin, pawn.HomeFaction, "HomeFaction after the return");
|
||||||
|
T.Equal(mode, pawn.guest.slaveInteractionMode, "slave interaction mode after the return");
|
||||||
|
T.Check(BrandUtility.IsBrandedByPlayer(pawn),
|
||||||
|
$"returned {pawn} lost the player's brand (branded={BrandUtility.IsBranded(pawn)}, owner={BrandUtility.BrandOf(pawn)?.owner.ToStringSafe()})");
|
||||||
|
T.Check(!GameComponent_BlaxRunaways.IsPending(pawn), $"returned {pawn} is still pending");
|
||||||
|
T.Check(RecordOf(pawn) == null, $"returned {pawn} still has a runaway record");
|
||||||
|
T.Check(!Find.WorldPawns.ForcefullyKeptPawns.Contains(pawn), $"returned {pawn} is still pinned in ForcefullyKeptPawns");
|
||||||
|
|
||||||
|
Letter letter = FindLetter(since, ReturnedLabelKey, pawn);
|
||||||
|
if (letter == null)
|
||||||
|
{
|
||||||
|
string fresh = string.Join(" | ", Find.LetterStack.LettersListForReading.Where(l => !since.letters.Contains(l)).Select(l => l.Label.RawText));
|
||||||
|
T.Fail($"no 'Runaway returned' letter for {pawn} in Find.LetterStack; letters since the escape: [{fresh}]");
|
||||||
|
}
|
||||||
|
T.Equal(LetterDefOf.PositiveEvent, letter.def, "returned letter def");
|
||||||
|
T.Equal(deliverer, letter.relatedFaction, "returned letter faction (the finder who brought them back)");
|
||||||
|
T.Check(letter.lookTargets != null && letter.lookTargets.targets.Any(t => t.Thing == pawn), "returned letter does not point at " + pawn);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- negative checks ----------------------------------------------------------------
|
||||||
|
|
||||||
|
private static void AssertNotRegistered(Pawn pawn, string why)
|
||||||
|
{
|
||||||
|
T.Check(!GameComponent_BlaxRunaways.IsPending(pawn), $"escapee {pawn} {why} is pending (registered), expected not");
|
||||||
|
T.Check(RecordOf(pawn) == null, $"escapee {pawn} {why} has a runaway record, expected none");
|
||||||
|
T.Check(!Find.WorldPawns.ForcefullyKeptPawns.Contains(pawn), $"escapee {pawn} {why} is pinned in ForcefullyKeptPawns, expected not");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void AssertNoRunawayMessages(Snapshot since, Pawn pawn, string why)
|
||||||
|
{
|
||||||
|
T.Check(!HasMessage(since, SearchMessageKey, pawn, pawn.Faction), $"'may bring them back' message for escapee {pawn} {why}");
|
||||||
|
T.Check(!HasMessage(since, GoneMessageKey, pawn), $"'nobody will bring them back' message for escapee {pawn} {why}; the mod should ignore this escape");
|
||||||
|
T.Check(FindLetter(since, KeptLabelKey, pawn) == null && FindLetter(since, ReturnedLabelKey, pawn) == null, $"runaway letter for escapee {pawn} {why}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Runs a patched vanilla check with the pawn pending and, as the control, with it taken out of
|
||||||
|
/// the pending set. Returns 1 when verified, 0 when vanilla itself rejects the pawn.
|
||||||
|
/// </summary>
|
||||||
|
private static int CheckBlockedWhilePending(string what, Pawn pawn, Func<bool> check)
|
||||||
|
{
|
||||||
|
bool whilePending = check();
|
||||||
|
HashSet<Pawn> pending = PendingSet();
|
||||||
|
bool removed = pending.Remove(pawn);
|
||||||
|
bool notPending;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
notPending = check();
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
if (removed)
|
||||||
|
pending.Add(pawn);
|
||||||
|
}
|
||||||
|
T.Check(removed, $"{pawn} was not in GameComponent_BlaxRunaways' pending set");
|
||||||
|
if (!notPending)
|
||||||
|
{
|
||||||
|
T.Info($"{what} rejects {pawn} even when it is not pending; this check can't tell the patch from vanilla");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
T.Check(!whilePending, $"{what} accepted pending runaway {pawn}: expected false while pending (it returns true once the pawn is not pending)");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- lookups ------------------------------------------------------------------------
|
||||||
|
|
||||||
|
private static List<RunawayRecord> Records()
|
||||||
|
{
|
||||||
|
GameComponent_BlaxRunaways comp = GameComponent_BlaxRunaways.Instance;
|
||||||
|
T.NotNull(comp, "GameComponent_BlaxRunaways.Instance");
|
||||||
|
var list = AccessTools.Field(typeof(GameComponent_BlaxRunaways), "records")?.GetValue(comp) as List<RunawayRecord>;
|
||||||
|
T.NotNull(list, "GameComponent_BlaxRunaways.records");
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static RunawayRecord RecordOf(Pawn pawn) => Records().FirstOrDefault(r => r != null && r.pawn == pawn);
|
||||||
|
|
||||||
|
private static HashSet<Pawn> PendingSet()
|
||||||
|
{
|
||||||
|
var set = AccessTools.Field(typeof(GameComponent_BlaxRunaways), "pending")?.GetValue(null) as HashSet<Pawn>;
|
||||||
|
T.NotNull(set, "GameComponent_BlaxRunaways.pending");
|
||||||
|
return set;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Faction FactionByLoadId(string loadId) =>
|
||||||
|
Find.FactionManager.AllFactionsListForReading.FirstOrDefault(f => f.GetUniqueLoadID() == loadId);
|
||||||
|
|
||||||
|
/// <summary>A message archived after the snapshot with exactly the text the mod sends for this pawn (and faction).</summary>
|
||||||
|
private static bool HasMessage(Snapshot since, string key, Pawn pawn, Faction faction = null)
|
||||||
|
{
|
||||||
|
string text = faction == null
|
||||||
|
? (string)key.Translate(pawn.Named("PAWN"))
|
||||||
|
: (string)key.Translate(pawn.Named("PAWN"), faction.Named("FACTION"));
|
||||||
|
text = text.CapitalizeFirst();
|
||||||
|
return Find.Archive.ArchivablesListForReading.OfType<Message>().Any(m => !since.messages.Contains(m) && m.text == text);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The newest letter received after the snapshot whose label is the mod's label for this pawn.</summary>
|
||||||
|
private static Letter FindLetter(Snapshot since, string labelKey, Pawn pawn)
|
||||||
|
{
|
||||||
|
string label = labelKey.Translate(pawn.Named("PAWN")).CapitalizeFirst().RawText;
|
||||||
|
return Find.LetterStack.LettersListForReading.LastOrDefault(l => !since.letters.Contains(l) && l.Label.RawText == label);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Phase-2 pawns are not tracked by Fixtures, so remove this one by hand.</summary>
|
||||||
|
private static void Dispose(Pawn pawn)
|
||||||
|
{
|
||||||
|
if (pawn == null)
|
||||||
|
return;
|
||||||
|
if (!pawn.Destroyed && !pawn.IsWorldPawn())
|
||||||
|
pawn.Destroy(DestroyMode.Vanish); // spawned, or still inside a drop pod
|
||||||
|
if (pawn.IsWorldPawn())
|
||||||
|
Find.WorldPawns.RemoveAndDiscardPawnViaGC(pawn); // alive, or passed to the world as dead by Pawn.Destroy
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,62 @@
|
||||||
|
using System.Linq;
|
||||||
|
using BlaxSlaves;
|
||||||
|
using HarmonyLib;
|
||||||
|
using RimWorld;
|
||||||
|
using Verse;
|
||||||
|
|
||||||
|
namespace BlaxSlavesTests
|
||||||
|
{
|
||||||
|
public static class SmokeTests
|
||||||
|
{
|
||||||
|
[BlaxTest("startup: patches applied and logged")]
|
||||||
|
public static void PatchesApplied()
|
||||||
|
{
|
||||||
|
var ours = Harmony.GetAllPatchedMethods()
|
||||||
|
.Select(Harmony.GetPatchInfo)
|
||||||
|
.Where(info => info != null)
|
||||||
|
.SelectMany(info => info.Prefixes.Concat(info.Postfixes).Concat(info.Finalizers).Concat(info.Transpilers))
|
||||||
|
.Count(p => p.owner == "blax.slaves");
|
||||||
|
T.Info("Harmony patches owned by blax.slaves: " + ours);
|
||||||
|
T.Check(ours >= 17, "expected at least 17 patches from blax.slaves, found " + ours);
|
||||||
|
bool logged = Log.Messages.Any(m => m.text != null && m.text.Contains("[Blax Slaves]") && m.text.Contains("patches applied"));
|
||||||
|
T.Check(logged, "startup line '[Blax Slaves] N patches applied' not in the log");
|
||||||
|
var errors = Log.Messages.Where(m => m.type == LogMessageType.Error && m.text != null && m.text.Contains("Blax")).ToList();
|
||||||
|
T.Check(errors.Count == 0, "errors mentioning Blax at startup: " + string.Join(" | ", errors.Take(3).Select(e => e.text)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("startup: settings and defs loaded")]
|
||||||
|
public static void DefsLoaded()
|
||||||
|
{
|
||||||
|
T.NotNull(BlaxSlavesMod.Settings, "BlaxSlavesMod.Settings");
|
||||||
|
T.NotNull(BlaxDefOf.BlaxSlaves_SlaveBrand, "hediff BlaxSlaves_SlaveBrand");
|
||||||
|
T.NotNull(DefDatabase<RecipeDef>.GetNamedSilentFail("BlaxSlaves_BrandSlave"), "recipe BlaxSlaves_BrandSlave");
|
||||||
|
T.NotNull(DefDatabase<RecipeDef>.GetNamedSilentFail("BlaxSlaves_RebrandSlave"), "recipe BlaxSlaves_RebrandSlave");
|
||||||
|
T.NotNull(DefDatabase<ThoughtDef>.GetNamedSilentFail("BlaxSlaves_Branded"), "thought BlaxSlaves_Branded");
|
||||||
|
T.Check(ThingDefOf.Human.AllRecipes.Any(r => r.defName == "BlaxSlaves_BrandSlave"), "humans don't list the branding surgery");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("harness: colony slave fixture")]
|
||||||
|
public static void SlaveFixture()
|
||||||
|
{
|
||||||
|
Pawn slave = Fixtures.ColonySlave();
|
||||||
|
T.Check(slave.Spawned, "slave not spawned");
|
||||||
|
T.Check(slave.IsSlaveOfColony, "fixture pawn is not a slave of the colony");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("harness: save and reload kept a marker pawn", phase: 2)]
|
||||||
|
public static void ReloadWorked()
|
||||||
|
{
|
||||||
|
T.Check(T.Carry.TryGetValue("marker", out string id), "phase 1 marker missing");
|
||||||
|
Pawn p = Fixtures.FindPawnById(id);
|
||||||
|
T.NotNull(p, "marker pawn " + id + " after reload");
|
||||||
|
T.Check(p.IsSlaveOfColony, "marker pawn lost slave status over save and load");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("harness: set up marker pawn for reload")]
|
||||||
|
public static void MarkerSetup()
|
||||||
|
{
|
||||||
|
Pawn slave = Fixtures.Keep(Fixtures.ColonySlave());
|
||||||
|
T.Carry["marker"] = slave.ThingID;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,797 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Reflection;
|
||||||
|
using BlaxSlaves;
|
||||||
|
using HarmonyLib;
|
||||||
|
using RimWorld;
|
||||||
|
using RimWorld.Planet;
|
||||||
|
using Verse;
|
||||||
|
|
||||||
|
namespace BlaxSlavesTests
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Slavers, slave stock and trader branding: Patches/BlaxSlaves_Traders.xml and
|
||||||
|
/// Patch_TraderSlaveBrand (postfix on ThingWithComps.PostGeneratedForTrader).
|
||||||
|
/// Stock is generated through vanilla's ThingSetMakerDefOf.TraderStock (what caravans use)
|
||||||
|
/// or a real TradeShip (what the orbital trader incident uses), then discarded again.
|
||||||
|
/// </summary>
|
||||||
|
public static class TradersTests
|
||||||
|
{
|
||||||
|
// ---- expected values, copied from Patches/BlaxSlaves_Traders.xml ----------------
|
||||||
|
|
||||||
|
private static readonly string[] Slavers =
|
||||||
|
{ "Caravan_Outlander_PirateMerchant", "Caravan_Neolithic_Slaver", "Orbital_PirateMerchant" };
|
||||||
|
|
||||||
|
private const float SlaverCommonality = 2f;
|
||||||
|
|
||||||
|
private static readonly (float x, float y)[] SlaverPopulationCurve = { (0f, 0.5f), (1f, 1f), (2f, 2f) };
|
||||||
|
|
||||||
|
private static readonly Dictionary<string, IntRange> SlaverSlaveCount = new Dictionary<string, IntRange>
|
||||||
|
{
|
||||||
|
{ "Caravan_Outlander_PirateMerchant", new IntRange(5, 9) },
|
||||||
|
{ "Caravan_Neolithic_Slaver", new IntRange(4, 7) },
|
||||||
|
{ "Orbital_PirateMerchant", new IntRange(6, 10) },
|
||||||
|
};
|
||||||
|
|
||||||
|
private static readonly IntRange OtherTraderSlaveCount = new IntRange(-1, 2);
|
||||||
|
|
||||||
|
private static readonly IntRange SettlementSlaveCount = new IntRange(1, 4);
|
||||||
|
|
||||||
|
private const string HarmonyId = "blax.slaves";
|
||||||
|
|
||||||
|
// ---- patch and defs --------------------------------------------------------------
|
||||||
|
|
||||||
|
[BlaxTest("traders: brand postfix sits on PostGeneratedForTrader and reaches pawns")]
|
||||||
|
public static void BrandPatchApplied()
|
||||||
|
{
|
||||||
|
MethodInfo target = AccessTools.Method(typeof(ThingWithComps), nameof(ThingWithComps.PostGeneratedForTrader));
|
||||||
|
T.NotNull(target, "ThingWithComps.PostGeneratedForTrader");
|
||||||
|
var info = Harmony.GetPatchInfo(target);
|
||||||
|
bool ours = info != null && info.Postfixes.Any(p => p.owner == HarmonyId && p.PatchMethod?.DeclaringType == typeof(Patch_TraderSlaveBrand));
|
||||||
|
T.Check(ours, "no blax.slaves postfix from Patch_TraderSlaveBrand on ThingWithComps.PostGeneratedForTrader (postfix owners: "
|
||||||
|
+ (info == null ? "none" : string.Join(", ", info.Postfixes.Select(p => p.owner))) + ")");
|
||||||
|
|
||||||
|
MethodInfo onPawn = typeof(Pawn).GetMethod(nameof(Pawn.PostGeneratedForTrader), BindingFlags.Public | BindingFlags.Instance);
|
||||||
|
T.Check(onPawn != null && onPawn.DeclaringType == typeof(ThingWithComps),
|
||||||
|
"Pawn.PostGeneratedForTrader resolves to " + (onPawn?.DeclaringType?.Name ?? "nothing") + ", expected the patched ThingWithComps method");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("traders: allies can request the slaver caravans")]
|
||||||
|
public static void SlaverCaravansRequestable()
|
||||||
|
{
|
||||||
|
foreach (string name in new[] { "Caravan_Outlander_PirateMerchant", "Caravan_Neolithic_Slaver" })
|
||||||
|
{
|
||||||
|
TraderKindDef def = TraderDef(name);
|
||||||
|
T.Check(def.requestable, name + ".requestable is false, so the comms console hides it");
|
||||||
|
T.Check(DefDatabase<FactionDef>.AllDefs.Any(f => f.caravanTraderKinds != null && f.caravanTraderKinds.Contains(def)),
|
||||||
|
"no faction lists " + name + " in caravanTraderKinds");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("traders: slavers have commonality 2 and the softened population curve")]
|
||||||
|
public static void SlaverCommonalityPatched()
|
||||||
|
{
|
||||||
|
var problems = new List<string>();
|
||||||
|
string expectedCurve = string.Join(" ", SlaverPopulationCurve.Select(p => $"({p.x}, {p.y})"));
|
||||||
|
foreach (string name in Slavers)
|
||||||
|
{
|
||||||
|
TraderKindDef def = TraderDef(name);
|
||||||
|
if (!Near(def.commonality, SlaverCommonality))
|
||||||
|
problems.Add($"{name}.commonality = {def.commonality}, expected {SlaverCommonality}");
|
||||||
|
|
||||||
|
SimpleCurve curve = def.commonalityMultFromPopulationIntent;
|
||||||
|
if (curve == null)
|
||||||
|
{
|
||||||
|
problems.Add(name + " has no commonalityMultFromPopulationIntent");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
bool same = curve.PointsCount == SlaverPopulationCurve.Length;
|
||||||
|
for (int i = 0; same && i < SlaverPopulationCurve.Length; i++)
|
||||||
|
same = Near(curve.Points[i].x, SlaverPopulationCurve[i].x) && Near(curve.Points[i].y, SlaverPopulationCurve[i].y);
|
||||||
|
if (!same)
|
||||||
|
problems.Add($"{name} population curve is {string.Join(" ", curve.Points.Select(p => $"({p.x}, {p.y})"))}, expected {expectedCurve}");
|
||||||
|
}
|
||||||
|
T.Check(problems.Count == 0, string.Join("; ", problems));
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("traders: slaver slave stock countRange matches the patch")]
|
||||||
|
public static void SlaverSlaveCountPatched()
|
||||||
|
{
|
||||||
|
var problems = new List<string>();
|
||||||
|
foreach (var kv in SlaverSlaveCount)
|
||||||
|
{
|
||||||
|
List<StockGenerator_Slaves> gens = SlaveGenerators(TraderDef(kv.Key));
|
||||||
|
if (gens.Count != 1)
|
||||||
|
problems.Add($"{kv.Key} has {gens.Count} StockGenerator_Slaves, expected exactly 1");
|
||||||
|
foreach (StockGenerator_Slaves g in gens)
|
||||||
|
if (!SameRange(g.countRange, kv.Value))
|
||||||
|
problems.Add($"{kv.Key} slave countRange {Show(g.countRange)}, expected {Show(kv.Value)}");
|
||||||
|
}
|
||||||
|
T.Check(problems.Count == 0, string.Join("; ", problems));
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("traders: every caravan and orbital trader carries a slave generator")]
|
||||||
|
public static void EveryCaravanAndOrbitalHasSlaves()
|
||||||
|
{
|
||||||
|
List<TraderKindDef> defs = DefDatabase<TraderKindDef>.AllDefsListForReading
|
||||||
|
.Where(d => d.defName.StartsWith("Caravan_", StringComparison.Ordinal) || d.defName.StartsWith("Orbital_", StringComparison.Ordinal))
|
||||||
|
.ToList();
|
||||||
|
T.Check(defs.Count >= Slavers.Length, "found only " + defs.Count + " Caravan_*/Orbital_* trader kinds");
|
||||||
|
|
||||||
|
var problems = new List<string>();
|
||||||
|
foreach (TraderKindDef def in defs)
|
||||||
|
{
|
||||||
|
List<StockGenerator_Slaves> gens = SlaveGenerators(def);
|
||||||
|
if (gens.Count == 0)
|
||||||
|
{
|
||||||
|
problems.Add(def.defName + " has no StockGenerator_Slaves");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
foreach (StockGenerator_Slaves g in gens)
|
||||||
|
if (g.trader != def)
|
||||||
|
problems.Add($"{def.defName}: slave generator's trader is {g.trader?.defName ?? "null"} (ResolveReferences missed it; GenerateThings reads trader.orbital)");
|
||||||
|
if (!SlaverSlaveCount.ContainsKey(def.defName) && !gens.Any(g => SameRange(g.countRange, OtherTraderSlaveCount)))
|
||||||
|
problems.Add($"{def.defName} slave countRange {string.Join("/", gens.Select(g => Show(g.countRange)))}, expected the patch's {Show(OtherTraderSlaveCount)}");
|
||||||
|
}
|
||||||
|
T.Info("checked " + defs.Count + " trader kinds: " + string.Join(", ", defs.Select(d => d.defName)));
|
||||||
|
T.Check(problems.Count == 0, string.Join("; ", problems));
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("traders: settlement slave countRange matches the patch")]
|
||||||
|
public static void SettlementSlaveCountPatched()
|
||||||
|
{
|
||||||
|
List<TraderKindDef> withSlaves = DefDatabase<TraderKindDef>.AllDefsListForReading
|
||||||
|
.Where(d => d.defName.StartsWith("Base_", StringComparison.Ordinal) && SlaveGenerators(d).Count > 0)
|
||||||
|
.ToList();
|
||||||
|
foreach (string must in new[] { "Base_Outlander_Standard", "Base_Neolithic_Standard" })
|
||||||
|
T.Check(withSlaves.Any(d => d.defName == must), must + " has no StockGenerator_Slaves, but vanilla gives it one");
|
||||||
|
|
||||||
|
var problems = new List<string>();
|
||||||
|
foreach (TraderKindDef def in withSlaves)
|
||||||
|
foreach (StockGenerator_Slaves g in SlaveGenerators(def))
|
||||||
|
if (!SameRange(g.countRange, SettlementSlaveCount))
|
||||||
|
problems.Add($"{def.defName} slave countRange {Show(g.countRange)}, expected {Show(SettlementSlaveCount)}");
|
||||||
|
|
||||||
|
TraderKindDef empire = DefDatabase<TraderKindDef>.GetNamedSilentFail("Base_Empire_Standard");
|
||||||
|
if (empire != null && !SlaveGenerators(empire).Any(g => g.slaveKindDef != null && g.slaveKindDef.defName == "Slave_Empire"))
|
||||||
|
problems.Add("Base_Empire_Standard lost its Slave_Empire slaveKindDef (the patch should only replace countRange)");
|
||||||
|
|
||||||
|
T.Info("settlement trader kinds with slaves: " + string.Join(", ", withSlaves.Select(d => d.defName)));
|
||||||
|
T.Check(problems.Count == 0, string.Join("; ", problems));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- stock generation ------------------------------------------------------------
|
||||||
|
|
||||||
|
[BlaxTest("traders: generated slaver stock holds the patched number of slaves")]
|
||||||
|
public static void SlaverStockCountInRange()
|
||||||
|
{
|
||||||
|
var problems = new List<string>();
|
||||||
|
var seen = new List<string>();
|
||||||
|
foreach (var kv in SlaverSlaveCount)
|
||||||
|
{
|
||||||
|
TraderKindDef def = TraderDef(kv.Key);
|
||||||
|
for (int seed = 1; seed <= 3; seed++)
|
||||||
|
{
|
||||||
|
TradeShip ship = null;
|
||||||
|
List<Thing> stock = null;
|
||||||
|
HashSet<Pawn> worldBefore = WorldSnapshot();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
string how;
|
||||||
|
if (def.orbital)
|
||||||
|
{
|
||||||
|
ship = SlaveShip(def, 4100 + seed);
|
||||||
|
stock = Goods(ship);
|
||||||
|
how = "trade ship";
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
stock = CaravanStock(def, CaravanFaction(def), 4100 + seed, out how);
|
||||||
|
}
|
||||||
|
int slaves = stock.OfType<Pawn>().Count(p => p.RaceProps.Humanlike);
|
||||||
|
seen.Add($"{def.defName}#{seed}={slaves} ({how})");
|
||||||
|
if (slaves < kv.Value.min || slaves > kv.Value.max)
|
||||||
|
problems.Add($"{def.defName} seed {seed}: {slaves} slaves via {how}, expected {Show(kv.Value)}");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
if (ship != null) RemoveShip(ship, worldBefore);
|
||||||
|
else DiscardAll(stock, worldBefore);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
T.Info(string.Join(", ", seen));
|
||||||
|
T.Check(problems.Count == 0, string.Join("; ", problems));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- trader branding on generated stock ------------------------------------------
|
||||||
|
|
||||||
|
[BlaxTest("traders: brand chance 1 marks every slave in slaver caravan stock as the trading faction's")]
|
||||||
|
public static void CaravanStockBrandedForTrader()
|
||||||
|
{
|
||||||
|
Fixtures.Settings.traderBrandChance = 1f;
|
||||||
|
var problems = new List<string>();
|
||||||
|
int exempt = 0, reused = 0;
|
||||||
|
var brandedPer = new Dictionary<string, int>();
|
||||||
|
string[] caravanSlavers = Slavers.Where(n => !TraderDef(n).orbital).ToArray();
|
||||||
|
for (int k = 0; k < caravanSlavers.Length; k++)
|
||||||
|
{
|
||||||
|
TraderKindDef def = TraderDef(caravanSlavers[k]);
|
||||||
|
Faction trading = CaravanFaction(def);
|
||||||
|
if (trading == null) T.Skip("no visible non-player humanlike faction to trade as");
|
||||||
|
brandedPer[def.defName] = 0;
|
||||||
|
for (int seed = 1; seed <= 2; seed++)
|
||||||
|
{
|
||||||
|
List<Thing> stock = null;
|
||||||
|
HashSet<Pawn> worldBefore = WorldSnapshot();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
stock = CaravanStock(def, trading, 4200 + 10 * k + seed, out string how);
|
||||||
|
if (seed == 1) T.Info($"{def.defName}: trading faction {trading.Name} ({trading.def.defName}), stock via {how}");
|
||||||
|
foreach (Pawn p in stock.OfType<Pawn>().Where(x => x.RaceProps.Humanlike))
|
||||||
|
{
|
||||||
|
if (worldBefore.Contains(p)) { reused++; continue; }
|
||||||
|
if (!BrandEligible(p, def))
|
||||||
|
{
|
||||||
|
exempt++;
|
||||||
|
if (BrandUtility.IsBranded(p))
|
||||||
|
problems.Add($"{def.defName}: {Who(p)} is exempt ({ExemptReason(p, def)}) but got branded");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
HediffComp_BrandOwner brand = BrandUtility.BrandOf(p);
|
||||||
|
if (brand == null) { problems.Add($"{def.defName}: {Who(p)} is unbranded at traderBrandChance = 1"); continue; }
|
||||||
|
brandedPer[def.defName]++;
|
||||||
|
if (brand.owner != trading)
|
||||||
|
problems.Add($"{def.defName}: {Who(p)} brand owner is {brand.owner?.Name ?? "null"}, expected the trading faction {trading.Name}");
|
||||||
|
if (brand.OwnerName != trading.Name)
|
||||||
|
problems.Add($"{def.defName}: {Who(p)} brand owner name is '{brand.OwnerName}', expected '{trading.Name}'");
|
||||||
|
problems.AddRange(BurnProblems(p));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
DiscardAll(stock, worldBefore);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
T.Info($"branded {string.Join(", ", brandedPer.Select(kv => kv.Key + "=" + kv.Value))}, exempt {exempt}, redressed world pawns skipped {reused}");
|
||||||
|
T.Check(problems.Count == 0, string.Join("; ", problems.Take(6)));
|
||||||
|
foreach (var kv in brandedPer)
|
||||||
|
T.Check(kv.Value > 0, kv.Key + " stock held no freshly generated brandable slave in 2 generations, so nothing was checked");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("traders: brand chance 0 leaves every slave in slaver stock unbranded")]
|
||||||
|
public static void ChanceZeroBrandsNobody()
|
||||||
|
{
|
||||||
|
Fixtures.Settings.traderBrandChance = 0f;
|
||||||
|
TraderKindDef caravanDef = TraderDef("Caravan_Outlander_PirateMerchant");
|
||||||
|
TraderKindDef shipDef = TraderDef("Orbital_PirateMerchant");
|
||||||
|
var problems = new List<string>();
|
||||||
|
int slaves = 0;
|
||||||
|
|
||||||
|
List<Thing> stock = null;
|
||||||
|
TradeShip ship = null;
|
||||||
|
HashSet<Pawn> worldBefore = WorldSnapshot();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
stock = CaravanStock(caravanDef, CaravanFaction(caravanDef), 4301, out _);
|
||||||
|
ship = SlaveShip(shipDef, 4302);
|
||||||
|
foreach (Pawn p in stock.Concat(Goods(ship)).OfType<Pawn>().Where(x => x.RaceProps.Humanlike && !worldBefore.Contains(x)))
|
||||||
|
{
|
||||||
|
slaves++;
|
||||||
|
if (BrandUtility.IsBranded(p))
|
||||||
|
problems.Add($"{Who(p)} branded by {BrandUtility.BrandOf(p)?.OwnerName ?? "?"} although traderBrandChance = 0");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
DiscardAll(stock, worldBefore);
|
||||||
|
if (ship != null) RemoveShip(ship, worldBefore);
|
||||||
|
}
|
||||||
|
T.Check(slaves > 0, "caravan and ship stock held no freshly generated slaves, so nothing was checked");
|
||||||
|
T.Check(problems.Count == 0, string.Join("; ", problems.Take(6)));
|
||||||
|
|
||||||
|
// Control: the same ship seed at chance 1 must brand someone, or "nobody branded" above proves nothing.
|
||||||
|
Fixtures.Settings.traderBrandChance = 1f;
|
||||||
|
int controlBranded = 0;
|
||||||
|
ship = null;
|
||||||
|
worldBefore = WorldSnapshot();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
ship = SlaveShip(shipDef, 4302);
|
||||||
|
controlBranded = Goods(ship).OfType<Pawn>().Count(p => p.RaceProps.Humanlike && !worldBefore.Contains(p) && BrandUtility.IsBranded(p));
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
if (ship != null) RemoveShip(ship, worldBefore);
|
||||||
|
}
|
||||||
|
T.Check(controlBranded > 0, "control: the same slave ship seed at traderBrandChance = 1 branded nobody either, so chance 0 was not what kept them unbranded");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("traders: orbital slave ship has no trading faction, its slaves get a fallback owner")]
|
||||||
|
public static void SlaveShipFallbackOwner()
|
||||||
|
{
|
||||||
|
Fixtures.Settings.traderBrandChance = 1f;
|
||||||
|
TraderKindDef def = TraderDef("Orbital_PirateMerchant");
|
||||||
|
var problems = new List<string>();
|
||||||
|
int branded = 0;
|
||||||
|
var owners = new HashSet<string>();
|
||||||
|
for (int seed = 1; seed <= 2; seed++)
|
||||||
|
{
|
||||||
|
TradeShip ship = null;
|
||||||
|
HashSet<Pawn> worldBefore = WorldSnapshot();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
ship = SlaveShip(def, 4400 + seed);
|
||||||
|
foreach (Pawn p in Goods(ship).OfType<Pawn>().Where(x => x.RaceProps.Humanlike && !worldBefore.Contains(x)))
|
||||||
|
{
|
||||||
|
if (!BrandEligible(p, def))
|
||||||
|
{
|
||||||
|
if (BrandUtility.IsBranded(p)) problems.Add($"{Who(p)} is exempt ({ExemptReason(p, def)}) but got branded");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
HediffComp_BrandOwner brand = BrandUtility.BrandOf(p);
|
||||||
|
if (brand == null) { problems.Add(Who(p) + " is unbranded although the ship passed no faction and the fallback should pick one"); continue; }
|
||||||
|
branded++;
|
||||||
|
Faction o = brand.owner;
|
||||||
|
if (o == null) { problems.Add(Who(p) + " brand has no owner"); continue; }
|
||||||
|
owners.Add(o.Name);
|
||||||
|
if (o.IsPlayer) problems.Add(Who(p) + " fallback owner is the player");
|
||||||
|
if (o.temporary) problems.Add($"{Who(p)} fallback owner {o.Name} is a temporary faction");
|
||||||
|
if (!o.def.humanlikeFaction) problems.Add($"{Who(p)} fallback owner {o.Name} is not humanlike");
|
||||||
|
if (o.Hidden) problems.Add($"{Who(p)} fallback owner {o.Name} is a hidden faction");
|
||||||
|
if (o == p.Faction) problems.Add($"{Who(p)} fallback owner {o.Name} is the slave's own faction");
|
||||||
|
problems.AddRange(BurnProblems(p));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
if (ship != null) RemoveShip(ship, worldBefore);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
T.Info($"branded {branded}, fallback owners: {string.Join(", ", owners)}");
|
||||||
|
T.Check(problems.Count == 0, string.Join("; ", problems.Take(6)));
|
||||||
|
T.Check(branded > 0, "slave ship stock held no brandable slave in 2 generations, so nothing was checked");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("traders: animals in slaver stock never get a brand")]
|
||||||
|
public static void AnimalsNeverBranded()
|
||||||
|
{
|
||||||
|
Fixtures.Settings.traderBrandChance = 1f;
|
||||||
|
TraderKindDef caravanDef = TraderDef("Caravan_Outlander_PirateMerchant");
|
||||||
|
TraderKindDef shipDef = TraderDef("Orbital_PirateMerchant");
|
||||||
|
var problems = new List<string>();
|
||||||
|
int animals = 0, items = 0, brandedSlaves = 0;
|
||||||
|
for (int seed = 1; seed <= 2; seed++)
|
||||||
|
{
|
||||||
|
List<Thing> stock = null;
|
||||||
|
TradeShip ship = null;
|
||||||
|
HashSet<Pawn> worldBefore = WorldSnapshot();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
stock = CaravanStock(caravanDef, CaravanFaction(caravanDef), 4500 + seed, out _);
|
||||||
|
ship = SlaveShip(shipDef, 4510 + seed);
|
||||||
|
foreach (Thing t in stock.Concat(Goods(ship)))
|
||||||
|
{
|
||||||
|
if (!(t is Pawn p)) { items++; continue; }
|
||||||
|
if (p.RaceProps.Humanlike)
|
||||||
|
{
|
||||||
|
// Only fresh pawns count as the control: a redressed world pawn may carry an older brand.
|
||||||
|
if (!worldBefore.Contains(p) && BrandUtility.IsBranded(p)) brandedSlaves++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
animals++;
|
||||||
|
if (BrandUtility.IsBranded(p))
|
||||||
|
problems.Add($"animal {Who(p)} ({p.def.defName}) got a slave brand");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
DiscardAll(stock, worldBefore);
|
||||||
|
if (ship != null) RemoveShip(ship, worldBefore);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
T.Info($"animals {animals}, items {items}, freshly branded slaves in the same stock {brandedSlaves}");
|
||||||
|
T.Check(problems.Count == 0, string.Join("; ", problems.Take(6)));
|
||||||
|
if (brandedSlaves == 0) T.Fail("no freshly generated slave in the same stock was branded at traderBrandChance = 1, so the brand patch did not run");
|
||||||
|
if (animals == 0) T.Skip("vanilla generated no animals in slaver caravan or slave ship stock, nothing to check");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- brand rules on the hooked vanilla method ------------------------------------
|
||||||
|
|
||||||
|
[BlaxTest("traders: join-as-colonist, child and non-slave pawns in stock stay unbranded")]
|
||||||
|
public static void ExemptPawnsUnbranded() => Seeded(4700, ExemptPawnsUnbrandedBody);
|
||||||
|
|
||||||
|
private static void ExemptPawnsUnbrandedBody()
|
||||||
|
{
|
||||||
|
Fixtures.Settings.traderBrandChance = 1f;
|
||||||
|
TraderKindDef def = TraderDef("Caravan_Outlander_PirateMerchant");
|
||||||
|
Faction trading = AnyTradingFaction();
|
||||||
|
if (trading == null) T.Skip("no visible non-player humanlike faction to trade as");
|
||||||
|
PlanetTile tile = Fixtures.Map.Tile;
|
||||||
|
|
||||||
|
Pawn control = Fixtures.Generate(PawnKindDefOf.Slave, trading);
|
||||||
|
control.guest.joinStatus = JoinStatus.JoinAsSlave;
|
||||||
|
control.PostGeneratedForTrader(def, tile, trading);
|
||||||
|
T.Check(BrandUtility.IsBranded(control), "control: an adult join-as-slave Slave pawn was not branded at traderBrandChance = 1");
|
||||||
|
T.Equal(trading, BrandUtility.BrandOf(control).owner, "control slave's brand owner");
|
||||||
|
|
||||||
|
Pawn joiner = Fixtures.Generate(PawnKindDefOf.Slave, trading);
|
||||||
|
joiner.guest.joinStatus = JoinStatus.JoinAsColonist;
|
||||||
|
joiner.PostGeneratedForTrader(def, tile, trading);
|
||||||
|
T.Check(!BrandUtility.IsBranded(joiner), "a Slave pawn that joins as a colonist got branded");
|
||||||
|
|
||||||
|
Pawn villager = Fixtures.Generate(PawnKindDefOf.Villager, trading);
|
||||||
|
if (villager.guest != null) villager.guest.joinStatus = JoinStatus.JoinAsSlave;
|
||||||
|
villager.PostGeneratedForTrader(def, tile, trading);
|
||||||
|
T.Check(!BrandUtility.IsBranded(villager), "a non-slave humanlike (Villager kind) passed through slaver stock got branded");
|
||||||
|
|
||||||
|
if (!ModsConfig.BiotechActive)
|
||||||
|
{
|
||||||
|
T.Info("Biotech inactive, child case not checked");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Pawn child = null;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
child = PawnGenerator.GeneratePawn(new PawnGenerationRequest(PawnKindDefOf.Slave, trading, PawnGenerationContext.NonPlayer,
|
||||||
|
forceGenerateNewPawn: true, canGeneratePawnRelations: false, colonistRelationChanceFactor: 0f,
|
||||||
|
developmentalStages: DevelopmentalStage.Child));
|
||||||
|
T.Check(!child.ageTracker.Adult, "child request produced an adult (" + child.ageTracker.AgeBiologicalYears + "y)");
|
||||||
|
if (child.guest != null) child.guest.joinStatus = JoinStatus.JoinAsSlave;
|
||||||
|
child.PostGeneratedForTrader(def, tile, trading);
|
||||||
|
T.Check(!BrandUtility.IsBranded(child), $"a child slave ({child.ageTracker.AgeBiologicalYears}y) got branded");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
DiscardAll(new List<Thing> { child });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("traders: a trader's custom slave kind counts as stock, a pawn-hire trader does not")]
|
||||||
|
public static void SlaveStockKindRules() => Seeded(4710, SlaveStockKindRulesBody);
|
||||||
|
|
||||||
|
private static void SlaveStockKindRulesBody()
|
||||||
|
{
|
||||||
|
Fixtures.Settings.traderBrandChance = 1f;
|
||||||
|
Faction trading = AnyTradingFaction();
|
||||||
|
if (trading == null) T.Skip("no visible non-player humanlike faction to trade as");
|
||||||
|
PlanetTile tile = Fixtures.Map.Tile;
|
||||||
|
|
||||||
|
Pawn control = Fixtures.Generate(PawnKindDefOf.Slave, trading);
|
||||||
|
control.guest.joinStatus = JoinStatus.JoinAsSlave;
|
||||||
|
control.PostGeneratedForTrader(TraderDef("Caravan_Outlander_PirateMerchant"), tile, trading);
|
||||||
|
T.Check(BrandUtility.IsBranded(control), "control: a Slave pawn in slaver stock was not branded at traderBrandChance = 1");
|
||||||
|
|
||||||
|
var rimdeed = new TraderKindDef { defName = "RD_PawnTrader" };
|
||||||
|
Pawn hired = Fixtures.Generate(PawnKindDefOf.Slave, trading);
|
||||||
|
hired.guest.joinStatus = JoinStatus.JoinAsSlave;
|
||||||
|
hired.PostGeneratedForTrader(rimdeed, tile, trading);
|
||||||
|
T.Check(!BrandUtility.IsBranded(hired), "a Slave pawn from the RD_PawnTrader trader kind got branded");
|
||||||
|
|
||||||
|
PawnKindDef empireSlave = DefDatabase<PawnKindDef>.GetNamedSilentFail("Slave_Empire");
|
||||||
|
TraderKindDef empireBase = DefDatabase<TraderKindDef>.GetNamedSilentFail("Base_Empire_Standard");
|
||||||
|
if (empireSlave == null || empireBase == null)
|
||||||
|
{
|
||||||
|
T.Info("Royalty's Slave_Empire or Base_Empire_Standard missing, custom slave kind not checked");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
T.Check(SlaveGenerators(empireBase).Any(g => g.slaveKindDef == empireSlave), "Base_Empire_Standard has no Slave_Empire slave generator");
|
||||||
|
|
||||||
|
Pawn imperial = Fixtures.Generate(empireSlave, trading);
|
||||||
|
imperial.guest.joinStatus = JoinStatus.JoinAsSlave;
|
||||||
|
imperial.PostGeneratedForTrader(empireBase, tile, trading);
|
||||||
|
T.Check(BrandUtility.IsBranded(imperial), "a Slave_Empire pawn in Base_Empire_Standard stock was not branded");
|
||||||
|
T.Equal(trading, BrandUtility.BrandOf(imperial).owner, "Slave_Empire brand owner");
|
||||||
|
|
||||||
|
TraderKindDef generic = TraderDef("Caravan_Outlander_BulkGoods");
|
||||||
|
Pawn stray = Fixtures.Generate(empireSlave, trading);
|
||||||
|
stray.guest.joinStatus = JoinStatus.JoinAsSlave;
|
||||||
|
stray.PostGeneratedForTrader(generic, tile, trading);
|
||||||
|
T.Check(!BrandUtility.IsBranded(stray), "a Slave_Empire pawn got branded by Caravan_Outlander_BulkGoods, whose slave generator uses the plain Slave kind");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("traders: an existing brand is kept, the player as trader falls back to another owner")]
|
||||||
|
public static void ExistingBrandAndPlayerFallback() => Seeded(4720, ExistingBrandAndPlayerFallbackBody);
|
||||||
|
|
||||||
|
private static void ExistingBrandAndPlayerFallbackBody()
|
||||||
|
{
|
||||||
|
Fixtures.Settings.traderBrandChance = 1f;
|
||||||
|
TraderKindDef def = TraderDef("Caravan_Outlander_PirateMerchant");
|
||||||
|
List<Faction> factions = VisibleTradingFactions();
|
||||||
|
if (factions.Count < 2) T.Skip("need two visible non-player humanlike factions, found " + factions.Count);
|
||||||
|
Faction first = factions[0], second = factions[1];
|
||||||
|
PlanetTile tile = Fixtures.Map.Tile;
|
||||||
|
|
||||||
|
// Control: the same call on an unbranded slave brands it for `second`, so keeping `first` below is the patch's choice.
|
||||||
|
Pawn fresh = Fixtures.Generate(PawnKindDefOf.Slave, second);
|
||||||
|
fresh.guest.joinStatus = JoinStatus.JoinAsSlave;
|
||||||
|
fresh.PostGeneratedForTrader(def, tile, second);
|
||||||
|
T.Equal(second, BrandUtility.BrandOf(fresh)?.owner, "control: brand owner of an unbranded slave passed through the same call");
|
||||||
|
|
||||||
|
Pawn marked = Fixtures.Generate(PawnKindDefOf.Slave, second);
|
||||||
|
marked.guest.joinStatus = JoinStatus.JoinAsSlave;
|
||||||
|
BrandUtility.Brand(marked, first);
|
||||||
|
marked.PostGeneratedForTrader(def, tile, second);
|
||||||
|
T.Equal(first, BrandUtility.BrandOf(marked)?.owner, "owner of a slave branded before it reached the trader");
|
||||||
|
T.Equal(1, marked.health.hediffSet.hediffs.Count(h => h.def == BlaxDefOf.BlaxSlaves_SlaveBrand), "brand hediffs on the pre-branded slave");
|
||||||
|
|
||||||
|
Pawn sold = Fixtures.Generate(PawnKindDefOf.Slave, first);
|
||||||
|
sold.guest.joinStatus = JoinStatus.JoinAsSlave;
|
||||||
|
sold.PostGeneratedForTrader(def, tile, Faction.OfPlayer);
|
||||||
|
HediffComp_BrandOwner brand = BrandUtility.BrandOf(sold);
|
||||||
|
T.NotNull(brand, "brand on a slave generated with the player as trading faction");
|
||||||
|
Faction o = brand.owner;
|
||||||
|
T.NotNull(o, "fallback brand owner");
|
||||||
|
T.Check(!o.IsPlayer, "player as trading faction: brand owner is still the player");
|
||||||
|
T.Check(o != sold.Faction, $"fallback owner {o.Name} is the slave's own faction");
|
||||||
|
T.Check(!o.temporary && o.def.humanlikeFaction && !o.Hidden, $"fallback owner {o.Name} ({o.def.defName}) is temporary, hidden or not humanlike");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- save and reload -------------------------------------------------------------
|
||||||
|
|
||||||
|
private const string CarryShip = "traders.ship";
|
||||||
|
private const string CarrySlave = "traders.slave";
|
||||||
|
private const string CarryOwner = "traders.owner";
|
||||||
|
private const string CarryOwnerName = "traders.ownerName";
|
||||||
|
|
||||||
|
[BlaxTest("traders: set up a trader-branded slave on a passing slave ship for reload")]
|
||||||
|
public static void ReloadSetup()
|
||||||
|
{
|
||||||
|
Fixtures.Settings.traderBrandChance = 1f;
|
||||||
|
TraderKindDef def = TraderDef("Orbital_PirateMerchant");
|
||||||
|
for (int seed = 4601; seed <= 4603; seed++)
|
||||||
|
{
|
||||||
|
HashSet<Pawn> worldBefore = WorldSnapshot();
|
||||||
|
TradeShip ship = SlaveShip(def, seed);
|
||||||
|
bool keep = false;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// A freshly generated pawn, so the brand is the trader brand and not an older one on a redressed world pawn.
|
||||||
|
Pawn slave = Goods(ship).OfType<Pawn>().FirstOrDefault(p => p.RaceProps.Humanlike && !worldBefore.Contains(p) && BrandUtility.BrandOf(p)?.owner != null);
|
||||||
|
if (slave == null) continue;
|
||||||
|
HediffComp_BrandOwner brand = BrandUtility.BrandOf(slave);
|
||||||
|
ship.ticksUntilDeparture = 1000 * GenDate.TicksPerDay;
|
||||||
|
T.Carry[CarryShip] = ship.GetUniqueLoadID();
|
||||||
|
T.Carry[CarrySlave] = slave.ThingID;
|
||||||
|
T.Carry[CarryOwner] = brand.owner.GetUniqueLoadID();
|
||||||
|
T.Carry[CarryOwnerName] = brand.OwnerName;
|
||||||
|
keep = true;
|
||||||
|
T.Info($"slave ship {ship.GetUniqueLoadID()} (seed {seed}) keeps {Who(slave)}, branded for {brand.OwnerName}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
if (!keep) RemoveShip(ship, worldBefore);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
T.Fail("no freshly generated slave with an owned brand in 3 slave ship stocks at traderBrandChance = 1");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("traders: a trader brand in slave ship stock survives save and reload", phase: 2)]
|
||||||
|
public static void ReloadKeepsTraderBrand()
|
||||||
|
{
|
||||||
|
T.Check(T.Carry.TryGetValue(CarryShip, out string shipId), "phase 1 slave ship setup did not run or failed");
|
||||||
|
TradeShip ship = Find.Maps.SelectMany(m => m.passingShipManager.passingShips).OfType<TradeShip>()
|
||||||
|
.FirstOrDefault(s => s.GetUniqueLoadID() == shipId);
|
||||||
|
T.NotNull(ship, "slave ship " + shipId + " after reload");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
string slaveId = T.Carry[CarrySlave];
|
||||||
|
Pawn slave = Goods(ship).OfType<Pawn>().FirstOrDefault(p => p.ThingID == slaveId);
|
||||||
|
T.NotNull(slave, "slave " + slaveId + " in the reloaded ship's stock");
|
||||||
|
HediffComp_BrandOwner brand = BrandUtility.BrandOf(slave);
|
||||||
|
T.NotNull(brand, "brand on " + slaveId + " after reload");
|
||||||
|
T.NotNull(brand.owner, "brand owner faction after reload (name cached: '" + brand.ownerName + "')");
|
||||||
|
T.Equal(T.Carry[CarryOwner], brand.owner.GetUniqueLoadID(), "brand owner faction after reload");
|
||||||
|
T.Equal(T.Carry[CarryOwnerName], brand.OwnerName, "brand owner name after reload");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
RemoveShip(ship);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- helpers ---------------------------------------------------------------------
|
||||||
|
|
||||||
|
private static TraderKindDef TraderDef(string defName)
|
||||||
|
{
|
||||||
|
TraderKindDef def = DefDatabase<TraderKindDef>.GetNamedSilentFail(defName);
|
||||||
|
T.NotNull(def, "TraderKindDef " + defName);
|
||||||
|
return def;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<StockGenerator_Slaves> SlaveGenerators(TraderKindDef def) =>
|
||||||
|
def.stockGenerators?.OfType<StockGenerator_Slaves>().ToList() ?? new List<StockGenerator_Slaves>();
|
||||||
|
|
||||||
|
private static bool Near(float a, float b) => Math.Abs(a - b) < 0.0001f;
|
||||||
|
|
||||||
|
private static bool SameRange(IntRange a, IntRange b) => a.min == b.min && a.max == b.max;
|
||||||
|
|
||||||
|
private static string Show(IntRange r) => r.min + "~" + r.max;
|
||||||
|
|
||||||
|
private static string Who(Pawn p) => p.LabelShort + " [" + p.ThingID + "]";
|
||||||
|
|
||||||
|
private static bool ApprovesSlavery(Faction f) =>
|
||||||
|
f.ideos == null || f.ideos.AllIdeos.All(i => i.IdeoApprovesOfSlavery());
|
||||||
|
|
||||||
|
private static List<Faction> VisibleTradingFactions() =>
|
||||||
|
Find.FactionManager.AllFactionsVisible
|
||||||
|
.Where(f => !f.IsPlayer && !f.defeated && !f.temporary && f.def.humanlikeFaction)
|
||||||
|
.OrderBy(f => f.loadID).ToList();
|
||||||
|
|
||||||
|
private static Faction AnyTradingFaction() => Fixtures.FriendlyFaction() ?? VisibleTradingFactions().FirstOrDefault();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The faction that sends this caravan. Vanilla's slave generator makes no slaves for a faction
|
||||||
|
/// whose ideoligions don't all approve of slavery, so one that does is preferred.
|
||||||
|
/// </summary>
|
||||||
|
private static Faction CaravanFaction(TraderKindDef def)
|
||||||
|
{
|
||||||
|
List<Faction> all = VisibleTradingFactions();
|
||||||
|
return all.FirstOrDefault(f => f.def.caravanTraderKinds.Contains(def) && ApprovesSlavery(f))
|
||||||
|
?? all.FirstOrDefault(ApprovesSlavery)
|
||||||
|
?? all.FirstOrDefault(f => f.def.caravanTraderKinds.Contains(def))
|
||||||
|
?? all.FirstOrDefault();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Caravan stock as PawnGroupKindWorker_Trader makes it: TraderStock with the caravan's faction.
|
||||||
|
/// If no faction approves of slavery (vanilla would then make no slaves at all), the generators
|
||||||
|
/// run without a faction and each thing goes through the hooked PostGeneratedForTrader with the
|
||||||
|
/// trading faction, as ThingSetMaker_TraderStock does.
|
||||||
|
/// </summary>
|
||||||
|
private static List<Thing> CaravanStock(TraderKindDef def, Faction faction, int seed, out string how)
|
||||||
|
{
|
||||||
|
PlanetTile tile = Fixtures.Map.Tile;
|
||||||
|
Rand.PushState(seed);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (faction == null || ApprovesSlavery(faction))
|
||||||
|
{
|
||||||
|
how = "ThingSetMaker TraderStock, faction " + (faction?.def.defName ?? "none");
|
||||||
|
return ThingSetMakerDefOf.TraderStock.root.Generate(new ThingSetMakerParams
|
||||||
|
{
|
||||||
|
traderDef = def,
|
||||||
|
tile = tile,
|
||||||
|
makingFaction = faction,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
how = "generators without faction + PostGeneratedForTrader for " + faction.def.defName + " (no faction approves of slavery)";
|
||||||
|
var list = new List<Thing>();
|
||||||
|
foreach (StockGenerator gen in def.stockGenerators)
|
||||||
|
foreach (Thing t in gen.GenerateThings(tile, null))
|
||||||
|
{
|
||||||
|
t.PostGeneratedForTrader(def, tile, faction);
|
||||||
|
list.Add(t);
|
||||||
|
}
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Rand.PopState();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A slave ship as IncidentWorker_OrbitalTraderArrival makes it: new TradeShip, added to the map,
|
||||||
|
/// GenerateThings (which passes no faction to the stock).
|
||||||
|
/// </summary>
|
||||||
|
private static TradeShip SlaveShip(TraderKindDef def, int seed)
|
||||||
|
{
|
||||||
|
Rand.PushState(seed);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Faction faction = def.faction == null ? null : Find.FactionManager.AllFactions.FirstOrDefault(f => f.def == def.faction);
|
||||||
|
var ship = new TradeShip(def, faction);
|
||||||
|
Fixtures.Map.passingShipManager.AddShip(ship);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
ship.GenerateThings();
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
RemoveShip(ship);
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
return ship;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Rand.PopState();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<Thing> Goods(TradeShip ship) => ship.GetDirectlyHeldThings().ToList();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// World pawns before stock generation. StockGenerator_Slaves asks for forceGenerateNewPawn: false,
|
||||||
|
/// so PawnGenerator may redress one of them (and take it out of WorldPawns) instead of making a new pawn.
|
||||||
|
/// </summary>
|
||||||
|
private static HashSet<Pawn> WorldSnapshot() => new HashSet<Pawn>(Find.WorldPawns.AllPawnsAliveOrDead);
|
||||||
|
|
||||||
|
/// <summary>Runs a test body under a fixed Rand seed (pawn generation and the brand roll use Rand).</summary>
|
||||||
|
private static void Seeded(int seed, Action body)
|
||||||
|
{
|
||||||
|
Rand.PushState(seed);
|
||||||
|
try { body(); }
|
||||||
|
finally { Rand.PopState(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void RemoveShip(TradeShip ship, HashSet<Pawn> formerWorldPawns = null)
|
||||||
|
{
|
||||||
|
if (ship == null) return;
|
||||||
|
List<Thing> goods = Goods(ship);
|
||||||
|
ship.passingShipManager?.RemoveShip(ship);
|
||||||
|
DiscardAll(goods, formerWorldPawns);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Destroys generated stock: fresh pawns are discarded the vanilla way, items destroyed. A pawn that was
|
||||||
|
/// a world pawn before generation (redressed into the stock) goes back to the world, as on a trader's
|
||||||
|
/// departure (ThingUtility.DestroyOrPassToWorld), so tests don't delete pawns other systems may reference.
|
||||||
|
/// </summary>
|
||||||
|
private static void DiscardAll(IEnumerable<Thing> things, HashSet<Pawn> formerWorldPawns = null)
|
||||||
|
{
|
||||||
|
if (things == null) return;
|
||||||
|
foreach (Thing t in things.Where(x => x != null).ToList())
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (t.Spawned) continue;
|
||||||
|
t.holdingOwner?.Remove(t);
|
||||||
|
if (t is Pawn p)
|
||||||
|
{
|
||||||
|
if (p.Discarded) continue;
|
||||||
|
if (Find.WorldPawns.Contains(p))
|
||||||
|
{
|
||||||
|
if (formerWorldPawns == null || !formerWorldPawns.Contains(p)) Find.WorldPawns.RemoveAndDiscardPawnViaGC(p);
|
||||||
|
}
|
||||||
|
else if (formerWorldPawns != null && formerWorldPawns.Contains(p)) Find.WorldPawns.PassToWorld(p);
|
||||||
|
else Find.WorldPawns.PassToWorld(p, PawnDiscardDecideMode.Discard);
|
||||||
|
}
|
||||||
|
else if (!t.Destroyed)
|
||||||
|
{
|
||||||
|
t.Destroy(DestroyMode.Vanish);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
T.Info("cleanup of " + t + " threw: " + e.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsSlaveKind(Pawn p, TraderKindDef def) =>
|
||||||
|
p.kindDef == PawnKindDefOf.Slave || SlaveGenerators(def).Any(g => g.slaveKindDef != null && g.slaveKindDef == p.kindDef);
|
||||||
|
|
||||||
|
/// <summary>The pawns Patch_TraderSlaveBrand should brand: adult, slave kind, not joining as a colonist.</summary>
|
||||||
|
private static bool BrandEligible(Pawn p, TraderKindDef def) => ExemptReason(p, def) == null;
|
||||||
|
|
||||||
|
private static string ExemptReason(Pawn p, TraderKindDef def)
|
||||||
|
{
|
||||||
|
if (p.Dead) return "dead";
|
||||||
|
if (!p.RaceProps.Humanlike) return "not humanlike";
|
||||||
|
if (p.ageTracker == null || !p.ageTracker.Adult) return "child, " + p.ageTracker?.AgeBiologicalYears + "y";
|
||||||
|
if (!IsSlaveKind(p, def)) return "kind " + p.kindDef?.defName;
|
||||||
|
if (p.guest != null && p.guest.joinStatus == JoinStatus.JoinAsColonist) return "joins as colonist";
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A trader brand is an old mark: no fresh burn, no infection.</summary>
|
||||||
|
private static IEnumerable<string> BurnProblems(Pawn p)
|
||||||
|
{
|
||||||
|
HediffDef burn = DamageDefOf.Burn?.hediff;
|
||||||
|
foreach (Hediff h in p.health.hediffSet.hediffs)
|
||||||
|
{
|
||||||
|
if (burn != null && h.def == burn && !h.IsPermanent())
|
||||||
|
yield return $"{Who(p)} has a fresh burn ({h.Part?.Label ?? "whole body"}, severity {h.Severity:0.#}) with the trader brand";
|
||||||
|
if (h.def == HediffDefOf.WoundInfection)
|
||||||
|
yield return Who(p) + " has a wound infection with the trader brand";
|
||||||
|
if (h.def == BlaxDefOf.BlaxSlaves_SlaveBrand && h is HediffWithComps hw && hw.comps.Any(c => c is HediffComp_Infecter))
|
||||||
|
yield return Who(p) + " brand hediff carries an infecter comp";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,102 @@
|
||||||
|
<#
|
||||||
|
Runs the in-game test suite. RimWorld 1.7 starts headless (no window, no focus change) with its
|
||||||
|
own save data folder, so your mod list, saves and settings stay untouched. Needs Steam running and
|
||||||
|
the Harmony mod from the Workshop. Exit code: 0 all passed, 1 failures, 2 the run didn't finish.
|
||||||
|
|
||||||
|
.\Tests\run-tests.ps1 Harmony, the installed DLCs, Blax Slaves
|
||||||
|
.\Tests\run-tests.ps1 -Compat also the installed mods Blax Slaves has compat code for
|
||||||
|
.\Tests\run-tests.ps1 -NoBuild skip dotnet build
|
||||||
|
|
||||||
|
While it runs, the test mod is linked into the game's Mods folder; the link is removed afterwards.
|
||||||
|
#>
|
||||||
|
param(
|
||||||
|
[string]$RimWorldDir = 'E:\SteamLibrary\steamapps\common\RimWorld',
|
||||||
|
[string]$DataDir = (Join-Path $env:TEMP 'BlaxSlavesTest'),
|
||||||
|
[switch]$Compat,
|
||||||
|
[switch]$NoBuild,
|
||||||
|
[int]$TimeoutSeconds = 900
|
||||||
|
)
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
$repo = Split-Path -Parent $PSScriptRoot
|
||||||
|
$testMod = Join-Path $PSScriptRoot 'BlaxSlavesTests'
|
||||||
|
$link = Join-Path $RimWorldDir 'Mods\BlaxSlavesTests'
|
||||||
|
$workshop = Join-Path $RimWorldDir '..\..\workshop\content\294100'
|
||||||
|
|
||||||
|
if (Get-Process -Name RimWorld -ErrorAction SilentlyContinue) { throw 'RimWorld is running. Close it first.' }
|
||||||
|
|
||||||
|
if (-not $NoBuild) {
|
||||||
|
foreach ($proj in (Join-Path $repo 'Source\BlaxSlaves\BlaxSlaves.csproj'), (Join-Path $testMod 'Source\BlaxSlavesTests.csproj')) {
|
||||||
|
& dotnet build $proj -c Release -nologo -v q "-p:RimWorldDir=$RimWorldDir"
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "build failed: $proj" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# packageId (lower case) -> About.xml, for every installed local and Workshop mod
|
||||||
|
$installed = @{}
|
||||||
|
foreach ($about in @(Get-ChildItem (Join-Path $RimWorldDir 'Mods\*\About\About.xml') -ErrorAction SilentlyContinue) +
|
||||||
|
@(Get-ChildItem (Join-Path $workshop '*\About\About.xml') -ErrorAction SilentlyContinue)) {
|
||||||
|
$x = [xml](Get-Content -LiteralPath $about.FullName -Raw -Encoding UTF8)
|
||||||
|
if ($x.ModMetaData.packageId) { $installed[$x.ModMetaData.packageId.Trim().ToLower()] = $x }
|
||||||
|
}
|
||||||
|
function Add-WithDependencies([string]$id, [System.Collections.ArrayList]$list) {
|
||||||
|
$id = $id.ToLower()
|
||||||
|
if ($list -contains $id -or $id -like 'ludeon.*') { return }
|
||||||
|
$x = $installed[$id]
|
||||||
|
if (-not $x) { Write-Warning "not installed, skipped: $id"; return }
|
||||||
|
foreach ($dep in @($x.ModMetaData.modDependencies.li)) { if ($dep.packageId) { Add-WithDependencies $dep.packageId $list } }
|
||||||
|
[void]$list.Add($id)
|
||||||
|
}
|
||||||
|
|
||||||
|
$mods = New-Object System.Collections.ArrayList
|
||||||
|
$expansions = @()
|
||||||
|
[void]$mods.Add('brrainz.harmony')
|
||||||
|
[void]$mods.Add('ludeon.rimworld')
|
||||||
|
foreach ($dlc in 'Royalty', 'Ideology', 'Biotech', 'Anomaly', 'Odyssey') {
|
||||||
|
if (Test-Path (Join-Path $RimWorldDir "Data\$dlc")) { $id = 'ludeon.rimworld.' + $dlc.ToLower(); [void]$mods.Add($id); $expansions += $id }
|
||||||
|
}
|
||||||
|
if ($Compat) {
|
||||||
|
foreach ($id in 'unlimitedhugs.hugslib', 'orion.hospitality', 'smuffle.harvestorganspostmortem',
|
||||||
|
'mersid.wce2updated.core', 'mlie.syrmoreslaves', 'bblkepling.everybodybuysslaves') {
|
||||||
|
Add-WithDependencies $id $mods
|
||||||
|
}
|
||||||
|
}
|
||||||
|
[void]$mods.Add('blax.slaves')
|
||||||
|
[void]$mods.Add('blax.slaves.tests')
|
||||||
|
|
||||||
|
# fresh test data folder: mod list only, no old save, results or mod settings
|
||||||
|
New-Item -ItemType Directory -Force (Join-Path $DataDir 'Config') | Out-Null
|
||||||
|
Remove-Item -Force -ErrorAction SilentlyContinue (Join-Path $DataDir 'Saves\BlaxSlavesTest.rws'), (Join-Path $DataDir 'BlaxSlavesTestResults.txt'), (Join-Path $DataDir 'Config\Mod_blax.slaves_*.xml')
|
||||||
|
$li = { param($ids) ($ids | ForEach-Object { " <li>$_</li>" }) -join "`n" }
|
||||||
|
$modsConfig = "<?xml version=`"1.0`" encoding=`"utf-8`"?>`n<ModsConfigData>`n <version>1.7</version>`n <activeMods>`n" +
|
||||||
|
(& $li $mods) + "`n </activeMods>`n <knownExpansions>`n" + (& $li $expansions) + "`n </knownExpansions>`n</ModsConfigData>`n"
|
||||||
|
[IO.File]::WriteAllText((Join-Path $DataDir 'Config\ModsConfig.xml'), $modsConfig)
|
||||||
|
Write-Host ("Mods: " + ($mods -join ', '))
|
||||||
|
|
||||||
|
$createdLink = $false
|
||||||
|
try {
|
||||||
|
if (-not (Test-Path $link)) {
|
||||||
|
New-Item -ItemType Junction -Path $link -Target $testMod | Out-Null
|
||||||
|
$createdLink = $true
|
||||||
|
}
|
||||||
|
$gameArgs = "-headless -quicktest -blaxslavestests -NoFileLog -NoCrashDialog `"-savedatafolder=$DataDir`""
|
||||||
|
$sw = [Diagnostics.Stopwatch]::StartNew()
|
||||||
|
$p = Start-Process -FilePath (Join-Path $RimWorldDir 'RimWorld.exe') -WorkingDirectory $RimWorldDir -ArgumentList $gameArgs `
|
||||||
|
-RedirectStandardOutput (Join-Path $DataDir 'game.log') -RedirectStandardError (Join-Path $DataDir 'game.err.log') `
|
||||||
|
-WindowStyle Hidden -PassThru
|
||||||
|
if (-not $p.WaitForExit($TimeoutSeconds * 1000)) {
|
||||||
|
$p.Kill()
|
||||||
|
Write-Warning "timed out after $TimeoutSeconds s, game killed"
|
||||||
|
}
|
||||||
|
Write-Host ("Game ran {0:N0} s. Log: {1}" -f $sw.Elapsed.TotalSeconds, (Join-Path $DataDir 'game.log'))
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
if ($createdLink -and (Test-Path $link)) { cmd /c rmdir "$link" | Out-Null }
|
||||||
|
}
|
||||||
|
|
||||||
|
$results = Join-Path $DataDir 'BlaxSlavesTestResults.txt'
|
||||||
|
if (-not (Test-Path $results)) { Write-Host 'No results file: the suite never started. See game.log.'; exit 2 }
|
||||||
|
$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 }
|
||||||
|
exit 0
|
||||||
|
|
@ -0,0 +1,53 @@
|
||||||
|
<#
|
||||||
|
Prepares a Steam Workshop upload. RimWorld's uploader copies the whole mod folder, hidden files
|
||||||
|
included, and this repo is the mod folder (junctioned into Mods\BlaxSlaves). So:
|
||||||
|
|
||||||
|
.\Tools\workshop-stage.ps1 swap the dev junction for a clean copy (only what players need)
|
||||||
|
(upload in game: Options > Development mode, Mods > Blax Slaves > More actions > Upload to Steam Workshop)
|
||||||
|
.\Tools\workshop-stage.ps1 -Done copy About\PublishedFileId.txt back into the repo, restore the junction
|
||||||
|
|
||||||
|
Run with RimWorld closed.
|
||||||
|
#>
|
||||||
|
param(
|
||||||
|
[string]$RimWorldDir = 'E:\SteamLibrary\steamapps\common\RimWorld',
|
||||||
|
[switch]$Done
|
||||||
|
)
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
$repo = Split-Path -Parent $PSScriptRoot
|
||||||
|
$modDir = Join-Path $RimWorldDir 'Mods\BlaxSlaves'
|
||||||
|
$ship = 'About', '1.7', 'Defs', 'Patches', 'Languages', 'Textures', 'Sounds'
|
||||||
|
|
||||||
|
if (Get-Process -Name RimWorld -ErrorAction SilentlyContinue) { throw 'Close RimWorld first.' }
|
||||||
|
|
||||||
|
function Test-Junction([string]$path) {
|
||||||
|
(Test-Path $path) -and ((Get-Item $path -Force).Attributes -band [IO.FileAttributes]::ReparsePoint)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (-not $Done) {
|
||||||
|
if (Test-Path $modDir) {
|
||||||
|
if (-not (Test-Junction $modDir)) { throw "$modDir is already a real folder. Run with -Done first." }
|
||||||
|
cmd /c rmdir "$modDir" | Out-Null
|
||||||
|
}
|
||||||
|
New-Item -ItemType Directory $modDir | Out-Null
|
||||||
|
foreach ($name in $ship) {
|
||||||
|
$src = Join-Path $repo $name
|
||||||
|
if (Test-Path $src) { Copy-Item $src (Join-Path $modDir $name) -Recurse }
|
||||||
|
}
|
||||||
|
Get-ChildItem $modDir -Recurse -File | Where-Object { $_.Extension -in '.pdb' } | Remove-Item
|
||||||
|
$files = Get-ChildItem $modDir -Recurse -File
|
||||||
|
Write-Host ("Clean copy ready at {0}: {1} files, {2:N0} KB" -f $modDir, $files.Count, (($files | Measure-Object Length -Sum).Sum / 1KB))
|
||||||
|
$files | ForEach-Object { ' ' + $_.FullName.Substring($modDir.Length + 1) } | Write-Host
|
||||||
|
Write-Host 'Now upload in game, then run: .\Tools\workshop-stage.ps1 -Done'
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
if (Test-Junction $modDir) { Write-Host 'Already restored.'; exit 0 }
|
||||||
|
$id = Join-Path $modDir 'About\PublishedFileId.txt'
|
||||||
|
if (Test-Path $id) {
|
||||||
|
Copy-Item $id (Join-Path $repo 'About\PublishedFileId.txt') -Force
|
||||||
|
Write-Host ("Workshop item: https://steamcommunity.com/sharedfiles/filedetails/?id=" + (Get-Content $id -Raw).Trim())
|
||||||
|
}
|
||||||
|
else { Write-Warning 'No PublishedFileId.txt: the upload did not happen (or failed).' }
|
||||||
|
if (Test-Path $modDir) { Remove-Item $modDir -Recurse -Force }
|
||||||
|
New-Item -ItemType Junction -Path $modDir -Target $repo | Out-Null
|
||||||
|
Write-Host 'Dev junction restored.'
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,562 @@
|
||||||
|
# Blax Slaves roadmap
|
||||||
|
|
||||||
|
Blax Slaves replaces a dozen dead or conflicting slavery mods with one mod maintained for RimWorld 1.7. You choose slave or colonist when you buy, sell captives by quality or ransom them home, end the rebellion doom timer, and treat slaves in one hospital with control implants, a blood bank and health certificates, every feature with its own toggle.
|
||||||
|
|
||||||
|
Current release: 1.1 (allied outlanders and tribes send a slaver caravan on request) is built and waiting for upload to Workshop item 3847282171 (5+ subscribers).
|
||||||
|
|
||||||
|
## At a glance
|
||||||
|
|
||||||
|
| Version | What players get | Mods it replaces | Days |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 1.2 | Economy: pick slave or colonist when you buy, every trader buys slaves, price sliders, slavers stay stocked | Trade as Slave or Colonist (111), Time As a Slave (35k), [SYR] More Slaves (14.8k + 22.7k), Everybody Buys Slaves (3.3k), 3 smaller | 5 |
|
||||||
|
| 1.3 | Rebellion and medicine: suppressed slaves never rebel, work rules, slave-free colonist bar, surgery bills and medical care survive status changes | Slave Rebellions Improved (71k + 11.5k), SlaveBar (24.6k), Capable Slaves (9.8k) and 5 work mods, No Slave Mental Breaks (2.3k), Dead Calm Slave (2.1k) | 5 |
|
||||||
|
| 1.4 | Economy: ransom captives at the comms console, factions buy back their people, slave ship on request | PrisonerRansom (91k), No Sympathy For Prisoners (16.4k), Prisoner Harvesting (13.1k), Prisoner Exchange (11.1k, partly) | 6 |
|
||||||
|
| 1.5 | Medicine: one hospital for slaves and colonists, compliance and endurance implants, sedation relay | Simple Slavery Collars (52k, control part), Pawn Suppression Implants (7.8k), BK's Suppression! (1.6k), 4 collar mods | 7 |
|
||||||
|
| 1.6 | Economy and medicine: slaves sell by quality, health certificates, blood bank, organ harvests that wait for health, honor by quality | Organ Harvest Button (1.1k), Profitable Slave Trade (378), BetterHemogenFarm (273) | 7 |
|
||||||
|
| 2.0 | Freedom: recruit and convert slaves, wardens calm breakdowns, room suppression, freedom gives a mood boost | Recruit Slaves (26k), Convert Slaves (7.1k) | 6 |
|
||||||
|
| 2.1 | Freedom: loyalty stages and indentured terms | Indentured Servitude (1.3k), stage ideas from Simple Slavery Collars (52k) and More Slavery Stuff (21.7k) | 7 |
|
||||||
|
| 2.2 | Economy: faction slave orders, slave wealth and raid weight sliders | Slaves Are Worthless (10.2k), Slaves Aren't People (1.9k), Slave Contract Quest (220) | 4 |
|
||||||
|
| 2.3 | Economy: hire out slaves to allied factions (optional release) | none (Prison Expanded does it for prisoners only) | 5 |
|
||||||
|
|
||||||
|
Medical depth lands in 1.3, 1.5 and 1.6. Economic depth lands in 1.2, 1.4, 1.6, 2.2 and 2.3. Effort: S = half a day, M = 2 days, L = 5 days, summed per release and rounded up. Total: 52 working days.
|
||||||
|
|
||||||
|
## Defaults I picked
|
||||||
|
|
||||||
|
Change if you disagree.
|
||||||
|
|
||||||
|
- Captive sale price stays at vanilla 60%. Appraisal (1.6) lifts well-kept slaves by up to 75%, capped below what a slaver would charge you for the same pawn.
|
||||||
|
- Safe suppression is on at 50%: a slave at or above it never rebels.
|
||||||
|
- Traders whose ideoligion rejects slavery still buy captives, as in vanilla. From 1.6 they "buy to free" at half price instead.
|
||||||
|
- Visitor groups buy slaves, like Everybody Buys Slaves.
|
||||||
|
- Unwaveringly loyal pawns stay slave-only when bought from orbital or settlement stock, and their loyalty stops at Loyal.
|
||||||
|
- Implants are surgery-only with vanilla items. The relay uses vanilla anesthesia with manual and area triggers. No explosives, no new art.
|
||||||
|
- Ransom pays 80% of market value. Pirates and other permanent enemies refuse.
|
||||||
|
- Surgery on prisoners of non-hostile factions still costs goodwill, as in vanilla.
|
||||||
|
|
||||||
|
## 1.2 Trade on your terms
|
||||||
|
|
||||||
|
The hard requirement: buy-mode replaces Trade as Slave or Colonist, which is in your mod list. Everything here is small and has no dependencies, so 1.2 ships after about a week of work. 5 days.
|
||||||
|
|
||||||
|
#### Buy as slave or colonist
|
||||||
|
|
||||||
|
- **Players get:** In the trade window, the "Joins as slave / Joins as colonist" label on each pawn a trader sells becomes a button. Click it to switch, and the price updates at once (a slave costs 60% of the colonist price, as in vanilla). Unwaveringly loyal pawns from orbital and settlement stock can only be bought as slaves, and the tooltip says why.
|
||||||
|
- **How:** A prefix on TransferableUIUtility.DrawCaptiveTradeInfo takes over only the trader-stock branch; TradeUI calls it only while Ideology is active. Colony captives keep vanilla's ransom and slave icon. The button fills vanilla's 140 px rect and its tooltip lists both prices. A click flips guest.joinStatus between JoinAsSlave and JoinAsColonist (colonist only if guest.Recruitable), sets Tradeable's private pricePlayerBuy and pricePlayerSell to -1 through FieldRefAccess so InitPriceDataIfNeeded recomputes, then calls TradeSession.deal.UpdateCurrencyCount(). ResolveTrade stays unpatched: vanilla Pawn.PreTraded(PlayerBuys) reads joinStatus. The default purchase mode is a new first step in the existing Patch_TraderSlaveBrand postfix on ThingWithComps.PostGeneratedForTrader. It must run before that postfix's early returns (children, non-Slave-kind stock, already branded pawns), or those pawns keep vanilla's 25/75 roll. Stands down and logs when Rhajiit.tradepurchasemode is active. Hidden without Ideology.
|
||||||
|
- **Settings:** buyModeEnabled (on). defaultPurchaseMode: vanilla roll (default), always slave, always colonist; recruitable pawns only.
|
||||||
|
- **Replaces:** Trade as Slave or Colonist 3838162426 (111 subs, in your mod list).
|
||||||
|
- **Effort:** M.
|
||||||
|
- **Tests:** Generate Orbital_PirateMerchant stock through a real TradeShip and TradeSession.SetupWith (existing TradersTests pattern). Toggle flips joinStatus, and the colonist to slave price ratio is 1/0.6 within 1%. With unwavering prisoners on, an orbital stock pawn with Recruitable false refuses the toggle. A caravan pawn stays recruitable (vanilla's LordJob_TradeWithColony clause), so the toggle works there. ResolveTrade as colonist gives !IsSlave, player faction and FreedFromSlavery; as slave it gives IsSlaveOfColony. "Always slave" makes every recruitable stock pawn JoinAsSlave, children and already branded pawns included, and the brand roll still runs. Phase 2: a toggled pawn keeps its joinStatus.
|
||||||
|
- **Risks:** Rimdeed also patches DrawCaptiveTradeInfo; we take only the stock branch. A choice made and then cancelled stays on the stock pawn (saved, harmless). A trader-branded slave bought as colonist keeps the old brand; SlaveHarm already ignores brands on free colonists.
|
||||||
|
|
||||||
|
#### Every trader buys slaves
|
||||||
|
|
||||||
|
- **Players get:** Settlements, visitor groups and modded traders buy your slaves and prisoners too, not only slavers and caravans. A setting lets factions whose ideoligion rejects slavery refuse; their rows then show greyed out with the reason instead of vanishing.
|
||||||
|
- **How:** At startup and when the settings window closes (never during a TradeSession), every TraderKindDef where no stock generator HandlesThingDef(ThingDefOf.Human) gets a StockGenerator_BlaxBuySlaves, a subclass of StockGenerator_BuySlaves, with ResolveReferences(trader). In vanilla that adds Visitor_Neolithic_Standard, Visitor_Outlander_Standard, Empire_Caravan_TraderGeneral and Orbital_Empire. Kinds in any FactionDef.visitorTraderKinds follow the visitors setting. Hospitality's guest kind is skipped. There are never duplicates, so Everybody Buys Slaves can stay installed. Refuse mode: a postfix on the Tradeable.TraderWillTrade getter (Tradeable_Pawn doesn't override it) returns false for a colony slave or prisoner when the trader's faction has an ideo failing IdeoUtility.IdeoApprovesOfSlavery, unless pawn.HomeFaction == trader.Faction (ransom). The DrawCaptiveTradeInfo hook adds the reason line. Factionless orbital traders always buy. The gate covers 1.1's caravan generators too.
|
||||||
|
- **Settings:** allTradersBuySlaves (on), visitorsBuySlaves (on), antiSlaveryTraders: buy anyway (default, vanilla) or refuse. 1.6 adds "buy to free" and makes it the default.
|
||||||
|
- **Replaces:** Everybody Buys Slaves 2799461327 (3,253 subs, XML, in your mod list).
|
||||||
|
- **Effort:** S.
|
||||||
|
- **Tests:** After startup every non-excluded TraderKindDef has one generator handling Human and none has two of ours; turning the setting off restores the original counts. In refuse mode, TraderWillTrade is false for a colony slave offered to a Slavery Abhorrent faction, true for that faction's own member, true for a factionless TradeShip. In buy-anyway mode it is true everywhere. A -Compat run with Everybody Buys Slaves shows no duplicate.
|
||||||
|
- **Risks:** Modded traders with their own humanlike generators are found through HandlesThingDef, not by name. Refuse mode means fewer buyers in mostly anti-slavery worlds, which is why it is opt-in.
|
||||||
|
|
||||||
|
#### Slave stock ignores colony size
|
||||||
|
|
||||||
|
- **Players get:** Settlements and tribal camps keep selling slaves after your colony grows, so the 1 to 4 settlement slaves Blax Slaves promises show up. Ideologies that forbid slavery still don't sell.
|
||||||
|
- **How:** StockGenerator_Slaves skips its whole stock when respectPopulationIntent is set and Rand.Value > PopulationIntent. Base_Neolithic_Standard, Base_Outlander_Standard and Royalty's Base_Empire_Standard set the flag. At startup the private field on every StockGenerator_Slaves is saved and cleared through FieldRefAccess, and restored when the setting goes off. slaveKindDef (Slave_Empire) stays intact, and vanilla's ideology check in GenerateThings still runs. If Mlie.SYRMoreSlaves is active, the Compat tab says its extra 3 to 5 slaves stack on ours. That replaces the README's loadAfter note.
|
||||||
|
- **Settings:** slaveStockIgnoresColonySize (on).
|
||||||
|
- **Replaces:** [SYR] More Slaves (Continued) 3361231919 (14,810 subs, in your mod list), [SYR] More Slaves 2021510577 (22,688, 1.4), Tribals Always Sell Slaves 3173095283 (5,182, abandoned), Simple more slaves 3227695395 (5,320, 1.6).
|
||||||
|
- **Effort:** S.
|
||||||
|
- **Tests:** Reflection shows the field false on every StockGenerator_Slaves, and Base_Empire_Standard keeps Slave_Empire. With PopulationIntent forced to 0 by a test-only patch, 20 Base_Outlander_Standard stocks generated for a null or pro-slavery faction all contain slaves; with the setting off, none do. (An anti-slavery faction yields nothing either way.)
|
||||||
|
- **Risks:** Late-game slave supply rises above vanilla (toggle). With SYR still loaded, its generator stacks on ours until the player removes it.
|
||||||
|
|
||||||
|
#### Slave price sliders
|
||||||
|
|
||||||
|
- **Players get:** Two sliders set what slaves cost (vanilla 60% of the colonist price) and what captives fetch (vanilla 60%). The trade tooltip shows the factor in use. A hard cap means no buy-low, sell-high loop between traders.
|
||||||
|
- **How:** One Patch_SlavePrices on the private Tradeable.InitPriceDataIfNeeded. A prefix stores in __state whether pricePlayerBuy <= 0, so the postfix only acts after a real compute, not after the cached early return. The postfix, for humanlike pawns with Ideology, sets priceFactorBuy_JoinAs (when it is 0.6) to slaveBuyFactor and priceFactorSell_HumanPawn to slaveSellFactor, then recomputes both prices with the public TradeUtility.GetPricePlayerBuy and GetPricePlayerSell, passing the stored priceFactor and priceGain fields read through FieldRefAccess. It does not scale the stored prices, because vanilla stores them already clamped and rounded. Then it re-clamps sell <= buy and applies the hard cap: a humanlike captive's sell price is at most 0.9 x TradeUtility.GetPricePlayerBuy for the same pawn as a slave, with slaveBuyFactor and the same negotiator and settlement gains. Vanilla's GetPriceTooltip reads the factor fields, so the tooltip updates with no extra patch. Numbers: vanilla sale is market value x 0.6 x 0.6 = 36%, so an average adult (MV 1,750) fetches 630. Appraisal, abolitionist buyers and indenture pricing extend this one postfix.
|
||||||
|
- **Settings:** slaveSellFactor 60% (30 to 100), slaveBuyFactor 60% (30 to 100).
|
||||||
|
- **Replaces:** Profitable Slave Trade 3492615816 (378 subs, its +30% part).
|
||||||
|
- **Effort:** S.
|
||||||
|
- **Tests:** At sell factor 0.8 the price equals GetPricePlayerSell with factor 0.8 (within 1) and never exceeds the buy price. A second InitPriceDataIfNeeded call leaves both prices unchanged. At 0.6/0.6 both prices equal vanilla exactly. A JoinAsSlave stock pawn at buy factor 0.5 costs the recomputed price. At sell factor 100% with a Social 20 negotiator the sell price stays below 0.9 x the slave buy price. The tooltip shows the new percentage.
|
||||||
|
- **Risks:** A higher sell factor makes raider farming pay, so the default is vanilla and the cap bounds loops.
|
||||||
|
|
||||||
|
#### Time as a slave
|
||||||
|
|
||||||
|
- **Players get:** The Records tab shows how long each pawn has been your slave, and the slave tab shows "Enslaved for 23 days (tracked since install)".
|
||||||
|
- **How:** New RecordDef BlaxSlaves_TimeAsColonySlave (type Time) with a RecordWorker whose ShouldMeasureTimeNow returns pawn.IsSlaveOfColony. Vanilla's records tracker adds the time every 80 ticks with no patch; vanilla's own colonist-time record excludes slaves. A postfix on the private ITab_Pawn_Visitor.DoSlavePriceListing puts the line next to "Slave price" (the method also runs in the prisoner tab, so check IsSlave). The tab sizes itself, so the line can't be cut off. This postfix becomes the one place for later lines: appraised value, persuasion, loyalty, term.
|
||||||
|
- **Settings:** showTimeInSlaveTab (on). The record always counts.
|
||||||
|
- **Replaces:** Time As a Slave 3310058867 (35,004 subs, no 1.7).
|
||||||
|
- **Effort:** S.
|
||||||
|
- **Tests:** Phase 1: Fixtures.ColonySlave, Tick(2500), record above 0; a free colonist's record is 0. Phase 2: the value survives save and reload (T.Carry).
|
||||||
|
- **Risks:** Recruit Slaves adds a similar record, which only duplicates a line.
|
||||||
|
|
||||||
|
#### Settings tabs, Compat tab and sibling hooks
|
||||||
|
|
||||||
|
- **Players get:** The settings window gets tabs (Trade, Rebellion, Medicine, Freedom, General, Compat), each with a reset button; a tab appears once its release ships. The Compat tab lists active mods this version replaces, so you know what to unsubscribe, and which Blax siblings it found.
|
||||||
|
- **How:** DoSettingsWindowContents draws TabDrawer.DrawTabs plus a scroll view per tab. Existing settings move to General with unchanged Scribe keys, so saved settings carry over. Compat.IsActive moves out of SlaveHarm.cs into a shared Compat.cs helper built on ModLister.GetActiveModWithIdentifier(id, ignorePostfix: true). ModsConfig.IsActive misses a mod installed both locally and from Steam, so nothing uses it. The Compat table is a static list of packageIds (Rhajiit.tradepurchasemode, bblkepling.EverybodyBuysSlaves, Mlie.SYRMoreSlaves, then the ones later releases add); check each against its Workshop About.xml. Sibling hooks bind BlaxCastes.CastesApi and BlaxZones.ZonesApi by reflection at startup (see "Works with the other Blax mods"). First user: RunawayDelivery.TryDeliver calls CastesApi.NotifyJoined(pawn, "blax.slaves.runawayReturned") one tick after a returned runaway is delivered. About.xml gains loadAfter entries for blax.castes and blax.zones.
|
||||||
|
- **Settings:** none of its own.
|
||||||
|
- **Replaces:** none.
|
||||||
|
- **Effort:** 2 x S (1 day).
|
||||||
|
- **Tests:** Smoke: SettingsCategory is set, the replaced-mod table resolves without exceptions, reset restores defaults (Fixtures.SnapshotSettings and RestoreSettings), an old settings file loads into the same values. Without siblings every API delegate is null and calls are no-ops. -Compat run with Blax Castes 1.3 or later: a returned runaway lands in its previous caste.
|
||||||
|
- **Risks:** None beyond wrong packageIds in the table.
|
||||||
|
|
||||||
|
## 1.3 No doom timer
|
||||||
|
|
||||||
|
Both reviewers put the rebellion fix right after 1.2: it is the top complaint (Slave Rebellions Improved, 71k). Work rules and the colonist bar come along because they have no dependencies and fill 1.7 gaps no active mod covers. 5 days.
|
||||||
|
|
||||||
|
#### No rebellion while suppressed
|
||||||
|
|
||||||
|
- **Players get:** A slave whose suppression stays at or above the safe threshold (50%) never starts or joins a rebellion. Only neglected slaves revolt, and the rebellion tooltip says why a slave is safe.
|
||||||
|
- **How:** A postfix on SlaveRebellionUtility.CanParticipateInSlaveRebellion returns false for a colony slave with Need_Suppression.CurLevelPercentage >= threshold. Vanilla's private InitiateSlaveRebellionMtbDaysHelper checks it first (MTB -1, shown as "Never"), and StartSlaveRebellion (the out-parameter overload both overloads reach), FindSlaveForRebellion and InteractionWorker_SparkSlaveRebellion all use it. MentalStateWorker_SlaveRebellion.StateCanOccur only checks FindSlaveForRebellion, so it gets its own postfix to block the Rebellion break for safe pawns. Below the threshold, a postfix on InitiateSlaveRebellionMtbDaysHelper multiplies a positive MTB by a setting; it runs inside vanilla's MTB cache, and the 1.5 implant factors go into this same postfix. A postfix on GetSlaveRebellionMtbCalculationExplanation adds a "Blax Slaves" line, since vanilla returns "" for non-participants. Alert_SlaveRebellionLikely goes quiet on its own. Numbers: a Social 10 warden keeps a slave cycling between about 65% and 90%, so only unattended slaves drop under 50%. SlavesApi.IsSafe(Pawn) ships here.
|
||||||
|
- **Settings:** safeSuppressionEnabled (on), safeThreshold 50% (0 to 100), unsafeRebellionMtbFactor 1.0 (0.25 to 4), blockRebellionBreakWhenSafe (on).
|
||||||
|
- **Replaces:** Slave Rebellions Improved (Continued) 3259932217 (71,014 subs), Slave Rebellions Improved 2601801303 (11,458).
|
||||||
|
- **Effort:** S.
|
||||||
|
- **Tests:** Test through the vanilla callers (InitiateSlaveRebellionMtbDays, StartSlaveRebellion), not only CanParticipate, so a patch inlined away under the Waylith backend shows up as a failure. Call ClearCache between steps. A slave at 0.8 gives MTB -1; at 0.3 the MTB is above 0 and factor 2 doubles it. StartSlaveRebellion with an unsafe initiator leaves a 0.8 slave out of the lord. StateCanOccur is false at 0.8.
|
||||||
|
- **Risks:** Slave Rebellions Improved patches the same methods; both only reduce rebellions, so they coexist and the Compat tab notes it. Slavery gets easier, which is the goal. Escape-route rules (orbit, asteroid) stay vanilla.
|
||||||
|
|
||||||
|
#### Rebellion options: armed slaves and calm genes
|
||||||
|
|
||||||
|
- **Players get:** Two switches. Armed slaves are never safe (off by default). Slaves with a gene that stops prison breaks, Dead Calm or a modded one, never rebel.
|
||||||
|
- **How:** Both live in the CanParticipate postfix. Armed: when on, a slave holding a weapon skips the safe rule, so vanilla's x4 weapon factor (CanApplyWeaponFactor) applies again; without this, the safe rule short-circuits it. Genes: any active gene with prisonBreakMTBFactor < 0 makes CanParticipate false, the same rule Pawn_GeneTracker uses for prisoners. It replaces a Dead Calm defName check: Dead Calm's aggro factor doesn't cover the Rebellion break, which is Malicious. Biotech only.
|
||||||
|
- **Settings:** armedSlavesNeverSafe (off), calmGenesNeverRebel (on).
|
||||||
|
- **Replaces:** Dead Calm Slave 2898122682 (2,071 subs, no 1.7).
|
||||||
|
- **Effort:** S.
|
||||||
|
- **Tests:** An armed slave at 0.8 has MTB above 0 with the switch on and -1 with it off. A Dead Calm slave at 0.1 gives -1 (Biotech only).
|
||||||
|
- **Risks:** Allowing Hunting in work rules arms slaves; the tooltip on that work type says so.
|
||||||
|
|
||||||
|
#### Rebellion alerts use the safe threshold
|
||||||
|
|
||||||
|
- **Players get:** Vanilla's "slaves unsuppressed" alert lists every slave below the safe threshold, worst first, with suppression and expected days to rebellion. Each vanilla slave alert can be hidden.
|
||||||
|
- **How:** No new alert: vanilla already names culprits and jumps to them, so a third alert would duplicate a row. A postfix on Alert_SlavesUnsuppressed.GetReport (or its Targets getter) changes the culprit test from vanilla's 30% to suppression < safeThreshold while safe suppression is on, sorted by InitiateSlaveRebellionMtbDays. A postfix on its GetExplanation lists each culprit with suppression % and days. Two hide switches return AlertReport.Inactive.
|
||||||
|
- **Settings:** hideUnsuppressedAlert (off), hideRebellionLikelyAlert (off).
|
||||||
|
- **Replaces:** Slave Rebellions Improved (its named-alert part).
|
||||||
|
- **Effort:** S.
|
||||||
|
- **Tests:** A slave at 0.4 with threshold 0.5 makes the alert active with that pawn as culprit (vanilla ignores 0.4). At 0.9 it is inactive. Hide on gives Inactive.
|
||||||
|
- **Risks:** Cosmetic only.
|
||||||
|
|
||||||
|
#### Suppressed slaves don't break
|
||||||
|
|
||||||
|
- **Players get:** Optionally, slaves at or above the safe threshold have no random mood breaks. The mood ring, trait states such as pyromania, and blood rage stay vanilla.
|
||||||
|
- **How:** A prefix on the public MentalBreaker.TryDoRandomMoodCausedMentalBreak (or the private CanHaveMentalBreak it calls first) returns false for a colony slave at or above safeThreshold. Not the CanDoRandomMentalBreaks getter the design named: that getter also drives the mood ring, the break markers and trait mental states, and a tiny getter is the most likely target for CoreCLR to inline.
|
||||||
|
- **Settings:** suppressedSlavesDontBreak (off).
|
||||||
|
- **Replaces:** No Slave Mental Breaks 3728648822 (2,307 subs).
|
||||||
|
- **Effort:** S.
|
||||||
|
- **Tests:** Through MentalBreakerTickInterval with TestMoodMentalBreak forced: a slave at 0.8 gets no break with the setting on and vanilla behaviour with it off. The colonist bar mood ring still draws. A colonist is unaffected.
|
||||||
|
- **Risks:** It removes a vanilla pressure valve, so it is off by default. 2.0's "wardens calm breakdowns" is the gentler fix.
|
||||||
|
|
||||||
|
#### Lingering terror
|
||||||
|
|
||||||
|
- **Players get:** Terror from skullspikes, gibbet cages and terror sculptures fades over hours instead of vanishing the moment a slave walks out of sight. The setting runs from 0 (vanilla) to 48 hours, default 12.
|
||||||
|
- **How:** A postfix on the extension method TerrorUtility.GetTerrorLevel(Pawn), the single source for StatWorker_Terror and StatPart_Terror, returns max(vanilla level, stored peak x linear decay). Peak and tick per pawn sit in an in-memory dictionary, so removing the mod leaves nothing behind. A postfix on the StatWorker_Terror explanation adds "lingering: x%". The design's version (raise ObservedTerror.durationDays) can't work: PawnObserver.ObserveSurroundingThings calls TerrorUtility.RemoveAllTerrorThoughts on every pass, about every 450 to 750 ticks.
|
||||||
|
- **Settings:** terrorLingerHours 12 (0 to 48).
|
||||||
|
- **Replaces:** none listed. It answers the top point of a 2,852-upvote thread and is what players recommend Useful Terror for.
|
||||||
|
- **Effort:** S.
|
||||||
|
- **Tests:** A slave next to a skullspike has terror X; moved away for one observation pass, it still has X x the decay for one hour; at 0 hours it drops to vanilla at once.
|
||||||
|
- **Risks:** A reload clears stored peaks until the next observation pass. Higher terror lowers the suppression fall rate through vanilla's curve, so slavery gets easier.
|
||||||
|
|
||||||
|
#### Slave work rules
|
||||||
|
|
||||||
|
- **Players get:** Choose which banned jobs slaves may do (warden, hunting, art, research and any modded type) and their work speed, flat or scaled by suppression. Slave wardens never suppress other slaves.
|
||||||
|
- **How:** The settings list every WorkTypeDef with disabledForSlaves true at load and record the originals. Allowing one sets disabledForSlaves false, which GuestUtility.GetDisabledWorkTypes reads live, then calls Notify_DisabledWorkTypesChanged on all colony slaves to clear the cache. Flat speed sets the private factor of the StatPart_Slave on WorkSpeedGlobal (Core XML 0.85, its only use) through FieldRefAccess. The suppression option sets that factor to 1.0 and adds a StatPart that runs from 70% at 0% suppression to 100% at full suppression; 2.1 can drive it by loyalty. A postfix on the protected WorkGiver_Warden.ShouldTakeCareOfSlave returns false when the warden is a slave, which also blocks self-suppression loops.
|
||||||
|
- **Settings:** Per work type "slaves may do" (all off = vanilla). slaveWorkSpeed 85% (50 to 100). speedFollowsSuppression (off), 70% to 100%.
|
||||||
|
- **Replaces:** Capable Slaves 2870120550 (9,842 subs, no 1.7), Capable Slaves plus Warden 2986875064 (1,381), Art n Smart Slaves 2605727464 (2,643), 100% Slave Work Speed 3106598768 (1,966), Slaves Work at Full Speed 3679470056 (388), Slaves Can Research 3743623338 (193).
|
||||||
|
- **Effort:** 2 x S (1 day).
|
||||||
|
- **Tests:** Allowing Research makes WorkTypeIsDisabled(Research) false for a slave; restoring makes it true. The WorkSpeedGlobal explanation shows x100% at 1.0. With the suppression option, a slave at 0% gets 0.7 and at 100% gets 1.0. A slave warden gets no SlaveSuppress job.
|
||||||
|
- **Risks:** Newly allowed work types start at priority 0. Allowing Hunting arms slaves, which brings back the x4 weapon factor below the threshold. The balance shifts toward slaves against mechs, as players asked.
|
||||||
|
|
||||||
|
#### Hide slaves from the colonist bar
|
||||||
|
|
||||||
|
- **Players get:** A toggle in the bottom-right play controls (vanilla slave icon) or a keybinding hides slaves on the map from the colonist bar, so big slave colonies keep a readable bar. Caravan slaves stay listed.
|
||||||
|
- **How:** A postfix on PlaySettings.DoPlaySettingsGlobalControls adds the toggle with GuestUtility.SlaveIcon, plus a KeyBindingDef with no default key. In 1.7, PlayerPawnsDisplayOrderUtility.Sort is only called from ColonistBar.CheckRecacheEntries, once for map pawns and once for caravans. A prefix on Sort removes spawned colony slaves while the setting is on, so caravan slaves stay. A context flag around CheckRecacheEntries only guards against other mods calling Sort. Toggling calls ColonistBar.MarkColonistsDirty.
|
||||||
|
- **Settings:** hideSlavesFromBar (off, also toggled in game).
|
||||||
|
- **Replaces:** SlaveBar 3019111152 (24,584 subs, stale since 1.5).
|
||||||
|
- **Effort:** S.
|
||||||
|
- **Tests:** A map with a colonist and a slave: ColonistBar.Entries contains the slave; after hide and MarkColonistsDirty it doesn't. A caravan with a slave still lists it. An all-slave map still gets vanilla's empty group entry.
|
||||||
|
- **Risks:** Colony Groups and other bar replacements bypass it; the Compat tab says so.
|
||||||
|
|
||||||
|
#### Surgery bills and medical care survive status changes
|
||||||
|
|
||||||
|
- **Players get:** Operations you queued survive enslaving a prisoner, imprisoning a slave or freeing a slave into the colony, as long as the operation still applies. Without Blax Castes, the medical care level you set also survives.
|
||||||
|
- **How:** Pawn_GuestTracker.SetGuestStatus ends with surgeryBills.Clear(), and BillStack.Clear doesn't mark bills deleted, so the same Bill instances can go back. A prefix copies the Bill_Medical list into __state. The postfix re-adds only bills no longer in the stack, only on these transitions: prisoner of colony to slave of colony, slave of colony to prisoner of colony, slave to free colonist through RecruitUtility.Recruit. It skips when the status didn't change (SetGuestStatus returns early then), when guest.Released is set, and while a prefix/finalizer flag on Pawn.PreTraded is set: a sale calls SetGuestStatus(null) while the pawn's Faction is still the player. Each bill must pass recipe.Worker.AvailableOnNow, plus CompletableEver for Recipe_Surgery workers. The same prefix and postfix save and restore the medCare that Pawn_PlayerSettings.ResetMedicalCare wipes; that part stands down when blax.castes is active, because Castes owns medical care.
|
||||||
|
- **Settings:** keepSurgeryBills (on), keepMedicalCare (on; inactive while Castes is loaded).
|
||||||
|
- **Replaces:** none. Vanilla gap and a recurring Simple Slavery bug report.
|
||||||
|
- **Effort:** 2 x S (1 day).
|
||||||
|
- **Tests:** A prisoner with a queued kidney bill keeps exactly one after GenGuest.EnslavePrisoner. A slave's brand bill is dropped on imprisonment (slave-only recipe). A slave sold through trade, or released, has no bills. SetGuestStatus to the same status duplicates nothing. "No medicine" survives enslavement without Castes; in a -Compat run with Castes our restore doesn't run.
|
||||||
|
- **Risks:** Low. Mods that expect bills to clear can turn it off.
|
||||||
|
|
||||||
|
## 1.4 Captives pay
|
||||||
|
|
||||||
|
PrisonerRansom (91k) has no 1.7 build: the largest economic opening on 1.7, so both reviewers moved this ahead of pricing. It also brings the purchase ledger and payout helper later features reuse. 6 days.
|
||||||
|
|
||||||
|
#### Purchase ledger and payouts
|
||||||
|
|
||||||
|
- **Players get:** Nothing visible on its own. It stops buy-and-ransom loops and delivers every silver payout from 1.4 on.
|
||||||
|
- **How:** New GameComponent_BlaxSlaveLedger, the per-pawn store later features reuse (Scribe references, nulls purged on load). A postfix on Tradeable_Pawn.ResolveTrade for PlayerBuys records seller faction, price and tick. This matters because PawnGroupKindWorker_Trader re-factions caravan slaves to the trader's faction and orbital or settlement stock gets a random visible faction, so a bought slave often has a friendly HomeFaction that would pay ransom. GameComponent_BlaxPayments queues silver with a delay. BlaxDelivery.DropSpot(Map, Thing) asks ZonesApi.TryFindDropSpot, falls back to DropCellFinder.TradeDropSpot, and drops with DropPodUtility.DropThingsNear.
|
||||||
|
- **Settings:** none.
|
||||||
|
- **Replaces:** none.
|
||||||
|
- **Effort:** S.
|
||||||
|
- **Tests:** Buying a stock slave writes a ledger entry with seller faction and price. A queued payment lands after its delay. Without Zones the drop uses TradeDropSpot. Phase 2: ledger and pending payment survive reload.
|
||||||
|
- **Risks:** None for players; every payout feature depends on it.
|
||||||
|
|
||||||
|
#### Slave ship on request
|
||||||
|
|
||||||
|
- **Players get:** Allied outlander factions that accept slavery send an orbital slave ship on request from the comms console, so you can sell captives any time. Vanilla terms apply: 30 goodwill and one orbital request per 15 days.
|
||||||
|
- **How:** No vanilla FactionDef sets canRequestOrbitalTrader, and Orbital_PirateMerchant (label "slave ship") has requestable false. An XML patch sets canRequestOrbitalTrader on the outlander FactionDefs, adds Orbital_PirateMerchant to their orbitalTraderKinds and makes it requestable. Vanilla FactionDialogMaker.RequestOrbitalTraderOption already demands an ally and runs a 900,000-tick cooldown. A postfix on that private method disables the option with a reason when the faction's ideo fails IdeoUtility.IdeoApprovesOfSlavery.
|
||||||
|
- **Settings:** slaveShipOnRequest (on).
|
||||||
|
- **Replaces:** none. Answers the "somewhere to sell any time" signal behind Call A Trader (52k) without the cut slave catalogue.
|
||||||
|
- **Effort:** S.
|
||||||
|
- **Tests:** An allied outlander faction with a pro-slavery ideo shows the option and the slave ship in the kind list; an anti-slavery one shows it disabled with the reason; a non-allied one shows vanilla's "must be ally".
|
||||||
|
- **Risks:** Other mods that set canRequestOrbitalTrader on outlanders add their kinds next to ours (harmless).
|
||||||
|
|
||||||
|
#### Ransom captives at the comms console
|
||||||
|
|
||||||
|
- **Players get:** Call a faction and offer back their people you hold, prisoners or slaves. They quote a price; your negotiator can push for 25% more at a time at lower odds, and the dialog shows the odds. If they accept, silver arrives by drop pod within hours and the captive walks home. If they refuse, they won't talk ransom for 10 days, and a hostile faction may come to free the captive by force.
|
||||||
|
- **How:** A postfix on FactionDialogMaker.FactionDialogFor(Pawn, Faction) inserts a DiaOption before Disconnect, found by position, not index. It is disabled with a reason when nobody qualifies or a cooldown runs.
|
||||||
|
- Candidates: PrisonersOfColony and SlavesOfColonySpawned with HomeFaction == faction, not downed, not in a mental state, and not in the purchase ledger.
|
||||||
|
- Price: MarketValue x 0.8 x relation (hostile 0.5, neutral 0.8, ally 1.0) x noble factor (1 + MostSeniorTitle seniority / 500; faction leader x3). An average neutral captive brings 1,120 silver, against 630 at a trader.
|
||||||
|
- Odds: 0.6 + goodwill/200 + negotiator Social x 0.02, minus 0.25 per push, clamped 0.05 to 0.95. Permanent-enemy factions refuse unless the setting allows them; then they start at 0.3.
|
||||||
|
- Accept: the payout helper delivers the silver after 0.1 to 0.3 days. GenGuest.PrisonerRelease or GenGuest.SlaveRelease frees the captive, so vanilla's walk-home goodwill applies, plus 5. No trade happens, so no SoldSlave event. A 3-day cooldown per faction follows.
|
||||||
|
- Refuse: 10-day cooldown per faction. A hostile faction has a 25% chance to queue IncidentDefOf.RaidEnemy at DefaultThreatPointsNow x 0.8 in 3 to 7 days through Storyteller.incidentQueue; hostility is checked again when it fires.
|
||||||
|
- **Settings:** ransomEnabled (on), ransomFactor 80% (20 to 200), pushStep 25%, refuseCooldownDays 10 (3 to 30), acceptCooldownDays 3 (0 to 10), rescueRaidChance 25% (0 to 100), permanentEnemiesMayAccept (off).
|
||||||
|
- **Replaces:** PrisonerRansom 794038005 (91,415 subs, no 1.7; in your mod list, where it loads its 1.6 DLL with a bundled Harmony 2.3.1.1), Prisoner Exchange 3495102506 (11,100, no 1.7; partly).
|
||||||
|
- **Effort:** M.
|
||||||
|
- **Tests:** With captives from a hostile and a neutral faction, the root node holds our option; with none it is disabled. A pawn bought from that faction's trader is not offered. Accept with odds forced to 1: a payment is pending, after 0.3 days map silver rises by the price and the captive is released; a second ransom within 3 days is disabled. Refuse with odds 0: cooldown set, and with raid chance 1 the queue holds RaidEnemy. Phase 2: payment and cooldowns survive reload.
|
||||||
|
- **Risks:** Ransoming every captured raider pays well; the price factor, odds and both cooldowns bound it. Comms-console overhauls that rebuild the dialog may hide the option.
|
||||||
|
|
||||||
|
#### Factions buy back their people
|
||||||
|
|
||||||
|
- **Players get:** Now and then a non-hostile faction with members among your captives writes in: "The Iron Ring offers 1,620 silver for Jana's freedom." Accept within 2 days for silver by drop pod and goodwill, and the pawn walks home. Nobles and leaders draw bigger offers.
|
||||||
|
- **How:** A GameComponent check every 2,500 ticks. Each eligible faction (non-hostile, humanlike, with a healthy member as your captive on a player map who is not in the purchase ledger) rolls Rand.MTBEventOccurs with a 20-day MTB. Price: the ransom base x Rand.Range(1.0, 1.5), no odds roll, as a reward for patience. Offers come as a ChoiceLetter with a 120,000-tick timeout (LetterWithTimeout.StartTimeout). Accepting reuses the ransom payout and release, plus 8 goodwill; declining or timing out changes nothing. One offer open at a time, at least 5 days apart. Pawns targeted by a pending rescue raid are skipped.
|
||||||
|
- **Settings:** buybackOffers (on), buybackMtbDays 20 (5 to 60), offer range 100 to 150% of the ransom price.
|
||||||
|
- **Replaces:** none directly. The resocialization-offer idea of Prison Labor 1899474310 (174,969 subs), for slaves; vanilla only has the reverse (IncidentWorker_RansomDemand).
|
||||||
|
- **Effort:** S.
|
||||||
|
- **Tests:** Force the MTB for a friendly faction's slave: our letter appears with a price in range. A slave bought from that faction's trader never draws an offer. Accepting queues a payment and releases the pawn. The letter expires after 120,000 ticks. A hostile faction never sends one. Phase 2: an open offer survives reload.
|
||||||
|
- **Risks:** Letter spam with many factions is held back by the one-offer limit and the gap.
|
||||||
|
|
||||||
|
#### Prisoners count too
|
||||||
|
|
||||||
|
- **Players get:** Optionally, the "harming slaves doesn't upset colonists" rule also covers prisoners, and it can reduce the mood hit instead of removing it. Factions can optionally stop losing goodwill over surgery on captives you hold.
|
||||||
|
- **How:**
|
||||||
|
- (a) Widen the victim predicate in the SlaveHarm frames to IsPrisonerOfColony, keeping the pacifist and family exceptions. It stands down while No Sympathy For Prisoners (sk.noprisonersympathy) is active, so two vetoes don't stack and undercut the pacifist rule.
|
||||||
|
- (b) Reduce mode: Patch_SlaveHarmGate scales Thought_Memory.moodPowerFactor and, for Thought_MemorySocial, opinionOffset by the same factor before letting the thought through. moodPowerFactor alone leaves opinion penalties (-5 to -20) at full strength.
|
||||||
|
- (c) A prefix on the protected RecipeWorker.ReportViolation skips it when the patient is a colony prisoner without questTags, for every worker except Recipe_ExecuteByCut, which keeps vanilla's -100. ReportViolation is the single funnel for surgery, hemogen, implants and execution, so the execution exclusion is explicit. Colony slaves never trigger it in vanilla.
|
||||||
|
- **Settings:** prisonersCountAsSlaves (off), harmMoodReduction 100% (0 to 100; 100 = full removal as today), captiveSurgeryNoGoodwillLoss (off; tooltip: execution still costs goodwill).
|
||||||
|
- **Replaces:** No Sympathy For Prisoners 3533769253 (16,399 subs, in your mod list), Prisoner Harvesting 3347850851 (13,090).
|
||||||
|
- **Effort:** M.
|
||||||
|
- **Tests:** Executing a prisoner with (a) on gives a non-pacifist colonist no new bad memories (Fixtures.NewBadMemories); a pacifist still minds. At 50% a mood memory and an opinion thought are both halved. Harvesting a neutral faction prisoner's kidney leaves goodwill unchanged with (c) on and drops it by 70 with it off. Executing that prisoner by cut still drops goodwill with (c) on. -Compat with NSFP: (a) stands down.
|
||||||
|
- **Risks:** (c) changes vanilla balance, so it is off by default. The broader gate needs more frame coverage in tests.
|
||||||
|
|
||||||
|
## 1.5 Slave medicine
|
||||||
|
|
||||||
|
Medical depth was your ask, and control implants are the strongest medical demand on the Workshop (Simple Slavery Collars 52k with no 1.7 build, Pawn Suppression Implants 7.8k). The implants need only the 1.3 MTB postfix. 7 days.
|
||||||
|
|
||||||
|
#### Shared infirmary and slave-surgeon rule
|
||||||
|
|
||||||
|
- **Players get:** Sick or injured slaves may lie in colonist medical beds when no slave medical bed is free, so one hospital serves everyone. Colonists in a medical bed no longer get "slept in a room with a slave". Optionally, colonists may use slave medical beds, and slave doctors can be barred from operating on free colonists.
|
||||||
|
- **How:** Vanilla RestUtility.CanUseBedNow rejects any bed whose ForSlaves differs from (guestStatusOverride ?? sleeper.GuestStatus), medical beds included. A postfix on CanUseBedNow always allows this case: setting on, sleeper IsSlaveOfColony, bed Medical, player-owned and of colonist owner type, and HealthAIUtility.ShouldSeekMedicalRest true. Because it always allows it, the per-tick job fail checks (Toils_Bed.FailOnBedNoLongerUsable), TuckIntoBed and the rescue float menu (IsValidBedFor) accept the bed too. The design's retry flag broke there: the slave would find the bed, fail the job next tick and loop. To keep slave medical beds first, a prefix on RestUtility.FindBedFor and FindPatientBedFor raises a [ThreadStatic] "strict" depth counter (FindPatientBedFor calls FindBedFor), so the first search behaves like vanilla; the postfix searches again with strict off only when the result is null. The colonist-into-slave-bed mirror works the same way (off). Thought: the existing TryGainMemory gate drops SleptInRoomWithSlave when the receiver's CurrentBed() is Medical. Surgeon rule: a postfix on Bill_Medical.PawnAllowedToStartAnew returns false with a JobFailReason when the doctor IsSlave and the patient IsFreeNonSlaveColonist; tending is unaffected.
|
||||||
|
- **Settings:** slavesUseColonistMedicalBeds (on), colonistsUseSlaveMedicalBeds (off), noSleptWithSlaveInMedicalBed (on), slavesNoSurgeryOnFreeColonists (off).
|
||||||
|
- **Replaces:** none. Vanilla gap behind the "slave-only, colonist-only furniture" wish.
|
||||||
|
- **Effort:** M.
|
||||||
|
- **Tests:** An injured colony slave with only a colonist medical bed: FindBedFor and FindPatientBedFor return it with the setting on and null with it off. The slave walks there and lies in it for 2,500 ticks without the job failing. A free slave medical bed wins. A non-medical colonist bed stays invalid. A colonist asleep in a medical bed next to a sleeping slave for 2,500 ticks gets no SleptInRoomWithSlave; in a normal bed the thought still comes. PawnAllowedToStartAnew(slave doctor) on a colonist's bill is true by default and false with the rule on.
|
||||||
|
- **Risks:** In a mass-casualty raid a slave can take the last colonist medical bed; colonists then fall back to normal beds, as vanilla does when beds run out. Colonies with only slave doctors get stuck with the surgeon rule on, so it is off. A Blax Zones sleeping zone switched to medical holds colonist medical beds, so slaves may use it too. Zones' own filters still decide, because its CanUseBedNow postfix runs after ours. Priority Treatment also postfixes PawnAllowedToStartAnew (harmless).
|
||||||
|
|
||||||
|
#### Compliance implant
|
||||||
|
|
||||||
|
- **Players get:** Surgery "install compliance implant" for colony slaves: Medicine 6, Microelectronics research, 2 components and 1 industrial medicine, no new item. Suppression falls 30% slower and the slave starts rebellions half as often, at -5% consciousness and a -4 mood. Removal is its own surgery and refunds a component; freed pawns keep a dormant implant with no effect.
|
||||||
|
- **How:** HediffDef BlaxSlaves_ComplianceImplant, class Hediff_SlaveImplant (a Hediff_Implant subclass on the Brain, countsAsAddedPartOrImplant). The stage follows Severity: a SetGuestStatus postfix sets severity 1 while the pawn is a slave and 0.5 when dormant, with stages at those thresholds, so vanilla's own change notifications refresh capacity, stat and thought caches. (Reviewers split here; one suggested calling Notify_HediffChanged on a status-driven stage. I took Severity because it uses vanilla's own notification path.) Active stage: capMods Consciousness -0.05, statFactors SlaveSuppressionFallRate 0.7 for display only. StatWorker_SuppressionFallRate.GetValueUnfinalized ignores hediff stat factors, so Brand.cs's Patch_BrandSuppressionFallRate and its explanation patch are generalised to every hediff with a BlaxSlaves_SuppressionFactor DefModExtension; the brand moves onto the extension, and indenture and loyalty reuse it. (One reviewer wanted this refactor in 1.3; it ships here with its first new user, so a real feature tests it.) The 1.3 MTB postfix doubles a positive MTB for implanted slaves. Install: a Recipe_InstallImplant subclass offered only for IsSlaveOfColony, research MicroelectronicsBasics, can fail like any vanilla implant. Removal: vanilla Recipe_RemoveImplant with removesHediff and spawnThingOnRemoved ComponentIndustrial; set priceImpact on purpose, since spawnThingOnRemoved raises market value. Mood: a slave-only ThoughtWorker, because the stock ThoughtWorker_Hediff maps hediff stages straight onto thought stages.
|
||||||
|
- **Settings:** complianceImplant (on), fallFactor 70% (50 to 100), rebellionMtbFactor 2 (1 to 5), consciousnessCost 5% (0 to 20).
|
||||||
|
- **Replaces:** Pawn Suppression Implants 2883152389 (7,801 subs; its suppressor), BK's Suppression! 2848034996 (1,628).
|
||||||
|
- **Effort:** M.
|
||||||
|
- **Tests:** After ApplyOnPawn on a colony slave the hediff sits on the Brain. Suppression fall rate is x0.7 against an identical slave, and the brand still gives x0.85 through the generalised patch. InitiateSlaveRebellionMtbDays is x2 after ClearCache. Emancipated into the colony: severity 0.5 and consciousness back to 100% with no other cache refresh. Removal refunds a component. The recipe isn't offered for colonists or prisoners. Phase 2: hediff and severity survive. -Compat with Slave Rebellions Improved.
|
||||||
|
- **Risks:** SRI rewrites the rebellion odds; our postfix multiplies whatever MTB comes out. Brand plus implant gives 0.85 x 0.7 = 0.6 fall rate (intended; both are sliders).
|
||||||
|
|
||||||
|
#### Sedation relay
|
||||||
|
|
||||||
|
- **Players get:** A second brain implant (Medicine 8, 3 components and 2 industrial medicine). When the slave starts or joins a rebellion or an aggressive mental break, the relay puts them under anesthesia after 2 seconds, and they wake up later still a slave. You can also fire it by hand from the slave's gizmo, or have it fire when the slave leaves an area you pick. One dose every 3 days; nothing explodes.
|
||||||
|
- **How:** Brain hediff with the same Severity-driven Hediff_SlaveImplant stage (dormant when free, -3 mood while a slave) and HediffComp_BlaxSedationRelay, which saves lastFiredTick. Triggers:
|
||||||
|
- A postfix on SlaveRebellionUtility.StartSlaveRebellion (out overload): when it returns true, every pawn in initiator.GetLord().ownedPawns with a charged relay is queued.
|
||||||
|
- A postfix on MentalStateHandler.TryStartMentalState: when it returns true for a colony slave with a relay and stateDef.IsAggro, or the Rebellion state, which is Malicious and needs its own check.
|
||||||
|
- Perimeter: a rare-tick check in the comp fires when the slave is outside its chosen area (default: home area) or starts an exit-map job outside a rebellion. The area picker sits on the gizmo.
|
||||||
|
- Manual: CompGetGizmos offers "Sedate now" (player only, needs a charge).
|
||||||
|
|
||||||
|
After 120 ticks the comp calls vanilla HealthUtility.TryAnesthetize (forceDowned), adding Severity only if vanilla's duration proves too short, and ends the mental state explicitly. Downed rebels leave the rebellion lord through Notify_PawnLost, and the lord ends when all members are down. A message names whose relay fired. Implanted slaves' rebellion MTB is x1.5 through the same MTB postfix.
|
||||||
|
- **Settings:** sedationRelay (on), delaySeconds 2 (0 to 10), rechargeDays 3 (1 to 10), manualTrigger (on), perimeterTrigger (on), relayMtbFactor 1.5 (1 to 5).
|
||||||
|
- **Replaces:** Simple Slavery Collars (+Tweaks) 2557274194 (52,376 subs, no 1.7; its control part, without explosives or new art), Pawn Suppression Implants 2883152389 (7,801; partly), Slavery Utilities 2559195643 (3,062, dead), Explosive Slave Collar 3536301170 (2,397; its anesthetic payload), Simple Shock Collar 3355202541 (840), Advanced Slave Collar 3540721928 (607).
|
||||||
|
- **Effort:** M, plus S for the perimeter trigger (2.5 days).
|
||||||
|
- **Tests:** Two slaves with relays: force StartSlaveRebellion(initiator, forceAggressive: true); after 120 ticks both carry Anesthetic and are downed, and a third slave without a relay isn't. A second trigger within 3 days does nothing, and the gizmo stays disabled until the recharge passes. A berserk state on an implanted slave sedates them. A slave leaving its area is sedated; one inside isn't. After the anesthetic wears off the pawn is still IsSlaveOfColony. The lord ends when all members are down. Phase 2: the charge persists.
|
||||||
|
- **Risks:** A slave sedated next to a fire or in deep water takes vanilla risks (accepted). Pawns immune to downing are not stopped. With safe suppression in place it fires rarely, so it is depth rather than a draw. Reviewers split on timing; it ships after the compliance implant and is the first feature to slip if 1.5 runs long.
|
||||||
|
|
||||||
|
#### Endurance implant
|
||||||
|
|
||||||
|
- **Players get:** "Endurance implant" for colony slaves (Medicine 6, Bionics research, 2 components and 1 industrial medicine). Work speed rises x1.15, which cancels vanilla's slave factor of x0.85. In exchange rest falls 20% faster and the slave takes a -3 mood. It goes dormant once the pawn is free.
|
||||||
|
- **How:** HediffDef with the shared Severity-driven Hediff_SlaveImplant stage. The active stage has statFactors WorkSpeedGlobal 1.15 and RestFallRateFactor 1.2, which the normal StatWorker applies with no patch. Recipe like the compliance implant's, research Bionics. It is the in-game route to full-speed slaves; the 1.3 work-speed slider stays for players who want it globally.
|
||||||
|
- **Settings:** enduranceImplant (on), workSpeedFactor 115% (100 to 130), restFallFactor 120% (100 to 150).
|
||||||
|
- **Replaces:** 100% Slave Work Speed (1,966 subs; partly), Slaves Work at Full Speed (388; partly).
|
||||||
|
- **Effort:** S.
|
||||||
|
- **Tests:** An implanted slave's WorkSpeedGlobal is x1.15 and RestFallRateFactor x1.2 against an identical slave. A free colonist with the implant shows no change.
|
||||||
|
- **Risks:** Stacks with work drugs, bionics and the work-speed slider like any implant; both factors are sliders.
|
||||||
|
|
||||||
|
## 1.6 A slave is worth what it is
|
||||||
|
|
||||||
|
Pricing comes after medicine, so appraisal counts implants from day one. The health certificate ships only with appraisal, which gives it a purpose. 7 days.
|
||||||
|
|
||||||
|
#### Slave appraisal
|
||||||
|
|
||||||
|
- **Players get:** Selling a slave pays for the slave's quality. The trade tooltip lists the appraisal: well suppressed, branded by you, a skilled specialist, certified healthy, implanted, sold to a faction that honors slavery, or recently rebellious. Each slave's info card shows an appraised sale value next to what its spare organs would fetch.
|
||||||
|
- **How:** Extends Patch_SlavePrices (1.2) for humanlike pawns while Ideology is active. pricePlayerSell is multiplied by SlaveAppraisal.Factor(pawn, TradeSession.trader); trader stock gets only the specialist factor on its buy price. Factors multiply, and the total is clamped to 0.5 to 1.75:
|
||||||
|
- Suppression: lerp(0.85, 1.15, suppression level), colony slaves only.
|
||||||
|
- Your brand: x1.10 (BrandUtility.IsBrandedByPlayer).
|
||||||
|
- Specialist: +3% per level of the best skill above 9 (Plants 14 = +15%, 20 = +33%).
|
||||||
|
- Certified healthy: x1.15, only if the pawn still passes the exam check at sale time.
|
||||||
|
- Compliance implant: x1.10.
|
||||||
|
- Recent rebel: x0.75 within 30 days. A postfix on StartSlaveRebellion (out overload) records participants in the ledger.
|
||||||
|
- Buyer ideology, from the Slavery precept of the trader faction's primary ideo: Honorable x1.20, Acceptable and Classic x1.00, Disapproved x0.85, Horrible x0.75, Abhorrent x0.65 (only reachable with "buy anyway"). Factionless orbital traders x1.00.
|
||||||
|
|
||||||
|
The 1.2 cap then applies: the sell price never exceeds 0.9 x what this negotiator would pay for the same pawn as a slave. Without it, a Social 20 negotiator buys a slave at 0.57 x market value and sells it branded and suppressed to an Honorable faction at 0.68, a profit on every slave at default sliders (vanilla loses: 0.475 against 0.57). The tooltip shows the cap line when it binds. A postfix on Tradeable.GetPriceTooltip adds one line per factor. New StatDef BlaxSlaves_AppraisedValue (category BasicsPawn, StatWorker_SlaveAppraisal, shown for colony slaves and prisoners) equals MarketValue x 0.6 x slaveSellFactor x grade for a neutral buyer. Its explanation also lists the summed trader sell price of the pawn's spare kidney and lung, so "harvest or sell" is visible. MarketValue itself is untouched, so wealth and raid points don't move. 2.1 adds Loyal x1.15. Example: an average adult (MV 1,750) sells for 630 in vanilla; at 80% suppression, your brand and Plants 14 the factor is x1.38 = 869, and to an Honorable faction x1.66 = 1,043 with an average negotiator.
|
||||||
|
- **Settings:** appraisalEnabled (on). Weight per factor: suppression 15%, brand 10%, specialist 3% per level, certificate 15%, implant 10%, recent rebel -25% over 30 days, buyer ideology (on). showAppraisalStat (on).
|
||||||
|
- **Replaces:** Profitable Slave Trade 3492615816 (378 subs, partly).
|
||||||
|
- **Effort:** M, plus S for the organ line (2.5 days).
|
||||||
|
- **Tests:** TradeSession with a TradeShip and with a faction whose test-made ideo has Slavery Honorable. A colony slave's sell price at 0% vs 100% suppression differs by 1.15/0.85 within 1%. Our brand gives x1.10, best skill 15 gives x1.18. After a recorded rebellion the price is x0.75. Sell <= buy holds for 50 random pawns. A Social 20 leader negotiator with every factor maxed sells below the slaver's buy price for the same pawn. The stat matches the trade sell price for a zero-bonus negotiator within 2%. Appraisal off gives exactly the 1.2 slider prices. The organ line lists kidney and lung for a healthy pawn and nothing for a pawn missing both spares. Phase 2: the rebellion record persists.
|
||||||
|
- **Risks:** RimMarket and Auction House price from MarketValue, so appraisal doesn't reach them (documented). The slave economy gets richer, bounded by the 1.75 clamp, the cap and the per-factor sliders.
|
||||||
|
|
||||||
|
#### Health examination and certificate
|
||||||
|
|
||||||
|
- **Players get:** A new medical bill, "health examination", for slaves and prisoners: no medicine, Medicine 4. A healthy pawn is certified for 30 days, worth +15% on sale. Otherwise the doctor's message lists what failed. A slave you harvested a kidney from can't be certified, so harvesting and selling compete.
|
||||||
|
- **How:** RecipeDef BlaxSlaves_HealthExam: workerClass Recipe_HealthExam (a Recipe_Surgery subclass), workAmount 400, no body part, no anesthesia, surgeryOutcomeEffect null so CheckSurgeryFail never fails it. It teaches Medicine. A pass needs all of: SummaryHealthPercent >= 0.9; no Hediff_Addiction; no bad hediff with HediffComp_Immunizable or a chronic def; no missing or added part on a Kidney, Lung, Liver, Heart or whole limb (a lost finger or toe doesn't count, or most captured raiders would fail). A pass adds HediffDef BlaxSlaves_HealthCertificate (not bad, HediffComp_Disappears at 1,800,000 ticks). No postfix on Pawn_HealthTracker.AddHediff, which runs for every hediff on every pawn: appraisal rechecks at sale time, and a rare-tick HediffComp check removes stale certificates. CompletableEver is false while a valid certificate exists, and a failed exam sets a 1-day cooldown in the ledger, so the bill is no free Medicine XP farm.
|
||||||
|
- **Settings:** healthExam (on), certificateDays 30 (10 to 60). The price bonus lives in appraisal.
|
||||||
|
- **Replaces:** none.
|
||||||
|
- **Effort:** S.
|
||||||
|
- **Tests:** A healthy slave gets the certificate. A slave missing a kidney gets none and a message; one missing a finger passes. Adding flu to a certified slave stops the bonus at sale at once, and the certificate is gone after the next rare tick. The bill isn't offered while certified or within a day of a fail. Phase 2: the certificate survives reload and expires on time.
|
||||||
|
- **Risks:** Low. Other mods' chronic hediffs block certificates (intended). Nobody asked for it directly, so it ships only as part of appraisal.
|
||||||
|
|
||||||
|
#### Organ harvests wait for health
|
||||||
|
|
||||||
|
- **Players get:** Harvest bills you queue on slaves and prisoners wait until the patient is healthy. They never take the last kidney or lung, and they wait while you already store enough of that organ.
|
||||||
|
- **How:** When the setting is on, a postfix on BillStack.AddBill flags new RemoveBodyPart bills in the ledger, and the bill label shows "(waits for health)". A postfix on Bill_Medical.ShouldDoNow returns false for a flagged bill while the patient fails the gate (summaryHealth >= threshold, no HasHediffsNeedingTend, no BloodLoss) or while stored organs of that def reach the stock target. The count uses map.listerThings.ThingsOfDef in storage, because ResourceCounter returns 0 for organs (they are Uncounted). A CompletableEver guard refuses the last natural kidney or lung (GetNotMissingParts, not HasDirectlyAddedPartFor). Thoughts use vanilla MyOrganHarvested and the existing harm gate. The player still queues every harvest; nothing is queued automatically.
|
||||||
|
- **Settings:** harvestWaitsForHealth (on), healthThreshold 85% (50 to 100), stock target per organ (kidney 2, lung 2; 0 = no limit, max 10).
|
||||||
|
- **Replaces:** Organ Harvest Button 3342852552 (1,127 subs, stale), Quick Ops 3844998950 (25, partly), Repeat Organ Harvest 3819036722 (3).
|
||||||
|
- **Effort:** S.
|
||||||
|
- **Tests:** A flagged kidney bill on a slave at 60% health: ShouldDoNow false; at 90% true. With 2 stored kidneys, false. A slave with one natural kidney: CompletableEver false. Phase 2: the flag survives reload.
|
||||||
|
- **Risks:** Prisoners of non-hostile factions still cost vanilla's -70 goodwill unless 1.4's captive-surgery setting is on. Demand is small; the value is the health gate.
|
||||||
|
|
||||||
|
#### Blood bank
|
||||||
|
|
||||||
|
- **Players get:** With Biotech, colony slaves get a "blood donor" toggle. Donors get a hemogen extraction bill whenever they're well enough, like vanilla's prisoner hemogen farm, which slaves never had. Optionally your sanguophages may feed on donor slaves when no hemogen pack is in reach.
|
||||||
|
- **How:** The ledger keeps the donor set. Every 15,000 ticks, the cadence of vanilla's prisoner-only HemogenFarm check in Pawn_GuestTracker, each donor who IsSlaveOfColony and passes SanguophageUtility.CanSafelyBeQueuedForHemogenExtraction (which already rejects a duplicate bill and BloodLoss) gets HealthCardUtility.CreateSurgeryBill(pawn, RecipeDefOf.ExtractHemogenPack, null, null, sendMessages: false). The toggle is a Command_Toggle from a Pawn.GetGizmos postfix with the vanilla HemogenPack icon, and it applies to every selected slave. Bloodfeeding: vanilla JobGiver_GetHemogen only feeds on prisoners, so a postfix on its TryGiveJob steps in when a bloodfeeder got null: it picks the nearest reachable donor slave without BloodLoss and gives JobDef BlaxSlaves_FeedOnDonor (go to touch, wait 120 ticks, SanguophageUtility.DoBite with vanilla's prisoner amounts). Colonists' thoughts pass the existing harm gate. Slaves has no "new slaves donate" default; per-pawn defaults belong to Castes.
|
||||||
|
- **Settings:** bloodBank (on, Biotech only), checkIntervalHours 6 (1 to 24), bloodfeedOnDonors (on).
|
||||||
|
- **Replaces:** BetterHemogenFarm 2967718207 (273 subs, 1.4), and the slave half of Prison Labor 1899474310's hemogen mode and Custom Prisoner Interactions 2841231775's auto hemogen (both prisoner-only).
|
||||||
|
- **Effort:** M.
|
||||||
|
- **Tests:** Skipped without Biotech. After Fixtures.Tick(15000) a donor slave's BillStack holds ExtractHemogenPack; a non-donor and a donor with BloodLoss get none. A bloodfeeder colonist with low hemogen and no packs on the map gets BlaxSlaves_FeedOnDonor; with the setting off, null. Phase 2: the donor set survives.
|
||||||
|
- **Risks:** Biotech-only: job and recipe references use MayRequire. Hemogen income per slave matches vanilla's prisoner farm. Doctors' workload rises with many donors. The bite path is rare, since the bank fills the fridge with packs.
|
||||||
|
|
||||||
|
#### Honor by quality at the tribute collector
|
||||||
|
|
||||||
|
- **Players get:** The Empire's tribute collector pays honor by quality instead of a flat 3. A sickly, cheap slave brings 1, an average adult 3, and a healthy, skilled slave with bionics up to 9.
|
||||||
|
- **How:** Core's StatDef RoyalFavorValue has no parts list. A PatchOperationConditional adds one, and a PatchOperationAdd puts BlaxSlaves.StatPart_SlaveFavor in it. TransformValue only touches humanlike pawns and checks ModsConfig.RoyaltyActive (the stat is Core, so MayRequire doesn't fit): value x clamp(MarketValue / 1750, 0.33, 3.0), x1.1 with your brand, rounded, minimum 1. TradeUtility.GetPricePlayerSell returns Thing.RoyalFavorValue for TradeCurrency.Favor, so the tribute collector uses it with no code patch. Gold passes through untouched.
|
||||||
|
- **Settings:** honorByValue (on), min multiplier 0.33, max 3.0 (1 to 5).
|
||||||
|
- **Replaces:** none. Asked for in Steam discussion 3808407695167544169.
|
||||||
|
- **Effort:** S.
|
||||||
|
- **Tests:** A crippled pawn gives 1, an average adult 3, a pawn worth over 5,250 gives 9. Animals and gold are unchanged. With the setting off every pawn gives 3; with Royalty inactive nothing changes.
|
||||||
|
- **Risks:** Honor per silver stays about constant, which weakens the vanilla cheapest-slave honor farm. Hediff offsets such as WCE2's brand still add before our factor.
|
||||||
|
|
||||||
|
#### Abolitionists buy to free
|
||||||
|
|
||||||
|
- **Players get:** A third choice for traders whose ideoligion rejects slavery: they buy your slaves at half price to set them free. Nobody in the colony minds the sale, even an Abhorrent negotiator can make it, and the trader's faction gains goodwill. It becomes the default for anti-slavery traders.
|
||||||
|
- **How:** Adds "buy to free" to antiSlaveryTraders (1.2) and makes it the default. Postfixes on GuestUtility.IsSellingToSlavery and TransferableUIUtility.TradeIsPlayerSellingToSlavery return false when the trader's faction is an abolitionist in this mode. That removes the SoldSlave event, the precept thoughts and the negotiator block in one place. (The design's plan to drop the event in Frame_HistoryEvent doesn't work: that frame never drops events.) Patch_SlavePrices multiplies the sell price by abolitionistPriceFactor and skips appraisal's buyer-ideology factor. Pawn_TraderTracker.AddPawnToStock would turn the freed pawn into a Slave-kind ware, so a ResolveTrade postfix takes it out of the trader's stock and makes it a free world pawn of its home faction, or of the trader's faction. The gift-pod path uses the same predicate. Goodwill: +price/40, capped at +10 per trade, through Faction.TryAffectGoodwillWith.
|
||||||
|
- **Settings:** antiSlaveryTraders gains "buy to free" (new default). abolitionistPriceFactor 50% (20 to 100).
|
||||||
|
- **Replaces:** none. Answers a 159-upvote counter-idea.
|
||||||
|
- **Effort:** S.
|
||||||
|
- **Tests:** Selling a colony slave to an anti-slavery trader in this mode: price x0.5 against the slider price, IsSellingToSlavery false, no SoldSlave event, goodwill up by about price/40, and afterwards the pawn is a free world pawn, not trader stock. An Abhorrent negotiator may sell.
|
||||||
|
- **Risks:** Goodwill farming is bounded by the price cut and the cap. Players who never changed the setting move from "buy anyway" to "buy to free" on update; the patch notes say so. Vanilla's MemberSold reaction from the pawn's other faction still applies.
|
||||||
|
|
||||||
|
## 2.0 Wardens and a way out
|
||||||
|
|
||||||
|
Recruiting is the strongest "path to freedom" signal (Recruit Slaves, 26k). It runs on its own persuasion counter, so it doesn't wait for loyalty. One reviewer wanted recruit next to the work rules in 1.3; I kept it here, the other reviewer's slot, so 1.3 stays at 5 days. 6 days.
|
||||||
|
|
||||||
|
#### Recruit slaves
|
||||||
|
|
||||||
|
- **Players get:** A new "recruit" order in the slave tab. Wardens keep the slave suppressed and talk them round once a day; at full persuasion the slave joins as a colonist, with no "imprison first" detour.
|
||||||
|
- **How:** SlaveInteractionModeDef BlaxSlaves_Recruit (listOrder 25); the slave tab lists every def by listOrder. WorkGiver_Warden_BlaxSlaveMode, a base shared with convert, hands out vanilla's SlaveSuppress job below 70% suppression while ScheduledForSlaveSuppression (JobDriver_SuppressSlave doesn't check the mode). Otherwise, once a day, a JobDriver (walk over, 180-tick wait) runs InteractionDef BlaxSlaves_PersuadeSlave: persuasion in the ledger rises by 4% x the warden's NegotiationAbility, so a warden at 1.0 needs 25 talks. The DoSlavePriceListing line shows progress. At 100%: CastesApi.HintJoinReason(pawn, "blax.slaves.slaveRecruited"), then InteractionWorker_RecruitAttempt.DoRecruit(warden, slave), which adds the quest signal, tale, record and RecruitedMe that RecruitUtility.Recruit alone skips, then FreedFromSlavery. Non-recruitable pawns are skipped with a reason line. 2.1 turns this counter into loyalty and adds passive gain. (The design's fallback was a 3% chance per talk; I took the counter because it persists, shows progress and becomes loyalty later.)
|
||||||
|
- **Settings:** recruitMode (on), persuadeGain 4% (1 to 15).
|
||||||
|
- **Replaces:** Recruit Slaves 2887124861 (26,336 subs), No Slave Mental Breaks (its recruit interaction).
|
||||||
|
- **Effort:** M.
|
||||||
|
- **Tests:** Recruit mode, warden and slave at 0.8 suppression: JobOnThing gives the persuade job; at 0.5 it gives SlaveSuppress. One talk raises persuasion. At 0.99 plus one talk the pawn is a non-slave member of the player faction with FreedFromSlavery, and the quest signal fired. An unrecruitable slave gets a null job. Phase 2: persuasion persists.
|
||||||
|
- **Risks:** With Recruit Slaves also active the tab shows two recruit modes; the Compat tab says so. Pawn_GuestTracker saves slaveInteractionMode with Scribe_Defs and no fallback, so removing the mod leaves slaves in Recruit or Convert with no mode and no suppression. The README and Compat tab say to switch them back to Suppress first. With many slaves, wardens rarely get a free daily slot; room suppression helps.
|
||||||
|
|
||||||
|
#### Convert slaves
|
||||||
|
|
||||||
|
- **Players get:** A "convert" order in the slave tab: wardens of the target ideoligion work on the slave's beliefs every day. When the slave converts, the order switches to suppress or recruit, whichever you chose.
|
||||||
|
- **How:** SlaveInteractionModeDef BlaxSlaves_Convert (listOrder 26) on the shared base, which suppresses first below 70%. The target is vanilla's saved guest.ideoForConversion, set through a picker in the slave tab like vanilla's prisoner convert, default the player's primary ideo. Only wardens whose Ideo equals the target get the job, so colonies with several ideos work. The driver is built from vanilla Toils_Interpersonal.TryConvert, which runs ConvertIdeoAttempt with no prisoner check. When the slave's ideo equals the target, the mode switches to the "then" setting. Vanilla colonists already try to convert slaves in passing; this adds daily, directed pressure.
|
||||||
|
- **Settings:** convertMode (on), afterConversion: Suppress (default) or Recruit.
|
||||||
|
- **Replaces:** Custom Prisoner Interactions 2841231775 (51,153 subs; its convert-then idea, for slaves), Convert Slaves 3411130205 (7,104, no 1.7).
|
||||||
|
- **Effort:** S.
|
||||||
|
- **Tests:** A slave with a foreign ideo at certainty 0.01, after one forced interaction, has the target ideo and its mode becomes Suppress (or Recruit by setting). A warden of another ideo gets no job. The picker sets ideoForConversion, and it survives reload.
|
||||||
|
- **Risks:** Ideology-only. Mods that change conversion math apply automatically.
|
||||||
|
|
||||||
|
#### Wardens calm breakdowns
|
||||||
|
|
||||||
|
- **Players get:** A warden walks over to a slave in a non-violent mental break and talks them out of it, at a 10% suppression cost, instead of watching a day-long tantrum.
|
||||||
|
- **How:** A WorkGiver_Warden subclass for colony slaves in a mental state that is neither IsAggro nor the Rebellion state. It needs its own precheck, because ShouldTakeCareOfSlave requires SlaveIsSecure, which is false during a mental state. JobDriver: go to touch, 180-tick talk, MentalState.RecoverFromState, then suppression drops by the setting.
|
||||||
|
- **Settings:** wardensCalmBreaks (on), calmSuppressionCost 10% (0 to 30).
|
||||||
|
- **Replaces:** none. Asked for by the opening post of the 1,785-upvote "Slavery Is Useless" thread.
|
||||||
|
- **Effort:** M (estimated S to M; I took the higher).
|
||||||
|
- **Tests:** A slave in a sad-wander break gets a warden with the calm job; afterwards the break is over and suppression is 10% lower. A berserk slave and a rebelling slave get no job.
|
||||||
|
- **Risks:** Modded mental states that block recovery stay as they are.
|
||||||
|
|
||||||
|
#### Suppress the whole room
|
||||||
|
|
||||||
|
- **Players get:** When a warden suppresses one slave, other awake slaves within 6 cells in the same room are suppressed too, at 70% strength, and count as done for the day. One warden can handle a barracks at mealtime.
|
||||||
|
- **How:** A postfix on SlaveRebellionUtility.IncrementInteractionSuppression(initiator, recipient), whose only caller is InteractionWorker_Suppress. For every other awake colony slave in the radius and room with Need_Suppression.CanBeSuppressedNow and ScheduledForSlaveSuppression, it calls the public SlaveRebellionUtility.IncrementSuppression(need, initiator, slave, share x SuppressionPower x curve(level)), with vanilla's private static CurrentSuppressionFactorCurve read through StaticFieldRefAccess, then sets mindState.lastSlaveSuppressedTick. Calling IncrementSuppression, not the interaction method, means no recursion.
|
||||||
|
- **Settings:** bystanderShare 70% (0 = off, max 100), radius 6 (2 to 12).
|
||||||
|
- **Replaces:** none.
|
||||||
|
- **Effort:** S.
|
||||||
|
- **Tests:** Three slaves at 0.4 in one room, suppress one: the other two rise by about 0.7x its gain and are no longer scheduled. A slave in the next room is unchanged. Share 0 does nothing.
|
||||||
|
- **Risks:** Wardens never suppress sleeping slaves, so it fires mostly at meals and in shared workrooms; expect a modest effect. Each bystander shows its own text mote.
|
||||||
|
|
||||||
|
#### Freedom pays off
|
||||||
|
|
||||||
|
- **Players get:** A slave you emancipate who stays in the colony gets "freed from slavery" (+15) instead of "was enslaved" (-6). Emancipated slaves who walk home leave your weapons and armor behind.
|
||||||
|
- **How:** A postfix on GenGuest.SlaveRelease: when the pawn stays as a colonist (HomeFaction is the player, the GenGuest.ShouldStayOnMapOnRelease case), remove WasEnslaved and add FreedFromSlavery. A prefix on the same method: when HomeFaction is not the player, drop carried weapons and Shell, Belt and Overhead apparel at the pawn's cell, keeping basic clothes. The drop also covers ransom and buy-back releases.
|
||||||
|
- **Settings:** freedomMoodSwap (on), releasedDropGear (on).
|
||||||
|
- **Replaces:** none. Asked for since 2019 ("+5 no longer a slave"), and the gear drop answers a 186-upvote thread.
|
||||||
|
- **Effort:** 2 x S (1 day).
|
||||||
|
- **Tests:** Emancipating a colony-born slave gives FreedFromSlavery and no WasEnslaved. Emancipating a foreign slave with a rifle and flak vest leaves both on the ground, and the pawn leaves dressed. A ransom release drops gear too.
|
||||||
|
- **Risks:** Low.
|
||||||
|
|
||||||
|
## 2.1 Loyalty and indentured servitude
|
||||||
|
|
||||||
|
The heaviest systems come last, on top of the persuasion counter, the fall-rate extension and the buy-mode button they need. If 2.1 runs long, indenture ships its gizmo and term-end letter first and the trade option later. 7 days.
|
||||||
|
|
||||||
|
#### Loyalty
|
||||||
|
|
||||||
|
- **Players get:** Well-kept slaves grow loyal over weeks. Stages show in the slave tab: Broken in, Obedient (never rebels), Loyal (sells for more, optionally full work and speed), then Devoted, when a letter asks whether to make them a colonist. Rebelling costs loyalty.
|
||||||
|
- **How:** A float per pawn in the ledger, the same number recruit mode uses: missing means 0, so slaves who existed before the update get it, and removal is clean. No hediff (it would clutter the health tab and log missing-def errors on removal). A DoSlavePriceListing line shows it with a stage tooltip. Every 2,500 ticks over SlavesOfColonySpawned: +2% per day while suppression >= safeThreshold. Slave mood sits high (ExpectationsSlave gives +28 to +46), so mood mostly scales gain by x1 to x1.5: above 75% x1.5, below 25% -2% per day (rare). Modifiers: your brand x1.25, indentured x1.5, compliance implant x0.5 (fear isn't loyalty). Joining a rebellion: -30% (StartSlaveRebellion postfix). Stages, each with a BlaxSlaves_SuppressionFactor through the generalised fall-rate patch:
|
||||||
|
- 0.25 Broken in: fall rate x0.8.
|
||||||
|
- 0.5 Obedient: x0.6, and safe at any suppression through the 1.3 postfix.
|
||||||
|
- 0.75 Loyal: x0.5, appraisal +15%, options for full work and full speed through work rules.
|
||||||
|
- 1.0 Devoted: a ChoiceLetter, batched per day: Make colonist (HintJoinReason "blax.slaves.slaveRecruited", DoRecruit(null, pawn), which skips the letter but keeps the quest signal, then FreedFromSlavery) or Keep.
|
||||||
|
|
||||||
|
Unwaveringly loyal pawns cap at Loyal unless a setting allows more. SlavesApi.Loyalty(Pawn) ships here.
|
||||||
|
- **Settings:** loyaltyEnabled (on), baseGainPerDay 2% (0.5 to 10), rebellionPenalty 30%, obedientNeverRebels (on), loyalAllWork (off), loyalFullSpeed (off), devotedLetter (on), unwaveringCanBeDevoted (off).
|
||||||
|
- **Replaces:** Simple Slavery Collars (+Tweaks) 2557274194 (52,376 subs, no 1.7; its slave-stage part), More Slavery Stuff 2896845138 (21,653; its "treatment decides rebellion" idea).
|
||||||
|
- **Effort:** L.
|
||||||
|
- **Tests:** A slave at 0.8 suppression and 0.6 mood, ticked 10 days, reaches about 0.2. A slave that existed before the feature starts at 0 and gains. At 0.5 the MTB is -1 even at 0.2 suppression. The fall-rate explanation shows x0.6. A forced rebellion costs 0.3. At 1.0 the letter arrives, and accepting gives !IsSlave and player faction. Phase 2: loyalty persists.
|
||||||
|
- **Risks:** Long games get easier; the rate sliders tune it. Stacked fall factors (brand 0.85 x implant 0.7 x indenture 0.7 x Loyal 0.5 = 0.21) make suppression nearly free, so each is a slider.
|
||||||
|
|
||||||
|
#### Indentured servitude
|
||||||
|
|
||||||
|
- **Players get:** A gizmo gives selected slaves a term of 15, 30, 60 or 120 days. Indentured slaves lose suppression 30% slower and grow loyal faster because they can see the end. The trade button gains a third choice, "joins indentured", at 80% of the colonist price. When a term ends, a letter says whether the slave is willing to stay: welcome them as a colonist (only if willing), send them home with goodwill, or extend 15 days at a mood cost. Either way out gives "served my term" (+8, 10 days) instead of "was enslaved".
|
||||||
|
- **How:** The ledger stores each pawn's term end tick. A SetGuestStatus postfix drops the term on sale, imprisonment or early release. The gizmo comes from a Pawn.GetGizmos postfix; the slave tab shows days left. While serving: a BlaxSlaves_SuppressionFactor x0.7 and loyalty gain x1.5. Term-end letters are grouped per day. Willing means loyalty >= 50% (with loyalty off, a seeded roll from 30% at 20% mood to 90% at 80% mood). Choices:
|
||||||
|
- Welcome: HintJoinReason "blax.slaves.indentureServed", then DoRecruit plus FreedFromSlavery; disabled if the pawn isn't Recruitable.
|
||||||
|
- Send home: GenGuest.SlaveRelease with vanilla walk-home goodwill. Disabled with a reason when HomeFaction is null or the player, because ShouldStayOnMapOnRelease would quietly keep the pawn as a colonist and skip the willingness check.
|
||||||
|
- Extend 15 days: BlaxSlaves_TermBroken (-10 for 15 days), loyalty -25%.
|
||||||
|
|
||||||
|
After Welcome or Send home, WasEnslaved is removed and BlaxSlaves_ServedTerm added. autoResolve: the willing join, the rest go home. Buying: JoinStatus has no indentured value, so buy-mode keeps a pending Dictionary<Pawn, PurchaseMode>, cleared when the session closes or the pawn leaves stock, and the button cycles slave, indentured (30 days), colonist. The price postfix applies 0.8/0.6 to the slave buy price. A ResolveTrade(PlayerBuys) prefix calls HintJoinReason "blax.slaves.boughtIndentured"; the postfix registers the term and writes the purchase ledger, so ransom and buy-back skip the pawn. SlavesApi.TermDaysLeft(Pawn) ships here.
|
||||||
|
- **Settings:** indentureEnabled (on), term choices 15/30/60/120 days, fallFactor 70%, joinChance 30% to 90% (loyalty off only), indenturedBuyPrice 80% of the colonist price, extendDays 15, autoResolve (off).
|
||||||
|
- **Replaces:** Indentured Servitude 2878184888 (1,311 subs, 8,244 lifetime, no 1.7), ServeTime 3259353607 (84).
|
||||||
|
- **Effort:** M.
|
||||||
|
- **Tests:** Indenture a slave for 15 days and tick 15 days: the letter is there. Welcome at loyalty 0.6 makes a free colonist with ServedTerm and no WasEnslaved; at 0.2 Welcome is disabled. Send home releases a foreign slave and is disabled for a colony-born one. Extend moves the end by 15 days and adds TermBroken. Fall rate is x0.7 while serving. Buying as indentured gives a slave with a 30-day term at 0.8/0.6 of the slave price, in the purchase ledger. Phase 2: the term survives reload.
|
||||||
|
- **Risks:** Coexists with Recruit Slaves, which is an interaction, not a term. Many slaves mean many letters, hence grouping and autoResolve. M is tight; the split above is the fallback.
|
||||||
|
|
||||||
|
## 2.2 Slave economy at scale
|
||||||
|
|
||||||
|
Slave orders need appraisal and the payout helper. Slave weights come late because Slaves Are Worthless is maintained on 1.7, so this is consolidation, not a gap. 4 days.
|
||||||
|
|
||||||
|
#### Faction slave orders
|
||||||
|
|
||||||
|
- **Players get:** Factions that approve of slavery post orders by letter: "Wanted: 2 slaves with Plants 8+, healthy, 15 to 50 years. Pays 160% of the sale price and +15 goodwill. 20 days." Accept, then sell matching slaves to any trader of that faction or gift them by drop pod. Matching slaves are marked in the trade window; the premium follows by drop pod and the goodwill comes when the order is full.
|
||||||
|
- **How:** GameComponent_BlaxMarket holds a List<SlaveOrder> (faction, SkillDef, minimum level, optional minimum loyalty stage, count, filled, expiry tick, premium, goodwill).
|
||||||
|
- Generation: MTB 15 days, at most 2 open orders, only non-hostile factions passing IdeoApprovesOfSlavery. Skill from Plants, Mining, Construction, Cooking, Crafting, Medicine, Melee or Shooting; minimum level 6 to 12 scaled by colony wealth; count 1 to 3; premium 1.4 to 1.8; goodwill 10 to 20. With loyalty on, a third of orders ask for Obedient or better. Offered as a ChoiceLetter.
|
||||||
|
- Filling, through patches Blax Slaves already has: Frame_SoldSlave on Tradeable_Pawn.ResolveTrade (the player sells a colony slave and trader.Faction == order.faction) and Frame_GiftArrived on TransportersArrivalAction_GiveGift.Arrived. A match (skill, age, health 80% or more, IsSlave, not bought from that same faction per the ledger) adds 1 to filled and queues appraised sell price x (premium - 1) through the payout helper. The premium inherits appraisal's cap.
|
||||||
|
- The buy-mode DrawCaptiveTradeInfo prefix draws "order +60%" on matching colony slaves; the captive branch keeps vanilla's icon and adds the tag.
|
||||||
|
- On expiry a letter arrives; an accepted, unfilled order costs 5 goodwill. Orders cancel if the faction turns hostile or is defeated.
|
||||||
|
- **Settings:** slaveOrders (on), ordersMtbDays 15 (5 to 60), maxOpenOrders 2 (1 to 5), premium 140 to 180%, unfilledPenalty -5 goodwill.
|
||||||
|
- **Replaces:** Slave Contract Quest 3677019267 (220 subs, no 1.7).
|
||||||
|
- **Effort:** M.
|
||||||
|
- **Tests:** A Plants 8, count 1 order for a friendly pro-slavery faction. Selling a matching slave to that faction's trader fills it, and the pending payment is the appraised price x 0.6 at premium 1.6, within the cap. A Plants 3 slave doesn't fill it, nor does a slave bought from that faction. A gift-pod arrival fills it. Past the deadline the expiry letter and penalty apply. Phase 2: open orders survive.
|
||||||
|
- **Risks:** Small Workshop signal (220 subs), so this is depth, not a draw. Letters instead of generated quests keep it at M.
|
||||||
|
|
||||||
|
#### Slave wealth, raid and population weight
|
||||||
|
|
||||||
|
- **Players get:** Three sliders set how much a slave counts toward colony wealth, raid points and storyteller population (vanilla 75% each). Set them to 50% if slaves shouldn't make raids so much bigger, or 100% for a harder game.
|
||||||
|
- **How:** Wealth: a postfix on WealthWatcher.ForceRecount adds sum(slave MarketValue x (setting - 0.75)) to the private wealthPawns field, with vanilla's filter (player-faction slaves on the map that aren't quest lodgers). Pocket-map watchers get their own call first, so nothing counts twice. Raid points: a transpiler on StorytellerUtility.DefaultThreatPointsNow replaces the ldc.r4 0.75 after get_IsSlaveOfColony with a call to SlaveWeight.RaidFactor(). If the pattern isn't found under the Waylith backend, it logs one warning, greys out the raid slider and leaves vanilla in place. Population: the private static, non-readonly StorytellerUtilityPopulation.PopulationValue_Slave is set at startup and when settings close. If Slaves Are Worthless is active, the raid and wealth parts stand down and log it.
|
||||||
|
- **Settings:** slaveWealthWeight 75% (0 to 100), slaveRaidWeight 75% (0 to 100), slavePopulationWeight 75% (0 to 100).
|
||||||
|
- **Replaces:** Slaves Are Worthless 3522135747 (10,157 subs, maintained on 1.7), Slaves Aren't People 2897601862 (1,930, 1.4).
|
||||||
|
- **Effort:** M.
|
||||||
|
- **Tests:** On a map with 3 slaves, wealthPawns at 75% equals vanilla and at 0% drops by sum(0.75 x market value). Under Rand.PushState(seed), DefaultThreatPointsNow at raid weight 0 equals the value with the slaves despawned. Harmony.GetPatchInfo shows our transpiler with its pattern-found flag set. PopulationValue_Slave reads back the setting.
|
||||||
|
- **Risks:** The mod's first transpiler under Waylith and the Harmony 3 RC, hence the log-and-skip fallback. Caravan storyteller wealth also counts slaves at 75% and isn't covered (documented). Low weights make raids easy, so vanilla is the default.
|
||||||
|
|
||||||
|
## 2.3 Hire out slaves
|
||||||
|
|
||||||
|
An optional release. It is the riskiest feature and players barely ask for it, so it ships only if 2.1 finished on time and players ask after 2.2; otherwise it moves to Backlog. 5 days.
|
||||||
|
|
||||||
|
#### Hire out slaves
|
||||||
|
|
||||||
|
- **Players get:** At the comms console, an allied or neutral pro-slavery faction can hire your slaves. Pick the slaves and a term of 7, 15 or 30 days; they leave and come back at the end with wages of 1.2% of market value per slave per day (about 21 silver a day for an average slave, 315 for 15 days), plus goodwill and skill practice. A poorly suppressed slave may escape, a few come back hurt, and if the faction turns hostile it keeps them.
|
||||||
|
- **How:** Built on vanilla's borrowed-pawn system instead of a custom holder: a Quest with a QuestPart_LendColonistsToFaction subclass. Vanilla then exempts the pawns from world-pawn garbage collection (IsBorrowedByAnyFaction), counts them for population (TotalBorrowedColonistCount), keeps GameEnder from ending the game while they're away, returns corpses of lent pawns who die, and shows the timer in the quest tab. Lent pawns stay world pawns and keep ageing. The subclass writes the private lentColonists list through FieldRefAccess, overrides Enable to take the chosen slaves, and overrides Complete to pay wages and roll escape and injury. Dialog_BlaxHireOut opens from a second option of the ransom FactionDialogFor postfix: a checklist of secure, healthy adult slaves, a term picker and a wage preview. Slaves leave by shuttle or drop pod; if they walk out, Patch_RunawayExitMap skips borrowed pawns.
|
||||||
|
- Escape roll per slave: base chance x (1 - suppression at departure) x 0.5 if branded x (1 - loyalty) with loyalty on. Branded escapees go to GameComponent_BlaxRunaways.Register with the hirer's faction; others are lost, with a letter.
|
||||||
|
- Return: RunawayDelivery's spawn logic (walk-in for tribal and medieval factions, drop pod for industrial and up), still IsSlaveOfColony. CastesApi.NotifyJoined(pawn, "blax.slaves.contractReturned") one tick after each return. Wages through the payout helper. SkillRecord.Learn grants 300 XP per day in the best enabled skill. +1 goodwill per slave per 5 days. An injury roll adds a random vanilla injury. A hirer hostile by then keeps them, with a letter.
|
||||||
|
- **Settings:** laborContracts (on), wagePerDay 1.2% of market value (0.5 to 3), baseEscapeChance 10% (0 to 30), injuryChance 5% (0 to 20), deathChance 0% (0 to 5), terms 7/15/30 days, hirerMustApproveSlavery (on).
|
||||||
|
- **Replaces:** none. Prison Expanded 3827258534 (3,298 subs) has labor contracts for prisoners only.
|
||||||
|
- **Effort:** L.
|
||||||
|
- **Tests:** Contract 2 slaves for 7 days to a friendly faction with escape chance 0: they leave, IsBorrowedByAnyFaction is true, they survive world-pawn GC, they aren't in the runaway registry, and the quest tab shows the timer. After 7 days they are back as IsSlaveOfColony, silver rose by 2 x 7 x 1.2% x market value, their best skill gained XP, and with Castes loaded each produced one NotifyJoined. Escape chance 1 plus a brand puts them in the runaway registry. A faction hostile at term end triggers the kept letter. Phase 2: an active contract survives reload mid-term.
|
||||||
|
- **Risks:** The map can close while slaves walk out (abort and keep them). Castes policies stay untouched while away. Balance: 15 days of wages is about half a sale, tunable.
|
||||||
|
|
||||||
|
## Works with the other Blax mods
|
||||||
|
|
||||||
|
- **Package ids:** blax.slaves (this mod), blax.castes, blax.zones. No hard dependencies. About.xml gets loadAfter entries for blax.castes and blax.zones next to the existing brrainz.harmony and Mlie.SYRMoreSlaves. No sibling goes into modDependencies, where Harmony stays the only entry, and there is no assembly reference. Load order is Castes, Zones, Slaves. Neither sibling lists blax.slaves, so there is no loadAfter cycle.
|
||||||
|
- **Detection:** one shared Compat helper, Compat.IsActive(id) = ModLister.GetActiveModWithIdentifier(id, ignorePostfix: true) != null. It moves out of SlaveHarm.cs in 1.2 and serves the siblings, the Compat tab and every stand-down check.
|
||||||
|
- **Binding:** at startup BlaxSlavesStartup resolves sibling APIs with AccessTools.TypeByName and AccessTools.Method into cached delegates and reads their int Version. A missing sibling or method makes that call a silent no-op, and every Slaves feature works alone. APIs only change additively.
|
||||||
|
- **Calls into BlaxCastes.CastesApi:** HintJoinReason(Pawn, string) right before a join Castes classifies itself (it expires at the end of the tick); NotifyJoined(Pawn, string) one tick after the status is final, for joins Castes can't see.
|
||||||
|
|
||||||
|
| Reason | Fired by | Call | Castes treats it as |
|
||||||
|
|---|---|---|---|
|
||||||
|
| blax.slaves.runawayReturned | RunawayDelivery.TryDeliver (existing code, wired in 1.2); it sets slave status directly | NotifyJoined | previous caste |
|
||||||
|
| blax.slaves.slaveRecruited | recruit mode (2.0), Devoted letter (2.1), before DoRecruit | HintJoinReason | recruited |
|
||||||
|
| blax.slaves.indentureServed | indenture Welcome (2.1), before DoRecruit | HintJoinReason | recruited |
|
||||||
|
| blax.slaves.boughtIndentured | indentured purchase (2.1), ResolveTrade prefix before PreTraded | HintJoinReason | bought as slave |
|
||||||
|
| blax.slaves.contractReturned | labor contract return (2.3) | NotifyJoined | keep current caste |
|
||||||
|
|
||||||
|
- **Buying needs no call:** buy-mode only sets guest.joinStatus before vanilla Pawn.PreTraded, and Castes classifies by the final status in its own PreTraded scope.
|
||||||
|
- **Not used yet:** CastesApi.CasteIdOf, CasteLabels and PrePick, for the trade-row caste picker in Backlog.
|
||||||
|
- **Calls into BlaxZones.ZonesApi:** TryFindDropSpot(map, thing, out cell) inside BlaxDelivery.DropSpot for every silver payout (ransom and buy-back in 1.4, order premiums in 2.2, wages in 2.3), with DropCellFinder.TradeDropSpot as fallback. Pawns are never routed into zones: returned runaways and hired-out slaves use the vanilla spot. HasSleepingZoneFor is not used; the shared infirmary only touches Medical beds.
|
||||||
|
- **BlaxSlaves.SlavesApi (static):** Version from 1.3. IsSafe(Pawn) from 1.3. Loyalty(Pawn) and TermDaysLeft(Pawn) from 2.1.
|
||||||
|
- **Ownership:** Castes owns every per-pawn policy default (apparel, food, drug, reading, medical care, schedule, area, hostility, self-tend, carried medicine), so Slaves never sets a policy: the 1.3 medical-care keeper stands down when Castes is loaded, and blood donor and term have no "new slaves" default here. Zones owns sleeping spots, beds by zone and every friendly drop location. Slaves owns slave status, trade, prices, suppression, rebellion, slave medicine and the slave economy.
|
||||||
|
- **Shared conventions:** patches applied one class at a time from a [StaticConstructorOnStartup] class with the "[Blax Slaves] N patches applied" log line (already in BlaxSlavesStartup); a ModSettings toggle for every feature; the headless test mod pattern (Tests/BlaxSlavesTests harness, run-tests.ps1), which Castes and Zones copy.
|
||||||
|
|
||||||
|
## Backlog
|
||||||
|
|
||||||
|
- Caste picker on the trade row, next to the buy-mode button (CasteLabels plus PrePick): waits for PrePick, which Blax Castes adds in its 1.4.
|
||||||
|
- Slave overview window (M, a text-label main button with one sortable row per slave): its best columns, loyalty and term, only exist after 2.1.
|
||||||
|
- Slave order chains such as "emancipate when healthy" or "convert, then recruit" (S to M): build on the warden-mode base once 2.0 proves it.
|
||||||
|
- Rebels may surrender (M): after 1.3, rebellions get rare; check whether players still hit fights to the death.
|
||||||
|
- Per-caste defaults for blood donor and indenture term: needs a CastesApi addition that the contract doesn't have today.
|
||||||
|
- Slave weight for caravan storyteller wealth: not covered by 2.2; add if players report it.
|
||||||
|
|
||||||
|
## Cut
|
||||||
|
|
||||||
|
- Turrets fire on rebelling slaves, turrets cause terror: Prisoners Should Fear Turrets (104k, maintained, in your mod list) stays installed for its prisoner half, so taking its slave half removes no mod. The Compat tab points to it.
|
||||||
|
- Longer terror memories through ObservedTerror.durationDays: can't work, vanilla clears terror thoughts on every observation pass. Lingering terror (1.3) replaces it.
|
||||||
|
- A separate at-risk rebellion alert: vanilla alerts already name culprits; 1.3 retunes them instead.
|
||||||
|
- Organ donor gizmo with automatic harvests: its stock check could never work (organs are uncounted) and demand is tiny (1.1k). "Organ harvests wait for health" (1.6) keeps the useful part.
|
||||||
|
- Slaves leave loose weapons alone: wrong premise, slaves and colonists don't pick up weapons in daily life; only rebels do.
|
||||||
|
- Comms-console slave catalogue: L effort with world-pawn cleanup risk, and 1.1 caravans, stock-any-size, every-trader-buys and the slave ship already cover supply. Revisit after 2.2 if players ask.
|
||||||
|
- Sedation collar apparel: needs art on every body type; the relay implant does the same job.
|
||||||
|
- Absorbing Raiders Never Die: vanilla 1.7 custom difficulty already has the slider.
|
||||||
|
- Per-join policy defaults (outfit, food, drugs, reading, medical care, area): Castes owns them, and the README points players there.
|
||||||
|
- Slave sleeping zones and mass sleeping spots: Zones owns them.
|
||||||
|
- Medical triage ("treat only if worth more than X"): medical care is a Castes policy; appraisal shows the value and the player decides.
|
||||||
|
- New collar and outfit looks: need art, and there is no artist.
|
||||||
|
- Explosive, shock or skull-piercer collars, torture, flogging, lobotomy, nerve staple, brainwash chair: beyond vanilla Ideology's tone. Sedation and the compliance implant cover control.
|
||||||
|
- Automated lethal harvests (heart, liver, harvest before execution): automating killing goes past vanilla's manual choice.
|
||||||
|
- Slave romance and marriage rules: not a pain point.
|
||||||
|
- Keeping slaves out of parties and funerals: vanilla 1.7 already does it.
|
||||||
|
- Home factions angry when bought slaves are harvested: vanilla treats colony slaves as player faction, so no violation fires. Prisoners are covered in 1.4.
|
||||||
|
- Slave auctions and market events: RimMarket (50k) and Auction House (5.5k) do it on 1.7 and are maintained.
|
||||||
|
- Prisoner arena and prisoner forced labor: maintained prisoner mods (Prison Labor, Prisoner Realism, Prison Expanded) cover it, and slaves already work.
|
||||||
|
- Gene extraction farm: Auto-Extract Genes (65.8k, 1.7) already covers slaves.
|
||||||
|
- Docility drug: needs item art, and drug schedules belong to Castes.
|
||||||
|
- Slave-surgeon sabotage: players dislike punitive randomness; the 1.5 surgeon rule covers trust.
|
||||||
|
- "Slavery: Pragmatic" price precept: touches every ideo; sliders and appraisal's buyer factor do the job.
|
||||||
|
- Flee AI and rebellion size rework: L pathing work for little gain once safe suppression lands.
|
||||||
|
- Mood-based suppression decay: a second axis next to loyalty confuses players.
|
||||||
|
- "Serving a term" +4 mood: indenture keeps one in-term benefit and the end reward.
|
||||||
|
- Hereditary slave status, slave recreation need, upkeep accounting, "break this slave" contract: low demand, already vanilla, or control content.
|
||||||
|
- WCE2 brand overlap, Prisoner Realism's contraband search and despair for slaves, History graph line, slave/colonist furniture toggles: WCE2 still loads a 1.6 DLL, the rest has weak demand, and the shared infirmary covers hospitals.
|
||||||
Loading…
Reference in New Issue