code:
#nullable enable

using Psychology;
using SyrTraits;
using System.Text;
using Verse;
using RimWorld;
using Multiplayer.API;
using System;

namespace rjw
{
	public class CompRJW : ThingComp
	{
		/// <summary>
		/// Core comp for genitalia and sexuality tracking.
		/// </summary>
		public CompRJW()
		{
			pawn = Pawn;
		}

		public CompProperties_RJW Props => (CompProperties_RJW)props;
		public Orientation orientation = Orientation.None;
		public StringBuilder quirks = new();
		public string quirksave = ""; // Not the most elegant way to do this, but it minimizes the save bloat.
		public int NextHookupTick;
		private bool BootStrapTriggered = false;
		public Need_Sex? sexNeed;
		public bool drawNude = false;
		public bool keep_hat_on = false;
		private PawnData? pawnData = null;
		public PawnData PawnData
		{
			get
			{
				if (pawnData == null && pawn != null)
				{
					pawnData = new PawnData(pawn);
				}
				return pawnData;
			}

		}
		/// <summary>
		/// <para>Gets the pawn for this comp.</para>
		/// <para>May return null if the comp's parent is somehow not a pawn.</para>
		/// </summary>
		private Pawn? pawn;
		private Pawn? Pawn => parent is Pawn pawn ? pawn : null;

		// This automatically checks that genitalia has been added to all freshly spawned pawns.
		public override void PostSpawnSetup(bool respawningAfterLoad)
		{
			base.PostSpawnSetup(respawningAfterLoad);

			if (pawn == null)
			{
				pawn = Pawn;
				if (pawn == null) return;
			}

			pawnData ??= new PawnData(pawn);

			if (pawn.kindDef.race.defName.Contains("AIRobot") // No genitalia/sexuality for roombas.
				|| pawn.kindDef.race.defName.Contains("AIPawn") // ...nor MAI.
				|| pawn.kindDef.race.defName.Contains("RPP_Bot")
				|| pawn.kindDef.race.defName.Contains("PRFDrone") // Project RimFactory Revived drones
				) return;

			// No genitalia
			//if (!pawn.RaceProps.body.AllParts.Exists(x => x.def == DefDatabase<BodyPartDef>.GetNamed("Genitals")))
			//	return;

			if (pawn.GetCompRJW().orientation == Orientation.None)
			{
				Sexualize(pawn);
				Sexualize(pawn, true);
			}

			//Log.Message("PostSpawnSetup for " + pawn?.Name);
		}

		public override void CompTick()
		{
			base.CompTick();

			if (pawn == null) return;

			if (pawn.IsHashIntervalTick(1500) && !pawn.health.Dead)
			// The `NeedInterval` function is called every 150 ticks but was formerly
			// rate limited by a factor of 10.  This will make the upkeep execute at
			// the same interval.
			{
				if (sexNeed == null)
				{
					sexNeed = pawn.needs?.TryGetNeed<Need_Sex>();
				}
				if (sexNeed != null)
				{
					DoUpkeep(pawn, sexNeed);
				}
			}
		}

		/// <summary>
		/// Performs some upkeep tasks originally handled in `Need_Sex.NeedInterval`.
		/// </summary>
		private void DoUpkeep(Pawn pawn, Need_Sex sexNeed)
		{
			if (pawn.Map == null) return;
			if (xxx.is_asexual(pawn)) return;

			var curLevel = sexNeed.CurLevel;

			// Update psyfocus if the pawn is awake.
			if (!RJWSettings.Disable_MeditationFocusDrain && pawn.Awake() && curLevel < sexNeed.thresh_frustrated())
				SexUtility.OffsetPsyfocus(pawn, -0.01f);
			//if (curLevel < sexNeed.thresh_horny())
			//	SexUtility.OffsetPsyfocus(pawn, -0.01f);
			//if (curLevel < sexNeed.thresh_frustrated() || curLevel > sexNeed.thresh_ahegao())
			//	SexUtility.OffsetPsyfocus(pawn, -0.05f);

			if (curLevel < sexNeed.thresh_horny() && (pawn.mindState.canLovinTick - Find.TickManager.TicksGame > 300))
				pawn.mindState.canLovinTick = Find.TickManager.TicksGame + 300;

			// This can probably all just go, since it's now a noop.
			// But I don't know if some mod is patching `xxx.bootstrap` or something.
			if (!BootStrapTriggered)
			{
				//--ModLog.Message("CompRJW::DoUpkeep::calling boostrap - pawn is " + xxx.get_pawnname(pawn));
				xxx.bootstrap(pawn.Map);
				BootStrapTriggered = true;
			}
			if (drawNude) {
				bool isFucking = pawn.jobs?.curDriver is JobDriver_Sex;
				if(!isFucking)
				{
					drawNude = false;
					keep_hat_on = false;
				}
			}

		}

		public override void PostExposeData()
		{
			base.PostExposeData();
			if (Pawn == null) return;

			// Saves the data.
			Scribe_Values.Look(ref orientation, "RJW_Orientation");
			Scribe_Values.Look(ref quirksave, "RJW_Quirks", "");
			Scribe_Values.Look(ref NextHookupTick, "RJW_NextHookupTick");
			Scribe_Values.Look(ref drawNude, "RJW_drawNude");
			Scribe_Values.Look(ref keep_hat_on, "RJW_keep_hat_on");
			Scribe_Deep.Look(ref pawnData, "pawnData");
			//Log.Message("PostExposeData for " + pawn?.Name);

			// Restore quirk data from the truncated save version.
			quirks = new StringBuilder(quirksave);
		}
		[Obsolete("CompRJW.Comp is deprecated, please use xxx.GetCompRJW() instead.")]
		public static CompRJW Comp(Pawn pawn)
		{
			// Call CompRJW.Comp(pawn).<method> to check sexuality, etc.
			return pawn.GetCompRJW();
		}

		public static void CopyPsychologySexuality(Pawn pawn)
		{
			try
			{
				int kinsey = pawn.TryGetComp<CompPsychology>().Sexuality.kinseyRating;
				//Orientation originalOrientation = pawn.GetCompRJW().orientation;

				if (!Genital_Helper.has_genitals(pawn) && (pawn.kindDef.race.defName.ToLower().Contains("droid") || pawn.kindDef.race.defName.ToLower().Contains("drone")))
					pawn.GetCompRJW().orientation = Orientation.Asexual;
				else if (kinsey == 0)
					pawn.GetCompRJW().orientation = Orientation.Heterosexual;
				else if (kinsey == 1)
					pawn.GetCompRJW().orientation = Orientation.MostlyHeterosexual;
				else if (kinsey == 2)
					pawn.GetCompRJW().orientation = Orientation.LeaningHeterosexual;
				else if (kinsey == 3)
					pawn.GetCompRJW().orientation = Orientation.Bisexual;
				else if (kinsey == 4)
					pawn.GetCompRJW().orientation = Orientation.LeaningHomosexual;
				else if (kinsey == 5)
					pawn.GetCompRJW().orientation = Orientation.MostlyHomosexual;
				else if (kinsey == 6)
					pawn.GetCompRJW().orientation = Orientation.Homosexual;
				else
					pawn.GetCompRJW().orientation = Orientation.Asexual;
				/*else
					Log.Error("RJW::ERRROR - unknown kinsey scale value: " + kinsey);/*

				/*if (pawn.GetCompRJW().orientation != originalOrientation)
					Log.Message("RJW + Psychology: Inherited pawn " + xxx.get_pawnname(pawn) + " sexuality from Psychology - " + pawn.GetCompRJW().orientation);*/
			}
			catch
			{
				if (!pawn.IsAnimal())
					ModLog.Warning("CopyPsychologySexuality " + pawn?.Name + ", def: " + pawn?.def?.defName + ", kindDef: " + pawn?.kindDef?.race.defName);
			}
		}

		public static void CopyIndividualitySexuality(Pawn pawn)
		{
			try
			{
				CompIndividuality.Sexuality individualitySexuality = pawn.TryGetComp<CompIndividuality>().sexuality;
				//Orientation originalOrientation = pawn.GetCompRJW().orientation;

				if (individualitySexuality == CompIndividuality.Sexuality.Asexual)
					pawn.GetCompRJW().orientation = Orientation.Asexual;
				else if (!Genital_Helper.has_genitals(pawn) && (pawn.kindDef.race.defName.ToLower().Contains("droid") || pawn.kindDef.race.defName.ToLower().Contains("drone")))
					pawn.GetCompRJW().orientation = Orientation.Asexual;
				else if (individualitySexuality == CompIndividuality.Sexuality.Straight)
					pawn.GetCompRJW().orientation = Orientation.Heterosexual;
				else if (individualitySexuality == CompIndividuality.Sexuality.Bisexual)
					pawn.GetCompRJW().orientation = Orientation.Bisexual;
				else if (individualitySexuality == CompIndividuality.Sexuality.Gay)
					pawn.GetCompRJW().orientation = Orientation.Homosexual;
				else
					pawn.GetCompRJW().orientation = Orientation.Asexual;

				/*if (pawn.GetCompRJW().orientation != originalOrientation)
					Log.Message("RJW + [SYR]Individuality: Inherited pawn " + xxx.get_pawnname(pawn) + " sexuality from Individuality - " + pawn.GetCompRJW().orientation);*/
			}
			catch
			{
				if (!pawn.IsAnimal())
					ModLog.Warning("CopyIndividualitySexuality " + pawn?.Name + ", def: " + pawn?.def?.defName + ", kindDef: " + pawn?.kindDef?.race.defName);
			}
		}

		public static void VanillaTraitCheck(Pawn pawn)
		{
			//Orientation originalOrientation = pawn.GetCompRJW().orientation;
			if (pawn.story.traits.HasTrait(TraitDefOf.Asexual))
				pawn.GetCompRJW().orientation = Orientation.Asexual;
			else if (!Genital_Helper.has_genitals(pawn) && (pawn.kindDef.race.defName.ToLower().Contains("droid") || pawn.kindDef.race.defName.ToLower().Contains("drone")))
				pawn.GetCompRJW().orientation = Orientation.Asexual;
			else if (pawn.story.traits.HasTrait(TraitDefOf.Gay))
				pawn.GetCompRJW().orientation = Orientation.Homosexual;
			else if (pawn.story.traits.HasTrait(TraitDefOf.Bisexual))
				pawn.GetCompRJW().orientation = Orientation.Bisexual;
			else
				pawn.GetCompRJW().orientation = Orientation.Heterosexual;
		}

		// The main method for adding genitalia and orientation.
		public void Sexualize(Pawn pawn, bool reroll = false)
		{
			if (reroll)
			{
				pawn.GetCompRJW().orientation = Orientation.None;

				if (xxx.has_quirk(pawn, "Fertile"))
				{
					Hediff fertility = pawn.health.hediffSet.GetFirstHediffOfDef(HediffDef.Named("IncreasedFertility"));
					if (fertility != null)
						pawn.health.RemoveHediff(fertility);
				}
				if (xxx.has_quirk(pawn, "Infertile"))
				{
					Hediff fertility = pawn.health.hediffSet.GetFirstHediffOfDef(HediffDef.Named("DecreasedFertility"));
					if (fertility != null)
						pawn.health.RemoveHediff(fertility);
				}
				quirks = new StringBuilder();
			}
			else if (pawn.GetCompRJW().orientation != Orientation.None)
				return;

			//roll random RJW orientation
			pawn.GetCompRJW().orientation = xxx.is_animal(pawn) ? RollAnimalOrientation(pawn) : RollOrientation(pawn);

			//Asexual nymp re-roll
			//if (xxx.is_nympho(pawn))
			//	while (pawn.GetCompRJW().orientation == Orientation.Asexual)
			//	{
			//		pawn.GetCompRJW().orientation = RollOrientation();
			//	}

			//Log.Message("Sexualizing pawn " + pawn?.Name + ", def: " + pawn?.def?.defName);

			if (!reroll)
				Sexualizer.sexualize_pawn(pawn);
			//Log.Message("Orientation for pawn " + pawn?.Name + " is " + orientation);

			if (xxx.has_traits(pawn) && Genital_Helper.has_genitals(pawn) && !(pawn.kindDef.race.defName.ToLower().Contains("droid") && !AndroidsCompatibility.IsAndroid(pawn)))
			{
				if (RJWPreferenceSettings.sexuality_distribution == RJWPreferenceSettings.Rjw_sexuality.Vanilla)
					VanillaTraitCheck(pawn);
				if (RJWPreferenceSettings.sexuality_distribution == RJWPreferenceSettings.Rjw_sexuality.Psychology)
					CopyPsychologySexuality(pawn);
				if (RJWPreferenceSettings.sexuality_distribution == RJWPreferenceSettings.Rjw_sexuality.SYRIndividuality)
					CopyIndividualitySexuality(pawn);
			}
			else if (((pawn.kindDef.race.defName.ToLower().Contains("droid")) && !AndroidsCompatibility.IsAndroid(pawn)) || !Genital_Helper.has_genitals(pawn))
			{
				// Droids with no genitalia are set as asexual.
				// If player later adds genitalia to the droid, the droid 'sexuality' gets rerolled.
				pawn.GetCompRJW().orientation = Orientation.Asexual;
			}

			QuirkAdder.Generate(pawn);

			if (quirks.Length == 0)
			{
				quirks.Append("None");
				quirksave = quirks.ToString();
			}
		}

		/// <summary>
		/// check try vanilla traits/mods, check rjw genitals, futa check, some rng rolls
		/// </summary>
		/// <param name="pawn"></param>
		/// <param name="partner"></param>
		/// <returns></returns>
		public static bool CheckPreference(Pawn pawn, Pawn partner)
		{
			if (RJWPreferenceSettings.sexuality_distribution == RJWPreferenceSettings.Rjw_sexuality.Vanilla)
			{
				if (xxx.has_traits(pawn))
					VanillaTraitCheck(pawn);
				if (xxx.has_traits(partner))
					VanillaTraitCheck(partner);
			}
			if (RJWPreferenceSettings.sexuality_distribution == RJWPreferenceSettings.Rjw_sexuality.SYRIndividuality)
			{
				CopyIndividualitySexuality(pawn);
				CopyIndividualitySexuality(partner);
			}
			if (RJWPreferenceSettings.sexuality_distribution == RJWPreferenceSettings.Rjw_sexuality.Psychology)
			{
				if (RJWPreferenceSettings.sexuality_distribution == RJWPreferenceSettings.Rjw_sexuality.Psychology)
					CopyPsychologySexuality(pawn);
				CopyPsychologySexuality(partner);
			}

			//if (xxx.is_mechanoid(pawn))
			//	return false;

			if (pawn.GetCompRJW() is CompRJW rjwComp)
			{
				var ori = rjwComp.orientation;

				if (ori == Orientation.Pansexual || ori == Orientation.Bisexual)
					return true;

				if (ori == Orientation.Asexual)
					return false;

				var pawnSex = GenderHelper.GetSex(pawn);
				var partnerSex = GenderHelper.GetSex(partner);

				var isHetero = GenderHelper.CanBeHetero(pawnSex, partnerSex);
				var isHomo = GenderHelper.CanBeHomo(pawnSex, partnerSex);

				// Oh you crazy futas. fuck all cuz horny!
				if (isHetero && isHomo)
					return true;

				//RMB ui lag fixes in mp intead of [SyncMethod]
				if (MP.IsInMultiplayer)
					return RollOriMP(ori, isHetero, isHomo);
				else
					return RollOriSP(ori, isHetero, isHomo);
			}
			else
			{
				//ModLog.Message("Error, pawn:" + pawn + " doesn't have orientation comp, modded race?");
				return false;
			}
		}

		//no rng no lag
		public static bool RollOriMP(Orientation ori, bool isHetero, bool isHomo)
		{
			switch (ori)
			{
				case Orientation.Heterosexual:
					return !isHomo;
				case Orientation.MostlyHeterosexual:
					return (!isHomo);
				case Orientation.LeaningHeterosexual:
					return (!isHomo);
				case Orientation.LeaningHomosexual:
					return (!isHetero);
				case Orientation.MostlyHomosexual:
					return (!isHetero);
				case Orientation.Homosexual:
					return !isHetero;
				default:
					ModLog.Error("ERROR - tried to check preference for undetermined sexuality.");
					return false;
			}
		}

		//slight rng, but heavy ddos lag in MP with [SyncMethod]
		public static bool RollOriSP(Orientation ori, bool isHetero, bool isHomo)
		{
			switch (ori)
			{
				case Orientation.Heterosexual:
					return !isHomo;
				case Orientation.MostlyHeterosexual:
					return (!isHomo || Rand.Chance(0.2f));
				case Orientation.LeaningHeterosexual:
					return (!isHomo || Rand.Chance(0.6f));
				case Orientation.LeaningHomosexual:
					return (!isHetero || Rand.Chance(0.6f));
				case Orientation.MostlyHomosexual:
					return (!isHetero || Rand.Chance(0.2f));
				case Orientation.Homosexual:
					return !isHetero;
				default:
					ModLog.Error("ERROR - tried to check preference for undetermined sexuality.");
					return false;
			}
		}

		[SyncMethod]
		public Orientation RollOrientation(Pawn pawn)
		{
			//Rand.PopState();
			//Rand.PushState(RJW_Multiplayer.PredictableSeed());
			float random = Rand.Range(0f, 1f);
			float checkpoint = RJWPreferenceSettings.asexual_ratio / RJWPreferenceSettings.GetTotal();

			float checkpoint_pan = checkpoint + (RJWPreferenceSettings.pansexual_ratio / RJWPreferenceSettings.GetTotal());
			float checkpoint_het = checkpoint_pan + (RJWPreferenceSettings.heterosexual_ratio / RJWPreferenceSettings.GetTotal());
			float checkpoint_bi = checkpoint_het + (RJWPreferenceSettings.bisexual_ratio / RJWPreferenceSettings.GetTotal());
			float checkpoint_gay = checkpoint_bi + (RJWPreferenceSettings.homosexual_ratio / RJWPreferenceSettings.GetTotal());

			if (random < checkpoint || !Genital_Helper.has_genitals(pawn))
				return Orientation.Asexual;
			else if (random < checkpoint_pan)
				return Orientation.Pansexual;
			else if (random < checkpoint_het)
				return Orientation.Heterosexual;
			else if (random < checkpoint_het + ((checkpoint_bi - checkpoint_het) * 0.33f))
				return Orientation.MostlyHeterosexual;
			else if (random < checkpoint_het + ((checkpoint_bi - checkpoint_het) * 0.66f))
				return Orientation.LeaningHeterosexual;
			else if (random < checkpoint_bi)
				return Orientation.Bisexual;
			else if (random < checkpoint_bi + ((checkpoint_gay - checkpoint_bi) * 0.33f))
				return Orientation.LeaningHomosexual;
			else if (random < checkpoint_bi + ((checkpoint_gay - checkpoint_bi) * 0.66f))
				return Orientation.MostlyHomosexual;
			else
				return Orientation.Homosexual;
		}

		// Simpler system for animals, with most of them being heterosexual.
		// Don't want to disturb player breeding projects by adding too many gay animals.
		[SyncMethod]
		public Orientation RollAnimalOrientation(Pawn pawn)
		{
			//Rand.PopState();
			//Rand.PushState(RJW_Multiplayer.PredictableSeed());
			float random = Rand.Range(0f, 1f);

			if (random < 0.03f || !Genital_Helper.has_genitals(pawn))
				return Orientation.Asexual;
			else if (random < 0.85f)
				return Orientation.Heterosexual;
			else if (random < 0.96f)
				return Orientation.Bisexual;
			else
				return Orientation.Homosexual;
		}
	}
}


code:
using RimWorld;

namespace rjw
{
	public class CompRJWHatcher : CompHatcher
	{
	}
}

license: mit


code:
using RimWorld;

namespace rjw
{
	public class CompRJWProperties_Hatcher : CompProperties_Hatcher
	{
		public CompRJWProperties_Hatcher()
		{
			this.compClass = typeof(CompRJWHatcher);
		}
	}
}


code:
using System.Text;
using Verse;
using RimWorld;
using Multiplayer.API;
using System.Collections.Generic;
using rjw.Modules.Shared.Logs;
using System.Runtime.InteropServices;
using System.Linq;
using System;

namespace rjw
{
	/// <summary>
	/// Comp for things
	/// </summary>
	public class CompThingBodyPart : ThingComp
	{
		/// <summary>
		/// Comp for rjw Thing parts.
		/// </summary>

		public HediffDef_SexPart hediffDef;

		public float? depth;
		public float? maxGirth;
		public float? length;
		public float? girth;
		public float? volume;
		public float? size;				// for label and fallback if no other size is available

		public float originalOwnerSize;
		public string originalOwnerRace;      //race of 1st owner race
		public string previousOwner;          //erm

		public SexFluidDef fluid;
		public float fluidAmount;		// absolute amount of fluid, for display
		public float? partFluidMultiplier;	// multiplier on fluid amount, random to each part

		public bool initialised;

		public CompProperties_ThingBodyPart Props => (CompProperties_ThingBodyPart)props;

		/// <summary>
		/// Thing/part size in label
		/// </summary>

		private string _label = "";
		public override string TransformLabel(string label)
		{
			if (!initialised)
				Init();

			if (_label.NullOrEmpty())
			{
				var humanSize = CalculateSize(1.0f);
				_label = $"{label} ({hediffDef.GetStandardSizeLabel(humanSize)})";
			}

			return _label;
		}

		public override string CompInspectStringExtra()
		{
			return InspectStringLines().ToLineList();
		}

		private IEnumerable<string> InspectStringLines()
		{
			if (length.HasValue)
			{
				yield return "RJW_PartInfo_length".Translate(length.Value.ToString("F1"));
			}
			if (girth.HasValue)
			{
				yield return "RJW_PartInfo_girth".Translate(girth.Value.ToString("F1"));
			}
			if (depth.HasValue && hediffDef.genitalFamily != GenitalFamily.FemaleOvipositor)
			{
				yield return "RJW_PartInfo_depth".Translate(depth.Value.ToString("F1"));
			}
			if (maxGirth.HasValue && hediffDef.genitalFamily != GenitalFamily.FemaleOvipositor)
			{
				yield return "RJW_PartInfo_maxGirth".Translate(maxGirth.Value.ToString("F1"));
			}

			if (volume.HasValue)
			{
				if (PartSizeCalculator.Inversion.TryInvertBreastVolume(hediffDef, volume.Value, 1.0f, out float _, out BreastSize breastSize))
				{
					yield return "RJW_PartInfo_braCup".Translate(breastSize.GetCupSize());
					yield return "RJW_PartInfo_weight".Translate(breastSize.weight.ToString("F3"));
				}
			}

			if (fluid != null)
			{
				yield return "RJW_PartInfo_fluidTypeFluidAmountHeading".Translate(fluid.label, fluidAmount.ToString("F0")).CapitalizeFirst();
			}
		}

		public override void PostExposeData()
		{
			base.PostExposeData();
			Scribe_Defs.Look(ref hediffDef, "hediffDef");
			Scribe_Defs.Look(ref fluid, "fluid");
			Scribe_Values.Look(ref size, "size");
			Scribe_Values.Look(ref originalOwnerSize, "originalOwnerSize");
			Scribe_Values.Look(ref originalOwnerRace, "originalOwnerRace");
			Scribe_Values.Look(ref previousOwner, "previousOwner");
			Scribe_Values.Look(ref fluidAmount, "fluidAmount");
			Scribe_Values.Look(ref partFluidMultiplier, "partFluidMultiplier");
			Scribe_Values.Look(ref initialised, "initialised", defaultValue: true);
			Scribe_Values.Look(ref length, "length");
			Scribe_Values.Look(ref depth, "depth");
			Scribe_Values.Look(ref maxGirth, "maxGirth");
			Scribe_Values.Look(ref girth, "girth");
			Scribe_Values.Look(ref volume, "volume");
		}

		public override IEnumerable<StatDrawEntry> SpecialDisplayStats()
		{
			// Absolutely terrible idea, but this check was originally in the description override as some kind of failsafe,
			// so sticking it here for now so as not to break things
			// TODO: Ensure this can be removed
			if (!initialised)
			{
				Init();
			}

			// Chosen semi-arbitrarily. Change these if stat ordering seems janky.
			int statOrder = StatDisplayOrder.Thing_BodyPartEfficiency + 10;
			var implantCategory = StatCategoryDefOf.Implant;
			var ownerCategory = RJWStatCategoryDefOf.OriginalPartOwner;

			//yield return new StatDrawEntry(category, "RJW_StatEntry_PartSize".Translate(), size.ToString("F2"), "", statOrder++);

			if (fluid != null)
			{
				yield return new StatDrawEntry(implantCategory, "RJW_StatEntry_Fluid".Translate(), fluid.LabelCap, "", statOrder++);
			}

			if (fluidAmount != 0)
			{
				string fluidAmountKey = hediffDef.genitalFamily switch
				{
					GenitalFamily.Penis or GenitalFamily.MaleOvipositor => "RJW_StatEntry_FluidAmount_ejaculation",
					GenitalFamily.Vagina or GenitalFamily.Anus => "RJW_StatEntry_FluidAmount_wetness",
					_ => "RJW_StatEntry_FluidAmount"
				};

				yield return new StatDrawEntry(implantCategory, fluidAmountKey.Translate(), fluidAmount.ToString("F2"), "", statOrder++);
			}

			if (length.HasValue)
			{
				yield return new StatDrawEntry(implantCategory, "RJW_StatEntry_PartLength".Translate(), length.Value.ToString("F2"), "", statOrder++);
			}

			if (girth.HasValue)
			{
				yield return new StatDrawEntry(implantCategory, "RJW_StatEntry_PartGirth".Translate(), girth.Value.ToString("F2"), "", statOrder++);
			}

			if (depth.HasValue)
			{
				yield return new StatDrawEntry(implantCategory, "RJW_StatEntry_PartDepth".Translate(), depth.Value.ToString("F2"), "", statOrder++);
			}

			if (maxGirth.HasValue)
			{
				yield return new StatDrawEntry(implantCategory, "RJW_StatEntry_PartMaxGirth".Translate(), maxGirth.Value.ToString("F2"), "", statOrder++);
			}

			if (volume.HasValue)
			{
				if (PartSizeCalculator.Inversion.TryInvertBreastVolume(hediffDef, volume.Value, 1.0f, out float _, out BreastSize breastSize))
				{
					yield return new StatDrawEntry(implantCategory, "RJW_StatEntry_PartCupSize".Translate(), breastSize.GetCupSize(), "", statOrder++);
					yield return new StatDrawEntry(implantCategory, "RJW_StatEntry_PartWeight".Translate(), breastSize.weight.ToString("F3"), "", statOrder++);
				}
			}

			if (!hediffDef.partTags.NullOrEmpty())
			{
				var tags = hediffDef.partTags;
				yield return new StatDrawEntry(implantCategory, "RJW_StatEntry_PartTags".Translate(), tags.ToCommaList(), "", statOrder++);
			}

			// Ownership info
			if (!previousOwner.NullOrEmpty())
			{
				yield return new StatDrawEntry(ownerCategory, "RJW_StatEntry_PreviousOwner".Translate(), previousOwner, "", 1);
			}
			if (!originalOwnerRace.NullOrEmpty())
			{
				yield return new StatDrawEntry(ownerCategory, "RJW_StatEntry_OriginalOwnerRace".Translate(), originalOwnerRace, "", 2);
			}
			if (originalOwnerSize > 0f)
			{
				yield return new StatDrawEntry(ownerCategory, "RJW_StatEntry_OriginalOwnerSize".Translate(), originalOwnerSize.ToString("F1"), "", 3);
			}
		}

		public override void PostPostMake()
		{
			base.PostPostMake();
			Init();
		}

		/// <summary>
		/// fill comp data
		/// </summary>
		[SyncMethod]
		private void Init(Pawn pawn = null)
		{
			// TODO: Maybe un-link this from ThingDef xml and instead set randomly or inherit from removed part
			hediffDef = Props.hediffDef;

			bool originalOwnerIsKnown = true;

			if (pawn == null)
			{
				InitFromDef(hediffDef);
				initialised = true;
			}
			else
			{
				Hediff hd = HediffMaker.MakeHediff(hediffDef, pawn);

				HediffComp_SexPart hediffComp = hd.TryGetComp<HediffComp_SexPart>();
				if (hediffComp != null)
				{
					InitFromComp(hediffComp, originalOwnerIsKnown);
				}
			}
		}

		public bool HasSize() {
			return length.HasValue || girth.HasValue || depth.HasValue || maxGirth.HasValue || volume.HasValue || size.HasValue;
		}

		public float CalculateSize(float newBodySize)
		{
			// try invert our measurments to get an appropriate severity for the new body size
			if(length.HasValue)
			{
				if(PartSizeCalculator.Inversion.TryInvertLength(hediffDef, length.Value, newBodySize, out float newSize))
				{
					return newSize;
				}
			}
			if(girth.HasValue)
			{
				if(PartSizeCalculator.Inversion.TryInvertGirth(hediffDef, girth.Value, newBodySize, out float newSize))
				{
					return newSize;
				}
			}
			if(depth.HasValue)
			{
				if(PartSizeCalculator.Inversion.TryInvertLength(hediffDef, depth.Value, newBodySize, out float newSize))
				{
					return newSize;
				}
			}
			if(maxGirth.HasValue)
			{
				if(PartSizeCalculator.Inversion.TryInvertGirth(hediffDef, maxGirth.Value, newBodySize, out float newSize))
				{
					return newSize;
				}
			}
			if(volume.HasValue)
			{
				if(PartSizeCalculator.Inversion.TryInvertBreastVolume(hediffDef, volume.Value, newBodySize, out float newSize, out BreastSize _))
				{
					return newSize;
				}
			}

			if(size.HasValue)
			{
				// fallback to size if nothing else is available
				return size.Value;
			}

			// really got nothing, random size
			return hediffDef.GetRandomSize();
		}

		public void InitFromComp(HediffComp_SexPart hediffComp, bool recordOriginalOwner = true)
		{
			hediffDef = hediffComp.Def;
			fluid = hediffComp.Fluid;
			fluidAmount = hediffComp.FluidAmount;
			partFluidMultiplier = hediffComp.partFluidMultiplier;
			size = hediffComp.GetSeverity();

			if (!hediffDef.genitalTags.NullOrEmpty())
			{
				if (hediffDef.genitalTags.Contains(GenitalTag.CanPenetrate))
				{
					if (PartSizeCalculator.TryGetLength(hediffComp.parent, out float length))
					{
						this.length = length;
					}
					if (PartSizeCalculator.TryGetGirth(hediffComp.parent, out float girth))
					{
						this.girth = girth;
					}
				}
				if (hediffDef.genitalTags.Contains(GenitalTag.CanBePenetrated))
				{
					if (PartSizeCalculator.TryGetLength(hediffComp.parent, out float depth))
					{
						this.depth = depth;
					}
					if (PartSizeCalculator.TryGetGirth(hediffComp.parent, out float maxGirth))
					{
						this.maxGirth = maxGirth;
					}
				}
			}
			if (PartSizeCalculator.TryGetBreastSize(hediffComp.parent, out BreastSize breastSize))
			{
				this.volume = breastSize.volume;
			}

			if (recordOriginalOwner)
			{
				originalOwnerSize = hediffComp.originalOwnerSize;
				previousOwner = hediffComp.Pawn?.LabelNoCount;
				if (hediffComp.Pawn.IsHuman() || hediffComp.Pawn.Name != null)
				{
					originalOwnerRace = hediffComp.Pawn?.kindDef.race.LabelCap;
				}
			}
			initialised = true;

		}

		[SyncMethod]
		private void InitFromDef(HediffDef_SexPart hediffDef)
		{
			this.hediffDef = hediffDef;
			var size = hediffDef.GetRandomSize();
			var bodySize = 1.0f;

			fluid = hediffDef.fluid;
			partFluidMultiplier = hediffDef.GetRandomPartFluidMultiplier();
			var totalFluidMultiplier = hediffDef.GetFluidMultiplier(size, partFluidMultiplier.Value, bodySize);
			fluidAmount = hediffDef.GetFluidAmount(totalFluidMultiplier);

			if (!hediffDef.genitalTags.NullOrEmpty())
			{
				if (hediffDef.genitalTags.Contains(GenitalTag.CanPenetrate))
				{
					if (PartSizeCalculator.Internal.TryGetLength(hediffDef, size, bodySize, out float length))
					{
						this.length = length;
					}
					if (PartSizeCalculator.Internal.TryGetGirth(hediffDef, size, bodySize, out float girth))
					{
						this.girth = girth;
					}
				}
				if (hediffDef.genitalTags.Contains(GenitalTag.CanBePenetrated))
				{
					if (PartSizeCalculator.Internal.TryGetLength(hediffDef, size, bodySize, out float depth))
					{
						this.depth = depth;
					}
					if (PartSizeCalculator.Internal.TryGetGirth(hediffDef, size, bodySize, out float maxGirth))
					{
						this.maxGirth = maxGirth;
					}
				}
			}
			if (PartSizeCalculator.Internal.TryGetBreastSize(hediffDef, size, bodySize, out BreastSize breastSize))
			{
				this.volume = breastSize.volume;
			}

			this.size = size;
		}
	}
}


code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace rjw
{
	public enum Orientation
	{
		None,
		Asexual,
		Pansexual,
		Heterosexual,
		MostlyHeterosexual,
		LeaningHeterosexual,
		Bisexual,
		LeaningHomosexual,
		MostlyHomosexual,
		Homosexual
	}
}


code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Verse;
using Verse.AI;
using RimWorld;

namespace rjw
{
	public class Quirk
	{
		public static List<Quirk> All = new List<Quirk>();

		public static readonly Quirk Breeder = new Quirk(
			"Breeder",
			"BreederQuirk");
		public static readonly Quirk Endytophile = new Quirk(
			"Endytophile",
			"EndytophileQuirk",
			(pawn, partner) => !partner.apparel.PsychologicallyNude,
			sexProps => !sexProps.pawn.apparel.PsychologicallyNude
			);
		public static readonly Quirk Exhibitionist = new Quirk(
			"Exhibitionist",
			"ExhibitionistQuirk",
			null,
			SatisfiesExhibitionist
			);
		public static readonly Quirk Fertile = new Quirk(
			"Fertile",
			"FertileQuirk");
		public static readonly Quirk Gerontophile = new Quirk(
			"Gerontophile",
			"GerontophileQuirk",
			(pawn, partner) => SexUtility.ScaleToHumanAge(partner) > 55,
			sexProps => sexProps.hasPartner() && SexUtility.ScaleToHumanAge(sexProps.partner) > 55
			);
		public static readonly Quirk ImpregnationFetish = new Quirk(
			"Impregnation fetish",
			"ImpregnationFetishQuirk",
			(pawn, partner) =>
				PregnancyHelper.CanImpregnate(pawn, partner)
				|| PregnancyHelper.CanImpregnate(partner, pawn),
			sexProps =>
				sexProps.hasPartner()
				&& (PregnancyHelper.CanImpregnate(sexProps.pawn, sexProps.partner, sexProps.sexType)
					|| PregnancyHelper.CanImpregnate(sexProps.partner, sexProps.pawn, sexProps.sexType))
			);
		public static readonly Quirk Incubator = new Quirk(
			"Incubator",
			"IncubatorQuirk");
		public static readonly Quirk Infertile = new Quirk(
			"Infertile",
			"InfertileQuirk");
		public static readonly Quirk Messy = new Quirk(
			"Messy",
			"MessyQuirk");
		public static readonly Quirk Podophile = new Quirk(
			"Podophile",
			"PodophileQuirk",
			null,
			sexProps => sexProps.hasPartner() && sexProps.sexType == xxx.rjwSextype.Footjob && sexProps.IsSubmissive()
			);
		public static readonly Quirk Cumslut = new Quirk(
			"Cumslut",
			"CumslutQuirk",
			null,
			sexProps => sexProps.hasPartner() && sexProps.sexType == xxx.rjwSextype.Fellatio && sexProps.IsSubmissive()
			);
		public static readonly Quirk Buttslut = new Quirk(
			"Buttslut",
			"ButtslutQuirk",
			null,
			sexProps => sexProps.hasPartner() && sexProps.sexType == xxx.rjwSextype.Anal && sexProps.IsSubmissive()
			);
		public static readonly Quirk PregnancyFetish = new Quirk(
			"Pregnancy fetish",
			"PregnancyFetishQuirk",
			(pawn, partner) => partner.IsVisiblyPregnant(),
			sexProps => sexProps.hasPartner() && sexProps.partner.IsVisiblyPregnant()
			);
		public static readonly Quirk Sapiosexual = new Quirk(
			"Sapiosexual",
			"SapiosexualQuirk",
			(pawn, partner) => SatisfiesSapiosexual(partner),
			null
			);
		public static readonly Quirk Somnophile = new Quirk(
			"Somnophile",
			"SomnophileQuirk",
			(pawn, partner) => !partner.Awake(),
			sexProps => sexProps.hasPartner() && !sexProps.partner.Awake()
			);
		public static readonly Quirk Teratophile = new Quirk(
			"Teratophile",
			"TeratophileQuirk",
			(pawn, partner) => SatisfiesTeratophile(partner),
			null
			);
		public static readonly Quirk Vigorous = new Quirk(
			"Vigorous",
			"VigorousQuirk");

		// There might be too many of these I dunno.
		// People have expressed "special interest" in some of them so I thought
		// it would be cool to have them in the game but since people are weird you end up with a lot of fetishes.
		public static readonly Quirk ChitinLover = MakeTagBasedQuirk("Chitin lover", "ChitinLoverQuirk", RaceTag.Chitin);
		public static readonly Quirk DemonLover = MakeTagBasedQuirk("Demon lover", "DemonLoverQuirk", RaceTag.Demon);
		public static readonly Quirk FeatherLover = MakeTagBasedQuirk("Feather lover", "FeatherLoverQuirk", RaceTag.Feathers);
		public static readonly Quirk FurLover = MakeTagBasedQuirk("Fur lover", "FurLoverQuirk", RaceTag.Fur);
		public static readonly Quirk PlantLover = MakeTagBasedQuirk("Plant lover", "PlantLoverQuirk", RaceTag.Plant);
		public static readonly Quirk RobotLover = MakeTagBasedQuirk("Robot lover", "RobotLoverQuirk", RaceTag.Robot);
		public static readonly Quirk ScaleLover = MakeTagBasedQuirk("Scale lover", "ScaleLoverQuirk", RaceTag.Scales);
		public static readonly Quirk SkinLover = MakeTagBasedQuirk("Skin lover", "SkinLoverQuirk", RaceTag.Skin);
		public static readonly Quirk SlimeLover = MakeTagBasedQuirk("Slime lover", "SlimeLoverQuirk", RaceTag.Slime);

		public string Key { get; }
		public string LocaliztionKey { get; }
		// Hack, quirk generation logic should be in the quirk not based on flags on the quirk.
		public RaceTag RaceTag { get; }
		readonly Func<Pawn, Pawn, bool> PawnSatisfiesFunc;
		readonly Func<SexProps, bool> SexSatisfiesFunc;
		readonly Action<Pawn> AfterAddFunc;

		public static Quirk MakeTagBasedQuirk(string key, string localizationKey, RaceTag tag)
		{
			return new Quirk(
				key,
				localizationKey,
				(pawn, partner) => partner.Has(tag),
				sexProps => sexProps.hasPartner() && sexProps.partner.Has(tag),
				null,
				tag);
		}

		public Quirk(
			string key,
			string localizationKey,
			Func<Pawn, Pawn, bool> pawnSatisfies = null,
			Func<SexProps, bool> sexSatisfies = null,
			Action<Pawn> afterAdd = null,
			RaceTag raceTag = null)
		{
			Key = key;
			LocaliztionKey = localizationKey;
			PawnSatisfiesFunc = pawnSatisfies;
			SexSatisfiesFunc = sexSatisfies;
			AfterAddFunc = afterAdd;
			RaceTag = raceTag;
			All.Add(this);
		}

		public bool IsSatisfiedBy(Pawn pawn, Pawn partner)
		{
			return pawn != null
				&& partner != null
				&& pawn.Has(this)
				&& PawnSatisfiesFunc != null
				&& PawnSatisfiesFunc(pawn, partner);
		}

		public static int CountSatisfiedQuirks(SexProps props)
		{
			Pawn pawn = props.pawn;
			Pawn partner = props.partner;
			var satisfies = All.Where(quirk =>
				quirk.SexSatisfiesFunc != null
				&& pawn.Has(quirk)
				&& quirk.SexSatisfiesFunc(props));
			return satisfies.Count();
		}

		public void DoAfterAdd(Pawn pawn)
		{
			AfterAddFunc?.Invoke(pawn);
		}

		public static bool SatisfiesExhibitionist(SexProps sexProps)
		{
			var zoo = xxx.is_zoophile(sexProps.pawn);
			return sexProps.pawn.Map.mapPawns.AllPawnsSpawned.Any(x =>
				x != sexProps.pawn
				&& x != sexProps.partner
				&& !x.Dead
				&& (zoo || !xxx.is_animal(x))
				&& x.CanSee(sexProps.pawn));
		}

		public static bool SatisfiesSapiosexual(Pawn partner)
		{
			if (!xxx.has_traits(partner)) return false;
			return partner.story.traits.HasTrait(VanillaTraitDefOf.TooSmart)
				|| (xxx.CTIsActive && partner.story.traits.HasTrait(xxx.RCT_Savant))
				|| (xxx.IndividualityIsActive && partner.story.traits.HasTrait(xxx.SYR_CreativeThinker))
				|| (xxx.CTIsActive && partner.story.traits.HasTrait(xxx.RCT_Inventor))
				|| partner.story.traits.HasTrait(TraitDefOf.GreatMemory)
				|| partner.story.traits.HasTrait(TraitDefOf.Transhumanist)
				|| partner.skills.GetSkill(SkillDefOf.Intellectual).levelInt >= 15;
		}

		public static bool SatisfiesTeratophile(Pawn partner)
		{
			if (partner.story == null) return false;
			var story = partner.story;
			return RelationsUtility.IsDisfigured(partner)
				|| story.bodyType == BodyTypeDefOf.Fat
				|| story.traits.HasTrait(TraitDefOf.CreepyBreathing)
				|| (story.traits.HasTrait(VanillaTraitDefOf.Beauty) && story.traits.DegreeOfTrait(VanillaTraitDefOf.Beauty) < 0)
				|| partner.GetStatValue(StatDefOf.PawnBeauty) < 0;
		}

		public static void AddThought(Pawn pawn)
		{
			var thoughtDef = DefDatabase<ThoughtDef>.GetNamed("ThatsMyFetish");
			pawn.needs.mood.thoughts.memories.TryGainMemory(thoughtDef);
		}
	}
}


code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Verse;
using Verse.AI;
using RimWorld;
using Multiplayer.API;

namespace rjw
{
	public static class QuirkAdder
	{
		public static void Add(Pawn pawn, Quirk quirk, bool warnOnFail = false)
		{
			if (!pawn.Has(quirk))
			{
				var hasFertility = pawn.RaceHasFertility();
				if (quirk == Quirk.Fertile && (!hasFertility || pawn.GetCompRJW().quirks.ToString().Contains(Quirk.Infertile.Key)))
				{
					if (warnOnFail)
					{
						ModLog.Warning($"Tried to add quirk {quirk} to {pawn.Name}, but either {pawn.def} does not have fertility or {pawn.Name} has a conflicting quirk");
					}
					return;
				}
				if (quirk == Quirk.Infertile && (!hasFertility || pawn.GetCompRJW().quirks.ToString().Contains(Quirk.Fertile.Key)))
				{
					if (warnOnFail)
					{
						ModLog.Warning($"Tried to add quirk {quirk} to {pawn.Name}, but either {pawn.def} does not have fertility or {pawn.Name} has a conflicting quirk");
					}
					return;
				}
				// No fair having a fetish for your own race.
				// But tags don't conflict so having a fetish for robot plant dragons is fine.
				if (quirk.RaceTag != null && pawn.Has(quirk.RaceTag))
				{
					if (warnOnFail)
					{
						ModLog.Warning($"Tried to add quirk {quirk} to {pawn.Name}, but {pawn} already has the associated race tag {quirk.RaceTag}");
					}
					return;
				}
				if (quirk == Quirk.Fertile)
				{
					var fertility = HediffDef.Named("IncreasedFertility");
					if (fertility != null)
						pawn.health.AddHediff(fertility);
				}
				if (quirk == Quirk.Infertile)
				{
					var infertility = HediffDef.Named("DecreasedFertility");
					if (infertility != null)
						pawn.health.AddHediff(infertility);
				}
				if ((quirk == Quirk.Buttslut && !RJWPreferenceSettings.PlayerIsButtSlut)
					|| (quirk == Quirk.Podophile && !RJWPreferenceSettings.PlayerIsFootSlut)
					|| (quirk == Quirk.Cumslut && !RJWPreferenceSettings.PlayerIsCumSlut))
				{
					if (warnOnFail)
					{
						ModLog.Warning($"Tried to add quirk {quirk} to {pawn.Name}, but all relevant sex types are pseudo-disabled (i.e. given minimum weight in settings)");
					}
					return;
				}

				pawn.GetCompRJW().quirks.AppendWithComma(quirk.Key);
				pawn.GetCompRJW().quirksave = pawn.GetCompRJW().quirks.ToString();
				quirk.DoAfterAdd(pawn);
			}
		}
		public static void Remove(Pawn pawn, Quirk quirk)
		{
			if (pawn.Has(quirk))
			{
				if (quirk == Quirk.Fertile)
				{
					var fertility = HediffDef.Named("IncreasedFertility");
					if (fertility != null)
						pawn.health.RemoveHediff(pawn.health.hediffSet.GetFirstHediffOfDef(fertility));
				}
				if (quirk == Quirk.Infertile)
				{
					var infertility = HediffDef.Named("DecreasedFertility");
					if (infertility != null)
						pawn.health.RemoveHediff(pawn.health.hediffSet.GetFirstHediffOfDef(infertility));
				}

				//pawn.GetCompRJW().quirks.AppendWithComma(quirk.Key);
				pawn.GetCompRJW().quirks.Replace(quirk.Key, null);

				if (pawn.GetCompRJW().quirks.Length == 0)
					pawn.GetCompRJW().quirks.Append("None");

				pawn.GetCompRJW().quirksave = pawn.GetCompRJW().quirks.ToString();
			}
		}

		public static void Clear(Pawn pawn)
		{
			Hediff fertility = pawn.health.hediffSet.GetFirstHediffOfDef(HediffDef.Named("IncreasedFertility"));
			if (fertility != null)
				pawn.health.RemoveHediff(fertility);
			Hediff infertility = pawn.health.hediffSet.GetFirstHediffOfDef(HediffDef.Named("DecreasedFertility"));
			if (infertility != null)
				pawn.health.RemoveHediff(infertility);

			pawn.GetCompRJW().quirks = new StringBuilder();

			if (pawn.GetCompRJW().quirks.Length == 0)
				pawn.GetCompRJW().quirks.Append("None");

			pawn.GetCompRJW().quirksave = pawn.GetCompRJW().quirks.ToString();
		}

		public static void Generate(Pawn pawn)
		{
			if (!pawn.RaceHasSexNeed() || (pawn.kindDef.race.defName.ToLower().Contains("droid") && !AndroidsCompatibility.IsAndroid(pawn)))
			{
				return;
			}
			else if (pawn.IsAnimal())
			{
				GenerateForAnimal(pawn);
			}
			else
			{
				GenerateForHumanlike(pawn);
			}
		}

		[SyncMethod]
		static void GenerateForHumanlike(Pawn pawn)
		{
			var count = Rand.RangeInclusive(0, RJWPreferenceSettings.MaxQuirks);
			var list = Quirk.All.ToList();
			list.Shuffle();

			// Some quirks may be hard for a given pawn to indulge in.
			// For example a female homosexual will have a hard time satisfying an impregnation fetish.
			// But rimworld is a weird place and you never know what the pawn will be capable of in the future.
			// We still don't want straight up contradictory results like fertile + infertile.
			var hasFertility = pawn.RaceHasFertility();
			var actual = new List<Quirk>();
			foreach (var quirk in list)
			{
				if (count == 0)
				{
					break;
				}

				// These special cases are sort of hacked in.
				// In theory there should be a general way for the quirk itself to decide when it applies.
				if (quirk == Quirk.Fertile && (!hasFertility || actual.Contains(Quirk.Infertile)))
				{
					continue;
				}
				if (quirk == Quirk.Infertile && (!hasFertility || actual.Contains(Quirk.Fertile)))
				{
					continue;
				}
				// Have to earn these.
				if (quirk == Quirk.Breeder || quirk == Quirk.Incubator)
				{
					continue;
				}
				// No fair having a fetish for your own race.
				// But tags don't conflict so having a fetish for robot plant dragons is fine.
				if (quirk.RaceTag != null && pawn.Has(quirk.RaceTag))
				{
					continue;
				}

				count--;
				actual.Add(quirk);
			}

			foreach (var quirk in actual)
			{
				pawn.Add(quirk);
			}
		}

		[SyncMethod]
		static void GenerateForAnimal(Pawn pawn)
		{
			if (Rand.Chance(0.1f))
			{
				pawn.Add(Quirk.Messy);
			}

			if (!pawn.RaceHasFertility())
			{
				return;
			}

			if (Rand.Chance(0.1f))
			{
				pawn.Add(Quirk.Fertile);
			}
			else if (Rand.Chance(0.1f))
			{
				pawn.Add(Quirk.Infertile);
			}
		}
	}
}


code:
using Verse;
using RimWorld;
using Verse.AI;

namespace rjw
{
	/// <summary>
	/// data for sex related stuff/outcome
	/// </summary>
	public class SexProps : IExposable
	{
		public Pawn pawn;
		public Pawn partner;
		public bool hasPartner() => partner != null && partner != pawn;

		public xxx.rjwSextype sexType = xxx.rjwSextype.None;
		public InteractionDef dictionaryKey = null;
		public string rulePack = null;

		public bool usedCondom = false;
		public bool isRape = false;
		public bool isReceiver = false;// as JobDriver_SexBaseReciever
		public bool isRevese = false;// brainfuck with who fucks who, see impregnation for clarity with tags n shit?.     interaction.HasInteractionTag(InteractionTag.Reverse)
		public bool isRapist = false;
		public bool isCoreLovin = false;//vanilla loving, skip some mechanics.  should really clean this up someday
		public bool isWhoring = false;
		public bool canBeGuilty = true;// can initiator pawn be counted guilty for percepts, player initiated/rmb actrions = false

		public int orgasms = 0; // The orgasms had by the pawn
		public SexProps()
		{
		}

		public bool IsInitiator() => !isReceiver;

		public bool IsSubmissive() => (isReceiver && !isRevese) || (!isReceiver && isRevese);

		public SexProps GetForPartner()
		{
			return new SexProps
			{
				pawn = partner,
				partner = pawn,
				sexType = sexType,
				dictionaryKey = dictionaryKey,
				rulePack = rulePack,
				usedCondom = usedCondom,
				isRape = isRape,
				isReceiver = !isReceiver,
				isRevese = isRevese,
				isRapist = isRapist,
				isCoreLovin = isCoreLovin,
				isWhoring = isWhoring,
				canBeGuilty = canBeGuilty,
				orgasms = orgasms
			};
		}

		public void ExposeData()
		{
			Scribe_References.Look(ref pawn, "pawn");
			Scribe_References.Look(ref partner, "partner");

			Scribe_Values.Look(ref sexType, "sexType");
			Scribe_Defs.Look(ref dictionaryKey, "dictionaryKey");
			Scribe_Values.Look(ref rulePack, "rulePack");

			Scribe_Values.Look(ref usedCondom, "usedCondom");
			Scribe_Values.Look(ref isRape, "isRape");
			Scribe_Values.Look(ref isReceiver, "isReceiver");
			Scribe_Values.Look(ref isRapist, "isRapist");
			Scribe_Values.Look(ref isCoreLovin, "isCoreLovin");
			Scribe_Values.Look(ref isWhoring, "isWhoring");
			Scribe_Values.Look(ref canBeGuilty, "canBeGuilty");
			Scribe_Values.Look(ref orgasms, "orgasms");
		}
	}
}


code:
using RimWorld;

namespace rjw
{
    [DefOf]
    public static class IssueDefOf
    {
		public static IssueDef Lovin;

        static IssueDefOf()
        {
            DefOfHelper.EnsureInitializedInCtor(typeof(IssueDefOf));
        }
    }
}


code:
using RimWorld;

namespace rjw
{
    [DefOf]
    public static class PreceptDefOf
    {
		[MayRequireIdeology]
		public static PreceptDef Lovin_Prohibited;

		[MayRequireIdeology]
		public static PreceptDef Lovin_Horrible;

		[MayRequireIdeology]
		public static PreceptDef Lovin_SpouseOnly_Strict;

		[MayRequireIdeology]
		public static PreceptDef Lovin_SpouseOnly_Moderate;

		[MayRequireIdeology]
		public static PreceptDef Lovin_SpouseOnly_Mild;

		public static PreceptDef Lovin_Free;

		[MayRequireIdeology]
		public static PreceptDef Lovin_FreeApproved;

        static PreceptDefOf()
        {
            DefOfHelper.EnsureInitializedInCtor(typeof(IssueDefOf));
        }
    }
}


code:
using RimWorld;
using Verse;

namespace rjw
{
	[DefOf]
	public static class RJWBodyPartDefOf
	{
		public static BodyPartDef Foot;
		public static BodyPartDef Paw;
		public static BodyPartDef Leg;
		public static BodyPartDef AnimalJaw;
		public static BodyPartDef Tail;
	}
}


code:
using Verse;
using RimWorld;

namespace rjw
{
    [DefOf]
    public static class RJWHediffDefOf
    {
        public static HediffDef HumpShroomAddiction;

        public static HediffDef HumpShroomEffect;
    }
}


code:
using Verse;
using RimWorld;

namespace rjw
{
	[DefOf]
	public static class RJWStatCategoryDefOf
	{
		[DefAlias("RJW_OriginalPartOwner")]
		public static StatCategoryDef OriginalPartOwner;

		static RJWStatCategoryDefOf()
		{
			DefOfHelper.EnsureInitializedInCtor(typeof(RJWStatCategoryDefOf));
		}
	}
}


code:
using Verse;
using RimWorld;
using Verse.AI;

namespace rjw
{
	[DefOf]
	public static class VanillaDutyDefOf
	{
		public static DutyDef EnterTransporter;

		static VanillaDutyDefOf()
		{
			DefOfHelper.EnsureInitializedInCtor(typeof(VanillaDutyDefOf));
		}
	}
}


code:
using Verse;
using RimWorld;

namespace rjw
{
	[DefOf]
	public static class VanillaRoomRoleDefOf
	{
		public static RoomRoleDef Laboratory;

		public static RoomRoleDef DiningRoom;

		public static RoomRoleDef RecRoom;

		static VanillaRoomRoleDefOf()
		{
			DefOfHelper.EnsureInitializedInCtor(typeof(VanillaRoomRoleDefOf));
		}
	}

}


code:
using Verse;
using RimWorld;

namespace rjw
{
	[DefOf]
	public static class VanillaThoughtDefOf
	{
		public static ThoughtDef AteHumanlikeMeatAsIngredient;

		static VanillaThoughtDefOf()
		{
			DefOfHelper.EnsureInitializedInCtor(typeof(VanillaThoughtDefOf));
		}
	}
}


code:
using Verse;
using RimWorld;

namespace rjw
{
	[DefOf]
	public static class VanillaTraitDefOf
	{
		public static TraitDef Tough;

		public static TraitDef Nerves;

		public static TraitDef Beauty;

		public static TraitDef TooSmart;

		public static TraitDef NaturalMood;

		public static TraitDef Cannibal;

		static VanillaTraitDefOf()
		{
			DefOfHelper.EnsureInitializedInCtor(typeof(VanillaTraitDefOf));
		}
	}
}


code:
using Verse;
using RimWorld;
using Multiplayer.API;

namespace rjw
{
	public static class PawnDesignations_Breedee
	{
		public static bool UpdateCanDesignateBreeding(this Pawn pawn)
		{
			//no permission to change designation for NON prisoner hero/ other player
			if (!pawn.CanChangeDesignationPrisoner() && !pawn.CanChangeDesignationColonist())
				return pawn.GetRJWPawnData().CanDesignateBreeding = false;

			//no permission to change designation for prisoner hero/ self
			if (!pawn.CanChangeDesignationPrisoner())
				return pawn.GetRJWPawnData().CanDesignateBreeding = false;

			//cant have penetrative sex
			if (!xxx.can_be_fucked(pawn))
				return pawn.GetRJWPawnData().CanDesignateBreeding = false;

			if (RJWSettings.bestiality_enabled && xxx.is_human(pawn))
			{
				if (!pawn.IsDesignatedHero())
				{
					if ((xxx.is_zoophile(pawn) || (RJWSettings.override_RJW_designation_checks && !MP.IsInMultiplayer)) && pawn.IsColonist)
						return pawn.GetRJWPawnData().CanDesignateBreeding = true;
				}
				else if (pawn.IsHeroOwner())
					return pawn.GetRJWPawnData().CanDesignateBreeding = true;

				if (pawn.IsPrisonerOfColony || xxx.is_slave(pawn))
					return pawn.GetRJWPawnData().CanDesignateBreeding = true;
			}

			if (RJWSettings.animal_on_animal_enabled && xxx.is_animal(pawn)
				&& pawn.Faction == Faction.OfPlayer)
				return pawn.GetRJWPawnData().CanDesignateBreeding = true;

			return pawn.GetRJWPawnData().CanDesignateBreeding = false;
		}
		public static bool CanDesignateBreeding(this Pawn pawn)
		{
			return pawn.GetRJWPawnData().CanDesignateBreeding;
		}
		public static void ToggleBreeding(this Pawn pawn)
		{
			pawn.UpdateCanDesignateBreeding();
			if (pawn.CanDesignateBreeding())
			{
				if (!pawn.IsDesignatedBreeding())
					DesignateBreeding(pawn);
				else
					UnDesignateBreeding(pawn);
			}
		}
		public static bool IsDesignatedBreeding(this Pawn pawn)
		{
			if (pawn.GetRJWPawnData().Breeding)
			{
				if (!xxx.is_animal(pawn))
				{
					if (!RJWSettings.bestiality_enabled)
						UnDesignateBreeding(pawn);

					else if (!pawn.IsDesignatedHero())
						if (!(xxx.is_zoophile(pawn) || pawn.IsPrisonerOfColony || xxx.is_slave(pawn)))
							if (!(RJWSettings.WildMode || (RJWSettings.override_RJW_designation_checks && !MP.IsInMultiplayer)))
								UnDesignateBreeding(pawn);
				}
				else
				{
					if (!RJWSettings.animal_on_animal_enabled)
						UnDesignateBreeding(pawn);

					else if (!pawn.Faction?.IsPlayer ?? false)
						UnDesignateBreeding(pawn);
				}
				if (pawn.Dead)
					pawn.UnDesignateBreeding();
			}

			return pawn.GetRJWPawnData().Breeding;
		}
		[SyncMethod]
		public static void DesignateBreeding(this Pawn pawn)
		{
			DesignatorsData.rjwBreeding.AddDistinct(pawn);
			pawn.GetRJWPawnData().Breeding = true;
		}
		[SyncMethod]
		public static void UnDesignateBreeding(this Pawn pawn)
		{
			DesignatorsData.rjwBreeding.Remove(pawn);
			pawn.GetRJWPawnData().Breeding = false;
		}
	}
}


code:
using Verse;
using RimWorld;
using Multiplayer.API;

namespace rjw
{
	public static class PawnDesignations_Breeder
	{
		public static bool UpdateCanDesignateBreedingAnimal(this Pawn pawn)
		{
			//no permission to change designation for NON prisoner hero/ other player
			if (!pawn.CanChangeDesignationPrisoner() && !pawn.CanChangeDesignationColonist())
				return pawn.GetRJWPawnData().CanDesignateBreedingAnimal = false;

			//no permission to change designation for prisoner hero/ self
			if (!pawn.CanChangeDesignationPrisoner())
				return pawn.GetRJWPawnData().CanDesignateBreedingAnimal = false;

			//Log.Message("CanDesignateAnimal for " + xxx.get_pawnname(pawn) + " " + SaveStorage.bestiality_enabled);
			//Log.Message("checking animal props " + (pawn.Faction?.IsPlayer.ToString()?? "tynanfag") + xxx.is_animal(pawn) + xxx.can_rape(pawn));
			if ((RJWSettings.bestiality_enabled || RJWSettings.animal_on_animal_enabled)
				&& xxx.is_animal(pawn)
				&& xxx.can_fuck(pawn)
				&& pawn.Faction == Faction.OfPlayer)
				return pawn.GetRJWPawnData().CanDesignateBreedingAnimal = true;

			return pawn.GetRJWPawnData().CanDesignateBreedingAnimal = false;
		}
		public static bool CanDesignateBreedingAnimal(this Pawn pawn)
		{
			return pawn.GetRJWPawnData().CanDesignateBreedingAnimal;
		}
		public static void ToggleBreedingAnimal(this Pawn pawn)
		{
			pawn.UpdateCanDesignateBreedingAnimal();
			if (pawn.CanDesignateBreedingAnimal())
			{
				if (!pawn.IsDesignatedBreedingAnimal())
					DesignateBreedingAnimal(pawn);
				else
					UnDesignateBreedingAnimal(pawn);
			}
		}
		public static bool IsDesignatedBreedingAnimal(this Pawn pawn)
		{
			if (pawn.GetRJWPawnData().BreedingAnimal)
			{
				if (!pawn.Faction?.IsPlayer ?? false)
					UnDesignateBreedingAnimal(pawn);

				if (pawn.Dead)
					pawn.UnDesignateBreedingAnimal();
			}

			return pawn.GetRJWPawnData().BreedingAnimal;
		}
		[SyncMethod]
		public static void DesignateBreedingAnimal(this Pawn pawn)
		{
			DesignatorsData.rjwBreedingAnimal.AddDistinct(pawn);
			pawn.GetRJWPawnData().BreedingAnimal = true;
		}
		[SyncMethod]
		public static void UnDesignateBreedingAnimal(this Pawn pawn)
		{
			DesignatorsData.rjwBreedingAnimal.Remove(pawn);
			pawn.GetRJWPawnData().BreedingAnimal = false;
		}
	}
}


code:
using Verse;
using Multiplayer.API;

namespace rjw
{
	public static class PawnDesignations_Comfort
	{
		public static bool UpdateCanDesignateComfort(this Pawn pawn)
		{
			//rape disabled
			if (!RJWSettings.rape_enabled)
				return pawn.GetRJWPawnData().CanDesignateComfort = false;

			//no permission to change designation for NON prisoner hero/ other player
			if (!pawn.CanChangeDesignationPrisoner() && !pawn.CanChangeDesignationColonist())
				return pawn.GetRJWPawnData().CanDesignateComfort = false;

			//no permission to change designation for prisoner hero/ self
			if (!pawn.CanChangeDesignationPrisoner())
				return pawn.GetRJWPawnData().CanDesignateComfort = false;

			//cant sex
			if (!(xxx.can_fuck(pawn) || xxx.can_be_fucked(pawn)))
				return pawn.GetRJWPawnData().CanDesignateComfort = false;

			if (!pawn.IsDesignatedHero())
			{
				if ((xxx.is_masochist(pawn) || (RJWSettings.override_RJW_designation_checks && !MP.IsInMultiplayer)) && pawn.IsColonist)
					return pawn.GetRJWPawnData().CanDesignateComfort = true;
			}
			else if (pawn.IsHeroOwner())
				return pawn.GetRJWPawnData().CanDesignateComfort = true;

			if (pawn.IsPrisonerOfColony || xxx.is_slave(pawn))
				return pawn.GetRJWPawnData().CanDesignateComfort = true;

			return pawn.GetRJWPawnData().CanDesignateComfort = false;
		}
		public static bool CanDesignateComfort(this Pawn pawn)
		{
			return pawn.GetRJWPawnData().CanDesignateComfort;
		}
		public static void ToggleComfort(this Pawn pawn)
		{
			pawn.UpdateCanDesignateComfort();
			if (pawn.CanDesignateComfort())
			{
				if (!pawn.IsDesignatedComfort())
					DesignateComfort(pawn);
				else
					UnDesignateComfort(pawn);
			}
		}
		public static bool IsDesignatedComfort(this Pawn pawn)
		{
			if (pawn.GetRJWPawnData().Comfort)
			{
				if (!pawn.IsDesignatedHero())
				{
					if (!pawn.IsPrisonerOfColony)
						if (!(xxx.is_masochist(pawn) || xxx.is_slave(pawn)))
						{
							if (!pawn.IsColonist)
								UnDesignateComfort(pawn);
							else if (!(RJWSettings.WildMode || (RJWSettings.override_RJW_designation_checks && !MP.IsInMultiplayer)))
								UnDesignateComfort(pawn);
						}
				}

				if (pawn.Dead)
					pawn.UnDesignateComfort();
			}

			return pawn.GetRJWPawnData().Comfort;
		}
		[SyncMethod]
		public static void DesignateComfort(this Pawn pawn)
		{
			DesignatorsData.rjwComfort.AddDistinct(pawn);
			pawn.GetRJWPawnData().Comfort = true;
		}
		[SyncMethod]
		public static void UnDesignateComfort(this Pawn pawn)
		{
			DesignatorsData.rjwComfort.Remove(pawn);
			pawn.GetRJWPawnData().Comfort = false;
		}
	}
}


code:
using Verse;
using RimWorld;
using Multiplayer.API;

namespace rjw
{
	public static class PawnDesignations_Hero
	{
		public static bool UpdateCanDesignateHero(this Pawn pawn)
		{
			if ((RJWSettings.RPG_hero_control)
				&& xxx.is_human(pawn)
				&& pawn.IsColonist
				&& !xxx.is_slave(pawn)
				&& !pawn.IsPrisoner)
			{
				if (!pawn.IsDesignatedHero())
				{
					foreach (Pawn item in DesignatorsData.rjwHero)
					{
						if (item.IsHeroOwner())
						{
							if (RJWSettings.RPG_hero_control_Ironman && !item.GetRJWPawnData().Ironman)
								SetHeroIronman(item);
							if (item.Dead && !item.GetRJWPawnData().Ironman)
							{
								UnDesignateHero(item);
								//Log.Warning("CanDesignateHero:: "  + MP.PlayerName + " hero is dead remove hero tag from " + item.Name);
							}
							else
							{
								//Log.Warning("CanDesignateHero:: "  + MP.PlayerName + " already has hero - " + item.Name);
								return pawn.GetRJWPawnData().CanDesignateHero = false;
							}

						}
						else
							continue;
					}
					return pawn.GetRJWPawnData().CanDesignateHero = true;
				}
			}
			return pawn.GetRJWPawnData().CanDesignateHero = false;
		}
		public static bool CanDesignateHero(this Pawn pawn)
		{
			return pawn.GetRJWPawnData().CanDesignateHero;
		}
		public static void ToggleHero(this Pawn pawn)
		{
			pawn.UpdateCanDesignateHero();
			if (pawn.CanDesignateHero() && Find.Selector.NumSelected <= 1)
			{
				if (!pawn.IsDesignatedHero())
					DesignateHero(pawn);
			}
		}
		public static bool IsDesignatedHero(this Pawn pawn)
		{
			return pawn.GetRJWPawnData().Hero;
		}
		public static void DesignateHero(this Pawn pawn)
		{
			SyncHero(pawn, MP.PlayerName);
		}
		[SyncMethod]
		public static void UnDesignateHero(this Pawn pawn)
		{
			DesignatorsData.rjwHero.Remove(pawn);
			pawn.GetRJWPawnData().Hero = false;
		}
		public static bool IsHeroOwner(this Pawn pawn)
		{
			if (!MP.enabled)
				return pawn.GetRJWPawnData().HeroOwner == "Player" || pawn.GetRJWPawnData().HeroOwner == null || pawn.GetRJWPawnData().HeroOwner == "";
			else
				return pawn.GetRJWPawnData().HeroOwner == MP.PlayerName;
		}
		[SyncMethod]
		static void SyncHero(Pawn pawn, string theName)
		{
			if (!MP.enabled)
				theName = "Player";
			pawn.GetRJWPawnData().Hero = true;
			pawn.GetRJWPawnData().HeroOwner = theName;
			pawn.GetRJWPawnData().Ironman = RJWSettings.RPG_hero_control_Ironman;
			DesignatorsData.rjwHero.AddDistinct(pawn);
			string text = pawn.Name + " is now hero of " + theName;
			Messages.Message(text, pawn, MessageTypeDefOf.NeutralEvent);
			//Log.Message(MP.PlayerName + "  set " + pawn.Name + " to hero:" + pawn.GetPawnData().Hero);

			pawn.UpdatePermissions();
		}
		[SyncMethod]
		public static void SetHeroIronman(this Pawn pawn)
		{
			pawn.GetRJWPawnData().Ironman = true;
		}
	}
}


code:
using Verse;
using Multiplayer.API;

namespace rjw
{
	public static class PawnDesignations_Milking
	{
		public static bool UpdateCanDesignateMilking(this Pawn pawn)
		{
			return pawn.GetRJWPawnData().CanDesignateMilking = false;
		}
		public static bool CanDesignateMilking(this Pawn pawn)
		{
			return pawn.GetRJWPawnData().CanDesignateMilking = false;
		}
		public static void ToggleMilking(this Pawn pawn)
		{
			if (pawn.CanDesignateMilking())
			{
				if (!pawn.IsDesignatedMilking())
					DesignateMilking(pawn);
				else
					UnDesignateMilking(pawn);
			}
		}
		public static bool IsDesignatedMilking(this Pawn pawn)
		{
			if (pawn.GetRJWPawnData().Milking)
			{
				if (!pawn.IsDesignatedHero())
					if (!(pawn.IsColonist || pawn.IsPrisonerOfColony || xxx.is_slave(pawn)))
						UnDesignateMilking(pawn);

				if (pawn.Dead)
					pawn.UnDesignateMilking();
			}

			return pawn.GetRJWPawnData().Milking;
		}
		[SyncMethod]
		public static void DesignateMilking(this Pawn pawn)
		{
			DesignatorsData.rjwMilking.AddDistinct(pawn);
			pawn.GetRJWPawnData().Milking = true;
		}
		[SyncMethod]
		public static void UnDesignateMilking(this Pawn pawn)
		{
			DesignatorsData.rjwMilking.Remove(pawn);
			pawn.GetRJWPawnData().Milking = false;
		}
	}
}


code:
using Verse;
using Multiplayer.API;

namespace rjw
{
	public static class PawnDesignations_Service
	{
		public static bool UpdateCanDesignateService(this Pawn pawn)
		{
			//no permission to change designation for NON prisoner hero/ other player
			if (!pawn.CanChangeDesignationPrisoner() && !pawn.CanChangeDesignationColonist())
				return pawn.GetRJWPawnData().CanDesignateService = false;

			//no permission to change designation for prisoner hero/ self
			if (!pawn.CanChangeDesignationPrisoner())
				return pawn.GetRJWPawnData().CanDesignateService = false;

			//cant sex
			if (!(xxx.can_fuck(pawn) || xxx.can_be_fucked(pawn)))
				return pawn.GetRJWPawnData().CanDesignateService = false;

			if (!pawn.IsDesignatedHero())
			{
				if (pawn.IsColonist)
					return pawn.GetRJWPawnData().CanDesignateService = true;
			}
			else if (pawn.IsHeroOwner())
				return pawn.GetRJWPawnData().CanDesignateService = true;

			if (pawn.IsPrisonerOfColony || xxx.is_slave(pawn))
				return pawn.GetRJWPawnData().CanDesignateService = true;

			return pawn.GetRJWPawnData().CanDesignateService = false;
		}
		public static bool CanDesignateService(this Pawn pawn)
		{
			return pawn.GetRJWPawnData().CanDesignateService;
		}
		public static void ToggleService(this Pawn pawn)
		{
			pawn.UpdateCanDesignateService();
			if (pawn.CanDesignateService())
			{
				if (!pawn.IsDesignatedService())
					DesignateService(pawn);
				else
					UnDesignateService(pawn);
			}
		}
		public static bool IsDesignatedService(this Pawn pawn)
		{
			if (pawn.GetRJWPawnData().Service)
			{
				if (!pawn.IsDesignatedHero())
					if (!(pawn.IsColonist || pawn.IsPrisonerOfColony || xxx.is_slave(pawn)))
						UnDesignateService(pawn);

				if (pawn.Dead)
					pawn.UnDesignateService();
			}

			return pawn.GetRJWPawnData().Service;
		}
		[SyncMethod]
		public static void DesignateService(this Pawn pawn)
		{
			DesignatorsData.rjwService.AddDistinct(pawn);
			pawn.GetRJWPawnData().Service = true;
		}
		[SyncMethod]
		public static void UnDesignateService(this Pawn pawn)
		{
			DesignatorsData.rjwService.Remove(pawn);
			pawn.GetRJWPawnData().Service = false;
		}
	}
}


code:
using Verse;
using System.Diagnostics;
using RimWorld;

namespace rjw
{
	public static class PawnDesignations_Utility
	{
		public static bool UpdatePermissions(this Pawn pawn)
		{
			pawn.UpdateCanChangeDesignationPrisoner();
			pawn.UpdateCanChangeDesignationColonist();
			pawn.UpdateCanDesignateService();
			pawn.UpdateCanDesignateComfort();
			pawn.UpdateCanDesignateBreedingAnimal();
			pawn.UpdateCanDesignateBreeding();
			pawn.UpdateCanDesignateHero();
			return true;
		}
		public static bool UpdateCanChangeDesignationColonist(this Pawn pawn)
		{
			//check if pawn is a hero of other player
			//if yes - limit widget access in mp for this pawn

			if ((pawn.IsDesignatedHero() && !pawn.IsHeroOwner()))
			{
				//Log.Warning("CanChangeDesignationColonist:: Pawn:" + xxx.get_pawnname(pawn));
				//Log.Warning("CanChangeDesignationColonist:: IsDesignatedHero:" + pawn.IsDesignatedHero());
				//Log.Warning("CanChangeDesignationColonist:: IsHeroOwner:" + pawn.IsHeroOwner());
				return pawn.GetRJWPawnData().CanChangeDesignationColonist = false;
			}

			return pawn.GetRJWPawnData().CanChangeDesignationColonist = true;
		}
		public static bool CanChangeDesignationColonist(this Pawn pawn)
		{
			return pawn.GetRJWPawnData().CanChangeDesignationColonist;
		}
		public static bool UpdateCanChangeDesignationPrisoner(this Pawn pawn)
		{
			//check if player hero is a slave/prisoner
			//if yes - limit widget access in mp for all widgets

			//Stopwatch sw = new Stopwatch();
			//sw.Start();

			//Log.Warning("rjwHero:: Count " + DesignatorsData.rjwHero.Count);
			//Log.Warning("rjwComfort:: Count " + DesignatorsData.rjwComfort.Count);
			//Log.Warning("rjwService:: Count " + DesignatorsData.rjwService.Count);
			//Log.Warning("rjwMilking:: Count " + DesignatorsData.rjwMilking.Count);
			//Log.Warning("rjwBreeding:: Count " + DesignatorsData.rjwBreeding.Count);
			//Log.Warning("rjwBreedingAnimal:: Count " + DesignatorsData.rjwBreedingAnimal.Count);

			foreach (Pawn item in DesignatorsData.rjwHero)
			{
				//Log.Warning("CanChangeDesignationPrisoner:: Pawn:" + xxx.get_pawnname(item));
				//Log.Warning("CanChangeDesignationPrisoner:: IsHeroOwner:" + item.IsHeroOwner());
				if (item.IsHeroOwner())
				{
					if (item.IsPrisonerOfColony || item.IsPrisoner || xxx.is_slave(item))
					{
						//Log.Warning("CanChangeDesignationPrisoner:: Pawn:" + xxx.get_pawnname(item));
						//Log.Warning("CanChangeDesignationPrisoner:: Hero of " + MP.PlayerName);
						//Log.Warning("CanChangeDesignationPrisoner:: is prisoner(colony):" + item.IsPrisonerOfColony);
						//Log.Warning("CanChangeDesignationPrisoner:: is prisoner:" + item.IsPrisoner);
						//Log.Warning("CanChangeDesignationPrisoner:: is slave:" + xxx.is_slave(item));
						return pawn.GetRJWPawnData().CanChangeDesignationPrisoner = false;
					}
				}
			}
			//sw.Stop();
			//Log.Warning("Elapsed={0}" + sw.Elapsed);

			return pawn.GetRJWPawnData().CanChangeDesignationPrisoner = true;
		}
		public static bool CanChangeDesignationPrisoner(this Pawn pawn)
		{
			return pawn.GetRJWPawnData().CanChangeDesignationPrisoner;
		}
	}
}


code:
using System.Collections.Generic;
using Verse;
using UnityEngine;

namespace rjw
{
	/// <summary>
	/// Handles creation of RJWdesignations button group for gui
	/// </summary>
	public class RJWdesignations : Command
	{
		//is actually a group of four buttons, but I've wanted them be small and so vanilla gizmo system is mostly bypassed for them

		private const float ContentPadding = 5f;
		private const float IconSize = 32f;
		private const float IconGap = 1f;

		private readonly Pawn parent;
		private Rect gizmoRect;
		/// <summary>
		/// This should keep track of last pressed pseudobutton. It is set in the pseudobutton callback.
		/// Then, the callback to encompassed Gizmo is performed by game, and this field is used to determine what exact button was pressed
		/// The callback is called by the tynancode right after the loop which detects click on button,
		/// so it will be called then and only then when it should be (no unrelated events).
		/// event handling  shit is needed to apply settings to all selected pawns.
		/// </summary>
		private static SubIcon lastClicked;

		static readonly List<SubIcon> subIcons = new List<SubIcon> {
			new Comfort(),
			//new Service(),
			//new BreederHuman(),
			new BreedingHuman(),
			new BreedingAnimal(),
			new Breeder(),
			//new Milking(),
			new Hero(),
			new HelpImStupid()
		};

		public RJWdesignations(Pawn pawn)
		{
			parent = pawn;
			defaultLabel = "RJWdesignations";
			defaultDesc = "RJWdesignations";
		}

		public override GizmoResult GizmoOnGUI(Vector2 topLeft, float maxWidth, GizmoRenderParms parms)
		{
			Rect rect = new Rect(topLeft.x, topLeft.y, 75f, 75f);
			gizmoRect = rect.ContractedBy(ContentPadding);
			Widgets.DrawWindowBackground(rect);

			//Log.Message("RJWgizmo");
			foreach (SubIcon icon in subIcons)
			{
				if (DrawSubIcon(icon))
				{
					lastClicked = icon;
					icon.state = icon.applied(parent);
					return new GizmoResult(GizmoState.Interacted, Event.current);
				}
			}
			return new GizmoResult(GizmoState.Clear);
		}

		//this and class mess below was supposed to be quick shortcut to not write four repeated chunks of code in GizmoOnGUI
		private bool DrawSubIcon(SubIcon icon)
		{
			if (!icon.applicable(parent)) { return false; }
			//Log.Message("sub gizmo");
			Rect iconRect = new Rect(gizmoRect.x + icon.offset.x, gizmoRect.y + icon.offset.y, IconSize, IconSize);
			TooltipHandler.TipRegion(iconRect, icon.desc(parent).Translate());
			bool applied = icon.applied(parent);
			Texture2D texture = applied ? icon.cancel : icon.texture(parent);
			GUI.DrawTexture(iconRect, texture);
			//GUI.color = Color.white;

			return Widgets.ButtonInvisible(iconRect, false);
		}

		public override void ProcessInput(Event ev)
		{
			SubIcon icon = lastClicked;
			if (icon.state)
				icon.unapply(parent);
			else
				icon.apply(parent);
		}

		[StaticConstructorOnStartup]//this  is needed for textures
		public abstract class SubIcon
		{
			public abstract Texture2D texture(Pawn pawn);
			public abstract Vector2 offset { get; }
			public abstract string desc(Pawn pawn);
			public abstract bool applicable(Pawn pawn);
			public abstract bool applied(Pawn pawn);
			public abstract void apply(Pawn pawn);
			public abstract void unapply(Pawn pawn);

			static readonly Texture2D cancellText = ContentFinder<Texture2D>.Get("UI/Commands/cancel");
			public virtual Texture2D cancel => cancellText;

			public bool state;
		}
		[StaticConstructorOnStartup]
		public class Comfort : SubIcon
		{
			//comfort raping
			static readonly Texture2D iconAccept = ContentFinder<Texture2D>.Get("UI/Commands/ComfortPrisoner_off");
			static readonly Texture2D iconRefuse = ContentFinder<Texture2D>.Get("UI/Commands/ComfortPrisoner_Refuse");
			static readonly Texture2D iconCancel = ContentFinder<Texture2D>.Get("UI/Commands/ComfortPrisoner_on");
			public override Texture2D texture(Pawn pawn) => (pawn.CanDesignateComfort() || pawn.IsDesignatedComfort()) && xxx.is_human(pawn) ? iconAccept : iconRefuse;
			public override Texture2D cancel { get; } = iconCancel;

			static readonly Vector2 posComf = new Vector2(IconGap + IconSize, 0);
			public override Vector2 offset => posComf;

			public override string desc(Pawn pawn) => pawn.CanDesignateComfort() ? "ForComfortDesc" :
														!pawn.CanChangeDesignationPrisoner() ? "ForHeroRefuse2Desc" :
														!pawn.CanChangeDesignationColonist() ? "ForHeroRefuse1Desc" : "ForComfortRefuseDesc";

			public override bool applicable(Pawn pawn) => RJWSettings.rape_enabled && xxx.is_human(pawn);
			public override bool applied(Pawn pawn) => pawn.IsDesignatedComfort();
			public override void apply(Pawn pawn) => pawn.ToggleComfort();
			public override void unapply(Pawn pawn) => pawn.ToggleComfort();
		}
		[StaticConstructorOnStartup]
		public class Service : SubIcon
		{
			//whoring
			static readonly Texture2D iconAccept = ContentFinder<Texture2D>.Get("UI/Commands/Service_off");
			static readonly Texture2D iconRefuse = ContentFinder<Texture2D>.Get("UI/Commands/Service_Refuse");
			static readonly Texture2D iconCancel = ContentFinder<Texture2D>.Get("UI/Commands/Service_on");
			public override Texture2D texture(Pawn pawn) => (pawn.CanDesignateService() || pawn.IsDesignatedService()) && xxx.is_human(pawn) ? iconAccept : iconRefuse;
			public override Texture2D cancel { get; } = iconCancel;

			public override Vector2 offset { get; } = new Vector2(0, 0);

			public override string desc(Pawn pawn) => pawn.CanDesignateService() ? "ForServiceDesc" :
														!pawn.CanChangeDesignationPrisoner() ? "ForHeroRefuse2Desc" :
														!pawn.CanChangeDesignationColonist() ? "ForHeroRefuse1Desc" : "ForServiceRefuseDesc";

			public override bool applicable(Pawn pawn) => xxx.is_human(pawn);
			public override bool applied(Pawn pawn) => pawn.IsDesignatedService() && xxx.is_human(pawn);
			public override void apply(Pawn pawn) => pawn.ToggleService();
			public override void unapply(Pawn pawn) => pawn.ToggleService();
		}
		[StaticConstructorOnStartup]
		public class BreedingHuman : SubIcon
		{
			//Breed humanlike
			static readonly Texture2D iconAccept = ContentFinder<Texture2D>.Get("UI/Commands/Breeding_Pawn_off");
			static readonly Texture2D iconRefuse = ContentFinder<Texture2D>.Get("UI/Commands/Breeding_Pawn_Refuse");
			static readonly Texture2D iconCancel = ContentFinder<Texture2D>.Get("UI/Commands/Breeding_Pawn_on");
			public override Texture2D texture(Pawn pawn) => (pawn.CanDesignateBreeding() || pawn.IsDesignatedBreeding()) && xxx.is_human(pawn) ? iconAccept : iconRefuse;
			public override Texture2D cancel { get; } = iconCancel;

			public override Vector2 offset { get; } = new Vector2(0, IconSize + IconGap);

			public override string desc(Pawn pawn) => pawn.CanDesignateBreeding() && xxx.is_human(pawn) ? "ForBreedingDesc" :
														!pawn.CanChangeDesignationPrisoner() ? "ForHeroRefuse2Desc" :
														!pawn.CanChangeDesignationColonist() ? "ForHeroRefuse1Desc" : "ForBreedingRefuseDesc";

			public override bool applicable(Pawn pawn) =>  RJWSettings.bestiality_enabled && xxx.is_human(pawn);
			public override bool applied(Pawn pawn) => pawn.IsDesignatedBreeding() && xxx.is_human(pawn);
			public override void apply(Pawn pawn) => pawn.ToggleBreeding();
			public override void unapply(Pawn pawn) => pawn.ToggleBreeding();
		}

		[StaticConstructorOnStartup]
		public class BreedingAnimal : SubIcon
		{
			//Breed animal
			static readonly Texture2D iconAccept = ContentFinder<Texture2D>.Get("UI/Commands/Breeding_Animal_off");
			static readonly Texture2D iconCancel = ContentFinder<Texture2D>.Get("UI/Commands/Breeding_Animal_on");
			public override Texture2D texture(Pawn pawn) => iconAccept;
			public override Texture2D cancel { get; } = iconCancel;

			public override Vector2 offset { get; } = new Vector2(0, IconSize + IconGap);

			public override string desc(Pawn pawn) => !pawn.CanChangeDesignationPrisoner() ? "ForHeroRefuse2Desc" : "ForBreedingDesc";

			public override bool applicable(Pawn pawn) => (pawn.CanDesignateBreeding() || pawn.IsDesignatedBreeding()) && xxx.is_animal(pawn);
			public override bool applied(Pawn pawn) => pawn.IsDesignatedBreeding() && xxx.is_animal(pawn);
			public override void apply(Pawn pawn) => pawn.ToggleBreeding();
			public override void unapply(Pawn pawn) => pawn.ToggleBreeding();
		}
		[StaticConstructorOnStartup]
		public class Breeder : SubIcon
		{
			//Breeder(fucker) animal
			static readonly Texture2D iconAccept = ContentFinder<Texture2D>.Get("UI/Commands/Breeder_Animal_off");
			static readonly Texture2D iconCancel = ContentFinder<Texture2D>.Get("UI/Commands/Breeder_Animal_on");
			public override Texture2D texture(Pawn pawn) => iconAccept;
			public override Texture2D cancel { get; } = iconCancel;

			public override Vector2 offset { get; } = new Vector2(0, 0);

			public override string desc(Pawn pawn) => !pawn.CanChangeDesignationPrisoner() ? "ForHeroRefuse2Desc" : "ForBreedingAnimalDesc";

			public override bool applicable(Pawn pawn) => pawn.CanDesignateBreedingAnimal() || pawn.IsDesignatedBreedingAnimal();
			public override bool applied(Pawn pawn) => pawn.IsDesignatedBreedingAnimal();
			public override void apply(Pawn pawn) => pawn.ToggleBreedingAnimal();
			public override void unapply(Pawn pawn) => pawn.ToggleBreedingAnimal();
		}
		[StaticConstructorOnStartup]
		public class Milking : SubIcon
		{
			static readonly Texture2D iconAccept = ContentFinder<Texture2D>.Get("UI/Commands/Milking_off");
			static readonly Texture2D iconCancel = ContentFinder<Texture2D>.Get("UI/Commands/Milking_on");
			public override Texture2D texture(Pawn pawn) => iconAccept;
			public override Texture2D cancel { get; } = iconCancel;

			public override Vector2 offset { get; } = new Vector2(IconGap + IconSize, IconSize + IconGap);

			public override string desc(Pawn pawn) => !pawn.CanChangeDesignationPrisoner() ? "ForHeroRefuse2Desc" : "ForMilkingDesc";

			public override bool applicable(Pawn pawn) => pawn.CanDesignateMilking() || pawn.IsDesignatedMilking();
			public override bool applied(Pawn pawn) => pawn.IsDesignatedMilking();
			public override void apply(Pawn pawn) => pawn.ToggleMilking();
			public override void unapply(Pawn pawn) => pawn.ToggleMilking();
		}
		[StaticConstructorOnStartup]
		public class Hero : SubIcon
		{
			static readonly Texture2D iconAccept = ContentFinder<Texture2D>.Get("UI/Commands/Hero_off");
			static readonly Texture2D iconCancel = ContentFinder<Texture2D>.Get("UI/Commands/Hero_on");
			public override Texture2D texture(Pawn pawn) => iconAccept;
			public override Texture2D cancel { get; } = iconCancel;

			public override Vector2 offset { get; } = new Vector2(IconGap + IconSize, IconSize + IconGap);

			//public override string desc(Pawn pawn) => pawn.CanDesignateHero() || (pawn.IsDesignatedHero() && pawn.IsHeroOwner()) ? "ForHeroDesc" : "Hero of " + pawn.GetPawnData().HeroOwner;
			public override string desc(Pawn pawn) => pawn.CanDesignateHero() ? "ForHeroDesc" :
														pawn.IsDesignatedHero() ? "Hero of " + pawn.GetRJWPawnData().HeroOwner : "ForHeroDesc";

			public override bool applicable(Pawn pawn) => pawn.CanDesignateHero() || pawn.IsDesignatedHero();
			public override bool applied(Pawn pawn) => pawn.IsDesignatedHero();
			public override void apply(Pawn pawn) => pawn.ToggleHero();
			public override void unapply(Pawn pawn) => pawn.ToggleHero();
		}
		[StaticConstructorOnStartup]
		public class HelpImStupid : SubIcon
		{
			// a question mark that shows when no other icons show; shows a hint to look at mod settings
			static readonly Texture2D myicon = ContentFinder<Texture2D>.Get("UI/Commands/HelpImStupid");
			public override Texture2D texture(Pawn pawn) => myicon;
			public override Texture2D cancel { get; } = myicon;

			static readonly Vector2 posComf = new Vector2(IconGap + IconSize, 0);
			public override Vector2 offset => posComf;

			public override string desc(Pawn pawn) => "GoToModSettings";

			public override bool applicable(Pawn pawn) => !(RJWSettings.rape_enabled && xxx.is_human(pawn)) && // comfort
														!(pawn.CanDesignateHero() || pawn.IsDesignatedHero()) && // hero
														//!(pawn.CanDesignateMilking() || pawn.IsDesignatedMilking()) && // milking
														!(pawn.CanDesignateBreedingAnimal() || pawn.IsDesignatedBreedingAnimal()) && // breeder
														!((pawn.CanDesignateBreeding() || pawn.IsDesignatedBreeding()) && xxx.is_animal(pawn)) && // breeding animal
														!(RJWSettings.bestiality_enabled && xxx.is_human(pawn));// && // breeding human
														//!(pawn.IsDesignatedService() && xxx.is_human(pawn)); // service

			public override bool applied(Pawn pawn) => true;
			public override void apply(Pawn pawn) { }
			public override void unapply(Pawn pawn) { }
		}
	}
}


code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using HarmonyLib;
using Verse;
using RimWorld;
using UnityEngine;

// Non-pregnancy Biotech-related patches
namespace rjw
{
    [HarmonyPatch]
    class LifeStageWorker_HumanlikeX_Notify_LifeStageStarted
    {
        static IEnumerable<MethodBase> TargetMethods()
        {
            const string lifeStageStarted = nameof(LifeStageWorker.Notify_LifeStageStarted);
            yield return AccessTools.Method(typeof(LifeStageWorker_HumanlikeChild), lifeStageStarted);
            yield return AccessTools.Method(typeof(LifeStageWorker_HumanlikeAdult), lifeStageStarted);
        }

        // Fixes errors caused by trying to spawn a biotech-only effector when a child starts a new lifestage
        // and by trying to send a biotech-only letter when a child turns three
        [HarmonyTranspiler]
        static IEnumerable<CodeInstruction> FixLifeStageStartError(IEnumerable<CodeInstruction> instructions, MethodBase original)
        {
            PropertyInfo thingSpawned = AccessTools.DeclaredProperty(typeof(Thing), nameof(Thing.Spawned));
            MethodInfo shouldSendNotificationsAbout = AccessTools.Method(typeof(PawnUtility), nameof(PawnUtility.ShouldSendNotificationAbout));
            bool foundAny = false;

            foreach (var instruction in instructions)
            {
                yield return instruction;

                // if (pawn.Spawned) SpawnBiotechOnlyEffector()
                // => if (pawn.Spawned && ModsConfig.IsBiotechActive) SpawnBiotechOnlyEffector()
                if (instruction.Calls(thingSpawned.GetMethod) || instruction.Calls(shouldSendNotificationsAbout))
                {
                    yield return CodeInstruction.Call(typeof(ModsConfig), "get_BiotechActive");
                    yield return new CodeInstruction(OpCodes.And);
                    foundAny = true;
                }
            }

            if (!foundAny)
            {
                ModLog.Error("Failed to patch " + original.Name);
            }
        }
    }

    [HarmonyPatch(typeof(WidgetsWork), "get_WorkBoxBGTex_AgeDisabled")]
    class WidgetsWork_WorkBoxBGTex_AgeDisabled
    {
        [HarmonyPrefix]
        static bool DontLoadMissingTexture(ref Texture2D __result)
        {
            if (!ModsConfig.BiotechActive)
            {
                __result = WidgetsWork.WorkBoxBGTex_Awful;
                return false;
            }

            return true;
        }
    }

    // If biotech is disabled, TeachOpportunity will NRE due to a null ConceptDef argument
    // Silence the error that interrupts AgeTick results by adding a null check.
    [HarmonyPatch(typeof(LessonAutoActivator), nameof(LessonAutoActivator.TeachOpportunity), new [] {typeof(ConceptDef), typeof(Thing), typeof(OpportunityType)})]
    static class Patch_LessonAutoActivator_TeachOpportunity
    {
        public static bool Prefix(ConceptDef conc)
        {
            // call the underlying method if concept is non-null
            return conc != null;
        }
    }

    // If biotech is disabled, make the Baby() method return false in the targeted method.
    [HarmonyPatch]
    static class Patch_DevelopmentalStageExtensions_Baby_Callers
    {

        static IEnumerable<MethodBase> TargetMethods()
        {
            // Make babies follow adult rules for food eligibility instead of requiring milk/baby food
            yield return AccessTools.Method(typeof(FoodUtility), nameof(FoodUtility.WillEat), new [] {typeof(Pawn), typeof(ThingDef), typeof(Pawn), typeof(bool), typeof(bool)});
            // Make babies able to be fed in bed as a patient in lieu of nursing
            yield return AccessTools.Method(typeof(WorkGiver_FeedPatient), nameof(WorkGiver_FeedPatient.HasJobOnThing), new [] {typeof(Pawn), typeof(Thing), typeof(bool)});
        }

        [HarmonyTranspiler]
        public static IEnumerable<CodeInstruction> BabyMethodShouldReturnFalse(IEnumerable<CodeInstruction> instructions, MethodBase original)
        {
            bool foundAny = false;
            MethodInfo developmentalStageIsBabyMethod = AccessTools.Method(typeof(DevelopmentalStageExtensions), nameof(DevelopmentalStageExtensions.Baby));
            List<CodeInstruction> codeInstructions = instructions.ToList();
            foreach (CodeInstruction instruction in codeInstructions)
            {
                yield return instruction;
                if (instruction.Calls(developmentalStageIsBabyMethod))
                {
                    foundAny = true;
                    if (!ModsConfig.BiotechActive)
                    {
                        // After calling the Baby() method, AND the result with 0, to make it as if DevelopmentalStageExtensions::Baby() returned false.
                        yield return new CodeInstruction(OpCodes.Ldc_I4_0);
                        yield return new CodeInstruction(OpCodes.And);
                    }
                }
            }
            if (!foundAny)
            {
                ModLog.Error("Failed to patch " + original.Name);
            }
        }
    }

	// Check for fertile penis instead of gender when compiling list of pawns that could fertilize ovum
	[HarmonyPatch]
	static class Patch_HumanOvum_CanFertilizeReport
	{
		static IEnumerable<MethodBase> TargetMethods()
		{
			yield return AccessTools.Method(typeof(HumanOvum), "CanFertilizeReport", new[] { typeof(Pawn) });
		}

		static bool hasPenis(Pawn p)
		{
			// need to use current hediffSet, else has_penis_fertile reads data from save (an issue if a pawn lost their penis since then)
			List<Hediff> parts = p?.health?.hediffSet?.hediffs;
			return Genital_Helper.has_penis_fertile(p, parts);
		}

		[HarmonyTranspiler]
		public static IEnumerable<CodeInstruction> CheckForPenisInsteadOfGender(IEnumerable<CodeInstruction> instructions, MethodBase original)
		{
			MethodInfo checkForPenis = AccessTools.Method(typeof(Patch_HumanOvum_CanFertilizeReport), nameof(Patch_HumanOvum_CanFertilizeReport.hasPenis));
			bool foundGenderCheck = false;

			foreach (CodeInstruction ci in instructions)
			{
				string cis = ci.ToString();
				if (cis.Contains("Verse.Gender Verse.Pawn::gender"))
				{
					// check for fertile penis instead of male gender
					foundGenderCheck = true;
					yield return new CodeInstruction(OpCodes.Call, checkForPenis);
				}
				else
				{
					yield return ci;
				}
			}
			if (!foundGenderCheck)
			{
				ModLog.Warning("Failed to patch " + original.Name);
			}
		}
	}

	// If babies are malnourished, mark them as needing urgent medical rest, despite being permanently downed.
	[HarmonyPatch(typeof(HealthAIUtility), nameof(HealthAIUtility.ShouldSeekMedicalRestUrgent), new [] {typeof(Pawn)})]
    static class Patch_HealthAIUtility_ShouldSeekMedicalRestUrgent
    {
        public static bool Prefix(Pawn pawn, ref bool __result)
        {
            if (!ModsConfig.BiotechActive && pawn.DevelopmentalStage.Baby())
            {
                __result = true;
                return false;
            }
            return true;
        }
    }
}


code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using HarmonyLib;

namespace rjw
{
	public static class CodeExtensions
	{
		/// <summary>
		/// <para>Breaks apart a list of instructions at some specific point, identified by a
		/// predicate function.  The first instruction that the predicate matches will be
		/// included in the `before` list, while all remaining instructions will be
		/// in the `after` list.</para>
		/// <para>If no instructions matched the predicate, all instructions will be in
		/// the `before` list and the `after` list will be empty.</para>
		/// <para>This is useful for breaking apart the instructions into more manageable
		/// chunks to better identify the target of your patch.</para>
		/// </summary>
		/// <param name="instructions">This list of instructions.</param>
		/// <param name="predicate">The predicate to identify the break point.</param>
		/// <returns>A tuple, the first being the instructions up to and including the
		/// instruction that matched the predicate and the second being everything
		/// afterward.</returns>
		public static (List<CodeInstruction> before, List<CodeInstruction> after) SplitAfter(
			this List<CodeInstruction> instructions,
			Predicate<CodeInstruction> predicate)
		{
			if (instructions.FindIndex(predicate) is var idx and not -1)
			{
				var before = instructions.Take(idx + 1).ToList();
				var after = instructions.Skip(before.Count).ToList();
				return (before, after);
			}

			return (instructions, new());
		}

		/// <summary>
		/// <para>Checks the next instructions in this list of instructions to make sure
		/// they all match some expectation, one predicate per instruction.  If the
		/// predicates all match, it produces two new lists, one with the matched
		/// instructions and the other with those matched instructions removed.</para>
		/// <para>If any predicate fails to match, the `cut` list will be empty and
		/// the `remainder` list will be the same instance as `instructions`.</para>
		/// <para>Use this to validate that the code actually is the code you expect
		/// and isolate it from other instructions so you can tweak it safely.</para>
		/// </summary>
		/// <param name="instructions">This list of instructions.</param>
		/// <param name="predicates">One or more predicates to test each instruction.</param>
		/// <returns>A tuple, the first being the list of cut instructions and the second
		/// being the remaining instructions after the cut.</returns>
		public static (List<CodeInstruction> cut, List<CodeInstruction> remainder) CutMatchingSequence(
			this List<CodeInstruction> instructions,
			params Predicate<CodeInstruction>[] predicates)
		{
			if (predicates.Length == 0)
				return (new(), instructions);
			if (instructions.Count < predicates.Length)
				return (new(), instructions);
			if (instructions.Zip(predicates, (il, pred) => pred(il)).Contains(false))
				return (new(), instructions);

			var cut = instructions.Take(predicates.Length).ToList();
			var remainder = instructions.Skip(predicates.Length).ToList();
			return (cut, remainder);
		}

		/// <summary>
		/// <para>Determines if this instruction is some form of `stloc` that matches the
		/// given index in the locals table.</para>
		/// <para>Why is this not a part of Harmony's API?</para>
		/// </summary>
		/// <param name="il">This instruction.</param>
		/// <param name="index">The locals table index to check for.</param>
		/// <returns>Whether this is a `stloc` targeting the given index.</returns>
		public static bool IsStlocOf(this CodeInstruction il, int index) => index switch
		{
			0 when il.opcode == OpCodes.Stloc_0 => true,
			1 when il.opcode == OpCodes.Stloc_1 => true,
			2 when il.opcode == OpCodes.Stloc_2 => true,
			3 when il.opcode == OpCodes.Stloc_3 => true,
			// Most common thing we'll see...
			_ when il.IsStloc() && il.operand is LocalBuilder lb => lb.LocalIndex == index,
			// ...but these are also technically possible with `stloc_s` and `stloc`.
			_ when il.IsStloc() && il.operand is byte bIndex => bIndex == Convert.ToByte(index),
			_ when il.IsStloc() && il.operand is ushort uIndex => uIndex == Convert.ToUInt16(index),
			_ => false
		};

		/// <summary>
		/// Copies the labels from this instruction to its replacement.  If the replacement
		/// instruction also has labels, it ensures that duplicate labels are discarded.
		/// </summary>
		/// <param name="il">This instruction.</param>
		/// <param name="newIl">The instruction that will replace it.</param>
		/// <returns>The replacement instruction.</returns>
		public static CodeInstruction Replace(this CodeInstruction il, CodeInstruction newIl)
		{
			var copyLabels = newIl.labels.ToList();
			newIl.labels.Clear();
			newIl.labels.AddRange(copyLabels.Concat(il.labels).Distinct());
			return newIl;
		}
	}
}


code:
using HarmonyLib;
using RimWorld;
using System;
using Verse;

namespace rjw
{
	///
	///unset designators on GuestRelease
	///until pawn leaves map, pawn is still guest/slave/prisoner, so they can actually be changed back
	///
	[HarmonyPatch(typeof(GenGuest), "GuestRelease")]
	[StaticConstructorOnStartup]
	static class PATCH_GenGuest_GuestRelease
	{
		[HarmonyPrefix]
		private static void GuestRelease_Update_Designators(Pawn p)
		{
			if (p != null)
			{
				//ModLog.Message("GenGuest GuestRelease");
				//ModLog.Message("pawn: " + xxx.get_pawnname(p));
				p.UnDesignateComfort();
				p.UnDesignateService();
				p.UnDesignateBreeding();
				p.UnDesignateBreedingAnimal();
				p.UnDesignateMilking();
				p.UnDesignateHero();
				//ModLog.Message(p.IsDesignatedComfort().ToString());
			}
		}
	}

	///
	///unset designators on Pawn_ExitMap
	///now pawn actually leaves map and get their factions reset
	///
	[HarmonyPatch(typeof(Pawn), "ExitMap")]
	[StaticConstructorOnStartup]
	static class PATCH_Pawn_ExitMap
	{
		[HarmonyPrefix]
		private static void Pawn_ExitMap_Update_Designators(Pawn __instance, bool allowedToJoinOrCreateCaravan, Rot4 exitDir)
		{
			Pawn p = __instance;
			if (p != null)
				if (!p.IsColonist)
				{
					//ModLog.Message("Pawn ExitMap");
					//ModLog.Message("pawn: " + xxx.get_pawnname(p));
					p.UnDesignateComfort();
					p.UnDesignateService();
					p.UnDesignateBreeding();
					p.UnDesignateBreedingAnimal();
					p.UnDesignateMilking();
					p.UnDesignateHero();
					//ModLog.Message(p.IsDesignatedComfort().ToString());
				}
		}
	}
}