code:
namespace rjw
{
	/// <summary>
	/// Patch:
	/// recipes
	/// </summary>

	//TODO: inject rjw recipes
	//[HarmonyPatch(typeof(HealthCardUtility), "GenerateSurgeryOption")]
	//internal static class PATCH_HealthCardUtility_recipes
	//{
	//	//private static FloatMenuOption GenerateSurgeryOption(Pawn pawn, Thing thingForMedBills, RecipeDef recipe, IEnumerable<ThingDef> missingIngredients, BodyPartRecord part = null)
	//	//public FloatMenuOption(string label, Action action, MenuOptionPriority priority = MenuOptionPriority.Default, Action mouseoverGuiAction = null, Thing revalidateClickTarget = null, float extraPartWidth = 0, Func<Rect, bool> extraPartOnGUI = null, WorldObject revalidateWorldClickTarget = null);
	//	//floatMenuOption = new FloatMenuOption(text, action, MenuOptionPriority.Default, null, null, 0f, null, null);
	//	[HarmonyPostfix]
	//	private static void Postfix(ref FloatMenuOption __result, ref Pawn pawn)
	//	{

	//		ModLog.Message("PATCH_HealthCardUtility_recipes");
	//		ModLog.Message("PATCH_HealthCardUtility_recipes list: " + __result);
	//		//foreach (FloatMenuOption recipe in recipeOptionsMaker)
	//		//	{
	//		//		ModLog.Message("PATCH_HealthCardUtility_recipes: " + recipe);
	//		//	}

	//		return;
	//	}
	//}

	//erm.. idk ?
	//[HarmonyPatch(typeof(HealthCardUtility), "GetTooltip")]
	//internal static class PATCH_HealthCardUtility_GetTooltip
	//{
	//	[HarmonyPostfix]
	//	private static void Postfix(Pawn pawn)
	//	{
	//		ModLog.Message("GetTooltip");
	//		//ModLog.Message("PATCH_HealthCardUtility_recipes list: " + floatMenuOption);
	//		//foreach (FloatMenuOption recipe in recipeOptionsMaker)
	//		//	{
	//		//		ModLog.Message("PATCH_HealthCardUtility_recipes: " + recipe);
	//		//	}
	//		return;
	//	}
	//}

	//TODO: make toggle/floatmenu to parts switching
	//[HarmonyPatch(typeof(HealthCardUtility), "EntryClicked")]
	//internal static class PATCH_HealthCardUtility_EntryClicked
	//{
	//	[HarmonyPostfix]
	//	private static void Postfix(Pawn pawn)
	//	{
	//		ModLog.Message("EntryClicked");
	//		//ModLog.Message("PATCH_HealthCardUtility_recipes list: " + floatMenuOption);
	//		//foreach (FloatMenuOption recipe in recipeOptionsMaker)
	//		//	{
	//		//		ModLog.Message("PATCH_HealthCardUtility_recipes: " + recipe);
	//		//	}
	//		return;
	//	}
	//}
}


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

namespace rjw
{
	/// <summary>
	/// Patch ui for hero mode
	/// - disable pawn control for non owned hero
	/// - disable equipment management for non owned hero
	/// hardcore mode:
	/// - disable equipment management for non hero
	/// - disable pawn rmb menu for non hero
	/// - remove drafting widget for non hero
	/// </summary>

	//disable forced works(rmb workgivers)
	[HarmonyPatch(typeof(FloatMenuMakerMap), "CanTakeOrder")]
	[StaticConstructorOnStartup]
	static class disable_FloatMenuMakerMap
	{
		[HarmonyPostfix]
		static void NonHero_disable_controls(ref bool __result, Pawn pawn)
		{
			if (RJWSettings.RPG_hero_control)
			{
				if ((pawn.IsDesignatedHero() && !pawn.IsHeroOwner()))
				{
					__result = false;   //not hero owner, disable menu
					return;
				}

				if (!pawn.IsDesignatedHero() && RJWSettings.RPG_hero_control_HC)
				{
					if (pawn.Drafted && pawn.CanChangeDesignationPrisoner() && pawn.CanChangeDesignationColonist())
					{
						//allow control over drafted pawns, this is limited by below disable_Gizmos patch
					}
					else
					{
						__result = false; //not hero, disable menu
					}
				}
			}
		}
	}

	//TODO: disable equipment management
	/*
	//disable equipment management
	[HarmonyPatch(typeof(ITab_Pawn_Gear), "CanControl")]
	static class disable_equipment_management
	{
		[HarmonyPostfix]
		static bool this_is_postfix(ref bool __result, Pawn selPawnForGear)
		{
			Pawn pawn = selPawnForGear;

			if (RJWSettings.RPG_hero_control)
			{
				if ((pawn.IsDesignatedHero() && !pawn.IsHeroOwner()))	//not hero owner, disable drafting
				{
					__result = false;   //not hero owner, disable menu
				}
				else if (!pawn.IsDesignatedHero() && RJWSettings.RPG_hero_control_HC)   //not hero, disable drafting
				{
					if (false)
					{
						//add some filter for bots and stuff? if there is such stuff
						//so it can be drafted and controlled for fighting
					}
					else
					{
						__result = false; //not hero, disable menu
					}
				}
			}
			return true;
		}
	}
	*/

	//TODO: allow shared control over non colonists(droids, etc)?
	//disable command gizmos
	[HarmonyPatch(typeof(Pawn), "GetGizmos")]
	[StaticConstructorOnStartup]
	static class disable_Gizmos
	{
		[HarmonyPostfix]
		[HarmonyPriority(100)]
		static IEnumerable<Gizmo> NonHero_disable_gizmos(IEnumerable<Gizmo> __result, Pawn __instance)
		{

			Pawn pawn = __instance;
			string disablementReason = string.Empty;

			if (RJWSettings.RPG_hero_control)
			{
				if ((pawn.IsDesignatedHero() && !pawn.IsHeroOwner()))	//not hero owner, disable drafting
				{
					disablementReason = "ForHeroRefuse1Desc";
				}
				else if (!pawn.IsDesignatedHero() && RJWSettings.RPG_hero_control_HC)   //not hero, disable drafting
				{
					//no permission to change designation for NON prisoner hero/ other player
					if (pawn.CanChangeDesignationPrisoner() && pawn.CanChangeDesignationColonist()
							&& (pawn.kindDef.race.defName.Contains("AIRobot")
							|| (pawn.kindDef.race.defName.Contains("Droid") && !pawn.kindDef.race.defName.Contains("AndDroid"))
							|| pawn.kindDef.race.defName.Contains("RPP_Bot")
							))
					//if (false)
					{
						//add some filter for bots and stuff? if there is such stuff
						//so it can be drafted and controlled for fighting
					}
					else
					{
						disablementReason = "ForHeroRefuseHCDesc";
					}
				}
			}

			foreach (var gizmo in __result)
			{
				if ( disablementReason.NullOrEmpty() || (!(gizmo is Command)) )  //we do not filter out non-command Gizmos, such as shield bar or psychic entropy
				{
					yield return gizmo;
				}

				//ModLog.Message("Gizmo for " + xxx.get_pawnname(__instance) + " type: " + gizmo.GetType()+ ": " + gizmo);

				if (!disablementReason.NullOrEmpty())
				{
					if (gizmo is Verse.Command_VerbTarget) { //weapon icons
						gizmo.Disable(disablementReason.Translate());
						yield return gizmo;
					}
				}
				//all other command gizmos are dropped

			}
		}
	}
}

repo_name: Euclidean/rjw

license: mit


code:
using System.Collections.Generic;
using System.Linq;
using HarmonyLib;
using RimWorld;
using Verse;
using UnityEngine;
using Multiplayer.API;

namespace rjw
{
	///
	/// Harmony patch to toggle the RJW designation box showing
	///
	[HarmonyPatch(typeof(PlaySettings), "DoPlaySettingsGlobalControls")]
	[StaticConstructorOnStartup]
	public static class RJW_corner_toggle
	{
		static readonly Texture2D icon = ContentFinder<Texture2D>.Get("UI/Commands/ComfortPrisoner_off");

		[HarmonyPostfix]
		public static void add_RJW_toggle(WidgetRow row, bool worldView)
		{
			if (worldView) return;
			if (!RJWSettings.show_RJW_designation_box) return;
			row.ToggleableIcon(ref RJWSettings.show_RJW_designation_box, icon, "RJW_designation_box_desc".Translate());
		}
	}

	///
	///Compact button group containing rjw designations on pawn
	///
	[HarmonyPatch(typeof(Pawn), "GetGizmos")]
	[StaticConstructorOnStartup]
	static class Rjw_buttons
	{
		[HarmonyPostfix]
		[HarmonyPriority(99)]
		static IEnumerable<Gizmo> add_designation_box(IEnumerable<Gizmo> __result, Pawn __instance)
		{
			foreach (var gizmo in __result)
			{
				yield return gizmo;
			}

			if (!RJWSettings.show_RJW_designation_box) yield break;
			if (!(__instance.Faction == Faction.OfPlayer || __instance.IsPrisonerOfColony)) yield break;
			//ModLog.Message("Harmony patch submit_button is called");
			var pawn = __instance;
			yield return new RJWdesignations(pawn);
		}
	}

	///
	///Submit gizmo
	///
	[HarmonyPatch(typeof(Pawn), "GetGizmos")]
	[StaticConstructorOnStartup]
	static class submit_button
	{
		[HarmonyPostfix]
		[HarmonyPriority(101)]
		static IEnumerable<Gizmo> add_button(IEnumerable<Gizmo> __result, Pawn __instance)
		{
			foreach (var gizmo in __result)
			{
				yield return gizmo;
			}

			//ModLog.Message("Harmony patch submit_button is called");
			var pawn = __instance;
			var enabled = RJWSettings.submit_button_enabled;

			if (enabled && pawn.IsColonistPlayerControlled && pawn.Drafted)
				if (pawn.CanChangeDesignationColonist())
					if (!(pawn.kindDef.race.defName.Contains("Droid") && !AndroidsCompatibility.IsAndroid(pawn)))
					{
						yield return new Command_Action
						{
							defaultLabel = "CommandSubmit".Translate(),
							icon = submit_icon,
							defaultDesc = "CommandSubmitDesc".Translate(),
							action = delegate
							{
								LayDownAndAccept(pawn);
							},
							hotKey = KeyBindingDefOf.Misc3
						};
					}

		}

		static Texture2D submit_icon = ContentFinder<Texture2D>.Get("UI/Commands/Submit", true);
		static HediffDef submit_hediff = HediffDef.Named("Hediff_Submitting");

		[SyncMethod]
		static void LayDownAndAccept(Pawn pawn)
		{
			//Log.Message("Submit button is pressed for " + pawn);
			pawn.health.AddHediff(submit_hediff);
		}
	}
}


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

namespace rjw
{
	[HarmonyPatch(typeof(CompAbilityEffect_WordOfLove), "ValidateTarget")]
	internal static class PATCH_CompAbilityEffect_WordOfLove_ValidateTarget
	{
		[HarmonyPrefix]
		static bool GenderChecks(ref LocalTargetInfo target, LocalTargetInfo ___selectedTarget, ref bool __result)
		{
			Pawn pawn = ___selectedTarget.Pawn;
			Pawn pawn2 = target.Pawn;
			if (pawn != pawn2 && pawn != null && pawn2 != null)
			{
				__result = !xxx.is_asexual(pawn) && (xxx.is_bisexual(pawn) || xxx.is_pansexual(pawn) || (xxx.is_heterosexual(pawn) && pawn.gender != pawn2.gender) || (xxx.is_homosexual(pawn) && pawn.gender == pawn2.gender));
				if (__result == false)
				{ Messages.Message("AbilityCantApplyWrongAttractionGender".Translate(pawn, pawn2), pawn, MessageTypeDefOf.RejectInput, false); }
				return false;
			}
			return true;
		}
	}
}


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

namespace rjw
{
	public class HediffCompProperties_SexPart : HediffCompProperties
	{
		public HediffCompProperties_SexPart()
		{
			compClass = typeof(HediffComp_SexPart);
		}
	}

	public class HediffCompProperties_Ovipositor : HediffCompProperties
	{

		// Currently unused in favour of searching parentDefs of every egg def, should refactor
		public List<HediffDef_InsectEgg> eggs;

		public IntRange eggIntervalTicks = new(GenDate.TicksPerDay, GenDate.TicksPerDay);

		public FloatRange eggCount = FloatRange.One;

		public HediffCompProperties_Ovipositor()
		{
			compClass = typeof(HediffComp_Ovipositor);
		}

		public override IEnumerable<string> ConfigErrors(HediffDef parentDef)
		{
			foreach (string err in base.ConfigErrors(parentDef))
			{
				yield return err;
			}
			// if (eggs.NullOrEmpty())
			// {
			// 	yield return "One or more <eggs> is required";
			// }
		}
	}

	public class HediffCompProperties_GrowsWithOwner : HediffCompProperties
	{
		public bool evenIfTransplanted;

		public HediffCompProperties_GrowsWithOwner()
		{
			compClass = typeof(HediffComp_GrowsWithOwner);
		}
	}
}


code:
using System.Collections.Generic;
using Verse;
using RimWorld;
using LudeonTK;

namespace rjw
{

	public static class DebugActions
	{
		[DebugAction("RJW", "Force Size Updates", allowedGameStates = AllowedGameStates.PlayingOnMap)]
		public static void ToggleForceUpdate()
		{
			HediffComp_GrowsWithOwner.ForceUpdate = !HediffComp_GrowsWithOwner.ForceUpdate;

			string status = HediffComp_GrowsWithOwner.ForceUpdate
				? "<color=green>Size Updated</color>"
				: "<color=red>disabled</color>";

			Messages.Message($"Debug {status}", MessageTypeDefOf.TaskCompletion);
		}
	}
	public class HediffComp_GrowsWithOwner : HediffComp
	{
		public float lastOwnerSize = -1;

		private const int UpdateInterval = GenTicks.TickRareInterval;

		public static bool ForceUpdate = false;
		public void UpdatePartSize(HediffComp_SexPart partComp)
		{
			//get ~relative size variable from calculation()
			var relativeSize = partComp.baseSize;

			//remove old lifestage bodysize mod
			relativeSize /= partComp.originalOwnerSize;

			//add new lifestage bodysize mod
			relativeSize *= Pawn.BodySize;

			//save new size
			partComp.baseSize = relativeSize;

			//update owner size
			partComp.originalOwnerSize = Pawn.BodySize;

			// update/reset part size
			partComp.UpdateSeverity();
		}
		public HediffCompProperties_GrowsWithOwner Props => (HediffCompProperties_GrowsWithOwner)props;

		public override void CompPostTick(ref float severityAdjustment)
		{
			// natural parts make sense to grow relative to the owner.
			// transplanted or bionic parts will appear to shrink (relatively) when a pawn grows in size.

			// this comp keeps part severity (relative size) FIXED by updating the baseSize when bodySize changes.
			// parts having extra growth/shrinkage with lifeStage (puberty) is handled by lifeStageFactor, not this.

			// Only update at interval to improve performance
			if (!ForceUpdate && !Pawn.IsHashIntervalTick(UpdateInterval))
				return;
			ForceUpdate = false;

			// Skip if body size hasn't changed since last check
			if (Pawn.BodySize == lastOwnerSize) return;

			// Attempt to get the sex part component
			if (!parent.TryGetComp<HediffComp_SexPart>(out var partComp))
			{
				Log.WarningOnce($"HediffComp_SexPart missing on {parent.def.defName}", parent.def.GetHashCode() + 450720);
				return;
			}

			//no changes for transplants
			if (partComp.isTransplant && !Props.evenIfTransplanted) return;
			UpdatePartSize(partComp);
			lastOwnerSize = Pawn.BodySize;
		}

		public override void CompExposeData()
		{
			base.CompExposeData();
			Scribe_Values.Look(ref lastOwnerSize, "lastOwnerSize");
		}
	}
}


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

using Verse;

namespace rjw
{
	public class HediffComp_Ovipositor : HediffComp
	{
		public IntRange eggInterval;

		private int nextEggTick;

		private static HediffDef_InsectEgg UnknownEgg = DefDatabase<HediffDef_InsectEgg>.GetNamed("RJW_UnknownEgg");

		public HediffCompProperties_Ovipositor Props => props as HediffCompProperties_Ovipositor;

		public override void CompPostMake()
		{
			eggInterval = Props.eggIntervalTicks;
		}
		/// <summary>
		/// egg production ticks
		/// </summary>
		public override void CompPostTick(ref float severityAdjustment)
		{
			base.CompPostTick(ref severityAdjustment);

			var thisTick = Find.TickManager.TicksGame;

			if (thisTick >= nextEggTick)
			{
				var def = parent.def as HediffDef_SexPart;
				var pawn = parent.pawn;
				var isPlayerFaction = pawn.Faction?.IsPlayer ?? false; // Colonists/animals/mechs/mutants
				var onHomeMap = pawn.Map?.IsPlayerHome ?? false;

				if (!onHomeMap && !isPlayerFaction && !pawn.IsPrisonerOfColony && !pawn.IsSlaveOfColony)
				{
					return;
				}

				if (pawn.health.capacities.GetLevel(PawnCapacityDefOf.Moving) <= 0.5)
				{
					return;
				}

				float maxEggsSize = PregnancyHelper.GetMaxEggsSize(pawn);
				float eggedSize = GetCombinedEggSize(pawn);

				if (RJWSettings.DevMode) ModLog.Message($"{xxx.get_pawnname(pawn)} filled with {eggedSize} out of max capacity of {maxEggsSize} eggs.");
				if (eggedSize < maxEggsSize)
				{
					HediffDef_InsectEgg egg;

					if (RJWSettings.DevMode) ModLog.Message($" Trying to find a {pawn.kindDef} egg");
					if (!TryGetEgg(pawn.kindDef.defName, out egg))
					{
						if (RJWSettings.DevMode) ModLog.Message($" No {pawn.kindDef} egg found, defaulting to UnknownEgg");
						egg = UnknownEgg;
					}

					if (RJWSettings.DevMode) ModLog.Message($"I choose you, {egg}!");

					var parentPart = parent.Part;
					if (parentPart != null)
					{
						AddEggs(egg, parentPart, Props.eggCount);
					}
				}

				// Reset for next egg.
				nextEggTick = RandomNextEggTick(thisTick);
			}
		}

		private static float GetCombinedEggSize(Pawn pawn)
		{
			float eggedSize = 0;
			List<Hediff_InsectEgg> ownEggs = new();
			pawn.health.hediffSet.GetHediffs(ref ownEggs);
			foreach (var ownEgg in ownEggs)
			{
				eggedSize += ownEgg.eggssize;
			}

			return eggedSize;
		}

		[SyncMethod]
		private int RandomNextEggTick(int fromTick)
		{
			return fromTick + eggInterval.RandomInRange;
		}

		[SyncMethod]
		private static bool TryGetEgg(string defname, out HediffDef_InsectEgg result)
		{
			var possibleEggs = PossibleEggs(defname);

			if(RJWSettings.DevMode) ModLog.Message($"TryGetEgg: Possible eggs for {defname} are {possibleEggs.Select(egg => egg.defName).ToCommaList()}");

			return possibleEggs.TryRandomElement(out result);
		}

		public static IEnumerable<HediffDef_InsectEgg> PossibleEggs(string defName)
		{
			if (defName == null)
			{
				return Enumerable.Empty<HediffDef_InsectEgg>();
			}
			var eggOptions = DefDatabase<HediffDef_InsectEgg>.AllDefs.Where(eggDef => eggDef.CanHaveParent(defName)).ToList();

			// Remove the unknown egg if we have other options
			if(eggOptions.Count > 1)
			{
				eggOptions = eggOptions.Where(eggDef => eggDef.defName != "RJW_UnknownEgg").ToList();
			}
			return eggOptions;
		}

		[SyncMethod]
		public void AddEggs(HediffDef_InsectEgg eggDef, BodyPartRecord bodyPart, FloatRange range)
		{
			float eggScore = range.RandomInRange + 0.5f;

			if (RJWSettings.DevMode)
			{
				ModLog.Message($"Added egg count: {eggScore}, int: {(int)eggScore}");
				ModLog.Message($"Min egg count: {range.min}, int: {(int)range.min}");
				ModLog.Message($"Max egg count: {range.max}, int: {(int)range.max}");
			}

			int eggsToAdd = (int) eggScore;
			for (int i = 0; i < eggsToAdd; i++)
			{
				var addedEgg = parent.pawn.health.AddHediff(eggDef, bodyPart) as Hediff_InsectEgg;
				addedEgg?.InitImplanter(parent.pawn);
			}
		}

		public override void CompExposeData()
		{
			base.CompExposeData();
			Scribe_Values.Look(ref nextEggTick, "nextEggTick");
			Scribe_Values.Look(ref eggInterval, "eggInterval", defaultValue: Props.eggIntervalTicks);
		}
	}
}


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

using ShowParts = rjw.RJWSettings.ShowParts;
using System.Text;
using System;

namespace rjw
{
	/// <summary>
	/// Comp for rjw hediff parts
	/// </summary>
	public class HediffComp_SexPart : HediffComp
	{
		public string SizeLabel => parent.CurStage?.label ?? "";

		public string originalOwnerRace = "";      //base race when part created
		public string previousOwner = "";            //base race when part created

		private float? forcedSize;
		public float baseSize;                              	// Absolute base size when part created, someday alter by operation
		public float originalOwnerSize = 0;                         // Body size of this part's first owner. Not used in calculations.
		public bool isTransplant = false;                   //transplanted from someone else

		// Whether this part could ever have been seen by the player based on mod settings and apparel.
		public bool discovered;

		private bool initialised;

		public new HediffDef_SexPart Def => (HediffDef_SexPart)base.Def;

		public HediffCompProperties_SexPart Props => (HediffCompProperties_SexPart)props;

		public float partFluidMultiplier = -1;            // Multiplier on Milk/Ejaculation/Wetness
		private SexFluidDef fluidOverride;           // Cummies/milk - insectjelly/honey etc
		public float FluidAmount => GetFluidAmount();
		public float FluidMultiplier => GetFluidMultiplier();
		public SexFluidDef Fluid
		{
			get => fluidOverride ?? Def.fluid;
			set {
				if (value == Def.fluid)
				{
					fluidOverride = null;
				}
				else
				{
					fluidOverride = value;
				}
			}
		}
		public float GetFluidMultiplier()
		{
			return Def.GetFluidMultiplier(GetSeverity(), partFluidMultiplier, GetBodySize(), SexUtility.ScaleToHumanAge(Pawn));
		}

		public float GetFluidAmount()
		{
			return Def.GetFluidAmount(GetFluidMultiplier());
		}

		private List<string> DefaultPositionNames
		{
			get
			{
				List<string> result = Def.defaultBodyPartList ?? new();
				string singleDefaultPart = Def.defaultBodyPart;
				if (!singleDefaultPart.NullOrEmpty() && !result.Contains(singleDefaultPart))
				{
					result.Add(singleDefaultPart);
				}
				return result;
			}
		}

		public float Size
		{
			get => GetSize();
		}

		// makes parts appear to grow with pawn (aka puberty)
		public bool HasForcedSize => forcedSize.HasValue;
		public float GetSize() {
			if (forcedSize.HasValue)
			{
				return forcedSize.Value;
			}
			return baseSize;
		}
		public float GetSeverity()
		{
			// Severity = baseSize * LifeStageFactor / Pawn.BodySize;
			return GetSize() / Pawn.BodySize;
		}
		public void SetSeverity(float newSeverity, bool sync = true)
		{
			if(!forcedSize.HasValue)
			{
				baseSize = newSeverity * Pawn.BodySize;
			}
			if (sync)
			{
				SyncSeverity();
			}
		}

		public void SyncSeverity()
		{
			parent.Severity = GetSeverity();
		}
		public void UpdateSeverity(float newSeverity = -1f)
		{
			if(newSeverity < 0)
			{
				SyncSeverity();
			}
			else
			{
				SetSeverity(newSeverity);
			}
		}
		public void ForceSize(float size)
		{
			forcedSize = size;
			UpdateSeverity();
		}
		public void UnforceSize()
		{
			forcedSize = null;
			UpdateSeverity();
		}
		public float GetBodySize()
		{
			return Pawn.BodySize;
		}

		/// <summary>
		/// save data
		/// </summary>
		public override void CompExposeData()
		{
			base.CompExposeData();

			Scribe_Values.Look(ref baseSize, nameof(baseSize));
			Scribe_Values.Look(ref originalOwnerSize, nameof(originalOwnerSize));
			Scribe_Values.Look(ref originalOwnerRace, nameof(originalOwnerRace));
			Scribe_Values.Look(ref previousOwner, nameof(previousOwner));
			Scribe_Defs.Look(ref fluidOverride, nameof(fluidOverride));
			Scribe_Values.Look(ref partFluidMultiplier, nameof(partFluidMultiplier), defaultValue: Def.GetRandomPartFluidMultiplier());
			Scribe_Values.Look(ref isTransplant, nameof(isTransplant));
			Scribe_Values.Look(ref forcedSize, nameof(forcedSize));
			Scribe_Values.Look(ref discovered, nameof(discovered));
			Scribe_Values.Look(ref initialised, nameof(initialised), defaultValue: true);
		}

		public override void CompPostPostAdd(DamageInfo? dinfo)
		{
			base.CompPostPostAdd(dinfo);
			try//error at world gen
			{
				Pawn.GetRJWPawnData().genitals = new List<Hediff>();
				Pawn.GetRJWPawnData().breasts = new List<Hediff>();
				Pawn.GetRJWPawnData().anus = new List<Hediff>();
			}
			catch
			{
			}
			if (!initialised)
			{
				//Log.Message("CompPostPostAdd");
				Init(reroll: false);
			}
		}

		// can be used instead of SexPartAdder::PartMaker, RacePartDef_Helper::PartMaker
		//public override void CompPostMake()
		//{
		//	base.CompPostMake();
		//	// A null pawn is only possible in vanilla in verb-related debug outputs, but better safe than sorry.
		//	if (Pawn != null)
		//	{
		//		if (!initialised)
		//		{
		//			Log.Message("CompPostMake");
		//			Init();
		//		}
		//	}
		//}

		public override void CompPostPostRemoved()
		{
			base.CompPostPostRemoved();
			try
			{
				Pawn.GetRJWPawnData().genitals = new List<Hediff>();
				Pawn.GetRJWPawnData().breasts = new List<Hediff>();
				Pawn.GetRJWPawnData().anus = new List<Hediff>();
			}
			catch
			{
			}
		}

		public override bool CompDisallowVisible()
		{
			if (base.CompDisallowVisible())
			{
				return true;
			}

			if (RJWSettings.ShowRjwParts == ShowParts.Hide)
			{
				return true;
			}

			if (discovered)
			{
				return false;
			}

			// Show if required by settings, or at game start if in dev mode
			if (RJWSettings.ShowRjwParts != ShowParts.Known || (Current.ProgramState != ProgramState.Playing && Prefs.DevMode))
			{
				discovered = true;
				return false;
			}

			// Show for hero and apparel-less pawns
			if (Pawn.IsDesignatedHero() && Pawn.IsHeroOwner() || Pawn.apparel == null)
			{
				discovered = true;
			}
			else
			{
				var partGroups = parent.Part.groups;
				if (!partGroups.Any(group => Pawn.apparel.BodyPartGroupIsCovered(group)))
				{
					discovered = true;
				}
			}
			return !discovered;
		}

		private static readonly StringBuilder sb = new();

		/// <summary>
		/// show part info in healthtab
		/// </summary>
		public override string CompTipStringExtra
		{
			get
			{
				if (!initialised)
				{
					ModLog.Warning(" " + xxx.get_pawnname(Pawn) + " part " + parent.def.defName + " is broken, resetting");
					Init();
					UpdateSeverity();
					updatepartposition();
				}
				// In theory the tip should be a condensed form and the longer form should be elsewhere, but where?
				sb.Clear();
				IEnumerable<string> tipLines = GetTipString(RJWSettings.ShowRjwParts == RJWSettings.ShowParts.Extended);
				foreach(string line in tipLines)
				{
					sb.AppendLine(line);
				}
				return sb.ToString();
			}
		}

		public IEnumerable<string> GetTipString(bool extended)
		{
			//ModLog.Message(" CompTipStringExtra " + xxx.get_pawnname(Pawn) + " " + parent.def.defName);
			// TODO: Part type should be a property in the extension.
			//StringBuilder defstringBuilder = new StringBuilder();
			if (parent.Part != null)
			{
				if (Def.genitalFamily == GenitalFamily.Breasts)
				{
					return GetBreastTip(extended);
				}
				else if (Def.genitalFamily == GenitalFamily.Penis)
				{
					return GetPenisTip(extended);
				}
				else if (Def.genitalFamily == GenitalFamily.Anus || Def.genitalFamily == GenitalFamily.Vagina)
				{
					return GetOrificeTip(extended);
				}
				else if (Def.genitalFamily == GenitalFamily.FemaleOvipositor || Def.genitalFamily == GenitalFamily.MaleOvipositor)
				{
					return GetEggTip();
				}
			}

			return Enumerable.Empty<string>();
		}

		private string _eggTip = null;
		IEnumerable<string> GetEggTip()
		{
			if (Def.genitalTags.Contains(GenitalTag.CanEgg))
			{
				if (_eggTip == null)
				{
					var possibleEggNames = HediffComp_Ovipositor.PossibleEggs(Pawn.kindDef?.defName)
						.SelectMany(eggDef => eggDef.childrenDefs)
						.Select(defName => DefDatabase<PawnKindDef>.GetNamedSilentFail(defName)?.LabelCap.ToString())
						.Where(label => label != null)
						.Distinct().ToList();

					_eggTip = possibleEggNames.ToCommaList();
				}
				yield return "RJW_PartInfo_eggs".Translate(_eggTip);
			}
		}

		IEnumerable<string> GetPenisTip(bool extended)
		{
			if (PartSizeCalculator.TryGetLength(parent, out float length))
			{
				yield return "RJW_PartInfo_length".Translate(length.ToString("F1"));
			}

			if (!extended)
			{
				yield break;
			}

			if (PartSizeCalculator.TryGetGirth(parent, out float girth))
			{
				yield return "RJW_PartInfo_girth".Translate(girth.ToString("F1"));
			}

			if (PartSizeCalculator.TryGetPenisWeight(parent, out float weight))
			{
				yield return "RJW_PartInfo_weight".Translate(weight.ToString("F1"));
			}

			foreach (var line in GetFluidTip())
			{
				yield return line;
			}

			foreach (var line in GetPropertiesTip())
			{
				yield return line;
			}
		}

		IEnumerable<string> GetOrificeTip(bool extended)
		{
			if (!extended)
			{
				yield break;
			}
			//defstringBuilder.Append(this.Def.description);
			//defstringBuilder.AppendLine("Cum: " + FluidType);
			//defstringBuilder.AppendLine("Ejaculation: " + (FluidAmmount * FluidModifier).ToString("F2") + "ml");

			// TODO: Should be scaled bigger than penis size either in xml or here.
			if (PartSizeCalculator.TryGetLength(parent, out float length))
			{
				yield return "RJW_PartInfo_maxLength".Translate(length.ToString("F1"));
			}

			if (PartSizeCalculator.TryGetGirth(parent, out float girth))
			{
				yield return "RJW_PartInfo_maxGirth".Translate(girth.ToString("F1"));
			}

			foreach (var line in GetFluidTip())
			{
				yield return line;
			}

			foreach (var line in GetPropertiesTip())
			{
				yield return line;
			}
		}

		IEnumerable<string> GetBreastTip(bool extended)
		{
			if(!extended)
			{
				foreach (var line in GetBraCupTip())
				{
					yield return line;
				}
				yield break;
			}

			if (PartSizeCalculator.TryGetBreastSize(parent, out BreastSize breastSize))
			{
				yield return "RJW_PartInfo_braSize".Translate(breastSize.GetBandSize(), breastSize.GetCupSize());
				yield return "RJW_PartInfo_weight".Translate(breastSize.weight.ToString("F3"));
			}

			foreach (var line in GetFluidTip())
			{
				yield return line;
			}

			foreach (var line in GetPropertiesTip())
			{
				yield return line;
			}
		}

		IEnumerable<string> GetBraCupTip()
		{
			if(GetSeverity() >= 0.02f)
			{
				if (PartSizeCalculator.TryGetBreastSize(parent, out BreastSize breastSize))
				{
					yield return "RJW_PartInfo_braCup".Translate(breastSize.GetCupSize());
				}
			}
		}

		IEnumerable<string> GetFluidTip()
		{
			if (FluidAmount != 0 && Fluid != null)
			{
				yield return "RJW_PartInfo_fluidTypeFluidAmount".Translate(
					Fluid.LabelCap,
					FluidAmount.ToString("F1"));
			}

			if (RJWSettings.DevMode)
			{
				yield return "RJW_PartInfo_fluidMultiplier".Translate($"{FluidMultiplier:F3} ({partFluidMultiplier:F3})");
			}
		}

		IEnumerable<string> GetPropertiesTip()
		{
			var showTransplant = isTransplant && parent is Hediff_NaturalSexPart;
			if (Def.partTags.Any() || showTransplant)
			{
				var tags = new List<string>();
				Def.partTags.ForEach(tag => tags.Add(("PartsTag_"+tag).Translate()));
				var tagList = tags.ToCommaList();
				if(showTransplant)
				{
					tagList = Def.partTags.Prepend("Transplant").ToCommaList();
				}
				yield return "RJW_PartInfo_properties".Translate(tagList);
			}
		}

		[SyncMethod]
		public void updatepartposition()
		{
			if (parent.def is not HediffDef_SexPart def)
			{
				return;
			}

			//Log.Message("0 " + (parent.Part == null));
			//Log.Message("1 " +parent.Part);
			//Log.Message("2 " +parent.Part.def);
			//Log.Message("3 " +parent.Part.def.defName);
			//Log.Message("4 " +partBase);
			//Log.Message("5 " +partBase.DefaultBodyPart);
			//ModLog.Message("pawn " + xxx.get_pawnname(Pawn) + ", part: " + parent.def.defName);
			if (parent.Part == null)
			{
				var bp = Pawn.RaceProps.body.AllParts.Find(x => DefaultPositionNames.Any(x.def.defName.Contains));
				if (bp != null)
				{
					ModLog.Warning(" " + xxx.get_pawnname(Pawn) + " part is null/wholebody? is in wrong BodyPart position, resetting to default: " + def.defaultBodyPart);
					parent.Part = bp;
					Pawn.GetRJWPawnData().genitals = new List<Hediff>();
					Pawn.GetRJWPawnData().breasts = new List<Hediff>();
					Pawn.GetRJWPawnData().anus = new List<Hediff>();
				}
				else
				{
					ModLog.Message(" " + xxx.get_pawnname(Pawn) + " default bodypart not found: " + def.defaultBodyPart + " -skip.");
				}
			}
			else if (def.defaultBodyPart != "" && !parent.Part.def.defName.Contains(def.defaultBodyPart))
			{
				//Log.Message("f");
				//Log.Message(partBase.DefaultBodyPartList.ToLineList());
				if (def.defaultBodyPartList.Any() && def.defaultBodyPartList.Any(parent.Part.def.defName.Contains))
				{
					return;
				}
				var bp = Pawn.RaceProps.body.AllParts.Find(x => x.def.defName.Contains(def.defaultBodyPart));
				if (bp != null)
				{
					ModLog.Warning(" " + xxx.get_pawnname(Pawn) + " part " + parent.def.defName + " is in wrong BodyPart position, resetting to default: " + def.defaultBodyPart);
					parent.Part = bp;
					Pawn.GetRJWPawnData().genitals = new List<Hediff>();
					Pawn.GetRJWPawnData().breasts = new List<Hediff>();
					Pawn.GetRJWPawnData().anus = new List<Hediff>();
				}
				else
				{
					ModLog.Message(" " + xxx.get_pawnname(Pawn) + " default bodypart not found: " + def.defaultBodyPart + " -skip.");
				}
				//if (pawn.IsColonist)
				//{
				//	Log.Message(xxx.get_pawnname(pawn) + " has broken hediffs, removing " + this.ToString());
				//	Log.Message(Part.ToString());
				//	Log.Message(bp.def.defName);
				//	Log.Message(partBase.DefaultBodyPart.ToString());
				//}
			}
		}

		/// <summary>
		/// fill comp data
		/// </summary>
		[SyncMethod]
		public void Init(Pawn pawn = null, bool reroll = true)
		{
			pawn ??= Pawn;

			if (originalOwnerSize == 0)
			{
				originalOwnerSize = pawn.BodySize;
			}

			if (reroll || baseSize == 0)
			{
				//var s = (parent is Hediff_NaturalSexPart) ? originalOwnerSize : Pawn.RaceProps.baseBodySize;
				baseSize = CalculateSize(pawn, originalOwnerSize);
			}

			if(reroll || partFluidMultiplier == -1)
			{
				partFluidMultiplier = Def.GetRandomPartFluidMultiplier();
			}

			if (originalOwnerRace.NullOrEmpty())
			{
				originalOwnerRace = pawn?.kindDef.race.LabelCap ?? "RJW_PartInfo_unknownSpecies".Translate();
			}
			previousOwner = pawn?.LabelNoCount ?? "RJW_PartInfo_unknownOwner".Translate();

			//Log.Message("1 "+originalOwnerSize);
			//Log.Message("2 " + baseSize);
			UpdateSeverity();
			//Log.Message("3 " + baseSize);
			initialised = true;
		}

		[SyncMethod]
		public float CalculateSize(Pawn pawn, float bodySize)
		{
			float relativeSize;
			if (Def.genitalFamily == GenitalFamily.Breasts && pawn?.gender == Gender.Male && !Rand.Chance(TrapChance(pawn)))
			{
				relativeSize = .01f;
			}
			else
			{
				relativeSize = Def.GetRandomSize();
			}
			return relativeSize * bodySize;
		}

		private static float TrapChance(Pawn pawn)
		{
			if (RJWSettings.MaleTrap && !xxx.is_animal(pawn))
			{
				if (xxx.is_nympho(pawn))
				{
					return RJWSettings.futa_nymph_chance;
				}
				if (pawn.Faction != null && (int)pawn.Faction.def.techLevel < 5)
				{
					return RJWSettings.futa_natives_chance;
				}
				return RJWSettings.futa_spacers_chance;
			}
			return 0f;
		}
	}
}


code:
using Verse;
using RimWorld;

namespace rjw
{
	/// <summary>
	/// FeelingBroken raise/lower severity
	/// </summary>
	public class HediffCompProperties_FeelingBrokenSeverityReduce : HediffCompProperties
	{
		public HediffCompProperties_FeelingBrokenSeverityReduce()
		{
			this.compClass = typeof(HediffComp_FeelingBrokenSeverityReduce);
		}

		public SimpleCurve severityPerDayReduce;
	}
	class HediffComp_FeelingBrokenSeverityReduce : HediffComp_SeverityModifierBase
	{
		private HediffCompProperties_FeelingBrokenSeverityReduce Props
		{
			get
			{
				return (HediffCompProperties_FeelingBrokenSeverityReduce)this.props;
			}
		}
		public override void CompPostTick(ref float severityAdjustment)
		{
			base.CompPostTick(ref severityAdjustment);
			if (base.Pawn.IsHashIntervalTick(SeverityUpdateInterval))
			{
				float num = this.SeverityChangePerDay();
				num *= 0.00333333341f;
				if (xxx.has_traits(Pawn))
				{
					if (xxx.RoMIsActive)
						if (Pawn.story.traits.HasTrait(xxx.Succubus))
							num *= 4.0f;
					if (Pawn.story.traits.HasTrait(VanillaTraitDefOf.Tough))
					{
						num *= 2.0f;
					}
					if (Pawn.story.traits.HasTrait(VanillaTraitDefOf.Tough))
					{
						num *= 2.0f;
					}
					if (Pawn.story.traits.HasTrait(TraitDefOf.Wimp))
					{
						num *= 0.5f;
					}
					if (Pawn.story.traits.HasTrait(VanillaTraitDefOf.Nerves))
					{
						int td = Pawn.story.traits.DegreeOfTrait(VanillaTraitDefOf.Nerves);
						switch (td)
						{
							case -2:
								num *= 2.0f;
								break;
							case -1:
								num *= 1.5f;
								break;
							case 1:
								num *= 0.5f;
								break;
							case 2:
								num *= 0.25f;
								break;
						}
					}
				}
				severityAdjustment += num;
			}
		}
		public override float SeverityChangePerDay()
		{
			return this.Props.severityPerDayReduce.Evaluate(this.parent.ageTicks / GenDate.TicksPerDay);
		}
	}

	public class HediffCompProperties_FeelingBrokenSeverityIncrease : HediffCompProperties
	{
		public HediffCompProperties_FeelingBrokenSeverityIncrease()
		{
			this.compClass = typeof(HediffComp_FeelingBrokenSeverityIncrease);
		}

		public SimpleCurve severityPerDayIncrease;
	}
	class HediffComp_FeelingBrokenSeverityIncrease : AdvancedHediffComp
	{
		private HediffCompProperties_FeelingBrokenSeverityIncrease Props
		{
			get
			{
				return (HediffCompProperties_FeelingBrokenSeverityIncrease)this.props;
			}
		}
		public override void CompPostMerged(Hediff other)
		{
			float num = Props.severityPerDayIncrease.Evaluate(this.parent.ageTicks / GenDate.TicksPerDay);
			if (xxx.has_traits(Pawn))
			{
				if (xxx.RoMIsActive)
					if (Pawn.story.traits.HasTrait(xxx.Succubus))
						num *= 0.25f;

				if (Pawn.story.traits.HasTrait(VanillaTraitDefOf.Tough))
				{
					num *= 0.5f;
				}
				if (Pawn.story.traits.HasTrait(TraitDefOf.Wimp))
				{
					num *= 2.0f;
				}
				if (Pawn.story.traits.HasTrait(VanillaTraitDefOf.Nerves))
				{
					int td = Pawn.story.traits.DegreeOfTrait(VanillaTraitDefOf.Nerves);
					switch (td)
					{
						case -2:
							num *= 0.25f;
							break;
						case -1:
							num *= 0.5f;
							break;
						case 1:
							num *= 1.5f;
							break;
						case 2:
							num *= 2.0f;
							break;
					}
				}
			}
			other.Severity *= num;
		}
	}

	public class AdvancedHediffWithComps : HediffWithComps
	{
		public override bool TryMergeWith(Hediff other)
		{
			for (int i = 0; i < this.comps.Count; i++)
			{
				if(this.comps[i] is AdvancedHediffComp) ((AdvancedHediffComp)this.comps[i]).CompBeforeMerged(other);
			}
			return base.TryMergeWith(other);
		}
	}
	public class AdvancedHediffComp : HediffComp
	{
		public virtual void CompBeforeMerged(Hediff other)
		{
		}
	}
}


code:
using System.Linq;
using Verse;
using RimWorld;
using System.Text;
using Multiplayer.API;
using UnityEngine;
using System.Collections.Generic;
using rjw.Modules.Genitals.Enums;
using RimWorld.QuestGen;
using System;

namespace rjw
{
//TODO figure out how this thing works and move eggs to comps

	[StaticConstructorOnStartup]
	public class HediffDef_SexPart : HediffDef
	{
		public const float BaseFluidAmount = 20f;
		private static readonly FloatRange FluidAmountVariation = new(.75f, 1.25f);

		public SexFluidDef fluid;					//cummies/milk - insectjelly/honey etc
		public float fluidMultiplier = 1;           //amount of Milk/Ejaculation/Wetness
		public bool produceFluidOnOrgasm;
		public string defaultBodyPart = "";			//Bodypart to move this part to, after fucking up with pc or other mod
		public List<string> defaultBodyPartList;    //Bodypart list to move this part to, after fucking up with pc or other mod

		public float sizeMultiplier = 1f;

		public PartSizeConfigDef sizeProfile;
		public List<string> partTags = new();
		public GenitalFamily genitalFamily;
		public List<GenitalTag> genitalTags = new();

		public override IEnumerable<string> ConfigErrors()
		{
			foreach (string err in base.ConfigErrors())
			{
				yield return err;
			}
			if (sizeProfile == null && genitalFamily != GenitalFamily.Undefined)
			{
				yield return $"Missing required <{nameof(sizeProfile)}> field. Pick a default from "
				+ "<RJW Defs folder>/ConfigDefs/PartSizeConfigs.xml.";
			}
		}

		[SyncMethod]
		public float GetRandomPartFluidMultiplier()
		{
			return FluidAmountVariation.RandomInRange;
		}

		public float GetFluidAmount(float totalFluidMultiplier)
		{
			return BaseFluidAmount * totalFluidMultiplier;
		}

		public float GetFluidMultiplier(float partSeverity, float partFluidMultipler, float pawnBodySize, float pawnAge=40)
		{
			// should be ~0.5 - 2 for average human
			// biggst vanilla animals with biggest parts, ~8

			var m = this.fluidMultiplier; // Base multiplier for part (pussy/breats/etc)
			m *= Math.Min(50 / Math.Max(1, pawnAge), 1.0f); // Lower when 50+ years old
			m *= pawnBodySize; // Creature size. Usually Race baseBodySize since Severity is already bodySize scaled.

			// Part size. Increases for above Average, decreases for below Average
			// (0 -> 0.5), (0.5 -> 1), (1 -> 2), (2 -> 4)
			m *= Math.Max(1f, partSeverity * 2f); // Above average, uncapped
			m *= Math.Min(1f, partSeverity + 0.5f); // Below average, capped to 0.5

			m *= partFluidMultipler; // Permanent multiplier for part, includes race part multiplier.
			return m;
		}

		[SyncMethod]
		public float GetRandomSize()
		{
			float sample = Rand.Gaussian(0.5f, 0.125f);
			return Mathf.Clamp(sample, 0.01f, 1f) * sizeMultiplier;
		}

		public string GetStandardSizeLabel(float size)
		{
			return stages.FindLast(stage => stage.minSeverity <= size)?.label;
		}
	}
}


code:
using Verse;
using RimWorld;

namespace rjw
{
	public class Hediff_ArtificialSexPart : Hediff_AddedPart, ISexPartHediff
	{
		public override bool ShouldRemove => false;

		public HediffDef_SexPart Def => def as HediffDef_SexPart;

		public HediffWithComps AsHediff => this;

		public override float Severity {
			get => base.Severity;
			set
			{
				var prevSeverity = base.Severity;
				base.Severity = value;
				ISexPartHediffExtensions.DetectExternalSeverityChange(this, prevSeverity, value);
			}
		}

		public override string LabelBase => def.label;

		/// <summary>
		/// stack hediff in health tab?
		/// </summary>
		public override int UIGroupKey
		{
			get
			{
				return loadID;
			}
		}

		/// <summary>
		/// do not merge same rjw parts into one
		/// </summary>
		public override bool TryMergeWith(Hediff other)
		{
			return false;
		}
	}
}


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

namespace rjw
{
	public class Cocoon : HediffWithComps
	{
		public int tickNext;

		public override void PostMake()
		{
			Severity = 1.0f;
			SetNextTick();
		}

		public override void ExposeData()
		{
			base.ExposeData();
			Scribe_Values.Look(ref tickNext, "tickNext", 1000, true);
		}

		public override void Tick()
		{
			if (Find.TickManager.TicksGame >= tickNext)
			{
				//Log.Message("Cocoon::Tick() " + base.xxx.get_pawnname(pawn));
				HealWounds();
				SatisfyHunger();
				SatisfyThirst();
				SetNextTick();
			}
		}

		public void HealWounds()
		{
			IEnumerable<Hediff> enumerable = from hd in pawn.health.hediffSet.hediffs
											 where !hd.IsTended() && hd.TendableNow()
											 select hd;
			if (enumerable != null)
			{
				foreach (Hediff item in enumerable)
				{
					HediffWithComps val = item as HediffWithComps;
					if (val != null)
						if (val.Bleeding)
						{
							//Log.Message("TrySealWounds " + xxx.get_pawnname(pawn) + ", Bleeding " + item.Label);
							//HediffComp_TendDuration val2 = HediffUtility.TryGetComp<HediffComp_TendDuration>(val);
							val.Heal(0.5f);
							//val2.tendQuality = 1f;
							//val2.tendTicksLeft = 10000;
							//pawn.health.Notify_HediffChanged(item);
						}
						// tend infections
						// tend lifeThreatening chronic
						else if ((!val.def.chronic && val.def.lethalSeverity > 0f) || (val.CurStage?.lifeThreatening ?? false))
						{
							//Log.Message("TryHeal " + xxx.get_pawnname(pawn) + ", infection(?) " + item.Label);
							HediffComp_TendDuration val2 = HediffUtility.TryGetComp<HediffComp_TendDuration>(val);
							val2.tendQuality = 1f;
							val2.tendTicksLeft = 10000;
							pawn.health.Notify_HediffChanged(item);
						}
				}
			}
		}

		public void SatisfyHunger()
		{
			Need_Food need = pawn.needs.TryGetNeed<Need_Food>();
			if (need == null)
			{
				return;
			}
			//pawn.PositionHeld.IsInPrisonCell(pawn.Map)
			//Log.Message("Cocoon::SatisfyHunger() " + xxx.get_pawnname(pawn) + " IsInPrisonCell " + pawn.PositionHeld.IsInPrisonCell(pawn.Map));
			//Log.Message("Cocoon::SatisfyHunger() " + xxx.get_pawnname(pawn) + " GetRoom " + pawn.PositionHeld.GetRoom(pawn.Map));
			//Log.Message("Cocoon::SatisfyHunger() " + xxx.get_pawnname(pawn) + " GetRoom " + pawn.PositionHeld.GetZone(pawn.Map));

			if (need.CurLevel < 0.15f)
			{
				//Log.Message("Cocoon::SatisfyHunger() " + xxx.get_pawnname(pawn) + " need to eat");
				float nutrition_amount = need.MaxLevel / 5f;
				pawn.needs.food.CurLevel += nutrition_amount;
			}
		}

		public void SatisfyThirst()
		{
			if (!xxx.DubsBadHygieneIsActive)
				return;

			Need need = pawn.needs.AllNeeds.Find(x => x.def == xxx.DBHThirst);
			if (need == null)
			{
				return;
			}

			if (need.CurLevel < 0.15f)
			{
				//Log.Message("Cocoon::SatisfyThirst() " + xxx.get_pawnname(pawn) + " need to drink");
				float nutrition_amount = need.MaxLevel / 5f;
				pawn.needs.TryGetNeed(need.def).CurLevel += nutrition_amount;
			}
		}

		public void SetNextTick()
		{
			//make actual tick every 16.6 sec
			tickNext = Find.TickManager.TicksGame + 1000;
			//Log.Message("Cocoon::SetNextTick() " + tickNext);
		}
	}
}


code:
using Verse;
using RimWorld;

namespace rjw
{
	public class Hediff_NaturalSexPart : HediffWithComps, ISexPartHediff
	{
		public override bool ShouldRemove => false;

		public HediffDef_SexPart Def => def as HediffDef_SexPart;

		public HediffWithComps AsHediff => this;

		public override float Severity {
			get => base.Severity;
			set
			{
				var prevSeverity = base.Severity;
				base.Severity = value;
				ISexPartHediffExtensions.DetectExternalSeverityChange(this, prevSeverity, value);
			}
		}

		public override string LabelBase
		{
			get
			{
				/*
				 * make patch to make/save capmods?
				if (CapMods.Count < 5)
				{
					PawnCapacityModifier pawnCapacityModifier = new PawnCapacityModifier();
					pawnCapacityModifier.capacity = PawnCapacityDefOf.Moving;
					pawnCapacityModifier.offset += 0.5f;
					CapMods.Add(pawnCapacityModifier);
				}
				*/

				//name/kind
				return def.label;
			}
		}

		/// <summary>
		/// stack hediff in health tab?
		/// </summary>
		public override int UIGroupKey
		{
			get
			{
				return loadID;
			}
		}

		/// <summary>
		/// do not merge same rjw parts into one
		/// </summary>
		public override bool TryMergeWith(Hediff other)
		{
			return false;
		}
	}
}


code:
using Verse;

//Hediff worker for pawns' "lay down and submit" button
namespace rjw
{
	public class Hediff_Submitting: HediffWithComps
	{
		public override bool ShouldRemove {
			get
			{
				Pawn daddy = pawn.CarriedBy;
				if (daddy != null && daddy.Faction == pawn.Faction)
				{
					return true;
				}
				else
					return base.ShouldRemove;
			}
		}
	}
}


code:
using Verse;
using UnityEngine;
using rjw.Modules.Shared.Extensions;

namespace rjw
{
	// Would be nice to call this just 'ISexPart', but ILewdablePart already exists and represents something similar but different.
	public interface ISexPartHediff
	{
		HediffDef_SexPart Def { get; }

		T GetComp<T>() where T : HediffComp;

		HediffWithComps AsHediff { get; }
	}

	public static class ISexPartHediffExtensions
	{
		public static HediffComp_SexPart GetPartComp(this ISexPartHediff partHediff) => partHediff.GetComp<HediffComp_SexPart>();

		public static Pawn GetOwner(this ISexPartHediff part) => part.AsHediff.pawn;

		public static void DetectExternalSeverityChange(HediffWithComps hediff, float prevValue, float newValue)
		{
			if(Find.TickManager.Paused && prevValue != newValue)
			{
				if(hediff.TryGetComp<HediffComp_SexPart>(out var comp))
				{
					if (newValue != comp.GetSeverity())
					{
						ModLog.Message($"DetectExternalSeverityChange: {hediff.LabelBaseCap} ({hediff.pawn.GetName()}), {prevValue} -> {newValue}.");
						comp.SetSeverity(newValue, sync: false);
					}
				}
			}
		}
	}
}


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

namespace rjw
{
	public class PartAdder
	{
		public float chance = 0f;
		public string rjwPart;
		public List<string> bodyParts;
	}
}


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

namespace rjw
{
	public static class PartSizeCalculator
	{
		public static bool TryGetLength(Hediff hediff, out float length)
		{
			if (!hediff.TryGetComp<HediffComp_SexPart>(out var comp))
			{
				length = 0;
				return false;
			}

			return Internal.TryGetLength(hediff.def, Internal.GetPartSeverity(hediff), Internal.GetBodySize(hediff), out length);
		}

		public static bool TryGetGirth(Hediff hediff, out float girth)
		{
			if (!hediff.TryGetComp<HediffComp_SexPart>(out var comp))
			{
				girth = 0;
				return false;
			}

			return Internal.TryGetGirth(hediff.def, Internal.GetPartSeverity(hediff), Internal.GetBodySize(hediff), out girth);
		}

		public static bool TryGetPenisWeight(Hediff hediff, out float weight)
		{
			if (!TryGetLength(hediff, out float length) ||
				!TryGetGirth(hediff, out float girth))
			{
				weight = 0f;
				return false;
			}

			var density = Curves.GetSizeConfig(hediff).density;
			if (density == null)
			{
				weight = 0f;
				return false;
			}

			var r = girth / (2.0 * Math.PI);
			var volume = r * r * Math.PI * length;

			weight = (float)(volume * density.Value / 1000f);
			return true;
		}

		public static bool TryGetBreastSize(Hediff hediff, out BreastSize breastSize)
		{
			if (!hediff.TryGetComp<HediffComp_SexPart>(out var comp))
			{
				breastSize = new BreastSize(0, 0, 1);
				return false;
			}

			return Internal.TryGetBreastSize(hediff.def, Internal.GetPartSeverity(hediff), Internal.GetBodySize(hediff), out breastSize);
		}

		public class Internal
		{
			public static float GetBodySize(Hediff hediff)
			{
				if (hediff.TryGetComp<HediffComp_SexPart>(out var comp))
				{
					return comp.GetBodySize();
				}
				return hediff.pawn.BodySize;
			}

			public static float GetPartSeverity(Hediff hediff)
			{
				if (hediff.TryGetComp<HediffComp_SexPart>(out var comp))
				{
					return comp.GetSeverity();
				}
				return hediff.Severity;
			}

			public static bool TryGetLength(HediffDef hediffDef, float severity, float bodySize, out float length)
			{
				var curve = Curves.LengthCurve(hediffDef);

				if(!Curves.EvaluateCurve(curve, severity, bodySize, out length)) {
					length = 0;
					return false;
				}

				return true;
			}

			public static bool TryGetGirth(HediffDef hediffDef, float severity, float bodySize, out float girth)
			{
				var curve = Curves.GirthCurve(hediffDef);

				if(!Curves.EvaluateCurve(curve, severity, bodySize, out girth)) {
					girth = 0;
					return false;
				}

				return true;
			}

			public static bool TryGetCupSize(HediffDef hediffDef, float severity, out float cupSize)
			{
				var curve = Curves.CupSizeCurve(hediffDef);

				if(!Curves.EvaluateCurve(curve, severity, 1.0f, out cupSize)) {
					cupSize = 0;
					return false;
				}

				return true;
			}

			public static bool TryGetBandSize(HediffDef hediffDef, float bodySize, out float bandSize)
			{
				var baseBandSize = BraSizeConfigDef.Instance.bandSizeBase;

				bandSize = (float)Math.Round(baseBandSize * bodySize / 2) * 2;

				return true;
			}

			public static bool TryGetBreastSize(HediffDef hediffDef, float severity, float bodySize, out BreastSize breastSize)
			{
				var density = Curves.GetSizeConfig(hediffDef).density;
				if (density == null)
				{
					density = 1.0f;
				}

				breastSize = new BreastSize(0, 0, 1);

				if(!TryGetCupSize(hediffDef, severity, out var cupSize))
				{
					return false;
				}

				if(!TryGetBandSize(hediffDef, bodySize, out var bandSize))
				{
					return false;
				}

				breastSize = new BreastSize(cupSize, bandSize, density.Value);
				return true;
			}
		}

		public static class Curves
		{
			public static SimpleCurve LengthCurve(HediffDef def)
			{
				return BuildCurve(def.stages, GetSizeConfig(def)?.lengths);
			}

			public static SimpleCurve GirthCurve(HediffDef def)
			{
				return BuildCurve(def.stages, GetSizeConfig(def)?.girths);
			}

			public static SimpleCurve CupSizeCurve(HediffDef def)
			{
				return BuildCurve(def.stages, GetSizeConfig(def)?.cupSizes);
			}

			public static SimpleCurve BuildCurve(List<HediffStage> stages, List<float> stageSizes)
			{
				if(stageSizes == null) return null;
				return new SimpleCurve(stages.Zip(stageSizes, (stage, stageSize) => new CurvePoint(stage.minSeverity, stageSize)));
			}

			public static bool EvaluateCurve(SimpleCurve curve, float input, float scale, out float measurement)
			{
				if (curve == null) {
					measurement = 0;
					return false;
				}
				measurement = curve.Evaluate(input) * scale;
				return true;
			}

			public static bool EvaluateInvertedCurve(SimpleCurve curve, float measurement, float scale, out float input)
			{
				if (curve == null) {
					input = 0;
					return false;
				}
				input = curve.EvaluateInverted(measurement/scale);
				return true;
			}

			public static PartSizeConfigDef GetSizeConfig(Hediff hediff)
			{
				return GetSizeConfig(hediff.def);
			}

			public static PartSizeConfigDef GetSizeConfig(HediffDef def)
			{
				return (def as HediffDef_SexPart)?.sizeProfile;
			}
		}

		public class Inversion
		{
			public static bool TryInvertLength(HediffDef hediffDef, float length, float bodySize, out float severity)
			{
				var curve = Curves.LengthCurve(hediffDef);

				if(!Curves.EvaluateInvertedCurve(curve, length, bodySize, out severity)) {
					severity = 0;
					return false;
				}

				return true;
			}

			public static bool TryInvertGirth(HediffDef hediffDef, float girth, float bodySize, out float severity)
			{
				var curve = Curves.GirthCurve(hediffDef);

				if(!Curves.EvaluateInvertedCurve(curve, girth, bodySize, out severity)) {
					severity = 0;
					return false;
				}

				return true;
			}

			public static bool TryInvertCupSize(HediffDef hediffDef, float cupSize, out float severity)
			{
				var curve = Curves.CupSizeCurve(hediffDef);

				if(!Curves.EvaluateInvertedCurve(curve, cupSize, 1.0f, out severity)) {
					severity = 0;
					return false;
				}

				return true;
			}

			public static bool TryInvertBreastWeight(HediffDef hediffDef, float weight, float bodySize, out float severity, out BreastSize breastSize)
			{
				var density = Curves.GetSizeConfig(hediffDef).density;
				if (density == null)
				{
					severity = 0f;
					breastSize = new BreastSize(0, 0, 1);
					return false;
				}

				var volume = weight / density.Value;
				return TryInvertBreastVolume(hediffDef, volume, bodySize, out severity, out breastSize);
			}

			public static bool TryInvertBreastVolume(HediffDef hediffDef, float volume, float bodySize, out float severity, out BreastSize breastSize)
			{
				severity = 0f;
				breastSize = new BreastSize(0, 0, 1);

				if(!Internal.TryGetBandSize(hediffDef, bodySize, out var bandSize))
				{
					return false;
				}

				var cupSize = BreastSize.CalculateCupSize(volume, bandSize);

				if(!TryInvertCupSize(hediffDef, cupSize, out severity))
				{
					return false;
				}

				var density = Curves.GetSizeConfig(hediffDef).density ?? 1.0f;

				breastSize = new BreastSize(cupSize, bandSize, density);

				return true;
			}
		}

		public class Modify
		{
			public static bool TryModifyLength(Hediff hediff, Func<float, float> lengthModifier, out float newSeverity)
			{
				if(!TryGetLength(hediff, out var length))
				{
					newSeverity = 0;
					return false;
				}

				return Inversion.TryInvertLength(hediff.def, lengthModifier(length), Internal.GetBodySize(hediff), out newSeverity);
			}

			public static bool TryModifyGirth(Hediff hediff, Func<float, float> girthModifier, out float newSeverity)
			{
				if(!TryGetGirth(hediff, out var girth))
				{
					newSeverity = 0;
					return false;
				}

				return Inversion.TryInvertGirth(hediff.def, girthModifier(girth), Internal.GetBodySize(hediff), out newSeverity);
			}

			public static bool TryModifyCupSize(Hediff hediff, Func<float, float> cupSizeModifier, out float newSeverity)
			{
				if(!Internal.TryGetCupSize(hediff.def, Internal.GetPartSeverity(hediff), out var cupSize))
				{
					newSeverity = 0;
					return false;
				}

				return Inversion.TryInvertCupSize(hediff.def, cupSizeModifier(cupSize), out newSeverity);
			}

			public static bool TryModifyBreastVolume(Hediff hediff, Func<float, float> volumeModifier, out float newSeverity)
			{
				if(!TryGetBreastSize(hediff, out var breastSize))
				{
					newSeverity = 0;
					return false;
				}

				return Inversion.TryInvertBreastVolume(hediff.def, volumeModifier(breastSize.volume), Internal.GetBodySize(hediff), out newSeverity, out _);
			}

			public static bool TryModifyBreastWeight(Hediff hediff, Func<float, float> weightModifier, out float newSeverity)
			{
				if(!TryGetBreastSize(hediff, out var breastSize))
				{
					newSeverity = 0;
					return false;
				}

				return Inversion.TryInvertBreastWeight(hediff.def, weightModifier(breastSize.weight), Internal.GetBodySize(hediff), out newSeverity, out _);
			}
		}
	}
}


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

namespace rjw
{
	public class PartSizeConfigDef : Def
	{
			public bool bodysizescale = false; // rescales parts sizes based on bodysize of initial owner race

			/// <summary>
			/// Human standard would be 1.0. Null for no weight display.
			/// </summary>
			public float? density = null;

			public List<float> lengths;
			public List<float> girths;
			public List<float> cupSizes;
	}
}


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

namespace rjw
{
	public class SexFluidDef : Def
	{
		public ThingDef filth;

		public ThingDef consumable;

		public float consumableFluidRatio = 1;

		public bool ingestThroughAnyOrifice;

		public bool alwaysProduceFilth;

		public float baseNutrition;

		public float baseNutritionCost = 1;

		public bool quenchesThirst = true;

		public List<string> tags = new List<string>();

		public List<SexFluidIngestionDoer> ingestionDoers;

		public override IEnumerable<string> ConfigErrors()
		{
			foreach (string err in base.ConfigErrors())
			{
				yield return err;
			}
			if (filth != null && filth.filth == null)
			{
				yield return $"{nameof(filth)} must be a ThingDef with a <filth> field.";
			}
			if (consumable != null && baseNutrition != 0)
			{
				yield return $"{nameof(consumable)} is set, so {nameof(baseNutrition)} is meaningless.";
			}
		}

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

			if (consumable != null)
			{
				descriptionHyperlinks ??= new();
				descriptionHyperlinks.AddDistinct(consumable);
			}
		}

	}
}


code:
using Verse;

namespace rjw
{
	public abstract class SexFluidIngestionDoer
	{
		public abstract void Ingested(Pawn pawn, SexFluidDef fluid, float amount, ISexPartHediff fromPart, ISexPartHediff toPart = null);
	}
}


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

using RimWorld;
using Verse;

namespace rjw
{
	internal class InteractionWorker_AnalSexAttempt : InteractionWorker
	{
		//initiator - rapist
		//recipient - victim
		public static bool AttemptAnalSex(Pawn initiator, Pawn recipient)
		{
			//--Log.Message(xxx.get_pawnname(initiator) + " is attempting to anally rape " + xxx.get_pawnname(recipient));
			return true;
		}

		public override float RandomSelectionWeight(Pawn initiator, Pawn recipient)
		{
			// this interaction is triggered by the jobdriver
			if (initiator == null || recipient == null)
				return 0.0f;

			return 0.0f; // base.RandomSelectionWeight(initiator, recipient);
		}

		public override void Interacted(Pawn initiator, Pawn recipient, List<RulePackDef> extraSentencePacks, out string letterText, out string letterLabel, out LetterDef letterDef, out LookTargets lookTargets)
		{
			//add something fancy here later?
			letterText = null;
			letterLabel = null;
			letterDef = null;
			lookTargets = recipient;
			//Find.LetterStack.ReceiveLetter("Rape attempt", "A wandering nymph has decided to join your colony.", LetterDefOf.NegativeEvent, recipient);

			if (initiator == null || recipient == null)
				return;
			//--ModLog.Message(" InteractionWorker_AnalRapeAttempt::Interacted( " + xxx.get_pawnname(initiator) + ", " + xxx.get_pawnname(recipient) + " ) called");
			AttemptAnalSex(initiator, recipient);
		}
	}

	internal class InteractionWorker_VaginalSexAttempt : InteractionWorker
	{
		//initiator - rapist
		//recipient - victim
		public static bool AttemptAnalSex(Pawn initiator, Pawn recipient)
		{
			//--Log.Message(xxx.get_pawnname(initiator) + " is attempting to anally rape " + xxx.get_pawnname(recipient));
			return false;
		}

		public override float RandomSelectionWeight(Pawn initiator, Pawn recipient)
		{
			// this interaction is triggered by the jobdriver
			if (initiator == null || recipient == null)
				return 0.0f;

			return 0.0f; // base.RandomSelectionWeight(initiator, recipient);
		}

		public override void Interacted(Pawn initiator, Pawn recipient, List<RulePackDef> extraSentencePacks, out string letterText, out string letterLabel, out LetterDef letterDef, out LookTargets lookTargets)
		{
			//add something fancy here later?
			letterText = null;
			letterLabel = null;
			letterDef = null;
			lookTargets = recipient;
			//Find.LetterStack.ReceiveLetter("Rape attempt", "A wandering nymph has decided to join your colony.", LetterDefOf.NegativeEvent, recipient);

			if (initiator == null || recipient == null)
				return;
			//--ModLog.Message(" InteractionWorker_AnalRapeAttempt::Interacted( " + xxx.get_pawnname(initiator) + ", " + xxx.get_pawnname(recipient) + " ) called");
			AttemptAnalSex(initiator, recipient);
		}
	}

	internal class InteractionWorker_OtherSexAttempt : InteractionWorker
	{
		//initiator - rapist
		//recipient - victim
		public static bool AttemptAnalSex(Pawn initiator, Pawn recipient)
		{
			//--Log.Message(xxx.get_pawnname(initiator) + " is attempting to anally rape " + xxx.get_pawnname(recipient));
			return false;
		}

		public override float RandomSelectionWeight(Pawn initiator, Pawn recipient)
		{
			// this interaction is triggered by the jobdriver
			if (initiator == null || recipient == null)
				return 0.0f;

			return 0.0f; // base.RandomSelectionWeight(initiator, recipient);
		}

		public override void Interacted(Pawn initiator, Pawn recipient, List<RulePackDef> extraSentencePacks, out string letterText, out string letterLabel, out LetterDef letterDef, out LookTargets lookTargets)
		{
			//add something fancy here later?
			letterText = null;
			letterLabel = null;
			letterDef = null;
			lookTargets = recipient;
			//Find.LetterStack.ReceiveLetter("Rape attempt", "A wandering nymph has decided to join your colony.", LetterDefOf.NegativeEvent, recipient);

			if (initiator == null || recipient == null)
				return;
			//--ModLog.Message(" InteractionWorker_AnalRapeAttempt::Interacted( " + xxx.get_pawnname(initiator) + ", " + xxx.get_pawnname(recipient) + " ) called");
			AttemptAnalSex(initiator, recipient);
		}
	}
}


code:
using System;
using System.Collections.Generic;
using System.Linq;
using Verse;
using Verse.Grammar;

using rjw.Modules.Interactions;
using rjw.Modules.Shared.Enums;
using RimWorld;

namespace rjw
{

	public enum SexInteractionType
	{
		Undefined, Masturbation, Consensual, Whoring, Rape, Bestiality, Animal, Necrophilia, Mechanoid
	}
	public enum SexInteractionTag // Extends InteractionType
	{
		Undefined, Masturbation, Consensual, Whoring, Rape, Bestiality, Animal, Necrophilia, Mechanoid,
		Reverse, Fertilization, EggFertilization, EggLaying, MechImplant, NonPenetrative
	}
	public class SexInteractionRequirement
	{
		public int? minimumCount = 1;
		public float? minimumSeverity;
		public List<string> partTags = new List<string>();
		public List<VanillaPartFamily> partFamilies = new List<VanillaPartFamily>();
		public List<GenitalTag> genitalTags = new List<GenitalTag>();
		public List<GenitalFamily> genitalFamilies = new List<GenitalFamily>();
		public List<PawnState> pawnStates = new List<PawnState>();

		public bool IsOrifice()
		{
			return genitalTags.Any(t => t == GenitalTag.CanBePenetrated)
				|| genitalFamilies.Any(f => f.AsLewdPartFamily().SatisfiesTag(GenitalTag.CanBePenetrated))
				|| partFamilies.Any(f => f.AsLewdPartFamily().SatisfiesTag(GenitalTag.CanBePenetrated));
		}

		public bool IsPenetrator()
		{
			return genitalTags.Any(t => t == GenitalTag.CanPenetrate)
				|| genitalFamilies.Any(f => f.AsLewdPartFamily().SatisfiesTag(GenitalTag.CanPenetrate))
				|| partFamilies.Any(f => f.AsLewdPartFamily().SatisfiesTag(GenitalTag.CanPenetrate));
		}

		public bool UsesPart(LewdablePartFamily part)
		{
			return genitalFamilies.Any(f => f.AsLewdPartFamily() == part)
				|| partFamilies.Any(f => f.AsLewdPartFamily() == part)
				|| genitalTags.Any(t => part.SatisfiesTag(t));
		}
	}

	public class SexInteractionExtension : DefModExtension
	{
		public string RMBLabel = ""; // rmb menu
		public string rjwSextype = ""; // xxx.rjwSextype
		public List<RulePackDef> extraSentencePacks;
		public List<SexInteractionTag> tags = new List<SexInteractionTag>();
		public SexInteractionRequirement initiatorRequirement;
		public SexInteractionRequirement recipientRequirement;
	}
}


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

namespace rjw
{
	public class JobDriver_BestialityForFemale : JobDriver_SexBaseInitiator
	{
		public IntVec3 SleepSpot => Bed.SleepPosOfAssignedPawn(pawn);
		public override bool TryMakePreToilReservations(bool errorOnFailed)
		{
			return pawn.Reserve(Target, job, 1, 0, null, errorOnFailed);
		}

		[SyncMethod]
		protected override IEnumerable<Toil> MakeNewToils()
		{
			setup_ticks();
			var PartnerJob = xxx.gettin_loved;

			this.FailOnDespawnedOrNull(iTarget);
			this.FailOnDespawnedNullOrForbidden(iBed);
			this.FailOn(() => !pawn.CanReserveAndReach(Partner, PathEndMode.Touch, Danger.Deadly));
			this.FailOn(() => pawn.Drafted);
			this.FailOn(() => Partner.IsFighting());
			this.FailOn(() => !Partner.CanReach(SleepSpot, PathEndMode.Touch, Danger.Deadly)); //changed to SleepSpot as partner will only move to bed

            yield return Toils_Reserve.Reserve(iTarget, 1, 0);
			yield return Toils_Goto.GotoThing(iTarget, PathEndMode.Touch);

			var gotoBed = new Toil();
			gotoBed.defaultCompleteMode = ToilCompleteMode.PatherArrival;
			gotoBed.initAction = delegate
			{
				pawn.pather.StartPath(SleepSpot, PathEndMode.OnCell);
				Partner.jobs.StopAll();
				Job job = JobMaker.MakeJob(JobDefOf.GotoMindControlled, SleepSpot);
				Partner.jobs.StartJob(job, JobCondition.InterruptForced);
			};
			gotoBed.FailOnDespawnedOrNull(iBed); //Changed from FailOnBedNoLongerUsable(iBed) due to pawn unable to use not owned bed.
			gotoBed.AddFailCondition(() => Partner.Downed);
			yield return gotoBed;

			var waitInBed = new Toil();
			waitInBed.defaultCompleteMode = ToilCompleteMode.Delay;
			waitInBed.initAction = delegate
			{
				ticksLeftThisToil = 5000;
			};
			waitInBed.tickAction = delegate
			{
				pawn.GainComfortFromCellIfPossible();
				if (IsInOrByBed(Bed, Partner) && pawn.PositionHeld == Partner.PositionHeld)
				{
					ReadyForNextToil();
				}
			};
			waitInBed.FailOn(() => pawn.GetRoom(RegionType.Set_Passable) == null);
			yield return waitInBed;

			var StartPartnerJob = new Toil();
			StartPartnerJob.defaultCompleteMode = ToilCompleteMode.Instant;
			StartPartnerJob.socialMode = RandomSocialMode.Off;
			StartPartnerJob.initAction = delegate
			{
				var gettin_loved = JobMaker.MakeJob(PartnerJob, pawn, Bed);
				Partner.jobs.StartJob(gettin_loved, JobCondition.InterruptForced);
			};
			yield return StartPartnerJob;

			var SexToil = new Toil();
			SexToil.defaultCompleteMode = ToilCompleteMode.Never;
			SexToil.socialMode = RandomSocialMode.Off;
			SexToil.handlingFacing = true;
			SexToil.initAction = delegate
			{
				Start();

				// TODO: replace this quick n dirty way
				CondomUtility.GetCondomFromRoom(pawn);
				// Try to use whore's condom first, then client's
				Sexprops.usedCondom = CondomUtility.TryUseCondom(pawn) || CondomUtility.TryUseCondom(Partner);
				if (Sexprops.usedCondom)
				{
					var receiverDriver = Partner?.jobs?.curDriver as JobDriver_SexBaseReciever;
					if (receiverDriver is not null && receiverDriver.Sexprops != null)
						receiverDriver.Sexprops.usedCondom = true;
				}
			};
			SexToil.FailOn(() => Partner.Dead);
			SexToil.FailOn(() => Partner.CurJob?.def != PartnerJob);
			SexToil.AddPreTickAction(delegate
			{
				if (pawn.IsHashIntervalTick(ticks_between_hearts))
					if (xxx.is_zoophile(pawn))
						ThrowMetaIconF(pawn.Position, pawn.Map, FleckDefOf.Heart);
					else
						ThrowMetaIconF(pawn.Position, pawn.Map, xxx.mote_noheart);
				SexTick(pawn, Partner);
				SexUtility.reduce_rest(Partner, 2);
				SexUtility.reduce_rest(pawn, 1);
				if (ticks_left <= 0)
					ReadyForNextToil();
			});
			SexToil.AddFinishAction(End);
			yield return SexToil;

			yield return new Toil
			{
				initAction = () => SexUtility.ProcessSex(Sexprops),
				defaultCompleteMode = ToilCompleteMode.Instant
			};
		}
	}
}


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

namespace rjw
{
	public class JobDriver_BestialityForMale : JobDriver_Rape
	{
		public override bool TryMakePreToilReservations(bool errorOnFailed)
		{
			return pawn.Reserve(Target, job, 1, 0, null, errorOnFailed);
		}

		[SyncMethod]
		protected override IEnumerable<Toil> MakeNewToils()
		{
			//--ModLog.Message(" JobDriver_BestialityForMale::MakeNewToils() called");

			setup_ticks();
			var PartnerJob = xxx.gettin_bred;

			//this.FailOn (() => (!Partner.health.capacities.CanBeAwake) || (!comfort_prisoners.is_designated (Partner)));
			// Fail if someone else reserves the prisoner before the pawn arrives or colonist can't reach animal
			this.FailOn(() => !pawn.CanReserveAndReach(Partner, PathEndMode.Touch, Danger.Deadly));
			this.FailOn(() => Partner.HostileTo(pawn));
			this.FailOnDespawnedNullOrForbidden(iTarget);
			this.FailOn(() => pawn.Drafted);

			yield return Toils_Reserve.Reserve(iTarget, 1, 0);
			yield return Toils_Sex.RapeTargetAlert(pawn, Partner);
			//ModLog.Message(" JobDriver_BestialityForMale::MakeNewToils() - moving towards animal");
			yield return Toils_Goto.GotoThing(iTarget, PathEndMode.Touch);
			yield return Toils_Interpersonal.WaitToBeAbleToInteract(pawn);
			yield return Toils_Interpersonal.GotoInteractablePosition(iTarget);

			if (xxx.is_kind(pawn)
				|| (xxx.CTIsActive && xxx.has_traits(pawn) && pawn.story.traits.HasTrait(xxx.RCT_AnimalLover)))
			{
				yield return TalkToAnimal(pawn, Partner);
				yield return TalkToAnimal(pawn, Partner);
			}

			if (Rand.Chance(0.6f))
				yield return TalkToAnimal(pawn, Partner);

			yield return Toils_Goto.GotoThing(iTarget, PathEndMode.OnCell);

			Toil StartPartnerJob = new Toil();
			StartPartnerJob.defaultCompleteMode = ToilCompleteMode.Instant;
			StartPartnerJob.socialMode = RandomSocialMode.Off;
			StartPartnerJob.initAction = delegate
			{
				//--ModLog.Message(" JobDriver_BestialityForMale::MakeNewToils() - Setting animal job driver");
				var dri = Partner.jobs.curDriver as JobDriver_SexBaseRecieverRaped;
				if (dri == null)
				{
					//wild animals may flee or attack
					if (pawn.Faction != Partner.Faction && Partner.RaceProps.wildness > Rand.Range(0.22f, 1.0f)
						&& !(pawn.TicksPerMoveCardinal < (Partner.TicksPerMoveCardinal / 2) && !Partner.Downed && xxx.is_not_dying(Partner)))
					{
						Partner.jobs.StopAll(); // Wake up animal if sleeping.

						float aggro = Partner.kindDef.RaceProps.manhunterOnTameFailChance;
						if (Partner.kindDef.RaceProps.predator)
							aggro += 0.2f;
						else
							aggro -= 0.1f;

						//wild animals may attack
						if (Rand.Chance(aggro) && Partner.CanSee(pawn))
						{
							Partner.rotationTracker.FaceTarget(pawn);
							LifeStageUtility.PlayNearestLifestageSound(Partner, (ls) => ls.soundAngry, null,null, 1.4f);
							ThrowMetaIconF(Partner.Position, Partner.Map, FleckDefOf.IncapIcon);
							ThrowMetaIcon(pawn.Position, pawn.Map, ThingDefOf.Mote_ColonistFleeing); //red '!'
							Partner.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Manhunter);
							if (Partner.kindDef.RaceProps.herdAnimal && Rand.Chance(0.2f))
							{ // 20% chance of turning the whole herd hostile...
								List<Pawn> packmates = Partner.Map.mapPawns.AllPawnsSpawned.Where(x =>
									x != Partner && x.def == Partner.def && x.Faction == Partner.Faction &&
									x.Position.InHorDistOf(Partner.Position, 24f) && x.CanSee(Partner)).ToList();

								foreach (Pawn packmate in packmates)
								{
									packmate.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Manhunter);
								}
							}
							Messages.Message(pawn.Name.ToStringShort + " is being attacked by " + xxx.get_pawnname(Partner) + ".", pawn, MessageTypeDefOf.ThreatSmall);
						}
						//wild animals may flee
						else
						{
							ThrowMetaIcon(Partner.Position, Partner.Map, ThingDefOf.Mote_ColonistFleeing);
							LifeStageUtility.PlayNearestLifestageSound(Partner, (ls) => ls.soundCall, g => g.soundCall, null);
							Partner.mindState.StartFleeingBecauseOfPawnAction(pawn);
							Partner.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.PanicFlee);
						}
						pawn.jobs.EndCurrentJob(JobCondition.Incompletable);
					}
					else
					{
						Job gettin_bred = JobMaker.MakeJob(PartnerJob, pawn, Partner);
						Partner.jobs.StartJob(gettin_bred, JobCondition.InterruptForced, null, true);
					}
				}
			};
			yield return StartPartnerJob;

			Toil SexToil = new Toil();
			SexToil.defaultCompleteMode = ToilCompleteMode.Never;
			SexToil.defaultDuration = duration;
			SexToil.handlingFacing = true;
			SexToil.FailOn(() => Partner.CurJob?.def != PartnerJob);
			SexToil.initAction = delegate
			{
				Partner.pather.StopDead();
				Partner.jobs.curDriver.asleep = false;
				Start();
			};
			SexToil.tickAction = delegate
			{
				if (pawn.IsHashIntervalTick(ticks_between_hearts))
					if (xxx.is_zoophile(pawn))
						ThrowMetaIconF(pawn.Position, pawn.Map, FleckDefOf.Heart);
					else
						ThrowMetaIconF(pawn.Position, pawn.Map, xxx.mote_noheart);
				SexTick(pawn, Partner);
				//no hitting wild animals, and getting rect by their Manhunter
				/*
				if (pawn.IsHashIntervalTick (ticks_between_hits))
					roll_to_hit (pawn, Partner);
					*/
				SexUtility.reduce_rest(Partner, 1);
				SexUtility.reduce_rest(pawn, 2);
				if (ticks_left <= 0)
					ReadyForNextToil();
			};
			SexToil.AddFinishAction(delegate
			{
				End();
			});
			yield return SexToil;

			yield return new Toil
			{
				initAction = delegate
				{
					//ModLog.Message(" JobDriver_BestialityForMale::MakeNewToils() - creating aftersex toil");
					SexUtility.ProcessSex(Sexprops);
				},
				defaultCompleteMode = ToilCompleteMode.Instant
			};
		}

		[SyncMethod]
		private Toil TalkToAnimal(Pawn pawn, Pawn animal)
		{
			Toil toil = new Toil();
			toil.initAction = delegate
			{
				pawn.interactions.TryInteractWith(animal, SexUtility.AnimalSexChat);
			};
			//Rand.PopState();
			//Rand.PushState(RJW_Multiplayer.PredictableSeed());
			toil.defaultCompleteMode = ToilCompleteMode.Delay;
			toil.defaultDuration = Rand.Range(120, 220);
			return toil;
		}
	}
}


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

namespace rjw
{
	/// <summary>
	/// This is the driver for animals mounting breeders.
	/// </summary>
	public class JobDriver_Breeding : JobDriver_Rape
	{
		public override bool TryMakePreToilReservations(bool errorOnFailed)
		{
			return pawn.Reserve(Target, job, BreederHelper.max_animals_at_once, 0);
		}

		[SyncMethod]
		protected override IEnumerable<Toil> MakeNewToils()
		{
			setup_ticks();
			var PartnerJob = xxx.gettin_raped;

			//--Log.Message("JobDriver_Breeding::MakeNewToils() - setting fail conditions");
			this.FailOnDespawnedNullOrForbidden(iTarget);
			this.FailOn(() => !pawn.CanReserve(Partner, BreederHelper.max_animals_at_once, 0)); // Fail if someone else reserves the target before the animal arrives.
			this.FailOn(() => !pawn.CanReach(Partner, PathEndMode.Touch, Danger.Some)); // Fail if animal cannot reach target.
			this.FailOn(() => pawn.Drafted);

			if (!(pawn.IsAnimal() && Partner.IsAnimal()))
			{
				yield return Toils_Sex.RapeTargetAlert(pawn, Partner);
			}

			// Path to target
			yield return Toils_Goto.GotoThing(iTarget, PathEndMode.OnCell);

			var StartPartnerJob = new Toil();
			StartPartnerJob.defaultCompleteMode = ToilCompleteMode.Instant;
			StartPartnerJob.socialMode = RandomSocialMode.Off;
			StartPartnerJob.initAction = delegate
			{
				if (Partner.jobs.curDriver is JobDriver_SexBaseRecieverRaped) return;

				var bed = Partner.CurrentBed();

				Partner.jobs.StartJob(
					JobMaker.MakeJob(PartnerJob, pawn),
					lastJobEndCondition: JobCondition.InterruptForced
				);

				if (bed is not null)
					if (Partner.jobs.curDriver is JobDriver_SexBaseRecieverRaped driver)
						driver.Set_bed(bed);
			};
			yield return StartPartnerJob;

			// Use happy heart instead of bad-touch heart when accepting of breeding.
			var fleckDef = xxx.is_zoophile(pawn) || xxx.is_animal(pawn) ? FleckDefOf.Heart : xxx.mote_noheart;

			// Breed target
			var SexToil = new Toil();
			SexToil.defaultCompleteMode = ToilCompleteMode.Never;
			SexToil.defaultDuration = duration;
			SexToil.handlingFacing = true;
			SexToil.initAction = delegate
			{
				Partner.pather.StopDead();
				Partner.jobs.curDriver.asleep = false;
				Start();
			};
			SexToil.tickAction = delegate
			{
				if (pawn.IsHashIntervalTick(ticks_between_hearts))
					ThrowMetaIconF(pawn.Position, pawn.Map, fleckDef);
				SexTick(pawn, Partner);
				if (!Partner.Dead)
					SexUtility.reduce_rest(Partner, 1);
				SexUtility.reduce_rest(pawn, 2);
				if (ticks_left <= 0)
					ReadyForNextToil();
			};
			SexToil.FailOn(() => Partner.CurJob?.def != PartnerJob);
			SexToil.AddFinishAction(End);
			yield return SexToil;

			yield return new Toil
			{
				initAction = delegate
				{
					//Log.Message("JobDriver_Breeding::MakeNewToils() - Calling aftersex");
					//// Trying to add some interactions and social logs
					Sexprops.isRape = !(pawn.relations.DirectRelationExists(PawnRelationDefOf.Bond, Partner) ||
					 	(xxx.is_animal(pawn) && (pawn.RaceProps.wildness - pawn.RaceProps.petness + 0.18f) > Rand.Range(0.36f, 1.8f)));
					SexUtility.ProcessSex(Sexprops);
				},
				defaultCompleteMode = ToilCompleteMode.Instant
			};
		}
	}
}


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

namespace rjw
{
	//biotech JobDriver_ControlMech
	public class JobDriver_HackMechPregnancy : JobDriver
	{
		private const TargetIndex MechInd = TargetIndex.A;

		private Pawn Mech => (Pawn)job.GetTarget(TargetIndex.A).Thing;

		private int MechControlTime => Mathf.RoundToInt(Mech.GetStatValue(StatDefOf.ControlTakingTime) * 60f);

		public override bool TryMakePreToilReservations(bool errorOnFailed)
		{
			return pawn.Reserve(Mech, job, 1, -1, null, errorOnFailed);
		}

		protected override IEnumerable<Toil> MakeNewToils()
		{
			if (ModsConfig.BiotechActive)
			{
				this.FailOnDestroyedNullOrForbidden(TargetIndex.A);
				yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch);
				yield return Toils_General.WaitWith(TargetIndex.A, MechControlTime, useProgressBar: true, maintainPosture: true, maintainSleep: false, TargetIndex.A).WithEffect(EffecterDefOf.ControlMech, TargetIndex.A);
				Toil toil = ToilMaker.MakeToil("MakeNewToils");
				toil.initAction = delegate
				{
					Hediff_MechanoidPregnancy pregnancy = (Hediff_MechanoidPregnancy)Mech.health.hediffSet.GetFirstHediffOfDef(HediffDef.Named("RJW_pregnancy_mech"));
					pregnancy.Hack();
				};
				toil.PlaySoundAtEnd(SoundDefOf.ControlMech_Complete);
				yield return toil;
			}
		}
	}
}


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

namespace rjw
{
	public class JobDriver_Knotted : JobDriver_Goto
	{
		/// <summary>
		/// Number of ticks to smooth out the start and end transitions.
		/// </summary>
		const int TweenTicks = 10;

		/// <summary>
		/// The pawn's partner.
		/// </summary>
		public Pawn Partner => job.GetTarget(TargetIndex.A).Pawn;

		/// <summary>
		/// Set this to apply a positional offset to this pawn.
		/// </summary>
		private Vector3 forcedBodyOffset = Vector3.zero;
		public override Vector3 ForcedBodyOffset => forcedBodyOffset;

		protected override IEnumerable<Toil> MakeNewToils()
		{
			if (job.def.waitAfterArriving <= 0)
				yield break;

			var waiter = Toils_General.Wait(job.def.waitAfterArriving);

			// TODO: Deal with clothing better.  If the pawn was fucking without
			// clothes, they should still be drawn nude.  Since tying is a separate
			// job and we don't know if this was something like an animal "breeding"
			// someone in their clothing, it isn't straightforward to tell when
			// they should remain nude.  This is probably a sign this should not
			// have been a separate job but actually an extra toil of sex jobs.

			// Just in case.  Animals may only pant, whine, or tug during a tie...
			if (xxx.is_animal(pawn))
				waiter.socialMode = RandomSocialMode.Off;

			// We should have a partner set.  If we don't, use fallback behavior
			// of just waiting (which is how knotting used to work), with none
			// of the partner related enhancements.
			if (Partner is not Pawn partner)
			{
				ModLog.Warning($"Knotting job for {xxx.get_pawnname(pawn)} did not receive a partner.");
				yield return waiter;
				yield break;
			}

			this.FailOnDespawnedOrNull(TargetIndex.A);
			this.FailOnDowned(TargetIndex.A);

			// Detect when the tie breaks early.  This can happen for a number of
			// reasons, but I often saw it when an animal starts being trained
			// during the tie.
			this.FailOn(() => !IsCouplingValid());

			// If another mod patches this method, they can use it to add more
			// complex animation or positioning to the waiter.
			AddAnimation(waiter);

			yield return waiter;
		}

		/// <summary>
		/// <para>Applies some special animaion handling during the tie.</para>
		/// <para>Animation systems can patch this to attach their own actions to
		/// enable more complex animation.</para>
		/// </summary>
		/// <param name="waiter">The wait toil.</param>
		void AddAnimation(Toil waiter)
		{
			if (Partner is not Pawn partner) return;

			// Only if the tie involves an animal will we turn the tie butt-to-butt.
			// Human-likes with knots will just hold their partner close.  <3
			if (!InvolvesAnimal()) return;

			var initTicks = waiter.defaultDuration;
			var remTicks = initTicks;

			waiter.handlingFacing = true;
			waiter.AddPreTickAction(delegate ()
			{
				pawn.rotationTracker.Face(partner.DrawPos);
				pawn.Rotation = pawn.Rotation.Opposite;

				var newOffset = GetOffset();
				if (newOffset == Vector3.zero) return;

				// Tween the offset at the start and end.
				// Can't really smooth it out for an interrupted tie, though.
				var tweenTicks = Math.Min(TweenTicks, Math.Min(initTicks - remTicks, remTicks));
				var curTween = (float)tweenTicks / TweenTicks;
				forcedBodyOffset = newOffset * curTween;

				remTicks -= 1;
			});
		}

		/// <summary>
		/// Gets an offset for the current pawn to improve the visuals.
		/// </summary>
		/// <returns>An offset to apply.</returns>
		public Vector3 GetOffset()
		{
			// Must be an animal.
			if (!xxx.is_animal(pawn))
				return Vector3.zero;

			// Partner must exist and be human.
			if (Partner is not Pawn partner || xxx.is_animal(partner))
				return Vector3.zero;

			// Only applicable for east or west facings.
			if (pawn.Rotation != Rot4.East && pawn.Rotation != Rot4.West)
				return Vector3.zero;

			// Nudge the animal for a better lineup.
			var offset = partner.BodySize * 0.15f;
			var sign = pawn.Rotation == Rot4.West ? -1f : 1f;
			return new Vector3(sign * offset, 0f, -0.2f);
		}

		/// <summary>
		/// Whether this tie involves at least one animal.
		/// </summary>
		/// <returns>Whether the partner and/or pawn is an animal.</returns>
		public bool InvolvesAnimal() => xxx.is_animal(pawn) || xxx.is_animal(Partner);

		/// <summary>
		/// <para>Makes sure that the designated partner is still coupled to this pawn.</para>
		/// <para>For hardiness, this actually checks the partner pawn to see if they're
		/// using either `JobDriver_Sex` or `JobDriver_Knotted`, and the partner is still
		/// this pawn.</para>
		/// </summary>
		/// <returns>Whether the coupling is valid.</returns>
		public bool IsCouplingValid()
		{
			if (Partner is not Pawn partner) return false;

			var result = partner.jobs.curDriver switch
			{
				JobDriver_Knotted knottedDriver => knottedDriver.Partner == pawn,
				JobDriver_Sex sexDriver => sexDriver.Partner == pawn,
				_ => false
			};
			if (result) return true;

			// It's possible our partner is queued to tie, but between jobs.
			if (partner.jobs.jobQueue.FirstOrDefault()?.job is not { } job) return false;
			if (job.def != xxx.knotted) return false;
			return job.AnyTargetIs(pawn);
		}
	}
}


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

namespace rjw
{
	public class JobDriver_Masturbate : JobDriver_SexBaseInitiator
	{
		public override bool TryMakePreToilReservations(bool errorOnFailed)
		{
			return true; // No reservations needed.
		}
		public virtual IntVec3 cell => (IntVec3)job.GetTarget(iCell);

		[SyncMethod]
		protected override void SetupDurationTicks()
		{
			// Faster fapping when frustrated.
			duration = (int)(xxx.is_frustrated(pawn) ? 2500.0f * Rand.Range(0.2f, 0.7f) : 2500.0f * Rand.Range(0.2f, 0.4f));
			ticks_left = duration;
		}

		protected override void SetupOrgasmTicks()
		{
			orgasmstick = 180;
			sex_ticks = duration;
			orgasmStartTick = sex_ticks;
		}

		protected override IEnumerable<Toil> MakeNewToils()
		{
			setup_ticks();

			//this.FailOn(() => PawnUtility.PlayerForcedJobNowOrSoon(pawn));
			this.FailOn(() => pawn.health.Downed);
			this.FailOn(() => pawn.IsBurning());
			this.FailOn(() => pawn.IsFighting());
			this.FailOn(() => pawn.Drafted);

			Toil findfapspot = new Toil
			{
				initAction = delegate
				{
					pawn.pather.StartPath(cell, PathEndMode.OnCell);
				},
				defaultCompleteMode = ToilCompleteMode.PatherArrival
			};
			yield return findfapspot;

			//ModLog.Message(" Making new toil for QuickFap.");

			Toil SexToil = Toils_General.Wait(duration);
			SexToil.handlingFacing = true;
			SexToil.initAction = delegate
			{
				Start();
			};
			SexToil.tickAction = delegate
			{
				if (pawn.IsHashIntervalTick(ticks_between_hearts))
					ThrowMetaIconF(pawn.Position, pawn.Map, FleckDefOf.Heart);
				SexTick(pawn, null);
				SexUtility.reduce_rest(pawn, 1);
				if (ticks_left <= 0)
					ReadyForNextToil();
			};
			SexToil.AddFinishAction(delegate
			{
				End();
			});
			yield return SexToil;

			yield return new Toil
			{
				initAction = delegate
				{
					SexUtility.Aftersex(Sexprops);
					if (!SexUtility.ConsiderCleaning(pawn)) return;

					LocalTargetInfo own_cum = pawn.PositionHeld.GetFirstThing<Filth>(pawn.Map);

					Job clean = JobMaker.MakeJob(JobDefOf.Clean);
					clean.AddQueuedTarget(TargetIndex.A, own_cum);

					pawn.jobs.jobQueue.EnqueueFirst(clean);
				},
				defaultCompleteMode = ToilCompleteMode.Instant
			};
		}
	}
}


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

namespace rjw
{
	/// <summary>
	/// This is the driver for animals mating.
	/// </summary>
	public class JobDriver_Mating : JobDriver_Rape
	{
		public override bool TryMakePreToilReservations(bool errorOnFailed)
		{
			return pawn.Reserve(Target, job, BreederHelper.max_animals_at_once, 0, null, errorOnFailed);
		}

		[SyncMethod]
		protected override IEnumerable<Toil> MakeNewToils()
		{
			setup_ticks();
			var partnerJob = xxx.gettin_loved;

			//--Log.Message("JobDriver_Mating::MakeNewToils() - setting fail conditions");
			this.FailOnDespawnedNullOrForbidden(iTarget);
			this.FailOn(() => !pawn.CanReserve(Partner, BreederHelper.max_animals_at_once, 0)); // Fail if someone else reserves the target before the animal arrives.
			this.FailOn(() => !pawn.CanReach(Partner, PathEndMode.Touch, Danger.Some)); // Fail if animal cannot reach target.
			this.FailOn(() => pawn.Drafted);

			// Path to target
			yield return Toils_Goto.GotoThing(iTarget, PathEndMode.OnCell);

			var startPartnerJob = new Toil();
			startPartnerJob.defaultCompleteMode = ToilCompleteMode.Instant;
			startPartnerJob.socialMode = RandomSocialMode.Off;
			startPartnerJob.initAction = delegate
			{
				if (Partner.jobs.curDriver is JobDriver_SexBaseRecieverLoved) return;

				var bed = Partner.CurrentBed();

				Partner.jobs.StartJob(
					JobMaker.MakeJob(partnerJob, pawn),
					JobCondition.InterruptForced
				);

				if (bed is not null)
					if (Partner.jobs.curDriver is JobDriver_SexBaseRecieverLoved driver)
						driver.Set_bed(bed);
			};
			yield return startPartnerJob;

			// Mate target
			var sexToil = new Toil();
			sexToil.defaultCompleteMode = ToilCompleteMode.Never;
			sexToil.defaultDuration = duration;
			sexToil.handlingFacing = true;
			sexToil.initAction = delegate
			{
				Partner.pather.StopDead();
				Partner.jobs.curDriver.asleep = false;

				Start();
				if (xxx.is_human(Partner))
					Sexprops.usedCondom = CondomUtility.TryUseCondom(Partner);
				if (Sexprops.usedCondom)
				{
					var receiverDriver = Partner?.jobs?.curDriver as JobDriver_SexBaseReciever;
					if (receiverDriver is not null && receiverDriver.Sexprops != null)
						receiverDriver.Sexprops.usedCondom = true;
				}
			};
			sexToil.tickAction = delegate
			{
				if (pawn.IsHashIntervalTick(ticks_between_hearts))
					ThrowMetaIconF(pawn.Position, pawn.Map, FleckDefOf.Heart);
				SexTick(pawn, Partner);
				if (!Partner.Dead)
					SexUtility.reduce_rest(Partner, 1);
				SexUtility.reduce_rest(pawn, 2);
				if (ticks_left <= 0)
					ReadyForNextToil();
			};
			sexToil.FailOn(() => Partner.CurJob?.def != partnerJob);
			sexToil.AddFinishAction(End);
			yield return sexToil;

			yield return new Toil
			{
				initAction = () => SexUtility.ProcessSex(Sexprops),
				defaultCompleteMode = ToilCompleteMode.Instant
			};
		}
	}
}


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

namespace rjw
{
	public class JobDriver_Rape : JobDriver_SexBaseInitiator
	{
		public override bool TryMakePreToilReservations(bool errorOnFailed)
		{
			return pawn.Reserve(Target, job, xxx.max_rapists_per_prisoner, 0, null, errorOnFailed);
		}

		protected override IEnumerable<Toil> MakeNewToils()
		{
			if (RJWSettings.DebugRape) ModLog.Message("" + this.GetType().ToString() + "::MakeNewToils() called");
			setup_ticks();
			var PartnerJob = xxx.gettin_raped;

			this.FailOnDespawnedNullOrForbidden(iTarget);
			this.FailOn(() => !pawn.CanReserve(Partner, xxx.max_rapists_per_prisoner, 0)); // Fail if someone else reserves the prisoner before the pawn arrives
			this.FailOn(() => pawn.IsFighting());
			this.FailOn(() => Partner.IsFighting());
			this.FailOn(() => pawn.Drafted);

			yield return Toils_Sex.RapeTargetAlert(pawn, Partner);
			yield return Toils_Goto.GotoThing(iTarget, PathEndMode.OnCell);

			var StartPartnerJob = new Toil();
			StartPartnerJob.defaultCompleteMode = ToilCompleteMode.Instant;
			StartPartnerJob.socialMode = RandomSocialMode.Off;
			StartPartnerJob.initAction = delegate
			{
				if (Partner.jobs.curDriver is JobDriver_SexBaseRecieverRaped) return;

				var bed = Partner.CurrentBed();

				Partner.jobs.StartJob(
					JobMaker.MakeJob(PartnerJob, pawn),
					lastJobEndCondition: JobCondition.InterruptForced
				);

				if (bed is not null)
					if (Partner.jobs.curDriver is JobDriver_SexBaseRecieverRaped driver)
						driver.Set_bed(bed);
			};
			yield return StartPartnerJob;

			var SexToil = new Toil();
			SexToil.defaultCompleteMode = ToilCompleteMode.Never;
			SexToil.defaultDuration = duration;
			SexToil.handlingFacing = true;
			SexToil.initAction = delegate
			{
				Partner.pather.StopDead();
				Partner.jobs.curDriver.asleep = false;
				if (RJWSettings.rape_stripping && (Partner.IsColonist || pawn.IsColonist))
					Partner.Strip();
				Start();
			};
			SexToil.tickAction = delegate
			{
				if (pawn.IsHashIntervalTick(ticks_between_hearts))
					ThrowMetaIconF(pawn.Position, pawn.Map, FleckDefOf.Heart);
				SexTick(pawn, Partner);
				SexUtility.reduce_rest(Partner, 1);
				SexUtility.reduce_rest(pawn, 2);
				if (ticks_left <= 0)
					ReadyForNextToil();
			};
			SexToil.FailOn(() => Partner.CurJob?.def != PartnerJob);
			SexToil.AddFinishAction(End);
			yield return SexToil;

			yield return new Toil
			{
				initAction = () => SexUtility.ProcessSex(Sexprops),
				defaultCompleteMode = ToilCompleteMode.Instant
			};
		}
	}
}


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

namespace rjw
{
	public class JobDriver_RapeComfortPawn : JobDriver_Rape
	{
		protected override IEnumerable<Toil> MakeNewToils()
		{
			if (RJWSettings.DebugRape) ModLog.Message("" + this.GetType().ToString() + "::MakeNewToils() called");
			setup_ticks();
			var PartnerJob = xxx.gettin_raped;

			this.FailOnDespawnedNullOrForbidden(iTarget);
			//this.FailOn(() => (!Partner.health.capacities.CanBeAwake) || (!comfort_prisoners.is_designated(Partner)));//this is wrong
			this.FailOn(() => (!Partner.IsDesignatedComfort()));
			this.FailOn(() => !pawn.CanReserve(Partner, xxx.max_rapists_per_prisoner, 0)); // Fail if someone else reserves the prisoner before the pawn arrives
			this.FailOn(() => pawn.Drafted);

			yield return Toils_Sex.RapeTargetAlert(pawn, Partner);
			yield return Toils_Goto.GotoThing(iTarget, PathEndMode.OnCell);

			Toil StartPartnerJob = new Toil();
			StartPartnerJob.defaultCompleteMode = ToilCompleteMode.Instant;
			StartPartnerJob.socialMode = RandomSocialMode.Off;
			StartPartnerJob.initAction = delegate
			{
				if (Partner.jobs.curDriver is JobDriver_SexBaseRecieverRaped) return;

				var bed = Partner.CurrentBed();

				Partner.jobs.StartJob(
					JobMaker.MakeJob(PartnerJob, pawn),
					lastJobEndCondition: JobCondition.InterruptForced
				);

				if (bed is not null)
					if (Partner.jobs.curDriver is JobDriver_SexBaseRecieverRaped driver)
						driver.Set_bed(bed);
			};
			yield return StartPartnerJob;

			Toil SexToil = new Toil();
			SexToil.defaultCompleteMode = ToilCompleteMode.Never;
			SexToil.defaultDuration = duration;
			SexToil.handlingFacing = true;
			SexToil.initAction = delegate
			{
				Partner.pather.StopDead();
				Partner.jobs.curDriver.asleep = false;

				Start();
				// Unlike normal rape try use comfort prisoner condom
				CondomUtility.GetCondomFromRoom(Partner);
				Sexprops.usedCondom = CondomUtility.TryUseCondom(Partner);
				if (Sexprops.usedCondom)
				{
					var receiverDriver = Partner?.jobs?.curDriver as JobDriver_SexBaseReciever;
					if (receiverDriver is not null && receiverDriver.Sexprops != null)
						receiverDriver.Sexprops.usedCondom = true;
				}

				if (RJWSettings.DebugRape) ModLog.Message("JobDriver_RapeComfortPawn::MakeNewToils() - reserving prisoner");
				//pawn.Reserve(Partner, xxx.max_rapists_per_prisoner, 0);
			};
			SexToil.tickAction = delegate
			{
				if (pawn.IsHashIntervalTick(ticks_between_hearts))
					ThrowMetaIconF(pawn.Position, pawn.Map, FleckDefOf.Heart);
				SexTick(pawn, Partner);
				SexUtility.reduce_rest(Partner, 1);
				SexUtility.reduce_rest(pawn, 2);
				if (ticks_left <= 0)
					ReadyForNextToil();
			};
			SexToil.FailOn(() => Partner.CurJob?.def != PartnerJob);
			SexToil.AddFinishAction(End);
			yield return SexToil;

			yield return new Toil
			{
				initAction = delegate
				{
					// Trying to add some interactions and social logs
					SexUtility.ProcessSex(Sexprops);
					Partner.records.Increment(xxx.GetRapedAsComfortPawn);
				},
				defaultCompleteMode = ToilCompleteMode.Instant
			};
		}
	}
}


code:
using System.Collections.Generic;
using RimWorld;
using Verse;
using Verse.AI;
using Verse.Sound;

namespace rjw
{
	public class JobDriver_ViolateCorpse : JobDriver_Rape
	{
		public override bool TryMakePreToilReservations(bool errorOnFailed)
		{
			return pawn.Reserve(Target, job, 1, -1, null, errorOnFailed);
		}

		protected override IEnumerable<Toil> MakeNewToils()
		{
			if (RJWSettings.DebugRape) ModLog.Message(" JobDriver_ViolateCorpse::MakeNewToils() called");
			setup_ticks();

			this.FailOnDespawnedNullOrForbidden(iTarget);
			this.FailOn(() => !pawn.CanReserve(Target, 1, 0));  // Fail if someone else reserves the prisoner before the pawn arrives
			this.FailOn(() => pawn.IsFighting());
			this.FailOn(() => pawn.Drafted);
			this.FailOn(Target.IsBurning);

			if (RJWSettings.DebugRape) ModLog.Message(" JobDriver_ViolateCorpse::MakeNewToils() - moving towards Target");
			yield return Toils_Goto.GotoThing(iTarget, PathEndMode.OnCell);

			var alert = RJWPreferenceSettings.rape_attempt_alert == RJWPreferenceSettings.RapeAlert.Disabled ?
				MessageTypeDefOf.SilentInput : MessageTypeDefOf.NeutralEvent;
			Messages.Message(xxx.get_pawnname(pawn) + " is trying to rape a corpse of " + xxx.get_pawnname(Partner), pawn, alert);

			setup_ticks();// re-setup ticks on arrival

			var SexToil = new Toil();
			SexToil.defaultCompleteMode = ToilCompleteMode.Never;
			SexToil.defaultDuration = duration;
			SexToil.handlingFacing = true;
			SexToil.initAction = delegate
			{
				if (RJWSettings.DebugRape) ModLog.Message(" JobDriver_ViolateCorpse::MakeNewToils() - stripping Target");
				(Target as Corpse).Strip();
				Start();
			};
			SexToil.tickAction = delegate
			{
				if (pawn.IsHashIntervalTick(ticks_between_hearts))
					if (xxx.is_necrophiliac(pawn))
						ThrowMetaIconF(pawn.Position, pawn.Map, FleckDefOf.Heart);
					else
						ThrowMetaIconF(pawn.Position, pawn.Map, xxx.mote_noheart);
				//if (pawn.IsHashIntervalTick (ticks_between_hits))
				//	roll_to_hit (pawn, Target);
				SexTick(pawn, Target);
				SexUtility.reduce_rest(pawn, 2);
				if (ticks_left <= 0)
					ReadyForNextToil();
			};
			SexToil.AddFinishAction(delegate
			{
				End();
			});
			yield return SexToil;

			yield return new Toil
			{
				initAction = delegate
				{
					if (RJWSettings.DebugRape) ModLog.Message(" JobDriver_ViolateCorpse::MakeNewToils() - creating aftersex toil");
					SexUtility.ProcessSex(Sexprops);
				},
				defaultCompleteMode = ToilCompleteMode.Instant
			};
		}
	}
}