code:
using Verse;
using Multiplayer.API;

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

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

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


code:
using Verse;
using Multiplayer.API;

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

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

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

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

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

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

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

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

repo_name: Chinchillanon/rjw

license: mit


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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

			return Widgets.ButtonInvisible(iconRect, false);
		}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

/// <summary>
/// patches Building_Bed to add stuff for WhoreBeds
///
/// Also contains smaller patches for RoomRoleWorker_Barracks (don't count whore beds) (disabled) and Toils_LayDown.ApplyBedThoughts (slept in brothel thought)
/// </summary>

namespace rjw
{
	public static class Building_Bed_Patch
	{

		private static readonly Color sheetColorForWhores = new Color(181 / 255f, 55 / 255f, 109 / 255f);

		// Set color for whore beds
		[HarmonyPatch(typeof(Building_Bed))]
		[HarmonyPatch(nameof(Building_Bed.DrawColorTwo), MethodType.Getter)]
		public static class Building_Bed_DrawColor_Patch
		{
			[HarmonyPostfix]
			public static void Postfix(Building_Bed __instance, ref Color __result)
			{
				if (__instance.IsAllowedForWhoringAll())
				{
					__result = sheetColorForWhores;
				}
			}
		}

		// add whoring toggles to beds
		[HarmonyPatch(typeof(Building_Bed), nameof(Building_Bed.GetGizmos))]
		public static class Building_Bed_GetGizmos_Patch
		{
			[HarmonyPostfix]
			public static void Postfix(Building_Bed __instance, ref IEnumerable<Gizmo> __result)
			{
				__result = Process(__instance, __result);
			}

			private static IEnumerable<Gizmo> Process(Building_Bed __instance, IEnumerable<Gizmo> __result)
			{

				var isPrisonCell = __instance.GetRoom()?.IsPrisonCell == true;
				if (!__instance.ForPrisoners && !__instance.Medical && __instance.def.building.bed_humanlike && __instance.Faction == Faction.OfPlayerSilentFail && !__instance.def.defName.Contains("Guest") && !isPrisonCell)
				{

					yield return
						new Command_Toggle
						{
							defaultLabel = "CommandBedAllowWhoringLabel".Translate(),
							defaultDesc = "CommandBedAllowWhoringDesc".Translate(),
							icon = ContentFinder<Texture2D>.Get("UI/Commands/AsWhore"),
							isActive = __instance.IsAllowedForWhoringOwner,
							toggleAction = __instance.ToggleAllowedForWhoringOwner,
							hotKey = KeyBindingDefOf.Misc5, // Guest Beds uses Misc4
							disabled = !__instance.def.HasAssignableCompFrom(typeof(CompAssignableToPawn_Bed)),
							disabledReason = "This bed type is not assignable to pawns."
						};

					yield return
						new Command_Toggle
						{
							defaultLabel = "CommandBedSetAsWhoreBedLabel".Translate(),
							defaultDesc = "CommandBedSetAsWhoreBedDesc".Translate(),
							icon = ContentFinder<Texture2D>.Get("UI/Commands/AsWhoreMany"),
							isActive = __instance.IsAllowedForWhoringAll,
							toggleAction = __instance.ToggleAllowedForWhoringAll,
							hotKey = KeyBindingDefOf.Misc6, // Guest Beds uses Misc4
							disabled = !__instance.def.HasAssignableCompFrom(typeof(CompAssignableToPawn_Bed)),
							disabledReason = "This bed type is not assignable to pawns."
						};
				}

				foreach (var gizmo in __result)
				{
					if (__instance.IsAllowedForWhoringAll())
					{
						if (gizmo is Command_Toggle && ((Command_Toggle)gizmo).defaultLabel == "CommandBedSetAsGuestLabel".Translate())
						{
							// hide set as guest bed
							continue;
						};
						// old: instead of hiding, just disable
						/*switch (gizmo)
						{
							case Command_Toggle toggle:
								{
									// Disable prisoner and medical, and guest buttons
									if (//toggle.defaultLabel == "CommandBedSetForPrisonersLabel".Translate() ||
										//toggle.defaultLabel == "CommandBedSetAsMedicalLabel".Translate() ||
										toggle.defaultLabel == "CommandBedSetAsGuestLabel".Translate()) gizmo.Disable();
									break;
								}
						}//*/
					}
					yield return gizmo;
				}
			}
		}

		// add description of whore price factor to inspect string (bottom left corner if item selected)
		[HarmonyPatch(typeof(Building_Bed), nameof(Building_Bed.GetInspectString))]
		public static class Building_Bed_GetInspectString_Patch
		{
			[HarmonyPostfix]
			public static void Postfix(Building_Bed __instance, ref string __result)
			{
				if (__instance.def.building.bed_humanlike && __instance.Faction == Faction.OfPlayerSilentFail && (__instance.IsAllowedForWhoringAll() || __instance.IsAllowedForWhoringOwner()))
				{
					__result = __result + "\n" + "WhorePriceCalcDesc".Translate(WhoreBed_Utility.CalculatePriceFactor(__instance).ToString("F2"));
					if (RJWSettings.DebugWhoring)
					{
						__result = __result + "\nbed.thingIDNumber: " + __instance.thingIDNumber.ToString();

						__result = __result + "\nscoreUpdateTickDelay: " + SaveStorage.DataStore.GetBedData(__instance).scoreUpdateTickDelay.ToString();

						if (SaveStorage.DataStore.GetBedData(__instance).reservedUntilGameTick > GenTicks.TicksGame)
						{
							__result = __result + "\nreserved by pawn id: " + SaveStorage.DataStore.GetBedData(__instance).reservedForPawnID.ToString();
						}
					}
				}
			}
		}

		// add whore price factor as overlay
		[HarmonyPatch(typeof(Building_Bed), nameof(Building_Bed.DrawGUIOverlay))]
		public static class Building_Bed_DrawGUIOverlay_Patch
		{
			[HarmonyPrefix]
			public static bool Prefix(Building_Bed __instance)
			{
				if (RJWSettings.show_whore_price_factor_on_bed && __instance.def.building.bed_humanlike && __instance.Faction == Faction.OfPlayerSilentFail) {
					// if whore bed, print price factor on it
					if (Find.CameraDriver.CurrentZoom == CameraZoomRange.Closest
						&& ((__instance.IsAllowedForWhoringOwner() && __instance.OwnersForReading.Any<Pawn>())
							|| __instance.IsAllowedForWhoringAll()))
					{
						Color defaultThingLabelColor = GenMapUI.DefaultThingLabelColor;

						// make string
						float whore_price_factor = WhoreBed_Utility.CalculatePriceFactor(__instance);
						string wpf;
						if (Math.Abs(whore_price_factor) >= 100)
						{
							wpf = ((int)whore_price_factor).ToString("D");
						}
						else if (Math.Abs(whore_price_factor) >= 10)
						{
							wpf = whore_price_factor.ToString("F1");
						}
						else
						{
							wpf = whore_price_factor.ToString("F2");
						}

						// get dimensions of text and make it appear above names
						Vector2 textsize = Text.CalcSize(wpf);
						Vector2 baseLabelPos = GenMapUI.LabelDrawPosFor(__instance, -0.4f); // -0.4f is copied from vanilla code
						baseLabelPos.y -= textsize.y * 0.75f;

						GenMapUI.DrawThingLabel(baseLabelPos, wpf, defaultThingLabelColor);

						if (__instance.IsAllowedForWhoringAll() && !__instance.OwnersForReading.Any<Pawn>())
						{
							// hide "Unowned" if whore bed with no owner
							return false;
						}
					}
				}
				// after drawing whore price factor, draw the actual names
				// could have been done as a postfix, but I started with a prefix, hoping I could get by with only one draw call
				return true;
			}

		}

		// barracks don't count whore beds, so room type switches to brothel sooner
		// disabled - barracks have their own slept in ~ debuff; doesn't really matter; put some effort in your brothels!
		/*[HarmonyPatch(typeof(RoomRoleWorker_Barracks), nameof(RoomRoleWorker_Barracks.GetScore))]
		public static class RoomRoleWorker_Barracks_GetScore_Patch
		{
			public static bool Prefix(Room room, ref float __result)
			{
				int num = 0;
				int num2 = 0;
				List<Thing> containedAndAdjacentThings = room.ContainedAndAdjacentThings;
				for (int i = 0; i < containedAndAdjacentThings.Count; i++)
				{
					Building_Bed building_Bed = containedAndAdjacentThings[i] as Building_Bed;
					if (building_Bed != null && building_Bed.def.building.bed_humanlike)
					{
						if (building_Bed.ForPrisoners)
						{
							__result = 0f;
							return false;
						}
						num++;
						if (!building_Bed.Medical && !building_Bed.IsAllowedForWhoringAll())
						{
							num2++;
						}
					}
				}
				if (num <= 1)
				{
					__result = 0f;
					return false;
				}
				__result = (float)num2 * 100100f;
				return false;
			}
		}*/

		// if pawns sleep in a brothel or a whoring bed, they get a thought
		[HarmonyPatch(typeof(Toils_LayDown), "ApplyBedThoughts")]
		public class Toils_LayDown_ApplyBedThoughts_Patch
		{
			[HarmonyPostfix]
			public static void Postfix(Pawn actor)
			{
				if (actor?.needs?.mood == null) return;

				Building_Bed building_Bed = actor.CurrentBed();

				actor?.needs?.mood?.thoughts?.memories?.RemoveMemoriesOfDef(WhoringThoughtDefOf.SleptInBrothel);

				if (building_Bed == null) return;

				if (building_Bed?.GetRoom()?.Role == WhoreBed_Utility.roleDefBrothel || building_Bed.IsAllowedForWhoringAll())
				{
					var memoryHandler = actor.needs.mood.thoughts.memories;
					int thoughtStage = 0;

					foreach (var thoughtDef in DefDatabase<ThoughtDef_Whore>.AllDefsListForReading)
					{
						var memory = memoryHandler.GetFirstMemoryOfDef(thoughtDef);
						if (memory?.CurStageIndex >= thoughtDef.stages.Count - 1)
						{
							thoughtStage = 1;
							break;
						}
					}

					memoryHandler.TryGainMemory(ThoughtMaker.MakeThought(WhoringThoughtDefOf.SleptInBrothel, thoughtStage));
				}
			}
		}

		// if room stats are updated, update beds within
		//	"necessary" if beds are toggled during pause
		[HarmonyPatch(typeof(Room), "UpdateRoomStatsAndRole")]
		public class Room_UpdateRoomStatsAndRole_Patch
		{
			[HarmonyPostfix]
			public static void Postfix(Room __instance)
			{
				// note: with room stat display enabled, this get's called quite often for whatever room the mouse hovers over
				//	even large outdoor areas
				//	where iterating over all things to find all beds (even if there are none) is expensive
				//	for now, skip doing anything if even the game decides it's not worth it
				//	(game sets role to None if region count >36 or something)
				//	- the beds will update eventually

				if (/*Find.PlaySettings.showRoomStats && */__instance.Role == RoomRoleDefOf.None)
					return;

				if (Find.TickManager.Paused)
				{
					// if paused, update immediately
					WhoreBed_Utility.CalculateBedFactorsForRoom(__instance);
				}
				else
				{
					// else, just make beds update as soon as needed
					WhoreBed_Utility.ResetTicksUntilUpdate(__instance);
				}
			}
		}
	}
}


code:
using System.Reflection;
using Harmony;
using RimWorld;
using Verse;

namespace rjw
{
	/// <summary>
	/// Conditional patching class that only does patching if CnP is active
	/// </summary>
	public class CnPcompatibility
	{
		//CnP (or BnC) try to address the joy need of a child, prisoners don't have that.
		//Considering how you can arrest children without rjw, it is more of a bug of that mod than ours.
		[HarmonyPatch(typeof(Pawn_NeedsTracker), "BindDirectNeedFields")]
		static class jfpk
		{
			[HarmonyPostfix]
			static void postfix(ref Pawn_NeedsTracker __instance)
			{
				Pawn_NeedsTracker tr = __instance;
				FieldInfo fieldInfo = AccessTools.Field(typeof(Pawn_NeedsTracker), "pawn");
				Pawn pawn = fieldInfo.GetValue(__instance) as Pawn;
				if (xxx.is_human(pawn) && pawn.ageTracker.CurLifeStageIndex < AgeStage.Teenager)
				{
					if (tr.TryGetNeed(NeedDefOf.Joy) == null)
					{
						MethodInfo method = AccessTools.Method(typeof(Pawn_NeedsTracker), "AddNeed");
						method.Invoke(tr, new object[] { NeedDefOf.Joy });
					}
				}
			}
		}

		//For whatever reason, harmony shits itself, when trying to patch non void private fields, below are variants the code that would work nicely, if it didn't
		//[HarmonyPatch]
		//[StaticConstructorOnStartup]
		//internal static class joy_for_prison_kids
		//{
		//    [HarmonyTargetMethod]
		//    static MethodBase CalculateMethod(HarmonyInstance instance)
		//    {
		//        var r = AccessTools.Method(typeof(Pawn_NeedsTracker), "ShouldHaveNeed");

		//        //Log.Message("Found method "+ r.ReturnType + ' ' + r.FullDescription());
		//        //Log.Message("Parameters " + r.GetType() );
		//        //Log.Message("return " + r.ReturnParameter);
		//        return AccessTools.Method(typeof(Pawn_NeedsTracker), "ShouldHaveNeed");
		//    }
		//    [HarmonyPrepare]
		//    static bool should_patch(HarmonyInstance instance)
		//    {
		//        Log.Clear();
		//        Log.Message("Will patch "+ xxx.RimWorldChildrenIsActive);
		//        return xxx.RimWorldChildrenIsActive;
		//    }

		//doesn't work, gets:  System.Reflection.TargetParameterCountException: parameters do not match signature
		//static void Postfix(HarmonyInstance instance)
		//{
		//    Log.Message("FOO");
		//}
		//[HarmonyPrefix]
		//static bool foo(NeedDef nd)
		//{
		//    Log.Message("Prerun ");
		//    return true;
		//}
		//[HarmonyPostfix]
		//static void postfix(ref bool __result, ref Pawn_NeedsTracker __instance, NeedDef nd)
		//{
		//    if (nd != NeedDefOf.Joy) { return; }
		//    FieldInfo fieldInfo = AccessTools.Field(typeof(Pawn_NeedsTracker), "pawn");
		//    Pawn pawn = fieldInfo.GetValue(__instance) as Pawn;
		//    if (pawn.ageTracker.CurLifeStageIndex < AgeStage.Teenager)
		//    {
		//        __result = true;
		//    }
		//}
		//}
		public static void Patch(HarmonyInstance harmony)
		{
			if (!xxx.RimWorldChildrenIsActive) return;
			Doit(harmony);
		}
		private static void Doit(HarmonyInstance harmony)
		{
			var original = typeof(RimWorldChildren.ChildrenUtility).GetMethod("CanBreastfeed");
			var postfix = typeof(CnPcompatibility).GetMethod("CanBreastfeed");
			harmony.Patch(original, null, new HarmonyMethod(postfix));

			original = typeof(Building_Bed).GetMethod("get_AssigningCandidates");
			postfix = typeof(CnPcompatibility).GetMethod("BedCandidates");
			harmony.Patch(original, null, new HarmonyMethod(postfix));

			//doesn't work cannot reflect private class
			//original = typeof(RimWorldChildren.Hediff_UnhappyBaby).GetMethod("IsBabyUnhappy", BindingFlags.Static | BindingFlags.NonPublic);
			//Log.Message("original is nul " + (original == null));
			//var prefix = typeof(CnPcompatibility).GetMethod("IsBabyUnhappy");
			//harmony.Patch(original, new HarmonyMethod(prefix), null);
		}
		private static void CanBreastfeed(ref  bool __result, ref Pawn __instance)//Postfix
		{
			__result = __instance.health.hediffSet.HasHediff(HediffDef.Named("Lactating"));//I'm a simple man
		}
		private static void BedCandidates(ref IEnumerable<Pawn> __result, ref Building_Bed bed)
		{
			if (!RimWorldChildren.BedPatchMethods.IsCrib(bed)) return;
			__result = bed.Map.mapPawns.FreeColonists.Where(x => x.ageTracker.CurLifeStageIndex <= 2 && x.Faction == Faction.OfPlayer);//Basically do all the work second time but with a tweak
		}
		private static bool IsBabyUnhappy(ref bool __result, ref RimWorldChildren.Hediff_UnhappyBaby __instance)
		{
			var pawn = __instance.pawn;

			if ((pawn.needs?.joy.CurLevelPercentage??1) < 0.2f)
				__result = true;
			else
				__result =  false;
			return false;
		}
	}
}


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

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

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


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

namespace rjw
{
	[StaticConstructorOnStartup]
	internal static class First
	{
		/*private static void show_bpr(String body_part_record_def_name)
		{
			var bpr = BodyDefOf.Human.AllParts.Find((BodyPartRecord can) => String.Equals(can.def.defName, body_part_record_def_name));
			--Log.Message(body_part_record_def_name + " BPR internals:");
			--Log.Message("  def: " + bpr.def.ToString());
			--Log.Message("  parts: " + bpr.parts.ToString());
			--Log.Message("  parts.count: " + bpr.parts.Count.ToString());
			--Log.Message("  height: " + bpr.height.ToString());
			--Log.Message("  depth: " + bpr.depth.ToString());
			--Log.Message("  coverage: " + bpr.coverage.ToString());
			--Log.Message("  groups: " + bpr.groups.ToString());
			--Log.Message("  groups.count: " + bpr.groups.Count.ToString());
			--Log.Message("  parent: " + bpr.parent.ToString());
			--Log.Message ("  fleshCoverage: " + bpr.fleshCoverage.ToString ());
			--Log.Message ("  absoluteCoverage: " + bpr.absoluteCoverage.ToString ());
			--Log.Message ("  absoluteFleshCoverage: " + bpr.absoluteFleshCoverage.ToString ());
		}*/

		//Children mod use same defname. but not has worker class. so overriding here.
		public static void inject_Reproduction()
		{
			PawnCapacityDef reproduction = DefDatabase<PawnCapacityDef>.GetNamed("RJW_Fertility");
			reproduction.workerClass = typeof(PawnCapacityWorker_Fertility);
		}

		public static void inject_whoringtab()
		{
			//InjectTab(typeof(MainTab.MainTabWindow_Brothel), def => def.race?.Humanlike == true);
		}

		private static void InjectTab(Type tabType, Func<ThingDef, bool> qualifier)
		{
			var defs = DefDatabase<ThingDef>.AllDefs.Where(qualifier).ToList();
			defs.RemoveDuplicates();

			var tabBase = InspectTabManager.GetSharedInstance(tabType);

			foreach (var def in defs)
			{
				if (def.inspectorTabs == null || def.inspectorTabsResolved == null) continue;

				if (!def.inspectorTabs.Contains(tabType))
				{
					def.inspectorTabs.Add(tabType);
					def.inspectorTabsResolved.Add(tabBase);
					//Log.Message(def.defName+": "+def.inspectorTabsResolved.Select(d=>d.GetType().Name).Aggregate((a,b)=>a+", "+b));
				}
			}
		}

		private static void inject_recipes()
		{
			//--ModLog.Message(" First::inject_recipes");
			// Inject the recipes to create the artificial privates into the crafting spot or machining bench.
			// BUT, also dynamically detect if EPOE is loaded and, if it is, inject the recipes into EPOE's
			// crafting benches instead.

			try
			{
				//Vanilla benches
				var cra_spo = DefDatabase<ThingDef>.GetNamed("CraftingSpot");
				var mac_ben = DefDatabase<ThingDef>.GetNamed("TableMachining");
				var fab_ben = DefDatabase<ThingDef>.GetNamed("FabricationBench");
				var tai_ben = DefDatabase<ThingDef>.GetNamed("ElectricTailoringBench");

				// Inject the bondage gear recipes into their appropriate benches
				//if (xxx.config.bondage_gear_enabled)
				//{
					//fab_ben.AllRecipes.Add(DefDatabase<RecipeDef>.GetNamed("MakeHololock"));
					//tai_ben.AllRecipes.Add(DefDatabase<RecipeDef>.GetNamed("MakeArmbinder"));
					//tai_ben.AllRecipes.Add(DefDatabase<RecipeDef>.GetNamed("MakeChastityBelt"));
					//tai_ben.AllRecipes.Add(DefDatabase<RecipeDef>.GetNamed("MakeChastityBeltO"));
					//tai_ben.AllRecipes.Add(DefDatabase<RecipeDef>.GetNamed("MakeChastityCage"));
					//tai_ben.AllRecipes.Add(DefDatabase<RecipeDef>.GetNamed("MakeBallGag"));
					//tai_ben.AllRecipes.Add(DefDatabase<RecipeDef>.GetNamed("MakeRingGag"));
				//}
			}
			catch
			{
				ModLog.Warning("Unable to inject recipes.");
				ModLog.Warning("Yay! Your medieval mod broke recipes. And, likely, parts too, expect errors.");
			}
		}

		/*private static void show_bs(Backstory bs)
		{
			--Log.Message("Backstory \"" + bs.Title + "\" internals:");
			--Log.Message("  identifier: " + bs.identifier);
			--Log.Message("  slot: " + bs.slot.ToString());
			--Log.Message("  Title: " + bs.Title);
			--Log.Message("  TitleShort: " + bs.TitleShort);
			--Log.Message("  baseDesc: " + bs.baseDesc);
			--Log.Message("  skillGains: " + ((bs.skillGains == null) ? "null" : bs.skillGains.ToString()));
			--Log.Message("  skillGainsResolved: " + ((bs.skillGainsResolved == null) ? "null" : bs.skillGainsResolved.ToString()));
			--Log.Message("  workDisables: " + bs.workDisables.ToString());
			--Log.Message("  requiredWorkTags: " + bs.requiredWorkTags.ToString());
			--Log.Message("  spawnCategories: " + bs.spawnCategories.ToString());
			--Log.Message("  bodyTypeGlobal: " + bs.bodyTypeGlobal.ToString());
			--Log.Message("  bodyTypeFemale: " + bs.bodyTypeFemale.ToString());
			--Log.Message("  bodyTypeMale: " + bs.bodyTypeMale.ToString());
			--Log.Message("  forcedTraits: " + ((bs.forcedTraits == null) ? "null" : bs.forcedTraits.ToString()));
			--Log.Message("  disallowedTraits: " + ((bs.disallowedTraits == null) ? "null" : bs.disallowedTraits.ToString()));
			--Log.Message("  shuffleable: " + bs.shuffleable.ToString());
		}*/

		//Quick check to see if an another mod is loaded.
		private static bool IsLoaded(string mod)
		{
			return LoadedModManager.RunningModsListForReading.Any(x => x.Name == mod);
		}

		private static void CheckingCompatibleMods()
		{
			{//Humanoid Alien Races Framework 2.0
				xxx.xenophobia = DefDatabase<TraitDef>.GetNamedSilentFail("Xenophobia");
				if (xxx.xenophobia is null)
				{
					xxx.AlienFrameworkIsActive = false;
				}
				else
				{
					xxx.AlienFrameworkIsActive = true;
					if (RJWSettings.DevMode) ModLog.Message("Humanoid Alien Races 2.0 is detected. Xenophile and Xenophobe traits active.");
				}
			}

			{//relations-orientation mods
				{//RomanceDiversified
					xxx.straight = DefDatabase<TraitDef>.GetNamedSilentFail("Straight");
					xxx.faithful = DefDatabase<TraitDef>.GetNamedSilentFail("Faithful");
					xxx.philanderer = DefDatabase<TraitDef>.GetNamedSilentFail("Philanderer");
					xxx.polyamorous = DefDatabase<TraitDef>.GetNamedSilentFail("Polyamorous");
					if (xxx.straight is null || xxx.faithful is null || xxx.philanderer is null || xxx.polyamorous is null)
					{
						xxx.RomanceDiversifiedIsActive = false;
					}
					else
					{
						xxx.RomanceDiversifiedIsActive = true;
						if (RJWSettings.DevMode) ModLog.Message("RomanceDiversified is detected.");
					}

					// any mod that features a polyamorous trait
					if(xxx.polyamorous is null)
					{
						xxx.AnyPolyamoryModIsActive = false;
					}
					else
					{
						xxx.AnyPolyamoryModIsActive = true;
					}
				}

				{//[SYR] Individuality
					xxx.SYR_CreativeThinker = DefDatabase<TraitDef>.GetNamedSilentFail("SYR_CreativeThinker");
					xxx.SYR_Haggler = DefDatabase<TraitDef>.GetNamedSilentFail("SYR_Haggler");
					if (xxx.SYR_CreativeThinker is null || xxx.SYR_Haggler is null)
					{
						xxx.IndividualityIsActive = false;
						if (RJWPreferenceSettings.sexuality_distribution == RJWPreferenceSettings.Rjw_sexuality.SYRIndividuality)
							RJWPreferenceSettings.sexuality_distribution = RJWPreferenceSettings.Rjw_sexuality.Vanilla;
					}
					else
					{
						xxx.IndividualityIsActive = true;
						if (RJWSettings.DevMode) ModLog.Message("Individuality is detected.");
					}
				}

				{//Psychology
					xxx.prude = DefDatabase<TraitDef>.GetNamedSilentFail("Prude");
					xxx.lecher = DefDatabase<TraitDef>.GetNamedSilentFail("Lecher");
					xxx.polygamous = DefDatabase<TraitDef>.GetNamedSilentFail("Polygamous");
					if (xxx.prude is null || xxx.lecher is null || xxx.polygamous is null)
					{
						xxx.PsychologyIsActive = false;
						if (RJWPreferenceSettings.sexuality_distribution == RJWPreferenceSettings.Rjw_sexuality.Psychology)
							RJWPreferenceSettings.sexuality_distribution = RJWPreferenceSettings.Rjw_sexuality.Vanilla;
					}
					else
					{
						xxx.PsychologyIsActive = true;
						if (RJWSettings.DevMode) ModLog.Message("Psychology is detected. (Note: only partially supported)");
					}

					// any mod that features a polygamous trait
					if (xxx.polygamous is null)
					{
						xxx.AnyPolygamyModIsActive = false;
					}
					else
					{
						xxx.AnyPolygamyModIsActive = true;
					}
				}

				if (xxx.PsychologyIsActive == false && xxx.IndividualityIsActive == false)
				{
					if (RJWPreferenceSettings.sexuality_distribution != RJWPreferenceSettings.Rjw_sexuality.Vanilla)
					{
						RJWPreferenceSettings.sexuality_distribution = RJWPreferenceSettings.Rjw_sexuality.Vanilla;
					}
				}
			}

			{//SimpleSlavery
				xxx.Enslaved = DefDatabase<HediffDef>.GetNamedSilentFail("Enslaved");
				if (xxx.Enslaved is null)
				{
					xxx.SimpleSlaveryIsActive = false;
				}
				else
				{
					xxx.SimpleSlaveryIsActive = true;
					if (RJWSettings.DevMode) ModLog.Message("SimpleSlavery is detected.");
				}
			}

			{//[KV] Consolidated Traits
				xxx.RCT_NeatFreak = DefDatabase<TraitDef>.GetNamedSilentFail("RCT_NeatFreak");
				xxx.RCT_Savant = DefDatabase<TraitDef>.GetNamedSilentFail("RCT_Savant");
				xxx.RCT_Inventor = DefDatabase<TraitDef>.GetNamedSilentFail("RCT_Inventor");
				xxx.RCT_AnimalLover = DefDatabase<TraitDef>.GetNamedSilentFail("RCT_AnimalLover");
				if (xxx.RCT_NeatFreak is null || xxx.RCT_Savant is null || xxx.RCT_Inventor is null || xxx.RCT_AnimalLover is null)
				{
					xxx.CTIsActive = false;
				}
				else
				{
					xxx.CTIsActive = true;
					if (RJWSettings.DevMode) ModLog.Message("Consolidated Traits found, adding trait compatibility.");
				}
			}

			{//Rimworld of Magic
				xxx.Succubus = DefDatabase<TraitDef>.GetNamedSilentFail("Succubus");
				xxx.Warlock = DefDatabase<TraitDef>.GetNamedSilentFail("Warlock");
				xxx.TM_Mana = DefDatabase<NeedDef>.GetNamedSilentFail("TM_Mana");
				xxx.TM_ShapeshiftHD = DefDatabase<HediffDef>.GetNamedSilentFail("TM_ShapeshiftHD");
				if (xxx.Succubus is null || xxx.Warlock is null || xxx.TM_Mana is null || xxx.TM_ShapeshiftHD is null)
				{
					xxx.RoMIsActive = false;
				}
				else
				{
					xxx.RoMIsActive = true;
					if (RJWSettings.DevMode) ModLog.Message("Rimworld of Magic is detected.");
				}
			}

			{//Nightmare Incarnation
				xxx.NI_Need_Mana = DefDatabase<NeedDef>.GetNamedSilentFail("NI_Need_Mana");
				if (xxx.NI_Need_Mana is null)
				{
					xxx.NightmareIncarnationIsActive = false;
				}
				else
				{
					xxx.NightmareIncarnationIsActive = true;
					if (RJWSettings.DevMode) ModLog.Message("Nightmare Incarnation is detected.");
				}
			}

			{//DubsBadHygiene
				xxx.DBHThirst = DefDatabase<NeedDef>.GetNamedSilentFail("DBHThirst");
				if (xxx.DBHThirst is null)
				{
					xxx.DubsBadHygieneIsActive = false;
				}
				else
				{
					xxx.DubsBadHygieneIsActive = true;
					if (RJWSettings.DevMode) ModLog.Message("Dubs Bad Hygiene is detected.");
				}
			}

			{//Immortals
				xxx.IH_Immortal = DefDatabase<HediffDef>.GetNamedSilentFail("IH_Immortal");
				if (xxx.IH_Immortal is null)
				{
					xxx.ImmortalsIsActive = false;
				}
				else
				{
					xxx.ImmortalsIsActive = true;
					if (RJWSettings.DevMode) ModLog.Message("Immortals is detected.");
				}
			}

			{//Children and Pregnancy
				xxx.BabyState = DefDatabase<HediffDef>.GetNamedSilentFail("BabyState");
				xxx.PostPregnancy = DefDatabase<HediffDef>.GetNamedSilentFail("PostPregnancy");
				xxx.Lactating = DefDatabase<HediffDef>.GetNamedSilentFail("Lactating");
				xxx.NoManipulationFlag = DefDatabase<HediffDef>.GetNamedSilentFail("NoManipulationFlag");
				xxx.IGaveBirthFirstTime = DefDatabase<ThoughtDef>.GetNamedSilentFail("IGaveBirthFirstTime");
				xxx.IGaveBirth = DefDatabase<ThoughtDef>.GetNamedSilentFail("IGaveBirth");
				xxx.PartnerGaveBirth = DefDatabase<ThoughtDef>.GetNamedSilentFail("PartnerGaveBirth");
				if (xxx.BabyState is null || xxx.PostPregnancy is null || xxx.Lactating is null || xxx.NoManipulationFlag is null || xxx.IGaveBirthFirstTime is null || xxx.IGaveBirth is null ||  xxx.PartnerGaveBirth is null)
				{
					xxx.RimWorldChildrenIsActive = false;
				}
				else
				{
					xxx.RimWorldChildrenIsActive = true;
					if (RJWSettings.DevMode) ModLog.Message("Children&Pregnancy is detected.");
				}
			}

			{//Babies and Children
				xxx.BnC_RJW_PostPregnancy = DefDatabase<HediffDef>.GetNamedSilentFail("BnC_RJW_PostPregnancy");
			}

			{// RJW-EX
				xxx.RjwEx_Armbinder = DefDatabase<HediffDef>.GetNamedSilentFail("Armbinder");
				if (xxx.RjwEx_Armbinder is null) { xxx.RjwExIsActive = false;}
				else { xxx.RjwExIsActive = true; }

			}

			{//Combat Extended
				xxx.MuscleSpasms = DefDatabase<HediffDef>.GetNamedSilentFail("MuscleSpasms");
				if (xxx.MuscleSpasms is null)
				{
					xxx.CombatExtendedIsActive = false;
				}
				else
				{
					xxx.CombatExtendedIsActive = true;
					if (RJWSettings.DevMode) ModLog.Message("Combat Extended is detected. Current compatibility unknown, use at your own risk. ");
				}
			}
		}

		static First()
		{
			//--ModLog.Message(" First::First() called");

			// check for required mods
			//CheckModRequirements();
			CheckIncompatibleMods();
			CheckingCompatibleMods();

			inject_Reproduction();
			//inject_recipes(); // No Longer needed.  Benches defined in recipe defs

			nymph_backstories.init();
			//bondage_gear_tradeability.init();

			var har = new Harmony("rjw");
			har.PatchAll(Assembly.GetExecutingAssembly());
			PATCH_Pawn_ApparelTracker_TryDrop.apply(har);
			//CnPcompatibility.Patch(har);							//CnP IS NO OUT YET
		}

		internal static void CheckModRequirements()
		{
			//--Log.Message("First::CheckModRequirements() called");
			List<string> required_mods = new List<string> {
				"HugsLib",
			};
			foreach (string required_mod in required_mods)
			{
				bool found = false;
				foreach (ModMetaData installed_mod in ModLister.AllInstalledMods)
				{
					if (installed_mod.Active && installed_mod.Name.Contains(required_mod))
					{
						found = true;
					}

					if (!found)
					{
						ErrorMissingRequirement(required_mod);
					}
				}
			}
		}

		internal static void CheckIncompatibleMods()
		{
			//--Log.Message("First::CheckIncompatibleMods() called");
			List<string> incompatible_mods = new List<string> {
				"Bogus Test Mod That Doesn't Exist",
				"Lost Forest"
			};
			foreach (string incompatible_mod in incompatible_mods)
			{
				foreach (ModMetaData installed_mod in ModLister.AllInstalledMods)
				{
					if (installed_mod.Active && installed_mod.Name.Contains(incompatible_mod))
					{
						ErrorIncompatibleMod(installed_mod);
					}
				}
			}
		}

		internal static void ErrorMissingRequirement(string missing)
		{
			ModLog.Error("Initialization error:  Unable to find required mod '" + missing + "' in mod list");
		}

		internal static void ErrorIncompatibleMod(ModMetaData othermod)
		{
			ModLog.Error("Initialization Error:  Incompatible mod '" + othermod.Name + "' detected in mod list");
		}
	}
}


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

/// <summary>
/// patches GenSpawn to:
/// check if spawned thing is pawn, and add sexualize it if parts missing
/// </summary>
namespace rjw
{
	[HarmonyPatch(typeof(GenSpawn), "Spawn", new Type[] { typeof(Thing), typeof(IntVec3), typeof(Map), typeof(Rot4), typeof(WipeMode), typeof(bool) })]
	static class Patch_GenSpawn_Spawn
	{
		[HarmonyPostfix]

		static void Sexualize_GenSpawn_Spawn(ref Thing __result)
		{
			if (__result != null)
				if (__result is Pawn)
				{
					//ModLog.Message("Sexualize_GenSpawn_Spawn:: " + xxx.get_pawnname(__result));
					Pawn pawn = __result as Pawn;
					if (pawn.kindDef.race.defName.Contains("AIRobot") // No genitalia/sexuality for roombas.
						|| pawn.kindDef.race.defName.Contains("AIPawn") // ...nor MAI.
						|| pawn.kindDef.race.defName.Contains("RPP_Bot")
						|| pawn.kindDef.race.defName.Contains("PRFDrone") // Project RimFactory Revived drones
						) return;

					if (!Genital_Helper.has_genitals(pawn))
					{
						Sexualizer.sexualize_pawn(pawn);
					}
				}
		}
	}
}


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

/// <summary>
/// patches PawnGenerator to:
/// add genitals to pawns
/// spawn nymph when needed
/// fix newborns beards and tattoos
/// </summary>
namespace rjw
{
	[HarmonyPatch(typeof(PawnGenerator), "GenerateNewPawnInternal")]
	static class Patch_PawnGenerator
	{
		[HarmonyPrefix]
		static void Generate_Nymph(ref PawnGenerationRequest request)
		{
			if (Nymph_Generator.IsNymph(request))
			{
				request = new PawnGenerationRequest(
					kind: request.KindDef = Nymph_Generator.GetFixedNymphPawnKindDef(),
					canGeneratePawnRelations: request.CanGeneratePawnRelations = false,
					validatorPreGear: Nymph_Generator.IsNymphBodyType,
					validatorPostGear: Nymph_Generator.IsNymphBodyType,
					fixedGender: request.FixedGender = Nymph_Generator.RandomNymphGender()
					);
			}
		}

		[HarmonyPostfix]
		static void Fix_Nymph(ref PawnGenerationRequest request, ref Pawn __result)
		{
			if (Nymph_Generator.IsNymph(request))
			{
				Nymph_Generator.set_story(__result);
				Nymph_Generator.set_skills(__result);
			}
		}

		[HarmonyPostfix]
		static void Sexualize_GenerateNewPawnInternal(ref PawnGenerationRequest request, ref Pawn __result)
		{
			//ModLog.Message("After_GenerateNewPawnInternal:: " + xxx.get_pawnname(__result));
			if (CompRJW.Comp(__result) != null && CompRJW.Comp(__result).orientation == Orientation.None)
			{
				//ModLog.Message("After_GenerateNewPawnInternal::Sexualize " + xxx.get_pawnname(__result));
				CompRJW.Comp(__result).Sexualize(__result);
			}
		}

		[HarmonyPostfix]
		static void Fix_Newborn_styles(ref PawnGenerationRequest request, ref Pawn __result)
		{
			if (request.Newborn)
			{
				if(__result.style != null)
				{
					__result.style.beardDef = BeardDefOf.NoBeard;
					__result.style.SetupTattoos_NoIdeology();
				}
			}
		}
	}
}


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

/// <summary>
/// patches PawnUtility to fix humanlike childrens post birth
/// </summary>
namespace rjw
{
	[HarmonyPatch(typeof(PawnUtility), "TrySpawnHatchedOrBornPawn")]
	static class Patch_PawnUtility
	{
		//[HarmonyPrefix]
		//static void prefix_TrySpawnHatchedOrBornPawn(ref Pawn pawn, Thing motherOrEgg)
		//{
		//	//ModLog.Message("prefix_TrySpawnHatchedOrBornPawn::");
		//	//ModLog.Message(" " + __result);
		//	//ModLog.Message(" " + xxx.get_pawnname(pawn));
		//	//ModLog.Message(" " + xxx.get_pawnname(motherOrEgg as Pawn));
		//	//ModLog.Message(" " + RJWPregnancySettings.humanlike_pregnancy_enabled);
		//	//ModLog.Message(" " + xxx.is_human(pawn));
		//	//ModLog.Message(" " + !xxx.is_mechanoid(pawn));
		//	//string last_name = NameTriple.FromString(pawn.Name.ToStringFull).Last;
		//	//ModLog.Message(" prefix_TrySpawnHatchedOrBornPawn Baby surname will be " + last_name);
		//}

		//resets pawn/doesn't work for some races with C# constructors
		[HarmonyPostfix]
		static void Process_Child_HatchOrBirth(ref bool __result, ref Pawn pawn, Thing motherOrEgg)
		{
			//ModLog.Message("postfix_TrySpawnHatchedOrBornPawn::");
			//ModLog.Message(" " + __result);
			//ModLog.Message(" " + xxx.get_pawnname(pawn));
			//ModLog.Message(" " + xxx.get_pawnname(motherOrEgg as Pawn));
			//ModLog.Message(" " + RJWPregnancySettings.humanlike_pregnancy_enabled);
			//ModLog.Message(" " + xxx.is_human(pawn));
			//ModLog.Message(" " + !xxx.is_mechanoid(pawn));
			//string last_name = NameTriple.FromString(pawn.Name.ToStringFull).Last;
			//ModLog.Message(" postfix_TrySpawnHatchedOrBornPawn 1 Baby surname will be " + last_name);
			//var skin_whiteness = pawn.story.melanin;
			//var last_name1 = pawn.story.birthLastName;
			if (__result
				&& RJWPregnancySettings.humanlike_pregnancy_enabled
				&& xxx.is_human(pawn)
				&& !xxx.is_mechanoid(pawn))
			{
				if ((motherOrEgg is Pawn && (motherOrEgg as Pawn).IsPregnant())	//vanilla + rjw pregnancy
					|| (motherOrEgg.TryGetComp<CompHatcher>() != null))			//vanilla + rjw eggnancy
				{
					changestory(pawn);
					removeimplants(pawn);
					removeskills(pawn);
					grow(pawn);
				}
			}
			//ModLog.Message(" postfix_TrySpawnHatchedOrBornPawn 2 Baby surname will be " + NameTriple.FromString(pawn.Name.ToStringFull).Last);
			//pawn.story.melanin = skin_whiteness;
			//pawn.story.birthLastName = last_name1;
		}

		static void removeimplants(Pawn pawn)
		{
			if (!pawn.health.hediffSet.hediffs.NullOrEmpty())
			{
				var hdlist = pawn.health.hediffSet.hediffs.ToList();
				foreach (Hediff hd in hdlist)
				{
					if (hd == null) continue;

					// remove DeathAcidifier
					//if (hd.def.defName == "DeathAcidifier")
					//{
					//	pawn.health.RemoveHediff(hd);
					//	continue;
					//}

					// remove implants
					if (hd is Hediff_Implant)
					{
						var part = hd.Part;
						pawn.health.RestorePart(part);
					}

					// remove immortality
					if (xxx.ImmortalsIsActive && hd.def == xxx.IH_Immortal)
					{
						pawn.health.RemoveHediff(hd);
					}
				}
			}
		}

		//resets/doest work for some races
		static void changestory(Pawn pawn)
		{
			if (!xxx.RimWorldChildrenIsActive)
			{
				pawn.story.childhood = null;
				pawn.story.adulthood = null;

				// set child to tribal
				try
				{
					Backstory bs = null;
					BackstoryDatabase.TryGetWithIdentifier("rjw_childT", out bs);

					pawn.story.childhood = bs;
				}
				catch (Exception e)
				{
					ModLog.Warning(e.ToString());
				}
			}
		}

		static void grow(Pawn pawn)
		{
			if (!xxx.RimWorldChildrenIsActive)
			{
				// add growing
				if (!pawn.Dead)
				{
					pawn.health.AddHediff(xxx.RJW_BabyState, null, null);
					Hediff_SimpleBaby pawnstate = (Hediff_SimpleBaby)pawn.health.hediffSet.GetFirstHediffOfDef(xxx.RJW_BabyState);
					if (pawnstate != null)
					{
						pawnstate.GrowUpTo(0, true);
					}
				}
			}
		}

		static void removeskills(Pawn pawn)
		{
			// remove skills
			foreach (var skill in pawn.skills?.skills)
				skill.Level = 0;
		}
	}
}


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

namespace rjw
{
	[HarmonyPatch(typeof(CharacterCardUtility), "DrawCharacterCard")]
	public static class SexcardPatch
	{
		public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			MethodInfo HighlightOpportunity = AccessTools.Method(typeof(UIHighlighter), "HighlightOpportunity");
			MethodInfo SexualityCardToggle = AccessTools.Method(typeof(SexcardPatch), nameof(SexualityCardToggle));
			bool traits = false;
			bool found = false;
			foreach (CodeInstruction i in instructions)
			{
				if (found)
				{
					yield return new CodeInstruction(OpCodes.Ldarg_0) { labels = i.labels.ListFullCopy() };//rect
					yield return new CodeInstruction(OpCodes.Ldarg_1);//pawn
					yield return new CodeInstruction(OpCodes.Ldarg_3);//creationRect
					yield return new CodeInstruction(OpCodes.Call, SexualityCardToggle);
					found = false;
					i.labels.Clear();
				}
				if (i.opcode == OpCodes.Call && i.operand == HighlightOpportunity)
				{
					found = true;
				}
				if (i.opcode == OpCodes.Ldstr && i.operand.Equals("Traits"))
				{
					traits = true;
				}
				if (traits && i.opcode == OpCodes.Ldc_R4 && i.operand.Equals(2f))//replaces rect y calculation
				{
					yield return new CodeInstruction(OpCodes.Ldc_R4, 0f);
					traits = false;
					continue;
				}
				yield return i;
			}
		}

		public static void SexualityCardToggle(Rect rect, Pawn pawn, Rect creationRect)
		{
			if (pawn == null) return;
			if (CompRJW.Comp(pawn) == null) return;

			//character bio
			Rect rectNew = new Rect(CharacterCardUtility.BasePawnCardSize.x - 50f, 2f, 24f, 24f);
			//character creator/game start
			if (Current.ProgramState != ProgramState.Playing)
			{
				//1.3
				if (ModsConfig.IdeologyActive) // Move icon lower to avoid overlap.
				{
					rectNew = new Rect(creationRect.width - 24f, 82f, 24f, 24f);
					if (xxx.IndividualityIsActive) // Move icon lower to avoid overlap.
						rectNew = new Rect(creationRect.width - 24f, 108f, 24f, 24f);
				}
				//1.1, 1.2
				else if (xxx.IndividualityIsActive) // Move icon lower to avoid overlap.
					rectNew = new Rect(creationRect.width - 24f, 56f, 24f, 24f);
				else
					rectNew = new Rect(creationRect.width - 24f, 30f, 24f, 24f);
			}
			Color old = GUI.color;

			GUI.color = rectNew.Contains(Event.current.mousePosition) ? new Color(0.25f, 0.59f, 0.75f) : new Color(1f, 1f, 1f);
			// TODO: Replace the placeholder icons with... something
			//if (CompRJW.Comp(pawn).quirks.ToString() != "None")
			//	GUI.DrawTexture(rectNew, ContentFinder<Texture2D>.Get("UI/Commands/Service_on"));
			//else
			//	GUI.DrawTexture(rectNew, ContentFinder<Texture2D>.Get("UI/Commands/Service_off"));
				GUI.DrawTexture(rectNew, ContentFinder<Texture2D>.Get("RJW-LOGO"));

			TooltipHandler.TipRegion(rectNew, "SexcardTooltip".Translate());
			if (Widgets.ButtonInvisible(rectNew))
			{
				SoundDefOf.InfoCard_Open.PlayOneShotOnCamera();
				Find.WindowStack.Add(new Dialog_Sexcard(pawn));
			}
			GUI.color = old;
		}
	}
}


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

namespace rjw
{
	//TODO: check slime stuff working in mp
	//TODO: separate menus in sub scripts
	//TODO: add demon switch parts
	//TODO: figure out and make interface?
	//TODO: add vibration toggle for bionics(+50% partner satisfaction?)
	public class Dialog_Sexcard : Window
	{
		private readonly Pawn pawn;

		public Dialog_Sexcard(Pawn editFor)
		{
			pawn = editFor;
		}

		public static breasts Breasts;
		public enum breasts
		{
			selectone,
			none,
			featureless_chest,
			flat_breasts,
			small_breasts,
			average_breasts,
			large_breasts,
			huge_breasts,
			slime_breasts,
		};

		public static anuses Anuses;
		public enum anuses
		{
			selectone,
			none,
			micro_anus,
			tight_anus,
			average_anus,
			loose_anus,
			gaping_anus,
			slime_anus,
		};

		public static vaginas Vaginas;
		public enum vaginas
		{
			selectone,
			none,
			micro_vagina,
			tight_vagina,
			average_vagina,
			loose_vagina,
			gaping_vagina,
			slime_vagina,
			feline_vagina,
			canine_vagina,
			equine_vagina,
			dragon_vagina,
		};

		public static penises Penises;
		public enum penises
		{
			selectone,
			none,
			micro_penis,
			small_penis,
			average_penis,
			big_penis,
			huge_penis,
			slime_penis,
			feline_penis,
			canine_penis,
			equine_penis,
			dragon_penis,
			raccoon_penis,
			hemipenis,
			crocodilian_penis,
		};

		public void SexualityCard(Rect rect, Pawn pawn)
		{
			CompRJW comp = pawn.TryGetComp<CompRJW>();
			if (pawn == null || comp == null) return;

			Text.Font = GameFont.Medium;
			Rect rect1 = new Rect(8f, 4f, rect.width - 8f, rect.height - 20f);
			Widgets.Label(rect1, "RJW");//rjw

			Text.Font = GameFont.Tiny;
			float num = rect1.y + 40f;
			Rect row1 = new Rect(10f, num, rect.width - 8f, 24f);//sexuality
			Rect row2 = new Rect(10f, num + 24, rect.width - 8f, 24f);//quirks
			Rect row3 = new Rect(10f, num + 48, rect.width - 8f, 24f);//whore price

			//Rect sexuality_button = new Rect(10f, rect1.height - 0f, rect.width - 8f, 24f);//change sex pref
			Rect button1 = new Rect(10f, rect1.height - 10f, rect.width - 8f, 24f);//re sexualize
			Rect button2 = new Rect(10f, rect1.height - 34f, rect.width - 8f, 24f);//archtech toggle
			Rect button3 = new Rect(10f, rect1.height - 58f, rect.width - 8f, 24f);//breast
			Rect button4 = new Rect(10f, rect1.height - 82f, rect.width - 8f, 24f);//anus
			Rect button5 = new Rect(10f, rect1.height - 106f, rect.width - 8f, 24f);//vagina
			Rect button6 = new Rect(10f, rect1.height - 130f, rect.width - 8f, 24f);//penis 1
			Rect button7 = new Rect(10f, rect1.height - 154f, rect.width - 8f, 24f);//penis 2
			Rect button8 = new Rect(10f, rect1.height + 14f, rect.width/2 - 8f, 24f);//show Would_fuck
			Rect button9 = new Rect(10f + rect.width / 2, rect1.height + 14f, rect.width/2 - 8f, 24f);//show Would_fuck table

			DrawSexuality(pawn, row1);
			DrawQuirks(pawn, row2);
			//DrawWhoring(pawn, row3);

			// TODO: Add translations. or not
			if (RJWSettings.DevMode || Current.ProgramState != ProgramState.Playing)
			{
				if (Widgets.ButtonText(button1, Current.ProgramState != ProgramState.Playing ? "Reroll" : "[DEV] Reroll"))
				{
					Re_sexualize(pawn);
				}
			}
			if (RJWSettings.DevMode && Current.ProgramState == ProgramState.Playing)
			{
				if (Widgets.ButtonText(button8, "Would_fuck chances"))
				{
					Would_fuck(pawn);
				}
				if (Widgets.ButtonText(button9, "Would_fuck chances (CSV Table)"))
				{
					Would_fuckT(pawn);
				}
			}
			if (pawn.health.hediffSet.HasHediff(Genital_Helper.archotech_penis) || pawn.health.hediffSet.HasHediff(Genital_Helper.archotech_vagina))
			{
				if (pawn.health.hediffSet.HasHediff(HediffDef.Named("ImpregnationBlocker")))
				{
					if (Widgets.ButtonText(button2, "[Archotech genitalia] Enable reproduction"))
					{
						Change_Archotechmode(pawn);
					}
				}
				else if (!pawn.health.hediffSet.HasHediff(HediffDef.Named("FertilityEnhancer")))
				{
					if (Widgets.ButtonText(button2, "[Archotech genitalia] Enchance fertility"))
					{
						Change_Archotechmode(pawn);
					}
				}
				else if (Widgets.ButtonText(button2, "[Archotech genitalia] Disable reproduction"))
				{
					Change_Archotechmode(pawn);
				}
			}
			// TODO: add mp synchronizers
			// TODO: clean that mess
			// TODO: add demon toggles
			if (MP.IsInMultiplayer)
				return;

			//List<String> Parts = null;
			//if (xxx.is_slime(pawn))
			//	Parts = new List<string>(DefDatabase<StringListDef>.GetNamed("SlimeMorphFilters").strings);
			//if (xxx.is_demon(pawn))
			//	Parts = new List<string>(DefDatabase<StringListDef>.GetNamed("DemonMorphFilters").strings);

			//if (Parts.Any() && (pawn.IsColonistPlayerControlled || pawn.IsPrisonerOfColony || pawn.IsSlaveOfColony))
				//if (xxx.is_slime(pawn) && (pawn.IsColonistPlayerControlled || pawn.IsPrisonerOfColony || pawn.IsSlaveOfColony))
			if (pawn.IsColonistPlayerControlled || pawn.IsPrisonerOfColony || pawn.IsSlaveOfColony)
			{
				BodyPartRecord bpr_genitalia = Genital_Helper.get_genitalsBPR(pawn);
				BodyPartRecord bpr_breasts = Genital_Helper.get_breastsBPR(pawn);
				BodyPartRecord bpr_anus = Genital_Helper.get_anusBPR(pawn);
				BodyPartRecord partBPR = null;
				Rect Button = new Rect();

				Button = button3;
				partBPR = bpr_breasts;
				Make_button(Button, pawn, partBPR);

				Button = button4;
				partBPR = bpr_anus;
				Make_button(Button, pawn, partBPR);

				Button = button5;
				partBPR = bpr_genitalia;
				Make_button(Button, pawn, partBPR, "p");

				Button = button6;
				partBPR = bpr_genitalia;
				Make_button(Button, pawn, partBPR, "v");
			}
		}

		static void DrawSexuality(Pawn pawn, Rect row)
		{
			string sexuality;

			if (RJWPreferenceSettings.sexuality_distribution == RJWPreferenceSettings.Rjw_sexuality.Vanilla)
				CompRJW.VanillaTraitCheck(pawn);
			if (RJWPreferenceSettings.sexuality_distribution == RJWPreferenceSettings.Rjw_sexuality.SYRIndividuality)
				CompRJW.CopyIndividualitySexuality(pawn);
			if (RJWPreferenceSettings.sexuality_distribution == RJWPreferenceSettings.Rjw_sexuality.Psychology)
				CompRJW.CopyPsychologySexuality(pawn);

			switch (CompRJW.Comp(pawn).orientation)
			{
				case Orientation.Asexual:
					sexuality = "Asexual";
					break;
				case Orientation.Bisexual:
					sexuality = "Bisexual";
					break;
				case Orientation.Heterosexual:
					sexuality = "Hetero";
					break;
				case Orientation.Homosexual:
					sexuality = "Gay";
					break;
				case Orientation.LeaningHeterosexual:
					sexuality = "Bisexual, leaning hetero";
					break;
				case Orientation.LeaningHomosexual:
					sexuality = "Bisexual, leaning gay";
					break;
				case Orientation.MostlyHeterosexual:
					sexuality = "Mostly hetero";
					break;
				case Orientation.MostlyHomosexual:
					sexuality = "Mostly gay";
					break;
				case Orientation.Pansexual:
					sexuality = "Pansexual";
					break;
				default:
					sexuality = "None";
					break;
			}

			//allow to change pawn sexuality for:
			//own hero, game start
			if (RJWPreferenceSettings.sexuality_distribution == RJWPreferenceSettings.Rjw_sexuality.RimJobWorld &&
				(((Current.ProgramState == ProgramState.Playing &&
				pawn.IsDesignatedHero() && pawn.IsHeroOwner()) ||
				Prefs.DevMode) ||
				Current.ProgramState == ProgramState.Entry))

			{
				if (Widgets.ButtonText(row, "Sexuality: " + sexuality, false))
				{
					Find.WindowStack.Add(new FloatMenu(new List<FloatMenuOption>()			//this needs fixing in 1.1 with vanilla orientation traits
					{
						new FloatMenuOption("Asexual", (() => Change_orientation(pawn, Orientation.Asexual)), MenuOptionPriority.Default),
						new FloatMenuOption("Pansexual", (() => Change_orientation(pawn, Orientation.Pansexual)), MenuOptionPriority.Default),
						new FloatMenuOption("Heterosexual", (() => Change_orientation(pawn, Orientation.Heterosexual)), MenuOptionPriority.Default),
						new FloatMenuOption("MostlyHeterosexual", (() => Change_orientation(pawn, Orientation.MostlyHeterosexual)), MenuOptionPriority.Default),
						new FloatMenuOption("LeaningHeterosexual", (() => Change_orientation(pawn, Orientation.LeaningHeterosexual)), MenuOptionPriority.Default),
						new FloatMenuOption("Bisexual", (() => Change_orientation(pawn, Orientation.Bisexual)), MenuOptionPriority.Default),
						new FloatMenuOption("LeaningHomosexual", (() => Change_orientation(pawn, Orientation.LeaningHomosexual)), MenuOptionPriority.Default),
						new FloatMenuOption("MostlyHomosexual", (() => Change_orientation(pawn, Orientation.MostlyHomosexual)), MenuOptionPriority.Default),
						new FloatMenuOption("Homosexual", (() => Change_orientation(pawn, Orientation.Homosexual)), MenuOptionPriority.Default),
					}));
				}
			}
			else
			{
				Widgets.Label(row, "Sexuality: " + sexuality);
				if (Mouse.IsOver(row))
					Widgets.DrawHighlight(row);
			}
		}

		static void DrawQuirks(Pawn pawn, Rect row)
		{

			var quirks = Quirk.All
				.Where(quirk => pawn.Has(quirk))
				.OrderBy(quirk => quirk.Key)
				.ToList();

			// Not actually localized.
			var quirkString = quirks.Select(quirk => quirk.Key).ToCommaList();

			if ((Current.ProgramState == ProgramState.Playing &&
				pawn.IsDesignatedHero() && pawn.IsHeroOwner() ||
				Prefs.DevMode) ||
				Current.ProgramState == ProgramState.Entry)

			{
				var quirksAll = Quirk.All
								.OrderBy(quirk => quirk.Key)
								.ToList();

				if (!RJWSettings.DevMode)
				{
					quirksAll.Remove(Quirk.Breeder);
					quirksAll.Remove(Quirk.Incubator);
				}

				if (xxx.is_insect(pawn))
					quirksAll.Add(Quirk.Incubator);

				if (Widgets.ButtonText(row, "Quirks".Translate() + quirkString, false))
				{
					var list = new List<FloatMenuOption>();
					list.Add(new FloatMenuOption("Reset", (() => QuirkAdder.Clear(pawn)), MenuOptionPriority.Default));
					foreach (Quirk quirk in quirksAll)
					{
						if (!pawn.Has(quirk))
							list.Add(new FloatMenuOption(quirk.Key, (() => QuirkAdder.Add(pawn, quirk))));
						//else
						//	list.Add(new FloatMenuOption(quirk.Key, (() => QuirkAdder.Remove(pawn, quirk))));
						//TODO: fix quirk description box in 1.1 menus
						//list.Add(new FloatMenuOption(quirk.Key, (() => QuirkAdder.Add(pawn, quirk)), MenuOptionPriority.Default, delegate
						//{
						//	TooltipHandler.TipRegion(row, quirk.LocaliztionKey.Translate(pawn.Named("pawn")));
						//}
						//));
					}
					Find.WindowStack.Add(new FloatMenu(list));
				}
			}
			else
			{
				// TODO: long quirk list support
				// This can be too long and line wrap.
				// Should probably be a vertical list like traits.
				Widgets.Label(row, "Quirks".Translate() + quirkString);

			}

			if (!Mouse.IsOver(row)) return;

			Widgets.DrawHighlight(row);
			if (quirks.NullOrEmpty())
			{
				TooltipHandler.TipRegion(row, "NoQuirks".Translate());
			}
			else
			{
				StringBuilder stringBuilder = new StringBuilder();
				foreach (var q in quirks)
				{
					stringBuilder.AppendLine(q.Key.Colorize(Color.yellow));
					stringBuilder.AppendLine(q.LocaliztionKey.Translate(pawn.Named("pawn")).AdjustedFor(pawn).Resolve());
					stringBuilder.AppendLine("");
				}
				string str = stringBuilder.ToString().TrimEndNewlines();
				TooltipHandler.TipRegion(row, str);
			}
		}

		//static string DrawWhoring(Pawn pawn, Rect row)
		//{
			//string price;
			//if (RJWSettings.sex_age_legacymode && pawn.ageTracker.AgeBiologicalYears < RJWSettings.sex_minimum_age)
			//	price = "Inapplicable (too young)";
			//else if (!RJWSettings.sex_age_legacymode && pawn.ageTracker.Growth < 1 && !pawn.ageTracker.CurLifeStage.reproductive)
			//	price = "Inapplicable (too young)";
			//else if (pawn.ownership.OwnedRoom == null)
			//{
			//	if (Current.ProgramState == ProgramState.Playing)
			//		price = WhoringHelper.WhoreMinPrice(pawn) + " - " + WhoringHelper.WhoreMaxPrice(pawn) + " (base, needs suitable bedroom)";
			//	else
			//		price = WhoringHelper.WhoreMinPrice(pawn) + " - " + WhoringHelper.WhoreMaxPrice(pawn) + " (base, modified by bedroom quality)";
			//}
			//else if (xxx.is_animal(pawn))
			//	price = "Incapable of whoring";
			//else
			//	price = WhoringHelper.WhoreMinPrice(pawn) + " - " + WhoringHelper.WhoreMaxPrice(pawn);

			//Widgets.Label(row, "WhorePrice".Translate() + price);
			//if (Mouse.IsOver(row))
			//	Widgets.DrawHighlight(row);
			//return price;
		//}

		[SyncMethod]
		static void Change_orientation(Pawn pawn, Orientation orientation)
		{
			CompRJW.Comp(pawn).orientation = orientation;
		}

		[SyncMethod]
		static void Change_Archotechmode(Pawn pawn)
		{
			BodyPartRecord genitalia = Genital_Helper.get_genitalsBPR(pawn);
			Hediff blocker = pawn.health.hediffSet.GetFirstHediffOfDef(HediffDef.Named("ImpregnationBlocker"));
			Hediff enhancer = pawn.health.hediffSet.GetFirstHediffOfDef(HediffDef.Named("FertilityEnhancer"));

			if (blocker != null)
			{
				pawn.health.RemoveHediff(blocker);
			}
			else if (enhancer == null)
			{
				pawn.health.AddHediff(HediffDef.Named("FertilityEnhancer"), genitalia);
			}
			else
			{
				if (enhancer != null)
					pawn.health.RemoveHediff(enhancer);
				pawn.health.AddHediff(HediffDef.Named("ImpregnationBlocker"), genitalia);
			}
		}

		[SyncMethod]
		static void Re_sexualize(Pawn pawn)
		{
			CompRJW.Comp(pawn).Sexualize(pawn, true);
		}

		static void Would_fuck(Pawn pawn)
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendLine();
			stringBuilder.AppendLine("canFuck: " + xxx.can_fuck(pawn) + ", canBeFucked: " + xxx.can_be_fucked(pawn) + ", canDoLoving: " + xxx.can_do_loving(pawn));
			stringBuilder.AppendLine("canRape: " + xxx.can_rape(pawn) + ", canBeRaped: " + xxx.can_get_raped(pawn));

			if (!pawn.IsColonist)
				if (pawn.Faction != null)
				{
					int pawnAmountOfSilvers = pawn.inventory.innerContainer.TotalStackCountOfDef(ThingDefOf.Silver);
					int caravanAmountOfSilvers = 0;
					Lord lord = pawn.GetLord();
					List<Pawn> caravanMembers = pawn.Map.mapPawns.PawnsInFaction(pawn.Faction).Where(x => x.GetLord() == lord && x.inventory?.innerContainer?.TotalStackCountOfDef(ThingDefOf.Silver) > 0).ToList();

					caravanAmountOfSilvers += caravanMembers.Sum(member => member.inventory.innerContainer.TotalStackCountOfDef(ThingDefOf.Silver));

					stringBuilder.AppendLine("pawnSilvers: " + pawnAmountOfSilvers + ", caravanSilvers: " + caravanAmountOfSilvers);
				}
			stringBuilder.AppendLine();

			stringBuilder.AppendLine("Humans - Colonists:");
			List<Pawn> pawns = pawn.Map.mapPawns.AllPawnsSpawned.Where(x => x != pawn && x.RaceProps.Humanlike && x.IsColonist).OrderBy(x => xxx.get_pawnname(x)).ToList();
			foreach (Pawn partner in pawns)
			{
				stringBuilder.AppendLine(partner.LabelShort + " (" + partner.gender.GetLabel() +
					", age: " + partner.ageTracker.AgeBiologicalYears +
					", " + CompRJW.Comp(partner).orientation +
					"): (would fuck) " + SexAppraiser.would_fuck(pawn, partner).ToString("F3") +
					"): (be fucked) " + SexAppraiser.would_fuck(partner, pawn).ToString("F3") +
					": (rape) " + SexAppraiser.would_rape(pawn, partner));
			}
			stringBuilder.AppendLine();

			stringBuilder.AppendLine("Humans - Prisoners:");
			pawns = pawn.Map.mapPawns.AllPawnsSpawned.Where(x => x != pawn && x.RaceProps.Humanlike && !x.IsColonist && x.IsPrisonerOfColony).OrderBy(x => xxx.get_pawnname(x)).ToList();
			foreach (Pawn partner in pawns)
			{
				stringBuilder.AppendLine(partner.LabelShort + " (" + partner.gender.GetLabel() +
					", age: " + partner.ageTracker.AgeBiologicalYears +
					", " + CompRJW.Comp(partner).orientation +
					"): (would fuck) " + SexAppraiser.would_fuck(pawn, partner).ToString("F3") +
					"): (be fucked) " + SexAppraiser.would_fuck(partner, pawn).ToString("F3") +
					": (rape) " + SexAppraiser.would_rape(pawn, partner));
			}
			stringBuilder.AppendLine();

			stringBuilder.AppendLine("Humans - Slaves:");
			pawns = pawn.Map.mapPawns.AllPawnsSpawned.Where(x => x != pawn && x.RaceProps.Humanlike && !x.IsColonist && x.IsSlaveOfColony).OrderBy(x => xxx.get_pawnname(x)).ToList();
			foreach (Pawn partner in pawns)
			{
				stringBuilder.AppendLine(partner.LabelShort + " (" + partner.gender.GetLabel() +
					", age: " + partner.ageTracker.AgeBiologicalYears +
					", " + CompRJW.Comp(partner).orientation +
					"): (would fuck) " + SexAppraiser.would_fuck(pawn, partner).ToString("F3") +
					"): (be fucked) " + SexAppraiser.would_fuck(partner, pawn).ToString("F3") +
					": (rape) " + SexAppraiser.would_rape(pawn, partner));
			}
			stringBuilder.AppendLine();

			stringBuilder.AppendLine("Humans - non Colonists:");
			pawns = pawn.Map.mapPawns.AllPawnsSpawned.Where(x => x != pawn && x.RaceProps.Humanlike && !x.IsColonist && !x.IsPrisonerOfColony && !x.IsSlaveOfColony).OrderBy(x => xxx.get_pawnname(x)).ToList();
			foreach (Pawn partner in pawns)
			{
				stringBuilder.AppendLine(partner.LabelShort + " (" + partner.gender.GetLabel() +
					", age: " + partner.ageTracker.AgeBiologicalYears +
					", " + CompRJW.Comp(partner).orientation +
					"): (would fuck) " + SexAppraiser.would_fuck(pawn, partner).ToString("F3") +
					"): (be fucked) " + SexAppraiser.would_fuck(partner, pawn).ToString("F3") +
					": (rape) " + SexAppraiser.would_rape(pawn, partner));
			}
			stringBuilder.AppendLine();

			stringBuilder.AppendLine("Animals - Colony:");
			pawns = pawn.Map.mapPawns.AllPawnsSpawned.Where(x => x != pawn && x.RaceProps.Animal && x.Faction == Faction.OfPlayer).OrderBy(x => xxx.get_pawnname(x)).ToList();
			foreach (Pawn partner in pawns)
			{
				stringBuilder.AppendLine(partner.LabelShort + " (" + partner.gender.GetLabel() +
					", age: " + partner.ageTracker.AgeBiologicalYears +
					//", " + CompRJW.Comp(partner).orientation +
					"): (would fuck) " + SexAppraiser.would_fuck(pawn, partner).ToString("F3") +
					"): (be fucked) " + SexAppraiser.would_fuck(partner, pawn).ToString("F3") +
					": (rape) " + SexAppraiser.would_rape(pawn, partner));
			}
			stringBuilder.AppendLine();

			stringBuilder.AppendLine("Animals - non Colony:");
			pawns = pawn.Map.mapPawns.AllPawnsSpawned.Where(x => x != pawn && x.RaceProps.Animal && x.Faction != Faction.OfPlayer).OrderBy(x => xxx.get_pawnname(x)).ToList();
			foreach (Pawn partner in pawns)
			{
				stringBuilder.AppendLine(partner.LabelShort + " (" + partner.gender.GetLabel() +
					", age: " + partner.ageTracker.AgeBiologicalYears +
					//", " + CompRJW.Comp(partner).orientation +
					"): (would fuck) " + SexAppraiser.would_fuck(pawn, partner).ToString("F3") +
					"): (be fucked) " + SexAppraiser.would_fuck(partner, pawn).ToString("F3") +
					": (rape) " + SexAppraiser.would_rape(pawn, partner));
			}
			Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder.ToString(), null, null, null, null, null, false, null, null));
		}
		static void Would_fuckT(Pawn pawn)
		{
			{
				DebugTables.MakeTablesDialog(pawn.Map.mapPawns.AllPawnsSpawned.Where(x => x != null & x != pawn),
					new TableDataGetter<Pawn>("Name", (Pawn p) => p.NameFullColored),
					new TableDataGetter<Pawn>("Age", (Pawn p) => p.ageTracker.AgeBiologicalYears),
					new TableDataGetter<Pawn>("Gender", (Pawn p) => p.gender.GetLabel()),
					new TableDataGetter<Pawn>("isAnimal", (Pawn p) => p.RaceProps.Animal),
					new TableDataGetter<Pawn>("isAnimalOfColony", (Pawn p) => p.RaceProps.Animal & p.Faction == Faction.OfPlayer),
					new TableDataGetter<Pawn>("IsColonist", (Pawn p) => p.IsColonist),
					new TableDataGetter<Pawn>("IsPrisonerOfColony", (Pawn p) => p.IsPrisonerOfColony),
					new TableDataGetter<Pawn>("IsSlaveOfColony", (Pawn p) => p.IsSlaveOfColony),
					new TableDataGetter<Pawn>("would fuck score", (Pawn p) => SexAppraiser.would_fuck(pawn, p).ToStringPercent()),
					new TableDataGetter<Pawn>("be fucked score", (Pawn p) => SexAppraiser.would_fuck(p, pawn).ToStringPercent()),
					new TableDataGetter<Pawn>("would rape", (Pawn p) => SexAppraiser.would_rape(pawn, p)),
					new TableDataGetter<Pawn>("be raped", (Pawn p) => SexAppraiser.would_rape(p, pawn))
				);
			}
		}

		static void Make_button(Rect Button, Pawn pawn, BodyPartRecord partBPR, string gen = "")
		{
			string ButtonLabel = "nothing here";
			bool resizable = RJWSettings.DevMode;
			List<Hediff> parts = new List<Hediff>();
			List<Hediff> parts1 = new List<Hediff>();
			Hediff hed = null;

			parts = Genital_Helper.get_PartsHediffList(pawn, partBPR);
			if (!parts.NullOrEmpty())
			{
				if (gen == "p")
					parts1.AddRange(parts.Where(x => Genital_Helper.is_penis(x)));
				if (gen == "v")
					parts1.AddRange(parts.Where(x => Genital_Helper.is_vagina(x)));
				if (gen != "")
					parts = parts1;

				if (!parts.NullOrEmpty())
					hed = parts.FirstOrDefault();

				if (hed != null)
				{
					//ButtonLabel = "Morph breasts";
					ButtonLabel = "Change " + hed.Label + " size";

					if (!resizable)
						foreach (var p in parts)
						{
							if (PartProps.TryGetProps(p, out List<string> l) && l.Contains("Resizable"))
								resizable = true;
						}

					if (resizable)
						if (hed is Hediff_PartBaseNatural)
						{
							Make_resize_button(Button, ButtonLabel, hed, parts);
						}
						else if (hed is Hediff_PartBaseArtifical)
						{
							Make_resize_button(Button, ButtonLabel, hed, parts);
						}
				}
			}
		}

		static void Make_resize_button(Rect Button, string ButtonLabel, Hediff hed, List<Hediff> parts)
		{
			if (Widgets.ButtonText(Button, ButtonLabel))
			{
				var stages = hed.def.stages;
				var opts = new List<FloatMenuOption>();

				foreach (var s in stages)
				{
					opts.Add(new FloatMenuOption(hed.def.label.CapitalizeFirst() + "(" + s.label.CapitalizeFirst() + ")", () =>
					{
						foreach (var p in parts)
						{
							if (RJWSettings.DevMode ||
							(PartProps.TryGetProps(p, out List<string> l) && l.Contains("Resizable")))
								p.Severity = s.minSeverity;
						}
					}, MenuOptionPriority.Default));
				}

				Find.WindowStack.Add(new FloatMenu(opts));
			}
		}

		public override void DoWindowContents(Rect inRect)
		{
			bool flag = false;
			soundClose = SoundDefOf.InfoCard_Close;
			closeOnClickedOutside = true;
			absorbInputAroundWindow = false;
			forcePause = true;
			preventCameraMotion = false;
			if (Event.current.type == EventType.KeyDown && (Event.current.keyCode == KeyCode.Return || Event.current.keyCode == KeyCode.Escape))
			{
				flag = true;
				Event.current.Use();
			}
			Rect windowRect = inRect.ContractedBy(17f);
			Rect mainRect = new Rect(windowRect.x, windowRect.y, windowRect.width, windowRect.height - 20f);
			Rect okRect = new Rect(inRect.width / 3, mainRect.yMax + 10f, inRect.width / 3f, 30f);
			SexualityCard(mainRect, pawn);
			if (Widgets.ButtonText(okRect, "CloseButton".Translate()) || flag)
			{
				Close();
			}
		}
	}
}


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

/// <summary>
/// patches PawnUtility to fix humanlike childrens post birth
/// </summary>
namespace rjw
{
	[HarmonyPatch(typeof(PawnRenderer), "DrawBodyApparel")]
	static class Patch_PawnRenderer_DrawBodyApparel
	{
		//[HarmonyPrefix]
		//static void prefix_TrySpawnHatchedOrBornPawn(ref Pawn pawn, Thing motherOrEgg)
		//{
		//	//ModLog.Message("prefix_TrySpawnHatchedOrBornPawn::");
		//	//ModLog.Message(" " + __result);
		//	//ModLog.Message(" " + xxx.get_pawnname(pawn));
		//	//ModLog.Message(" " + xxx.get_pawnname(motherOrEgg as Pawn));
		//	//ModLog.Message(" " + RJWPregnancySettings.humanlike_pregnancy_enabled);
		//	//ModLog.Message(" " + xxx.is_human(pawn));
		//	//ModLog.Message(" " + !xxx.is_mechanoid(pawn));
		//	//string last_name = NameTriple.FromString(pawn.Name.ToStringFull).Last;
		//	//ModLog.Message(" prefix_TrySpawnHatchedOrBornPawn Baby surname will be " + last_name);
		//}

		//resets pawn/doesn't work for some races with C# constructors
		[HarmonyPrefix]
		static bool prefix_DrawBodyApparel(ref Pawn pawn)
		{
			if (pawn.jobs?.curDriver is JobDriver_Sex)
			{
				ModLog.Message(pawn.Name+ " sex");
				SexUtility.DrawNude(pawn);
				return false;
			}
			return true;
		}
	}
}


code:
using System;
using System.Collections.Generic;
using HarmonyLib;
using RimWorld;
using Verse;
using Verse.AI.Group;
using System.Reflection;

namespace rjw
{
	//ABF?? raid rape before leaving?
	[HarmonyPatch(typeof(LordJob_AssaultColony), "CreateGraph")]
	internal static class Patches_AssaultColonyForRape
	{
		[HarmonyPostfix]
		public static void Postfix(StateGraph __result)
		{
			//--Log.Message("[ABF]AssaultColonyForRape::CreateGraph");
			if (__result == null) return;
			//--ModLog.Message("AssaultColonyForRape::CreateGraph");
			foreach (var trans in __result.transitions)
			{
				if (HasDesignatedTransition(trans))
				{
					foreach (Trigger t in trans.triggers)
					{
						if (t.filters == null)
						{
							t.filters = new List<TriggerFilter>() { new Trigger_SexSatisfy(0.3f) };
						}
						else
						{
							t.filters.Add(new Trigger_SexSatisfy(0.3f));
						}
					}
					//--Log.Message("[ABF]AssaultColonyForRape::CreateGraph Adding SexSatisfyTrigger to " + trans.ToString());
				}
			}
		}

		private static bool HasDesignatedTransition(Transition t)
		{
			if (t.target == null) return false;
			if (t.target.GetType() == typeof(LordToil_KidnapCover)) return true;

			foreach (Trigger ta in t.triggers)
			{
				if (ta.GetType() == typeof(Trigger_FractionColonyDamageTaken)) return true;
			}
			return false;
		}
	}

	/*
	[HarmonyPatch(typeof(JobGiver_Manhunter), "TryGiveJob")]
	static class Patches_ABF_MunHunt
	{
		public static void Postfix(Job __result, ref Pawn pawn)
		{
			//--ModLog.Message("Patches_ABF_MunHunt::Postfix called");
			if (__result == null) return;

			if (__result.def == JobDefOf.Wait || __result.def == JobDefOf.Goto) __result = null;
		}
	}
	*/

	[HarmonyPatch(typeof(SkillRecord), "CalculateTotallyDisabled")]
	internal static class Patches_SkillRecordDebug
	{
		[HarmonyPrefix]
		public static bool Prefix(SkillRecord __instance, ref bool __result)
		{
			var field = __instance.GetType().GetField("pawn", BindingFlags.GetField | BindingFlags.SetField | BindingFlags.NonPublic | BindingFlags.Instance);
			Pawn pawn = (field.GetValue(__instance) as Pawn);
			if (__instance.def == null)
			{
				ModLog.Message("no def!");
				__result = false;
				return false;
			}
			return true;
		}
	}
}


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

namespace rjw
{
	//adds new gizmo for adding semen for testing
	[HarmonyPatch(typeof(Pawn), "GetGizmos")]
	class Patch_AddSexGizmo
	{
		[HarmonyPriority(99),HarmonyPostfix]
		static IEnumerable<Gizmo> AddSexGizmo(IEnumerable<Gizmo> __result, Pawn __instance)
		{

			foreach (Gizmo entry in __result)
			{
				yield return entry;
			}

			if (ModsConfig.RoyaltyActive)
				if (__instance?.jobs?.curDriver is JobDriver_Sex)
				{
					Gizmo SexGizmo = new SexGizmo(__instance);
					yield return SexGizmo;
				}
		}
	}
}


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 adding_RJW_toggle(WidgetRow row, bool worldView)
		{
			if (worldView) 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]
		static void this_is_postfix(ref IEnumerable<Gizmo> __result, ref Pawn __instance)
		{
			if (!RJWSettings.show_RJW_designation_box) return;
			if (!(__instance.Faction == Faction.OfPlayer || __instance.IsPrisonerOfColony)) return;
			//Log.Message("[rjw]Harmony patch submit_button is called");
			var pawn = __instance;
			var gizmos = __result.ToList();
			gizmos.Add(new RJWdesignations(pawn));
			__result = gizmos.AsEnumerable();
		}
	}

AnimalTab
Extensions
        public static bool Pregnant( this Pawn pawn )
        {
            // get hediff
            var _hediff = pawn.health.hediffSet.GetFirstHediffOfDef( HediffDefOf.Pregnant );

            // if pregnant, and pregnancy is far enough advanced to be visible
            if ( _hediff?.Visible ?? false )
                return true;

            // not (visibly) pregnant.
            return false;
        }	///
	///Submit gizmo
	///
	[HarmonyPatch(typeof(Pawn), "GetGizmos")]
	[StaticConstructorOnStartup]
	static class submit_button
	{
		[HarmonyPostfix]
		static void this_is_postfix(ref IEnumerable<Gizmo> __result, ref Pawn __instance)
		{
			//Log.Message("[rjw]Harmony patch submit_button is called");
			var pawn = __instance;
			var gizmos = __result.ToList();
			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)))
					{
						gizmos.Add(new Command_Action
						{
							defaultLabel = "CommandSubmit".Translate(),
							icon = submit_icon,
							defaultDesc = "CommandSubmitDesc".Translate(),
							action = delegate
							{
								LayDownAndAccept(pawn);
							},
							hotKey = KeyBindingDefOf.Misc3
						});
					}
			__result = gizmos.AsEnumerable();
		}

		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.Reflection;
using Harmony;
using RimWorld;
using Verse;
using System;

namespace rjw
{
	/// <summary>
	/// Conditional patching class that only does patching if CnP is active
	/// </summary>
	public class patch_CnPBnC
	{
		private readonly static Type Hediff_Baby = AccessTools.TypeByName("Hediff_Baby");
		Notify_TraitChanged()
			//CnP (or BnC) try to address the joy need of a child, prisoners don't have that.
								//Considering how you can arrest children without rjw, it is more of a bug of that mod than ours.
		[HarmonyPatch(typeof(HediffGiver_Birthday), "GrowUpTo")]
		static class jfpk
		{
			[HarmonyPostfix]
			static void postfix(ref Pawn_NeedsTracker __instance)
			{
				Pawn_NeedsTracker tr = __instance;
				FieldInfo fieldInfo = AccessTools.Field(typeof(Pawn_NeedsTracker), "pawn");
				Pawn pawn = fieldInfo.GetValue(__instance) as Pawn;
				if (xxx.is_human(pawn) && pawn.ageTracker.CurLifeStageIndex < AgeStage.Teenager)
				{
					if (tr.TryGetNeed(NeedDefOf.Joy) == null)
					{
						MethodInfo method = AccessTools.Method(typeof(Pawn_NeedsTracker), "AddNeed");
						method.Invoke(tr, new object[] { NeedDefOf.Joy });
					}
				}
			}
		}
	}
}


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

namespace rjw
{
	/// <summary>
	/// count (rjw) bodypart with missing rjw part as missing to prevent damage
	/// </summary>
	[HarmonyPatch(typeof(HediffSet), "PartIsMissing")]
	internal static class PATCH_HediffSet_GetRandomNotMissingPart
	{
		[HarmonyPostfix]
		private static void rjwPartIsMissing(ref bool __result, ref HediffSet __instance, BodyPartRecord part)
		{
			if (__result == true)
				return;

			var pawn = __instance.pawn;

			if (__instance.pawn != null)
			{
				if (part.def == xxx.genitalsDef && pawn.GetGenitalsList().NullOrEmpty())
					__result = true;
				else if (part.def == xxx.breastsDef && pawn.GetBreastList().NullOrEmpty())
					__result = true;
				else if (part.def == xxx.anusDef && pawn.GetAnusList().NullOrEmpty())
					__result = true;
			}
		}
	}

	/// <summary>
	/// count (rjw) bodypart with missing rjw part as missing to prevent damage
	/// </summary>
	[HarmonyPatch(typeof(HediffSet), "GetNotMissingParts")]
	internal static class PATCH_HediffSet_GetRandomNotMissingPart
	{
		[HarmonyPostfix]
		private static IEnumerable<BodyPartRecord> rjwGetNotMissingParts(IEnumerable<BodyPartRecord> __result, Pawn pawn)
		{
			//IEnumerable<BodyPartRecord> t;
			foreach (var bpr in __result)
			{
				if (bpr.def == xxx.genitalsDef && pawn.GetGenitalsList().NullOrEmpty())
					continue;
				else if (bpr.def == xxx.breastsDef && pawn.GetBreastList().NullOrEmpty())
					continue;
				else if (bpr.def == xxx.anusDef && pawn.GetAnusList().NullOrEmpty())
					continue;

				yield return bpr;
			}
		}
	}

	/// <summary>
	/// count rjw bodypart with missing rjw part as missing to prevent damage
	/// </summary>
	[HarmonyPatch(typeof(DamageWorker.DamageResult), "AddPart")]
	internal static class PATCH_DamageWorker_AddPart
	{
		[HarmonyPrefix]
		private static bool Disable_damage(Thing hitThing, BodyPartRecord part)
		{
			Pawn pawn = hitThing as Pawn;

			if (pawn != null)
			{
				if (part.def == xxx.genitalsDef && pawn.GetGenitalsList().NullOrEmpty())
					return false;
				if (part.def == xxx.breastsDef && pawn.GetBreastList().NullOrEmpty())
					return false;
				if (part.def == xxx.anusDef && pawn.GetAnusList().NullOrEmpty())
					return false;
			}

			return true;
		}
	}
}


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

namespace rjw
{
	///<summary>
	///Disable vanilla(?) traders from buying/selling natural rjw parts
	///</summary>
	[HarmonyPatch(typeof(StockGenerator_BuyExpensiveSimple), "HandlesThingDef")]
	[StaticConstructorOnStartup]
	static class PATCH_StockGenerator_BuyExpensiveSimple_HandlesThingDef
	{
		[HarmonyPostfix]
		static void remove_RJW_stuff_fromtraderBUY(ref bool __result, ThingDef thingDef)
		{
			if (thingDef == null)
				return;
			if (thingDef.tradeTags.NullOrEmpty())
				return;
			if (thingDef.tradeTags.Contains("RJW_NoBuy"))
				__result = false;
		}
	}
}