code stringlengths 0 56.1M | repo_name stringlengths 3 57 | path stringlengths 2 176 | language stringclasses 672 values | license stringclasses 8 values | size int64 0 56.8M |
|---|---|---|---|---|---|
using System.Collections.Generic;
using System.Linq;
using RimWorld;
using Verse;
using rjw.Modules.Testing;
using LudeonTK;
namespace rjw
{
public static class Genital_Helper
{
public static HediffDef generic_anus = HediffDef.Named("GenericAnus");
public static HediffDef generic_penis = HediffDef.Named("GenericPenis");
public static HediffDef generic_vagina = HediffDef.Named("GenericVagina");
public static HediffDef generic_breasts = HediffDef.Named("GenericBreasts");
public static HediffDef average_penis = HediffDef.Named("Penis");
public static HediffDef hydraulic_penis = HediffDef.Named("HydraulicPenis");
public static HediffDef bionic_penis = HediffDef.Named("BionicPenis");
public static HediffDef archotech_penis = HediffDef.Named("ArchotechPenis");
public static HediffDef average_vagina = HediffDef.Named("Vagina");
public static HediffDef hydraulic_vagina = HediffDef.Named("HydraulicVagina");
public static HediffDef bionic_vagina = HediffDef.Named("BionicVagina");
public static HediffDef archotech_vagina = HediffDef.Named("ArchotechVagina");
public static HediffDef average_breasts = HediffDef.Named("Breasts");
public static HediffDef hydraulic_breasts = HediffDef.Named("HydraulicBreasts");
public static HediffDef bionic_breasts = HediffDef.Named("BionicBreasts");
public static HediffDef archotech_breasts = HediffDef.Named("ArchotechBreasts");
public static HediffDef featureless_chest = HediffDef.Named("FeaturelessChest");
public static HediffDef udder_breasts = HediffDef.Named("UdderBreasts");
public static HediffDef average_anus = HediffDef.Named("Anus");
public static HediffDef hydraulic_anus = HediffDef.Named("HydraulicAnus");
public static HediffDef bionic_anus = HediffDef.Named("BionicAnus");
public static HediffDef archotech_anus = HediffDef.Named("ArchotechAnus");
public static HediffDef peg_penis = HediffDef.Named("PegDick");
public static HediffDef insect_anus = HediffDef.Named("InsectAnus");
public static HediffDef ovipositorM = HediffDef.Named("OvipositorM");
public static HediffDef ovipositorF = HediffDef.Named("OvipositorF");
public static HediffDef demonT_penis = HediffDef.Named("DemonTentaclePenis");
public static HediffDef demon_penis = HediffDef.Named("DemonPenis");
public static HediffDef demon_vagina = HediffDef.Named("DemonVagina");
public static HediffDef demon_anus = HediffDef.Named("DemonAnus");
public static HediffDef slime_breasts = HediffDef.Named("SlimeBreasts");
public static HediffDef slime_penis = HediffDef.Named("SlimeTentacles");
public static HediffDef slime_vagina = HediffDef.Named("SlimeVagina");
public static HediffDef slime_anus = HediffDef.Named("SlimeAnus");
public static HediffDef feline_penis = HediffDef.Named("CatPenis");
public static HediffDef feline_vagina = HediffDef.Named("CatVagina");
public static HediffDef canine_penis = HediffDef.Named("DogPenis");
public static HediffDef canine_vagina = HediffDef.Named("DogVagina");
public static HediffDef equine_penis = HediffDef.Named("HorsePenis");
public static HediffDef equine_vagina = HediffDef.Named("HorseVagina");
public static HediffDef dragon_penis = HediffDef.Named("DragonPenis");
public static HediffDef dragon_vagina = HediffDef.Named("DragonVagina");
public static HediffDef raccoon_penis = HediffDef.Named("RaccoonPenis");
public static HediffDef hemipenis = HediffDef.Named("HemiPenis");
public static HediffDef crocodilian_penis = HediffDef.Named("CrocodilianPenis");
// I'm not a big fan of looking for defs through string matching, but
// I suppose it handles the odd rebelious race mod.
public static readonly BodyPartTagDef BodyPartTagDefEatingSource = DefDatabase<BodyPartTagDef>.GetNamed("EatingSource");
public static readonly BodyPartTagDef BodyPartTagDefMetabolismSource = DefDatabase<BodyPartTagDef>.GetNamed("MetabolismSource");
public static readonly BodyPartTagDef BodyPartTagDefTongue = DefDatabase<BodyPartTagDef>.GetNamed("Tongue");
private static readonly HashSet<BodyPartDef> mouthBPs =
DefDatabase<BodyPartDef>.AllDefsListForReading
.Where((def) => def.defName.ToLower().ContainsAny("mouth", "teeth", "jaw", "beak") || def.tags.Contains(BodyPartTagDefEatingSource))
.ToHashSet();
private static readonly HashSet<BodyPartDef> tongueBPs =
DefDatabase<BodyPartDef>.AllDefsListForReading
.Where((def) => def.defName.ToLower().Contains("tongue") || def.tags.Contains(BodyPartTagDefTongue))
.ToHashSet();
private static readonly HashSet<BodyPartDef> stomachBPs =
DefDatabase<BodyPartDef>.AllDefsListForReading
.Where((def) => def.defName.ToLower().Contains("stomach") || def.tags.Contains(BodyPartTagDefMetabolismSource))
.ToHashSet();
private static readonly HashSet<BodyPartDef> torsoBPs =
DefDatabase<BodyPartDef>.AllDefsListForReading
.Where((def) => def.defName.ToLower().Contains("torso"))
.ToHashSet();
private static readonly HashSet<BodyPartDef> tailBPs =
DefDatabase<BodyPartDef>.AllDefsListForReading
.Where((def) => def.defName.ToLower().Contains("tail"))
.ToHashSet();
private static readonly HashSet<BodyPartDef> bodyBPs =
DefDatabase<BodyPartDef>.AllDefsListForReading
.Where((def) => def.defName.ToLower().Contains("body"))
.ToHashSet();
private static readonly BodyPartTagDef bodyPartTagDef_tongue =
DefDatabase<BodyPartTagDef>.GetNamed("Tongue");
// These BPRs are added by RJW. They must have some sex part attached
// to count as being present.
public static BodyPartRecord get_genitalsBPR(Pawn pawn)
{
//--Log.Message("Genital_Helper::get_genitals( " + xxx.get_pawnname(pawn) + " ) called");
var bpr = pawn?.RaceProps.body.AllParts.Find(bpr => bpr.def == xxx.genitalsDef);
if (bpr is not null) return bpr;
//--ModLog.Message(" get_genitals( " + xxx.get_pawnname(pawn) + " ) - Part is null");
return null;
}
public static BodyPartRecord get_anusBPR(Pawn pawn)
{
//--ModLog.Message(" get_anus( " + xxx.get_pawnname(pawn) + " ) called");
var bpr = pawn?.RaceProps.body.AllParts.Find(bpr => bpr.def == xxx.anusDef);
if (bpr is not null) return bpr;
//--ModLog.Message(" get_anus( " + xxx.get_pawnname(pawn) + " ) - Part is null");
return null;
}
public static BodyPartRecord get_breastsBPR(Pawn pawn)
{
//--ModLog.Message(" get_breasts( " + xxx.get_pawnname(pawn) + " ) called");
var bpr = pawn?.RaceProps.body.AllParts.Find(bpr => bpr.def == xxx.breastsDef);
if (bpr is not null) return bpr;
//--ModLog.Message(" get_breasts( " + xxx.get_pawnname(pawn) + " ) - Part is null");
return null;
}
// These BPRs are either pre-existing or added by other mods. They are considered
// present as long as they have no `Hediff_PartRemoved` on them. Use the `has_bpr`
// method to check that they're not chopped off, blown off, smashed off, or whatever
// other kinds of terrible things can befall a poor pawn.
public static BodyPartRecord get_mouthBPR(Pawn pawn)
{
//--ModLog.Message(" get_mouth( " + xxx.get_pawnname(pawn) + " ) called");
var bpr = pawn?.RaceProps.body.AllParts.Find((bpr) => mouthBPs.Contains(bpr.def));
if (bpr is not null) return bpr;
//--ModLog.Message(" get_mouth( " + xxx.get_pawnname(pawn) + " ) - Part is null");
return null;
}
public static BodyPartRecord get_tongueBPR(Pawn pawn)
{
//--ModLog.Message(" get_tongue( " + xxx.get_pawnname(pawn) + " ) called");
if (pawn?.RaceProps.body.AllParts is { } allParts)
{
foreach (var bpr in allParts)
{
if (tongueBPs.Contains(bpr.def)) return bpr;
if (bpr.def.tags.Contains(bodyPartTagDef_tongue)) return bpr;
}
}
//--ModLog.Message(" get_tongue( " + xxx.get_pawnname(pawn) + " ) - Part is null");
return null;
}
public static BodyPartRecord get_stomachBPR(Pawn pawn)
{
//--ModLog.Message(" get_stomach( " + xxx.get_pawnname(pawn) + " ) called");
if (pawn?.RaceProps.body.AllParts is { } allParts)
{
var bpr = allParts.Find((bpr) => stomachBPs.Contains(bpr.def));
if (bpr is not null) return bpr;
//--ModLog.Message(" get_stomach( " + xxx.get_pawnname(pawn) + " ) - Part is null, trying to get torso...");
bpr = allParts.Find((bpr) => torsoBPs.Contains(bpr.def));
if (bpr is not null) return bpr;
}
//--ModLog.Message(" get_stomach( " + xxx.get_pawnname(pawn) + " ) - Part is null, no stomach or torso.");
return null;
}
public static BodyPartRecord get_tailBPR(Pawn pawn)
{
//should probably make scale race check or something
//--ModLog.Message(" get_tail( " + xxx.get_pawnname(pawn) + " ) called");
var bpr = pawn?.RaceProps.body.AllParts.Find(bpr => tailBPs.Contains(bpr.def));
if (bpr is not null) return bpr;
//--ModLog.Message(" get_tail( " + xxx.get_pawnname(pawn) + " ) - Part is null");
return null;
}
public static BodyPartRecord get_torsoBPR(Pawn pawn)
{
//--ModLog.Message(" get_torsoBPR( " + xxx.get_pawnname(pawn) + " ) called");
if (pawn?.RaceProps.body.AllParts is { } allParts)
{
var bpr = allParts.Find((bpr) => torsoBPs.Contains(bpr.def));
if (bpr is not null) return bpr;
//--ModLog.Message(" get_torsoBPR( " + xxx.get_pawnname(pawn) + " ) - Part is null, trying to get body...");
bpr = allParts.Find((bpr) => bodyBPs.Contains(bpr.def));
if (bpr is not null) return bpr;
}
//--ModLog.Message(" get_torsoBPR( " + xxx.get_pawnname(pawn) + " ) - Part is null, no torso or body");
return null;
}
public static bool breasts_blocked(Pawn pawn)
{
if (pawn.apparel?.WornApparel is not { } wornApparel) return false;
return wornApparel.ToBondageGear().Any((def) => def.blocks_breasts);
}
public static bool anus_blocked(Pawn pawn)
{
if (pawn.apparel?.WornApparel is not { } wornApparel) return false;
return wornApparel.ToBondageGear().Any((def) => def.blocks_anus);
}
public static bool genitals_blocked(Pawn pawn)
{
if (pawn.apparel?.WornApparel is not { } wornApparel) return false;
return wornApparel.ToBondageGear().Any((def) => def.blocks_penis || def.blocks_vagina);
}
public static bool hands_blocked(Pawn pawn)
{
if (pawn.apparel?.WornApparel is not { } wornApparel) return false;
return wornApparel.ToBondageGear().Any((def) => def.blocks_hands);
}
public static bool penis_blocked(Pawn pawn)
{
if (pawn.apparel?.WornApparel is not { } wornApparel) return false;
return wornApparel.ToBondageGear().Any((def) => def.blocks_penis);
}
public static bool oral_blocked(Pawn pawn)
{
if (pawn.apparel?.WornApparel is not { } wornApparel) return false;
return wornApparel.ToBondageGear().Any((def) => def.blocks_oral);
}
public static bool vagina_blocked(Pawn pawn)
{
if (pawn.apparel?.WornApparel is not { } wornApparel) return false;
return wornApparel.ToBondageGear().Any((def) => def.blocks_vagina);
}
private static IEnumerable<bondage_gear_def> ToBondageGear(this List<Apparel> wornApparel) =>
wornApparel.Select((app) => app.def).OfType<bondage_gear_def>();
public static bool is_sex_part(Hediff hed) => hed is ISexPartHediff;
public static List<Hediff> get_PartsHediffList(Pawn pawn, BodyPartRecord Part) =>
pawn.health.hediffSet.hediffs.FindAll((hed) => is_sex_part(hed) && hed.Part == Part);
public static List<Hediff> get_AllPartsHediffList(Pawn pawn) =>
pawn.health.hediffSet.hediffs.FindAll(is_sex_part);
public static bool has_genitals(Pawn pawn, List<Hediff> parts = null)
{
parts ??= pawn.GetGenitalsList();
return !parts.NullOrEmpty();
}
public static bool has_breasts(Pawn pawn, List<Hediff> parts = null)
{
parts ??= pawn.GetBreastList();
if (parts.NullOrEmpty()) return false;
return parts.Any((hed) => hed.def != featureless_chest);
}
public static bool has_male_breasts(Pawn pawn, List<Hediff> parts = null)
{
parts ??= pawn.GetBreastList();
if (parts.NullOrEmpty()) return false;
return parts.Any((hed) => is_sex_part(hed) && hed.CurStageIndex == 0);
}
/// <summary>
/// Can do breastjob if breasts are average or bigger
/// </summary>
/// <param name="pawn"></param>
/// <returns></returns>
public static bool can_do_breastjob(Pawn pawn, List<Hediff> parts = null)
{
parts ??= pawn.GetBreastList();
if (parts.NullOrEmpty()) return false;
return parts.Any((hed) => is_sex_part(hed) && hed.CurStageIndex > 1);
}
public static bool has_tail(Pawn pawn) =>
has_bpr(pawn, get_tailBPR(pawn));
public static bool has_mouth(Pawn pawn) =>
has_bpr(pawn, get_mouthBPR(pawn));
public static bool has_tongue(Pawn pawn) =>
has_bpr(pawn, get_tongueBPR(pawn));
/// <summary>
/// <para>Checks to see if a body part is actually attached.</para>
/// <para>This applies to BPRs that are not added by RJW. For those,
/// we count the part as missing if they do not have an accompanying
/// sex-part.</para>
/// </summary>
/// <param name="pawn">The pawn to check.</param>
/// <param name="bpr">The `BodyPartRecord` indicating the body part.</param>
/// <returns>Whether the part is missing.</returns>
public static bool has_bpr(Pawn pawn, BodyPartRecord bpr)
{
if (bpr is null) return false;
return !pawn.health.hediffSet.hediffs
.Where((hed) => hed.Part == bpr)
.Any((hed) => hed is Hediff_MissingPart);
}
public static bool has_anus(Pawn pawn, List<Hediff> parts = null)
{
parts ??= pawn.GetAnusList();
if (parts.NullOrEmpty()) return false;
for (int i = 0; i < parts.Count; i++)
if (is_anus(parts[i]))
return true;
return false;
}
public static bool is_anus(Hediff hed)
{
if (hed.def is not HediffDef_SexPart def) return false;
return def.genitalFamily == GenitalFamily.Anus;
}
/// <summary>
/// Insertable, this is both vagina and ovipositorf
/// </summary>
/// <param name="pawn"></param>
/// <param name="parts"></param>
/// <returns></returns>
public static bool has_vagina(Pawn pawn, List<Hediff> parts = null)
{
parts ??= pawn.GetGenitalsList();
if (parts.NullOrEmpty()) return false;
for (int i = 0; i < parts.Count; i++)
if (is_vagina(parts[i]))
return true;
return false;
}
private static bool is_vagina_family(GenitalFamily family) => family switch
{
GenitalFamily.Vagina => true,
GenitalFamily.FemaleOvipositor => true,
_ => false
};
public static bool is_vagina(Hediff hed)
{
if (hed.def is not HediffDef_SexPart def)
{
return false;
}
return is_vagina_family(def.genitalFamily);
}
/// <summary>
/// <para>Checks to see if a pawn has a penis, whether fertile or not.</para>
/// <para>This includes male ovipositors, but not female ovipositors (that is
/// regarded more like a vagina).</para>
/// </summary>
/// <param name="pawn">The pawn to inspect.</param>
/// <param name="parts">The pre-obtained parts, if available.</param>
public static bool has_male_bits(Pawn pawn, List<Hediff> parts = null)
{
parts ??= pawn.GetGenitalsList();
if (parts.NullOrEmpty()) return false;
return parts.Any(is_penis);
}
public static bool has_penis_fertile(Pawn pawn, List<Hediff> parts = null)
{
parts ??= pawn.GetGenitalsList();
if (parts.NullOrEmpty()) return false;
for (int i = 0; i < parts.Count; i++)
if (is_fertile_penis(parts[i]))
return true;
return false;
}
public static bool has_penis_infertile(Pawn pawn, List<Hediff> parts = null)
{
parts ??= pawn.GetGenitalsList();
if (parts.NullOrEmpty()) return false;
for (int i = 0; i < parts.Count; i++)
if (is_infertile_penis(parts[i]))
return true;
return false;
}
private static bool is_penis_family(GenitalFamily family) => family switch
{
GenitalFamily.Penis => true,
GenitalFamily.MaleOvipositor => true,
_ => false
};
private static bool is_fertile_tag(GenitalTag tag) => tag switch
{
GenitalTag.CanFertilize => true,
GenitalTag.CanFertilizeEgg => true,
_ => false
};
public static bool is_penis(Hediff hed)
{
if (hed.def is not HediffDef_SexPart def) return false;
return is_penis_family(def.genitalFamily);
}
public static bool is_fertile_penis(Hediff hed)
{
if (hed.def is not HediffDef_SexPart def) return false;
if (!is_penis_family(def.genitalFamily)) return false;
for (int i = 0; i < def.genitalTags.Count; i++)
if (is_fertile_tag(def.genitalTags[i]))
return true;
return false;
}
public static bool is_infertile_penis(Hediff hed)
{
if (hed.def is not HediffDef_SexPart def) return false;
if (!is_penis_family(def.genitalFamily)) return false;
for (int i = 0; i < def.genitalTags.Count; i++)
if (is_fertile_tag(def.genitalTags[i]))
return false;
return true;
}
public static bool has_multipenis(Pawn pawn, List<Hediff> parts = null)
{
parts ??= pawn.GetGenitalsList();
if (parts.NullOrEmpty()) return false;
int count = 0;
foreach (Hediff hed in parts)
{
if (!is_penis(hed)) continue;
// Matches hemipenis.
var props = (hed.def as HediffDef_SexPart)?.tags;
if (!props.NullOrEmpty() && props.Contains("Multiple"))
{
return true;
}
count += 1;
if (count > 1) return true;
}
return false;
}
public static bool has_ovipositorM(Pawn pawn, List<Hediff> parts = null)
{
parts ??= pawn.GetGenitalsList();
if (parts.NullOrEmpty()) return false;
for (int i = 0; i < parts.Count; i++)
if (is_male_ovipositor(parts[i]))
return true;
return false;
}
public static bool is_male_ovipositor(Hediff hed)
{
if (hed.def is not HediffDef_SexPart def) return false;
return def.genitalFamily == GenitalFamily.MaleOvipositor;
}
public static bool has_ovipositorF(Pawn pawn, List<Hediff> parts = null)
{
parts ??= pawn.GetGenitalsList();
if (parts.NullOrEmpty()) return false;
for (int i = 0; i < parts.Count; i++)
if (is_female_ovipositor(parts[i]))
return true;
return false;
}
public static bool is_female_ovipositor(Hediff hed)
{
if (hed.def is not HediffDef_SexPart def) return false;
return def.genitalFamily == GenitalFamily.FemaleOvipositor;
}
/// <summary>
/// Can do autofellatio if penis is huge or bigger
/// </summary>
/// <param name="pawn"></param>
/// <returns></returns>
public static bool can_do_autofelatio(Pawn pawn, List<Hediff> parts = null)
{
parts ??= pawn.GetGenitalsList();
if (parts.NullOrEmpty()) return false;
return parts.Any((hed) => is_penis(hed) && hed.CurStageIndex > 3);
}
/// <summary>
/// Count only fertile penises
/// </summary>
/// <param name="pawn"></param>
/// <returns></returns>
public static bool is_futa(Pawn pawn, List<Hediff> parts = null)
{
parts ??= pawn.GetGenitalsList();
return has_vagina(pawn, parts) && has_penis_fertile(pawn, parts);
}
public static int min_EggsProduced(Pawn pawn, List<Hediff> parts = null)
{
parts ??= pawn.GetGenitalsList();
// No fitting parts - return 0
if (parts.NullOrEmpty()) return 0;
// set min to -1 in case it is not defined in the xml file
float minEggsProduced = -1;
var ovipositors = parts.Select(part => part.TryGetComp<HediffComp_Ovipositor>()).Where(p => p != null);
foreach (var ovi in ovipositors)
{
//if (hed.minEggAmount)
if (minEggsProduced < 0)
{
minEggsProduced = ovi.Props.eggCount.min;
}
}
return (int)minEggsProduced;
}
public static int max_EggsProduced(Pawn pawn, List<Hediff> parts = null)
{
parts ??= pawn.GetGenitalsList();
// No fitting parts - return 0
if (parts.NullOrEmpty()) return 0;
// set min to -1 in case it is not defined in the xml file
float maxEggsProduced = -1;
var ovipositorComps = parts.Select(part => part.TryGetComp<HediffComp_Ovipositor>()).Where(p => p != null);
foreach (var ovi in ovipositorComps)
{
if (maxEggsProduced < 0)
{
maxEggsProduced = ovi.Props.eggCount.max;
}
}
return (int)maxEggsProduced;
}
/// <summary>
/// <para>This utility appears in the "Output" tab of the debug menu.</para>
/// <para>It generates every kind of pawn in the game and runs all these methods
/// against them. You can use this to validate changes to these utilities.</para>
/// <para>Just run this before your changes, then after, and use some kind of diff
/// utility to see if anything is ...different.</para>
/// <para>Be aware that sometimes pawns can just generate in an imperfect way,
/// like an iguana whose tail is currently severed off will change how `has_tail`
/// might generate its output.</para>
/// </summary>
[DebugOutput("RJW", onlyWhenPlaying = true)]
public static void GenitalsOfAllPawnKinds()
{
var artificialParts = DefDatabase<RecipeDef>.AllDefsListForReading
.Where((r) => r.workerClass == typeof(Recipe_InstallGenitals))
.Where((r) => r.addsHediff is HediffDef_SexPart && !r.addsHediff.organicAddedBodypart)
.ToArray();
var dataSources = DefDatabase<PawnKindDef>.AllDefsListForReading
.Where((d) => d.race != null)
.OrderBy((d) => d.defName)
.SelectMany(CreatePawns)
.ToArray();
var table = new TableDataGetter<(Pawn pawn, string label)>[]
{
new("kind", (d) => d.pawn.kindDef.defName),
new("sex", (d) => GenderHelper.GetSex(d.pawn).ToString().CapitalizeFirst()),
new("gender", (d) => d.pawn.gender),
new("label", (d) => d.label),
new("genitalsBPR", (d) => get_genitalsBPR(d.pawn)?.def.defName),
new("breastsBPR", (d) => get_breastsBPR(d.pawn)?.def.defName),
new("mouthBPR", (d) => get_mouthBPR(d.pawn)?.def.defName),
new("tongueBPR", (d) => get_tongueBPR(d.pawn)?.def.defName),
new("stomachBPR", (d) => get_stomachBPR(d.pawn)?.def.defName),
new("tailBPR", (d) => get_tailBPR(d.pawn)?.def.defName),
new("anusBPR", (d) => get_anusBPR(d.pawn)?.def.defName),
new("torsoBPR", (d) => get_torsoBPR(d.pawn)?.def.defName),
new("has_genitals", (d) => has_genitals(d.pawn)),
new("has_breasts", (d) => has_breasts(d.pawn)),
new("has_male_breasts", (d) => has_male_breasts(d.pawn)),
new("can_do_breastjob", (d) => can_do_breastjob(d.pawn)),
new("has_tail", (d) => has_tail(d.pawn)),
new("has_mouth", (d) => has_mouth(d.pawn)),
new("has_tongue", (d) => has_tongue(d.pawn)),
new("has_anus", (d) => has_anus(d.pawn)),
new("has_vagina", (d) => has_vagina(d.pawn)),
new("has_male_bits", (d) => has_male_bits(d.pawn)),
new("has_penis_fertile", (d) => has_penis_fertile(d.pawn)),
new("has_penis_infertile", (d) => has_penis_infertile(d.pawn)),
new("has_multipenis", (d) => has_multipenis(d.pawn)),
new("has_ovipositorM", (d) => has_ovipositorM(d.pawn)),
new("has_ovipositorF", (d) => has_ovipositorF(d.pawn)),
new("is_futa", (d) => is_futa(d.pawn)),
new("min_EggsProduced", (d) => min_EggsProduced(d.pawn)),
new("max_EggsProduced", (d) => max_EggsProduced(d.pawn))
};
DebugTables.MakeTablesDialog(dataSources, table);
IEnumerable<PawnGenerationRequest> CreateRequests(PawnKindDef def)
{
if (!def.RaceProps.hasGenders)
{
yield return new PawnGenerationRequest(kind: def)
.RequestDefaults();
}
else
{
yield return new PawnGenerationRequest(kind: def, fixedGender: Gender.Male)
.RequestDefaults();
yield return new PawnGenerationRequest(kind: def, fixedGender: Gender.Female)
.RequestDefaults();
}
}
IEnumerable<(Pawn pawn, string label)> CreatePawns(PawnKindDef def)
{
foreach (var request in CreateRequests(def))
if (TestHelper.GenerateSeededPawn(request) is { } pawn)
yield return (pawn, "natural");
// Only going to test artificial parts and complex sexes on colonists.
if (def.defName != "Colonist") yield break;
// Producing fertile and infertile futa.
foreach (var request in CreateRequests(def))
{
if (request.FixedGender == Gender.Female)
{
if (TestHelper.GenerateSeededPawn(request) is { } fertileFemale)
if (TestHelper.MakeIntoFuta(fertileFemale))
yield return (fertileFemale, "as fertile female futa");
if (TestHelper.GenerateSeededPawn(request) is { } infertileFemale)
if (TestHelper.MakeIntoFuta(infertileFemale, true))
yield return (infertileFemale, "as infertile female futa");
}
else if (request.FixedGender == Gender.Male)
{
if (TestHelper.GenerateSeededPawn(request) is { } fertileMale)
if (TestHelper.MakeIntoFuta(fertileMale))
yield return (fertileMale, "as fertile male futa");
if (TestHelper.GenerateSeededPawn(request) is { } infertileMale)
if (TestHelper.MakeIntoFuta(infertileMale))
yield return (infertileMale, "as infertile male futa");
}
}
// Producing a trap.
foreach (var request in CreateRequests(def))
{
if (request.FixedGender != Gender.Male) continue;
if (TestHelper.GenerateSeededPawn(request) is { } malePawn)
if (TestHelper.MakeIntoTrap(malePawn))
yield return (malePawn, "as trap");
}
// Testing artifical parts.
foreach (var recipe in artificialParts)
{
foreach (var request in CreateRequests(def))
{
var pawn = TestHelper.GenerateSeededPawn(request);
if (pawn is null) continue;
if (!TestHelper.ApplyPartToPawn(pawn, recipe)) continue;
yield return (pawn, $"has {recipe.addsHediff.defName}");
}
}
}
}
}
}
| Korth95/rjw | 1.5/Source/Common/Helpers/Genital_Helper.cs | C# | mit | 25,582 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Verse;
namespace rjw
{
public static class HediffHelper
{
/// <summary>
/// Creates hediff with custom hediff class
/// </summary>
/// <typeparam name="T">hediff class. Should be class defined by hediff or subclass of that class</typeparam>
/// <param name="def">hediffDef</param>
/// <param name="pawn">owner of newly created hediff</param>
/// <param name="partRecord">bodypart heduff assigned to</param>
/// <returns>newly created hediff</returns>
public static T MakeHediff<T>(HediffDef def, Pawn pawn, BodyPartRecord partRecord = null) where T : Hediff
{
if (!def.hediffClass.IsAssignableFrom(typeof(T)))
{
throw new InvalidOperationException($"trying to create hediff with incompatible class: {typeof(T).Name} is not a {def.hediffClass.Name} or its subclass");
}
T hediff = (T)Activator.CreateInstance(typeof(T));
hediff.def = def;
hediff.pawn = pawn;
hediff.Part = partRecord;
hediff.loadID = Find.UniqueIDsManager.GetNextHediffID();
hediff.PostMake();
return hediff;
}
/// <summary>
/// Fill existing hediff class with data
/// </summary>
/// <typeparam name="T">hediff class. Should be class defined by hediff or subclass of that class</typeparam>
/// <param name="def">hediffDef</param>
/// <param name="hediff">empty hediff instance</Hediff>
/// <param name="pawn">owner of newly created hediff</param>
/// <param name="partRecord">bodypart heduff assigned to</param>
/// <returns>newly created hediff</returns>
public static T FillHediff<T>(HediffDef def, T hediff, Pawn pawn, BodyPartRecord partRecord = null) where T : Hediff
{
if (!def.hediffClass.IsAssignableFrom(typeof(T)))
{
throw new InvalidOperationException($"trying to create hediff with incompatible class: {typeof(T).Name} is not a {def.hediffClass.Name} or its subclass");
}
hediff.def = def;
hediff.pawn = pawn;
hediff.Part = partRecord;
hediff.loadID = Find.UniqueIDsManager.GetNextHediffID();
hediff.PostMake();
return hediff;
}
public static bool IsNaturalSexPart(this HediffDef def)
{
return def is HediffDef_SexPart && typeof(Hediff_NaturalSexPart).IsAssignableFrom(def.hediffClass);
}
public static bool IsArtificialSexPart(this HediffDef def)
{
return def is HediffDef_SexPart && typeof(Hediff_ArtificialSexPart).IsAssignableFrom(def.hediffClass);
}
}
}
| Korth95/rjw | 1.5/Source/Common/Helpers/HediffHelper.cs | C# | mit | 2,473 |
using System.Collections.Generic;
using Verse;
using RimWorld;
using static rjw.PreceptDefOf;
namespace rjw
{
public static class IdeoHelper
{
public static readonly List<PreceptDef> freeLovePrecepts;
public static readonly List<PreceptDef> nonPolyPrecepts;
public static readonly List<PreceptDef> prudePrecepts;
public static bool ClassicMode => !ModsConfig.IdeologyActive || Find.IdeoManager.classicMode;
static IdeoHelper()
{
if (ModsConfig.IdeologyActive)
{
freeLovePrecepts = new() { Lovin_Free, Lovin_FreeApproved };
nonPolyPrecepts = new() {
Lovin_SpouseOnly_Mild,
Lovin_SpouseOnly_Moderate,
Lovin_SpouseOnly_Strict
};
prudePrecepts = new() { Lovin_Prohibited, Lovin_Horrible };
}
else
{
freeLovePrecepts = new() { Lovin_Free };
}
}
/// <summary>
/// Check whether pawn has an ideo with a free love precept.
/// </summary>
/// <param name="pawn">The pawn whose ideo is being checked</param>
/// <param name="allowClassic">
/// Whether the hidden 'Lovin: Free' precept included in classic and non-DLC ideos should be respected.<br />
/// In other words, whether we are strong enough to accept canon or cling fearfully to our silly 21st century mores.
/// </param>
/// <returns>True if etc etc, false otherwise</returns>
public static bool IsIdeologicallyPoly(this Pawn pawn, bool allowClassic = true)
{
if (pawn.Ideo == null)
{
return false;
}
if (ClassicMode)
{
return allowClassic;
}
var lovinPrecept = GetLovinPreceptDef(pawn.Ideo);
if (lovinPrecept == null)
{
return false;
}
return freeLovePrecepts.Contains(lovinPrecept);
}
public static bool IsIdeologicallyPrudish(this Pawn pawn)
{
if (pawn.Ideo == null || ClassicMode)
{
return false;
}
var lovinPrecept = GetLovinPreceptDef(pawn.Ideo);
if (lovinPrecept == null)
{
return false;
}
return prudePrecepts.Contains(lovinPrecept);
}
private static PreceptDef GetLovinPreceptDef(Ideo ideo)
{
return ideo.PreceptsListForReading.FirstOrDefault(p => p.def.issue == IssueDefOf.Lovin)?.def;
}
}
} | Korth95/rjw | 1.5/Source/Common/Helpers/IdeoHelper.cs | C# | mit | 2,152 |
using Multiplayer.API;
using RimWorld;
using Verse;
namespace rjw
{
/// <summary>
/// Old, hardcoded part choosing code. Used as a fallback if no RaceGroupDef is found.
/// </summary>
public static class LegacySexPartAdder
{
static bool privates_gender(Pawn pawn, Gender gender)
{
return SexPartAdder.IsAddingPenis(pawn, gender);
}
[SyncMethod]
public static double GenderTechLevelCheck(Pawn pawn)
{
bool lowtechlevel = true;
//Rand.PopState();
//Rand.PushState(RJW_Multiplayer.PredictableSeed());
double value = Rand.Value;
if (pawn?.Faction != null)
lowtechlevel = (int)pawn.Faction.def.techLevel < 5;
else if (pawn == null)
lowtechlevel = false;
//--save savages from inventing hydraulic and bionic genitals
while (lowtechlevel && value >= 0.90)
{
value = Rand.Value;
}
return value;
}
public static void AddBreasts(Pawn pawn, BodyPartRecord bpr, Pawn parent)
{
var temppawn = parent ?? pawn;
HediffDef part;
double value = GenderTechLevelCheck(pawn);
string racename = temppawn.kindDef.race.defName.ToLower();
part = Genital_Helper.generic_breasts;
if (xxx.is_mechanoid(pawn))
{
return;
}
if (xxx.is_insect(temppawn))
{
// this will probably need override in case there are humanoid insect race
//--ModLog.Message(" add_breasts( " + xxx.get_pawnname(pawn) + " ) - is insect,doesn't need breasts");
return;
}
//alien races - MoreMonstergirls
else if (racename.Contains("slime"))
{
//slimes are always females, and idc what anyone else say!
part = Genital_Helper.slime_breasts;
}
else
{
if (pawn.RaceProps.Humanlike)
{
//alien races - ChjDroid, ChjAndroid
if (racename.ContainsAny("mantis", "rockman", "slug", "zoltan", "engie", "sergal", "cutebold", "dodo", "owl", "parrot",
"penguin", "cassowary", "chicken", "vulture"))
{
if (!pawn.health.hediffSet.HasHediff(Genital_Helper.featureless_chest))
pawn.health.AddHediff(Genital_Helper.featureless_chest, bpr);
return;
}
else if (racename.ContainsAny("avali", "khess"))
{
return;
}
else if (AndroidsCompatibility.IsAndroid(pawn))
{
if (pawn.story.GetBackstory(BackstorySlot.Childhood) != null)
{
if (pawn.story.Childhood.untranslatedTitleShort.ToLower().Contains("bishojo"))
part = Genital_Helper.bionic_breasts;
else if (pawn.story.Childhood.untranslatedTitleShort.ToLower().Contains("pleasure"))
part = Genital_Helper.bionic_breasts;
else if (pawn.story.Childhood.untranslatedTitleShort.ToLower().Contains("idol"))
part = Genital_Helper.bionic_breasts;
else if (pawn.story.Childhood.untranslatedTitleShort.ToLower().Contains("social"))
part = Genital_Helper.hydraulic_breasts;
else if (pawn.story.Childhood.untranslatedTitleShort.ToLower().Contains("substitute"))
part = Genital_Helper.average_breasts;
else if (pawn.story.GetBackstory(BackstorySlot.Adulthood) != null)
{
if (pawn.story.Adulthood.untranslatedTitleShort.ToLower().Contains("courtesan"))
part = Genital_Helper.bionic_breasts;
else if (pawn.story.Adulthood.untranslatedTitleShort.ToLower().Contains("social"))
part = Genital_Helper.hydraulic_breasts;
}
else
return;
}
else if (pawn.story.GetBackstory(BackstorySlot.Adulthood) != null)
{
if (pawn.story.Adulthood.untranslatedTitleShort.ToLower().Contains("courtesan"))
part = Genital_Helper.bionic_breasts;
else if (pawn.story.Adulthood.untranslatedTitleShort.ToLower().Contains("social"))
part = Genital_Helper.hydraulic_breasts;
}
if (part == Genital_Helper.generic_breasts)
return;
}
//alien races - MoreMonstergirls
else if (racename.Contains("cowgirl"))
{
part = Genital_Helper.average_breasts;
if (value < 0.50 && !pawn.health.hediffSet.HasHediff(Genital_Helper.udder_breasts) && pawn.gender != Gender.Male)
{
var bp = Genital_Helper.get_breastsBPR(pawn);
pawn.health.AddHediff(SexPartAdder.MakePart(Genital_Helper.udder_breasts, pawn, bp), bp);
}
}
else
{
if (value < 0.90 || (pawn.ageTracker.AgeBiologicalYears < 2))
part = Genital_Helper.average_breasts;
else if (value < 0.95)
part = Genital_Helper.hydraulic_breasts;
else
part = Genital_Helper.bionic_breasts;
}
}
else if (racename.ContainsAny("mammoth", "elasmotherium", "chalicotherium", "megaloceros", "sivatherium", "deinotherium",
"aurochs", "zygolophodon", "uintatherium", "gazelle", "ffalo", "boomalope", "cow", "miltank", "elk", "reek", "nerf",
"bantha", "tauntaun", "caribou", "deer", "ibex", "dromedary", "alpaca", "llama", "goat", "moose", "horse", "donkey", "yak"))
{
if (!pawn.health.hediffSet.HasHediff(Genital_Helper.udder_breasts) && pawn.gender != Gender.Male)
{
bpr = Genital_Helper.get_breastsBPR(pawn);
part = Genital_Helper.udder_breasts;
}
else
return;
}
else if (racename.ContainsAny("cassowary", "emu", "dinornis", "ostrich", "turkey", "chicken", "duck", "murkroW", "bustard", "palaeeudyptes",
"goose", "tukiri", "porg", "yi", "kiwi", "penguin", "quail", "ptarmigan", "doduo", "flamingo", "plup", "empoleon", "meadow ave") && !racename.ContainsAny("duck-billed"))
{
return; // Separate list for birds, to make it easier to add cloaca at some later date.
} // Other breastless creatures.
else if (racename.ContainsAny("titanis", "titanoboa", "guan", "tortoise", "turt", "aerofleet", "quinkana", "megalochelys",
"purussaurus", "cobra", "dewback", "rancor", "frog", "onyx", "flommel", "lapras", "aron", "chinchou",
"squirtle", "wartortle", "blastoise", "totodile", "croconaw", "feraligatr", "litwick", "pumpkaboo", "shuppet", "haunter",
"gastly", "oddish", "hoppip", "tropius", "budew", "roselia", "bellsprout", "drifloon", "chikorita", "bayleef", "meganium",
"char", "drago", "dratini", "saur", "tyrannus", "carnotaurus", "baryonyx", "minmi", "diplodocus", "phodon", "indominus",
"raptor", "caihong", "coelophysis", "cephale", "compsognathus", "mimus", "troodon", "dactyl", "tanystropheus", "geosternbergia",
"deino", "suchus", "dracorex", "cephalus", "trodon", "quetzalcoatlus", "pteranodon", "antarctopelta", "stygimoloch", "rhabdodon",
"rhamphorhynchus", "ceratops", "ceratus", "zalmoxes", "mochlodon", "gigantophis", "crab", "pulmonoscorpius", "manipulator",
"meganeura", "euphoberia", "holcorobeus", "protosolpuga", "barbslinger", "blizzarisk", "frostmite", "devourer", "hyperweaver",
"macrelcana", "acklay", "elemental", "megalania", "gecko", "gator", "komodo", "scolipede", "shuckle", "combee", "shedinja",
"caterpie", "wurmple", "lockjaw", "needlepost", "needleroll", "squid", "slug", "gila", "pleura"))
{
return;
}
pawn.health.AddHediff(SexPartAdder.MakePart(part, pawn, bpr), bpr);
}
}
[SyncMethod]
public static void AddGenitals(Pawn pawn, Pawn parent, Gender gender, BodyPartRecord bpr, HediffDef part)
{
var temppawn = parent ?? pawn;
double value = GenderTechLevelCheck(pawn);
string racename = temppawn.kindDef.race.defName.ToLower();
//Log.Message("Genital_Helper::add_genitals( " + xxx.get_pawnname(pawn));
//Log.Message("Genital_Helper::add_genitals( " + pawn.kindDef.race.defName);
//Log.Message("Genital_Helper::is male( " + privates_gender(pawn, gender));
//Log.Message("Genital_Helper::is male1( " + pawn.gender);
//Log.Message("Genital_Helper::is male2( " + gender);
if (xxx.is_mechanoid(pawn))
{
return;
}
//insects
else if (xxx.is_insect(temppawn)
|| racename.Contains("apini")
|| racename.Contains("mantodean")
|| racename.Contains("insect")
|| racename.Contains("bug"))
{
part = (privates_gender(pawn, gender)) ? Genital_Helper.ovipositorM : Genital_Helper.ovipositorF;
//override for Better infestations, since queen is male at creation
if (racename.Contains("Queen"))
part = Genital_Helper.ovipositorF;
}
//space cats pawns
else if ((racename.Contains("orassan") || racename.Contains("neko")) && !racename.ContainsAny("akaneko"))
{
if ((value < 0.70) || (pawn.ageTracker.AgeBiologicalYears < 2) || !pawn.RaceProps.Humanlike)
part = (privates_gender(pawn, gender)) ? Genital_Helper.feline_penis : Genital_Helper.feline_vagina;
else if (value < 0.90)
part = (privates_gender(pawn, gender)) ? Genital_Helper.hydraulic_penis : Genital_Helper.hydraulic_vagina;
else
part = (privates_gender(pawn, gender)) ? Genital_Helper.bionic_penis : Genital_Helper.bionic_vagina;
}
//space dog pawns
else if (racename.Contains("fennex")
|| racename.Contains("xenn")
|| racename.Contains("leeani")
|| racename.Contains("ferian")
|| racename.Contains("callistan"))
{
if ((value < 0.70) || (pawn.ageTracker.AgeBiologicalYears < 2) || !pawn.RaceProps.Humanlike)
part = (privates_gender(pawn, gender)) ? Genital_Helper.canine_penis : Genital_Helper.canine_vagina;
else if (value < 0.90)
part = (privates_gender(pawn, gender)) ? Genital_Helper.hydraulic_penis : Genital_Helper.hydraulic_vagina;
else
part = (privates_gender(pawn, gender)) ? Genital_Helper.bionic_penis : Genital_Helper.bionic_vagina;
}
//space horse pawns
else if (racename.Contains("equium"))
{
if ((value < 0.70) || (pawn.ageTracker.AgeBiologicalYears < 2) || !pawn.RaceProps.Humanlike)
part = (privates_gender(pawn, gender)) ? Genital_Helper.equine_penis : Genital_Helper.equine_vagina;
else if (value < 0.90)
part = (privates_gender(pawn, gender)) ? Genital_Helper.hydraulic_penis : Genital_Helper.hydraulic_vagina;
else
part = (privates_gender(pawn, gender)) ? Genital_Helper.bionic_penis : Genital_Helper.bionic_vagina;
}
//space raccoon pawns
else if (racename.Contains("racc") && !racename.Contains("raccoon"))
{
if ((value < 0.70) || (pawn.ageTracker.AgeBiologicalYears < 2) || !pawn.RaceProps.Humanlike)
part = (privates_gender(pawn, gender)) ? Genital_Helper.raccoon_penis : Genital_Helper.generic_vagina;
else if (value < 0.90)
part = (privates_gender(pawn, gender)) ? Genital_Helper.hydraulic_penis : Genital_Helper.hydraulic_vagina;
else
part = (privates_gender(pawn, gender)) ? Genital_Helper.bionic_penis : Genital_Helper.bionic_vagina;
}
//alien races - ChjDroid, ChjAndroid
else if (AndroidsCompatibility.IsAndroid(pawn))
{
if (pawn.story.GetBackstory(BackstorySlot.Childhood) != null)
{
if (pawn.story.Childhood.untranslatedTitleShort.ToLower().Contains("bishojo"))
part = (privates_gender(pawn, gender)) ? Genital_Helper.bionic_penis : Genital_Helper.bionic_vagina;
else if (pawn.story.Childhood.untranslatedTitleShort.ToLower().Contains("pleasure"))
part = (privates_gender(pawn, gender)) ? Genital_Helper.bionic_penis : Genital_Helper.bionic_vagina;
else if (pawn.story.Childhood.untranslatedTitleShort.ToLower().Contains("idol"))
part = (privates_gender(pawn, gender)) ? Genital_Helper.bionic_penis : Genital_Helper.bionic_vagina;
else if (pawn.story.Childhood.untranslatedTitleShort.ToLower().Contains("social"))
part = (privates_gender(pawn, gender)) ? Genital_Helper.hydraulic_penis : Genital_Helper.hydraulic_vagina;
else if (pawn.story.Childhood.untranslatedTitleShort.ToLower().Contains("substitute"))
part = (privates_gender(pawn, gender)) ? Genital_Helper.average_penis : Genital_Helper.average_vagina;
else if (pawn.story.GetBackstory(BackstorySlot.Adulthood) != null)
{
if (pawn.story.Adulthood.untranslatedTitleShort.ToLower().Contains("courtesan"))
part = (privates_gender(pawn, gender)) ? Genital_Helper.bionic_penis : Genital_Helper.bionic_vagina;
else if (pawn.story.Adulthood.untranslatedTitleShort.ToLower().Contains("social"))
part = (privates_gender(pawn, gender)) ? Genital_Helper.hydraulic_penis : Genital_Helper.hydraulic_vagina;
}
else
return;
}
else if (pawn.story.GetBackstory(BackstorySlot.Adulthood) != null)
{
if (pawn.story.Adulthood.untranslatedTitleShort.ToLower().Contains("courtesan"))
part = (privates_gender(pawn, gender)) ? Genital_Helper.bionic_penis : Genital_Helper.bionic_vagina;
else if (pawn.story.Adulthood.untranslatedTitleShort.ToLower().Contains("social"))
part = (privates_gender(pawn, gender)) ? Genital_Helper.hydraulic_penis : Genital_Helper.hydraulic_vagina;
}
if (part == Genital_Helper.generic_penis || part == Genital_Helper.generic_vagina)
return;
}
//animal cats
else if (racename.ContainsAny("cat", "cougar", "lion", "leopard", "cheetah", "panther", "tiger", "lynx", "smilodon", "akaneko"))
{
part = (privates_gender(pawn, gender)) ? Genital_Helper.feline_penis : Genital_Helper.feline_vagina;
}
//animal canine/dogs
else if (racename.ContainsAny("husky", "warg", "terrier", "collie", "hound", "retriever", "mastiff", "wolf", "fox",
"vulptex", "dachshund", "schnauzer", "corgi", "pug", "doberman", "chowchow", "borzoi", "saintbernard", "newfoundland",
"poodle", "dog", "coyote"))
{
part = (privates_gender(pawn, gender)) ? Genital_Helper.canine_penis : Genital_Helper.canine_vagina;
}
//animal horse - MoreMonstergirls
else if (racename.ContainsAny("horse", "centaur", "zebra", "donkey", "dryad"))
{
part = (privates_gender(pawn, gender)) ? Genital_Helper.equine_penis : Genital_Helper.equine_vagina;
}
//animal raccoon
else if (racename.Contains("racc"))
{
part = (privates_gender(pawn, gender)) ? Genital_Helper.raccoon_penis : Genital_Helper.generic_vagina;
}
//animal crocodilian (alligator, crocodile, etc)
else if (racename.ContainsAny("alligator", "crocodile", "caiman", "totodile", "croconaw", "feraligatr", "quinkana", "purussaurus", "kaprosuchus", "sarcosuchus"))
{
part = (privates_gender(pawn, gender)) ? Genital_Helper.crocodilian_penis : Genital_Helper.generic_vagina;
}
//hemipenes - mostly reptiles and snakes
else if (racename.ContainsAny("guana", "cobra", "gecko", "snake", "boa", "quinkana", "megalania", "gila", "gigantophis", "komodo", "basilisk", "thorny", "onix", "lizard", "slither") && !racename.ContainsAny("boar"))
{
part = (privates_gender(pawn, gender)) ? Genital_Helper.hemipenis : Genital_Helper.generic_vagina;
}
//animal dragon - MoreMonstergirls
else if (racename.ContainsAny("dragon", "thrumbo", "drake", "charizard", "saurus"))
{
part = (privates_gender(pawn, gender)) ? Genital_Helper.dragon_penis : Genital_Helper.dragon_vagina;
}
//animal slime - MoreMonstergirls
else if (racename.Contains("slime"))
{
// slime always futa
pawn.health.AddHediff(SexPartAdder.MakePart(privates_gender(pawn, gender) ? Genital_Helper.slime_penis : Genital_Helper.slime_vagina, pawn, bpr), bpr);
pawn.health.AddHediff(SexPartAdder.MakePart(privates_gender(pawn, gender) ? Genital_Helper.slime_vagina : Genital_Helper.slime_penis, pawn, bpr), bpr);
return;
}
//animal demons - MoreMonstergirls
else if (racename.Contains("impmother") || racename.Contains("demon"))
{
// 25% futa
pawn.health.AddHediff(SexPartAdder.MakePart(privates_gender(pawn, gender) ? Genital_Helper.demon_penis : Genital_Helper.demon_vagina, pawn, bpr), bpr);
if (Rand.Value < 0.25f)
pawn.health.AddHediff(SexPartAdder.MakePart(privates_gender(pawn, gender) ? Genital_Helper.demon_penis : Genital_Helper.demonT_penis, pawn, bpr), bpr);
return;
}
//animal demons - MoreMonstergirls
else if (racename.Contains("baphomet"))
{
if (Rand.Value < 0.50f)
pawn.health.AddHediff(SexPartAdder.MakePart(privates_gender(pawn, gender) ? Genital_Helper.demon_penis : Genital_Helper.demon_vagina, pawn, bpr), bpr);
else
pawn.health.AddHediff(SexPartAdder.MakePart(privates_gender(pawn, gender) ? Genital_Helper.equine_penis : Genital_Helper.demon_vagina, pawn, bpr), bpr);
return;
}
else if (pawn.RaceProps.Humanlike)
{
//--Log.Message("Genital_Helper::add_genitals( " + xxx.get_pawnname(pawn) + " ) - race is humanlike");
if (value < 0.90 || (pawn.ageTracker.AgeBiologicalYears < 2))
part = (privates_gender(pawn, gender)) ? Genital_Helper.average_penis : Genital_Helper.average_vagina;
else if (value < 0.95)
part = (privates_gender(pawn, gender)) ? Genital_Helper.hydraulic_penis : Genital_Helper.hydraulic_vagina;
else
part = (privates_gender(pawn, gender)) ? Genital_Helper.bionic_penis : Genital_Helper.bionic_vagina;
}
//--Log.Message("Genital_Helper::add_genitals final ( " + xxx.get_pawnname(pawn) + " ) " + part.defName);
var hd = SexPartAdder.MakePart(part, pawn, bpr);
//Log.Message("Genital_Helper::add_genitals final ( " + xxx.get_pawnname(pawn) + " ) " + hd.def.defName + " sev " + hd.Severity + " bpr " + BPR.def.defName);
pawn.health.AddHediff(hd, bpr);
//Log.Message("Genital_Helper::add_genitals final ( " + xxx.get_pawnname(pawn) + " ) " + pawn.health.hediffSet.HasHediff(hd.def));
}
public static void AddAnus(Pawn pawn, BodyPartRecord bpr, Pawn parent)
{
var temppawn = parent ?? pawn;
HediffDef part;
double value = GenderTechLevelCheck(pawn);
string racename = temppawn.kindDef.race.defName.ToLower();
part = Genital_Helper.generic_anus;
if (xxx.is_mechanoid(pawn))
{
return;
}
else if (xxx.is_insect(temppawn))
{
part = Genital_Helper.insect_anus;
}
//alien races - ChjDroid, ChjAndroid
else if (AndroidsCompatibility.IsAndroid(pawn))
{
if (pawn.story.GetBackstory(BackstorySlot.Childhood) != null)
{
if (pawn.story.Childhood.untranslatedTitleShort.ToLower().Contains("bishojo"))
part = Genital_Helper.bionic_anus;
else if (pawn.story.Childhood.untranslatedTitleShort.ToLower().Contains("pleasure"))
part = Genital_Helper.bionic_anus;
else if (pawn.story.Childhood.untranslatedTitleShort.ToLower().Contains("idol"))
part = Genital_Helper.bionic_anus;
else if (pawn.story.Childhood.untranslatedTitleShort.ToLower().Contains("social"))
part = Genital_Helper.hydraulic_anus;
else if (pawn.story.Childhood.untranslatedTitleShort.ToLower().Contains("substitute"))
part = Genital_Helper.average_anus;
else if (pawn.story.GetBackstory(BackstorySlot.Adulthood) != null)
{
if (pawn.story.Adulthood.untranslatedTitleShort.ToLower().Contains("courtesan"))
part = Genital_Helper.bionic_anus;
else if (pawn.story.Adulthood.untranslatedTitleShort.ToLower().Contains("social"))
part = Genital_Helper.hydraulic_anus;
}
}
else if (pawn.story.GetBackstory(BackstorySlot.Adulthood) != null)
{
if (pawn.story.Adulthood.untranslatedTitleShort.ToLower().Contains("courtesan"))
part = Genital_Helper.bionic_anus;
else if (pawn.story.Adulthood.untranslatedTitleShort.ToLower().Contains("social"))
part = Genital_Helper.hydraulic_anus;
}
if (part == Genital_Helper.generic_anus)
return;
}
else if (racename.Contains("slime"))
{
part = Genital_Helper.slime_anus;
}
//animal demons - MoreMonstergirls
else if (racename.Contains("impmother") || racename.Contains("baphomet") || racename.Contains("demon"))
{
part = Genital_Helper.demon_anus;
}
else if (pawn.RaceProps.Humanlike)
{
if (value < 0.90 || (pawn.ageTracker.AgeBiologicalYears < 2))
part = Genital_Helper.average_anus;
else if (value < 0.95)
part = Genital_Helper.hydraulic_anus;
else
part = Genital_Helper.bionic_anus;
}
pawn.health.AddHediff(SexPartAdder.MakePart(part, pawn, bpr), bpr);
}
}
}
| Korth95/rjw | 1.5/Source/Common/Helpers/LegacySexPartAdder.cs | C# | mit | 19,977 |
using System;
using System.Collections.Generic;
using RimWorld;
using Verse;
namespace rjw
{
class OviHelper
{
static readonly IDictionary<PawnKindDef, ThingDef> FertileEggPawnKinds = new Dictionary<PawnKindDef, ThingDef>();
static readonly IDictionary<PawnKindDef, ThingDef> UnfertileEggPawnKinds = new Dictionary<PawnKindDef, ThingDef>();
public static CompProperties_EggLayer GenerateEggLayerProperties(PawnKindDef pawnKindDef, RaceGroupDef raceGroupDef)
{
CompProperties_EggLayer comp = new CompProperties_EggLayer();
comp.eggFertilizedDef = DefDatabase<ThingDef>.GetNamed(raceGroupDef.eggFertilizedDef);
comp.eggUnfertilizedDef = DefDatabase<ThingDef>.GetNamed(raceGroupDef.eggUnfertilizedDef);
comp.eggProgressUnfertilizedMax = raceGroupDef.eggProgressUnfertilizedMax;
comp.eggLayIntervalDays = raceGroupDef.eggLayIntervalDays;
return comp;
}
}
} | Korth95/rjw | 1.5/Source/Common/Helpers/OviHelper.cs | C# | mit | 889 |
using Verse;
using Verse.AI;
namespace rjw
{
public static class Pather_Utility
{
public static bool cells_to_target_casual(Pawn pawn, IntVec3 Position)
{
//less taxing, ignores walls
return pawn.Position.DistanceTo(Position) < RJWSettings.maxDistanceCellsCasual;
}
public static bool cells_to_target_rape(Pawn pawn, IntVec3 Position)
{
//less taxing, ignores walls
return pawn.Position.DistanceTo(Position) < RJWSettings.maxDistanceCellsRape;
}
public static bool can_path_to_target(Pawn pawn, IntVec3 Position)
{
//more taxing, using real pathing
bool canit = true;
if (RJWSettings.maxDistancePathCost > 0)
{
PawnPath pawnPath = pawn.Map.pathFinder.FindPath(pawn.Position, Position, pawn);
if (pawnPath.TotalCost > RJWSettings.maxDistancePathCost)
canit = false;// too far
pawnPath.Dispose();
}
return canit;
}
}
} | Korth95/rjw | 1.5/Source/Common/Helpers/Pather_Utility.cs | C# | mit | 890 |
using System.Collections.Generic;
using System.Linq;
using Verse;
namespace rjw
{
class RaceGroupDef_Helper
{
/// <summary>
/// Cache for TryGetRaceGroupDef.
/// </summary>
static readonly IDictionary<PawnKindDef, RaceGroupDef> RaceGroupByPawnKind = new Dictionary<PawnKindDef, RaceGroupDef>();
public static bool TryGetRaceGroupDef(PawnKindDef pawnKindDef, out RaceGroupDef raceGroupDef)
{
if (RaceGroupByPawnKind.TryGetValue(pawnKindDef, out raceGroupDef))
{
return raceGroupDef != null;
}
else
{
raceGroupDef = GetRaceGroupDefInternal(pawnKindDef);
RaceGroupByPawnKind.Add(pawnKindDef, raceGroupDef);
return raceGroupDef != null;
}
}
public static bool TryGetRaceGroupDef(Pawn pawn, out RaceGroupDef raceGroupDef)
{
return TryGetRaceGroupDef(pawn.kindDef, out raceGroupDef);
}
/// <summary>
/// Returns the best match RaceGroupDef for the given pawn, or null if none is found.
/// </summary>
static RaceGroupDef GetRaceGroupDefInternal(Pawn pawn)
{
return GetRaceGroupDefInternal(pawn.kindDef);
}
static RaceGroupDef GetRaceGroupDefInternal(PawnKindDef kindDef)
{
var raceName = kindDef.race.defName;
var pawnKindName = kindDef.defName;
var groups = DefDatabase<RaceGroupDef>.AllDefs;
var kindMatches = groups.Where(group => group.pawnKindNames?.Contains(pawnKindName) ?? false).ToList();
var raceMatches = groups.Where(group => group.raceNames?.Contains(raceName) ?? false).ToList();
var count = kindMatches.Count() + raceMatches.Count();
if (count == 0)
{
//ModLog.Message($"Pawn named '{pawn.Name}' matched no RaceGroupDef. If you want to create a matching RaceGroupDef you can use the raceName '{raceName}' or the pawnKindName '{pawnKindName}'.");
return null;
}
else if (count == 1)
{
// ModLog.Message($"Pawn named '{pawn.Name}' matched 1 RaceGroupDef.");
return kindMatches.Concat(raceMatches).Single();
}
else
{
// ModLog.Message($"Pawn named '{pawn.Name}' matched {count} RaceGroupDefs.");
// If there are multiple RaceGroupDef matches, choose one of them.
// First prefer defs NOT defined in rjw.
// Then prefer a match by kind over a match by race.
return kindMatches.FirstOrDefault(match => !IsThisMod(match))
?? raceMatches.FirstOrDefault(match => !IsThisMod(match))
?? kindMatches.FirstOrDefault()
?? raceMatches.FirstOrDefault();
}
}
static bool IsThisMod(Def def)
{
var rjwContent = LoadedModManager.RunningMods.Single(pack => pack.Name == "RimJobWorld");
return rjwContent.AllDefs.Contains(def);
}
/// <summary>
/// Returns true if a race part was chosen (even if that part is "no part").
/// </summary>
public static bool TryAddRacePart(Pawn pawn, SexPartType sexPartType)
{
if (!TryGetRaceGroupDef(pawn, out var raceGroupDef))
{
// No race, so nothing was chosen.
return false;
}
if (!RacePartDef_Helper.TryChooseRacePartDef(raceGroupDef, sexPartType, out var racePartDef))
{
// Failed to find a part, so nothing was chosen.
return false;
}
if (racePartDef.IsNone)
{
// "no part" was explicitly chosen.
return true;
}
var target = sexPartType.GetBodyPartDef();
var bodyPartRecord = pawn.RaceProps.body.AllParts.Find(bpr => bpr.def == target);
if (!racePartDef.TryGetHediffDef(out var hediffDef))
{
// Failed to find hediffDef.
return false;
}
var hediff = RacePartDef_Helper.MakePart(hediffDef, pawn, bodyPartRecord, racePartDef);
pawn.health.AddHediff(hediff, bodyPartRecord);
// A part was chosen and added.
return true;
}
}
}
| Korth95/rjw | 1.5/Source/Common/Helpers/RaceGroupDef_Helper.cs | C# | mit | 3,652 |
using Multiplayer.API;
using System.Collections.Generic;
using System.Linq;
using Verse;
using RimWorld;
namespace rjw
{
class RacePartDef_Helper
{
/// <summary>
/// Returns true if a partAdders was chosen (even if that part is "no part").
/// </summary>
[SyncMethod]
public static bool TryRacePartDef_partAdders(Pawn pawn)
{
//RaceGroupDef_Helper.TryGetRaceGroupDef(pawn.kindDef, out var raceGroupDef);
if (!RaceGroupDef_Helper.TryGetRaceGroupDef(pawn.kindDef, out var raceGroupDef))
return false;
if (raceGroupDef.partAdders.NullOrEmpty())
return false;
List<BodyPartRecord> pawnParts = pawn.RaceProps?.body?.AllParts;
pawnParts = pawnParts.FindAll(record => !pawn.health.hediffSet.PartIsMissing(record));
foreach (var Adder in raceGroupDef.partAdders)
{
if (Adder.chance <= Rand.Value)
continue;
var racePartDef = DefDatabase<RacePartDef>.GetNamedSilentFail(Adder.rjwPart);
if (racePartDef == null)
{
//No part found
continue;
}
if (!racePartDef.TryGetHediffDef(out var rjwPartDef))
{
//No part found
continue;
}
pawnParts = pawnParts.FindAll(record => Adder.bodyParts.Contains(record.def.defName));
foreach (BodyPartRecord record in pawnParts)
{
var hediff = RacePartDef_Helper.MakePart(rjwPartDef, pawn, record, racePartDef);
pawn.health.AddHediff(hediff, record);
}
}
return true;
}
/// <summary>
/// Returns true if a race part was chosen (even if that part is "no part").
/// </summary>
[SyncMethod]
public static bool TryChooseRacePartDef(RaceGroupDef raceGroupDef, SexPartType sexPartType, out RacePartDef racePartDef)
{
var partNames = raceGroupDef.GetRacePartDefNames(sexPartType);
if (partNames == null)
{
// Missing list, so nothing was chosen.
racePartDef = null;
return false;
}
else if (!partNames.Any())
{
// Empty list, so "no part" was chosen.
racePartDef = RacePartDef.None;
return true;
}
var chances = raceGroupDef.GetChances(sexPartType);
var hasChances = chances != null && chances.Count() > 0;
if (hasChances && chances.Count() != partNames.Count())
{
// No need for this to be runtime, should probably be a config error in RaceGroupDef.
ModLog.Error($"RaceGroupDef named {raceGroupDef.defName} has {partNames.Count()} parts but {chances.Count()} chances for {sexPartType}.");
racePartDef = null;
return false;
}
string partName;
if (hasChances)
{
var indexes = partNames.Select((x, i) => i);
partName = partNames[indexes.RandomElementByWeight(i => chances[i])];
}
else
{
partName = partNames.RandomElement();
}
racePartDef = DefDatabase<RacePartDef>.GetNamedSilentFail(partName);
if (racePartDef == null)
{
ModLog.Error($"Could not find a RacePartDef named {partName} referenced by RaceGroupDef named {raceGroupDef.defName}.");
return false;
}
else
{
return true;
}
}
[SyncMethod]
public static Hediff MakePart(HediffDef hediffDef, Pawn pawn, BodyPartRecord bodyPartRecord, RacePartDef racePartDef)
{
var hediff = HediffMaker.MakeHediff(hediffDef, pawn, bodyPartRecord);
var compHediff = hediff.TryGetComp<HediffComp_SexPart>();
if (compHediff != null)
{
compHediff.Init(pawn);
if (racePartDef.FluidDef != null)
{
compHediff.Fluid = racePartDef.FluidDef;
}
if (racePartDef.severityCurve != null && racePartDef.severityCurve.Any())
{
if (!(compHediff.baseSize == 0.01f && hediff.def.defName.ToLower().Contains("breast") && pawn.gender == Gender.Male))
{
var severity = racePartDef.severityCurve.Evaluate(Rand.Value);
compHediff.baseSize = severity * pawn.BodySize;
}
}
if (racePartDef.fluidModifier.HasValue)
{
compHediff.partFluidFactor *= racePartDef.fluidModifier.Value;
}
compHediff.UpdateSeverity();
}
return hediff;
}
/// <summary>
/// Generates and logs RacePartDef xml shells for each RJW hediff so they can be manually saved as a def file and referenced by RaceGroupDefs.
/// In theory this could be done automatically at run time. But then we also might want to add real configuration
/// to the shells so for now just checking in the shells.
/// </summary>
public static void GeneratePartShells()
{
var defs = DefDatabase<HediffDef_SexPart>.AllDefs.OrderBy(def => def.defName);
var template = "\t<rjw.RacePartDef>\n\t\t<defName>{0}</defName>\n\t\t<hediffName>{0}</hediffName>\n\t</rjw.RacePartDef>";
var strings = defs.Select(def => string.Format(template, def.defName));
ModLog.Message(" RacePartDef shells:\n" + string.Join("\n", strings));
}
}
}
| Korth95/rjw | 1.5/Source/Common/Helpers/RacePartDef_Helper.cs | C# | mit | 4,731 |
using Multiplayer.API;
using RimWorld;
using Verse;
using System.Collections.Generic;
using System.Linq;
namespace rjw
{
public class SexPartAdder
{
/// <summary>
/// return true if going to set penis,
/// return false for vagina
/// </summary>
public static bool IsAddingPenis(Pawn pawn, Gender gender)
{
return (pawn.gender == Gender.Male) ? (gender != Gender.Female) : (gender == Gender.Male);
}
/// <summary>
/// generate part hediff
/// </summary>
public static Hediff MakePart(HediffDef def, Pawn pawn, BodyPartRecord bpr)
{
//Log.Message("SexPartAdder::PartMaker ( " + xxx.get_pawnname(pawn) + " ) " + def.defName);
Hediff hd = HediffMaker.MakeHediff(def, pawn, bpr);
//Log.Message("SexPartAdder::PartMaker ( " + xxx.get_pawnname(pawn) + " ) " + hd.def.defName);
HediffComp_SexPart compHediff = hd.TryGetComp<HediffComp_SexPart>();
if (compHediff != null)
{
//Log.Message("SexPartAdder::PartMaker init comps");
compHediff.Init(pawn);
compHediff.UpdateSeverity();
}
return hd;
}
/// <summary>
/// operation - move part data from thing to hediff
/// </summary>
public static Hediff recipePartAdder(RecipeDef recipe, Pawn pawn, BodyPartRecord part, List<Thing> ingredients)
{
Hediff hd = HediffMaker.MakeHediff(recipe.addsHediff, pawn, part);
Thing thing = ingredients.Find(x => x.def.defName == recipe.addsHediff.defName);
CompThingBodyPart thingComp = thing.TryGetComp<rjw.CompThingBodyPart>();
HediffComp_SexPart hediffComp = hd.TryGetComp<rjw.HediffComp_SexPart>();
if (hediffComp != null && thingComp != null)
{
if (thingComp.size > 0)
{
if (thingComp.fluid != null && thingComp.fluid != hediffComp.Def.fluid)
{
hediffComp.Fluid = thingComp.fluid;
}
hediffComp.partFluidFactor = thingComp.fluidAmount;
hediffComp.originalOwnerSize = thingComp.originalOwnerSize;
hediffComp.originalOwnerRace = thingComp.originalOwnerRace;
hediffComp.previousOwner = thingComp.previousOwner;
hediffComp.isTransplant = true;
hediffComp.ForceSize(thingComp.size);
}
else //not initialised things, drop pods, trader? //TODO: figure out how to populate rjw parts at gen
hd = MakePart(hd.def, pawn, part);
}
return hd;
}
/// <summary>
/// operation - move part data from hediff to thing
/// </summary>
public static Thing recipePartRemover(Hediff hd)
{
Thing thing = null;
if (hd.def.spawnThingOnRemoved != null)
{
thing = ThingMaker.MakeThing(hd.def.spawnThingOnRemoved);
CompThingBodyPart thingComp = thing.TryGetComp<rjw.CompThingBodyPart>();
HediffComp_SexPart hediffComp = hd.TryGetComp<rjw.HediffComp_SexPart>();
if (thingComp != null && hediffComp != null)
{
thingComp.InitFromComp(hediffComp);
}
}
return thing;
}
[SyncMethod]
public static void add_genitals(Pawn pawn, Pawn parent = null, Gender gender = Gender.None)
{
//--Log.Message("Genital_Helper::add_genitals( " + xxx.get_pawnname(pawn) + " ) called");
BodyPartRecord partBPR = Genital_Helper.get_genitalsBPR(pawn);
var parts = pawn.GetGenitalsList();
//--Log.Message("Genital_Helper::add_genitals( " + xxx.get_pawnname(pawn) + " ) - checking genitals");
if (partBPR == null)
{
//--ModLog.Message(" add_genitals( " + xxx.get_pawnname(pawn) + " ) doesn't have a genitals");
return;
}
else if (pawn.health.hediffSet.PartIsMissing(partBPR))
{
//--ModLog.Message(" add_genitals( " + xxx.get_pawnname(pawn) + " ) had a genital but was removed.");
return;
}
if (Genital_Helper.has_genitals(pawn, parts) && gender == Gender.None)//allow to add gender specific genitals(futa)
{
//--ModLog.Message(" add_genitals( " + xxx.get_pawnname(pawn) + " ) already has genitals");
return;
}
HediffDef part;
// maybe add some check based on bodysize of pawn for genitals size limit
//Log.Message("Genital_Helper::add_genitals( " + pawn.RaceProps.baseBodySize + " ) - 1");
//Log.Message("Genital_Helper::add_genitals( " + pawn.kindDef.race.size. + " ) - 2");
part = (IsAddingPenis(pawn, gender)) ? Genital_Helper.generic_penis : Genital_Helper.generic_vagina;
if (Genital_Helper.has_vagina(pawn, parts) && part == Genital_Helper.generic_vagina)
{
//--ModLog.Message(" add_genitals( " + xxx.get_pawnname(pawn) + " ) already has vagina");
return;
}
if (Genital_Helper.has_male_bits(pawn, parts) && part == Genital_Helper.generic_penis)
{
//--ModLog.Message(" add_genitals( " + xxx.get_pawnname(pawn) + " ) already has penis");
return;
}
//override race genitals
if (part == Genital_Helper.generic_vagina && pawn.TryAddRacePart(SexPartType.FemaleGenital))
{
return;
}
if (part == Genital_Helper.generic_penis && pawn.TryAddRacePart(SexPartType.MaleGenital))
{
return;
}
LegacySexPartAdder.AddGenitals(pawn, parent, gender, partBPR, part);
}
public static void add_breasts(Pawn pawn, Pawn parent = null, Gender gender = Gender.None)
{
//--ModLog.Message(" add_breasts( " + xxx.get_pawnname(pawn) + " ) called");
BodyPartRecord partBPR = Genital_Helper.get_breastsBPR(pawn);
if (partBPR == null)
{
//--ModLog.Message(" add_breasts( " + xxx.get_pawnname(pawn) + " ) - pawn doesn't have a breasts");
return;
}
else if (pawn.health.hediffSet.PartIsMissing(partBPR))
{
//--ModLog.Message(" add_breasts( " + xxx.get_pawnname(pawn) + " ) had breasts but were removed.");
return;
}
if (pawn.GetBreastList().Count > 0)
//if (Genital_Helper.has_breasts(pawn))
{
//--ModLog.Message(" add_breasts( " + xxx.get_pawnname(pawn) + " ) - pawn already has breasts");
return;
}
//TODO: figure out how to add (flat) breasts to males
//Check for (flat) breasts to males done in RacepartDef_Helper.cs when severity curve checked
var racePartType = (pawn.gender == Gender.Female || gender == Gender.Female)
? SexPartType.FemaleBreast
: SexPartType.MaleBreast;
if (pawn.TryAddRacePart(racePartType))
{
return;
}
LegacySexPartAdder.AddBreasts(pawn, partBPR, parent);
}
public static void add_anus(Pawn pawn, Pawn parent = null)
{
BodyPartRecord partBPR = Genital_Helper.get_anusBPR(pawn);
if (partBPR == null)
{
//--ModLog.Message(" add_anus( " + xxx.get_pawnname(pawn) + " ) doesn't have an anus");
return;
}
else if (pawn.health.hediffSet.PartIsMissing(partBPR))
{
//--ModLog.Message(" add_anus( " + xxx.get_pawnname(pawn) + " ) had an anus but was removed.");
return;
}
if (pawn.GetAnusList().Count > 0)
{
//--ModLog.Message(" add_anus( " + xxx.get_pawnname(pawn) + " ) already has an anus");
return;
}
if (pawn.TryAddRacePart(SexPartType.Anus))
{
return;
}
LegacySexPartAdder.AddAnus(pawn, partBPR, parent);
}
}
}
| Korth95/rjw | 1.5/Source/Common/Helpers/SexPartAdder.cs | C# | mit | 6,910 |
using System;
using System.Collections.Generic;
using System.Linq;
using RimWorld;
using UnityEngine;
using Verse;
using Verse.AI;
using Verse.Sound;
using HarmonyLib;
using Multiplayer.API;
using rjw.Modules.Interactions.Contexts;
using rjw.Modules.Interactions.Implementation;
using rjw.Modules.Interactions;
using rjw.Modules.Interactions.Objects;
using rjw.Modules.Interactions.Enums;
using static HarmonyLib.Code;
using rjw.Modules.Interactions.Helpers;
using rjw.Modules.Interactions.Extensions;
using rjw.Modules.Interactions.Objects.Parts;
using SexType = rjw.xxx.rjwSextype;
namespace rjw
{
public class SexUtility
{
private const float base_sat_per_fuck = 0.40f;
private const float base_sat_per_quirk = 0.20f;
public static readonly InteractionDef AnimalSexChat = DefDatabase<InteractionDef>.GetNamed("AnimalSexChat");
public static readonly List<InteractionDef> SexInterractions = DefDatabase<InteractionDef>.AllDefsListForReading.Where(x => x.HasModExtension<InteractionExtension>()).ToList();
// Alert checker that is called from several jobs. Checks the pawn relation, and whether it should sound alert.
// notification in top left corner
// rape attempt
public static void RapeTargetAlert(Pawn rapist, Pawn target)
{
if (target.IsDesignatedComfort() && rapist.jobs.curDriver.GetType() == typeof(JobDriver_RapeComfortPawn))
if (!RJWPreferenceSettings.ShowForCP)
return;
if (target.IsDesignatedComfort() && rapist.jobs.curDriver.GetType() == typeof(JobDriver_Breeding))
if (target.IsDesignatedBreeding())
if (!RJWPreferenceSettings.ShowForBreeding)
return;
bool silent = false;
PawnRelationDef relation = rapist.GetMostImportantRelation(target);
string rapeverb = "rape";
if (xxx.is_mechanoid(rapist)) rapeverb = "assault";
else if (xxx.is_animal(rapist) || xxx.is_animal(target)) rapeverb = "breed";
// TODO: Need to write a cherker method for family relations. Would be useful for other things than just this, such as incest settings/quirk.
string message = (xxx.get_pawnname(rapist) + " is trying to " + rapeverb + " " + xxx.get_pawnname(target));
message += relation == null ? "." : (", " + rapist.Possessive() + " " + relation.GetGenderSpecificLabel(target) + ".");
switch (RJWPreferenceSettings.rape_attempt_alert)
{
case RJWPreferenceSettings.RapeAlert.Enabled:
break;
case RJWPreferenceSettings.RapeAlert.Humanlikes:
if (!xxx.is_human(target))
return;
break;
case RJWPreferenceSettings.RapeAlert.Colonists:
if (!target.IsColonist)
return;
break;
case RJWPreferenceSettings.RapeAlert.Silent:
silent = true;
break;
default:
return;
}
if (!silent)
{
Messages.Message(message, rapist, MessageTypeDefOf.NegativeEvent);
}
else
{
Messages.Message(message, rapist, MessageTypeDefOf.SilentInput);
}
}
// Alert checker that is called from several jobs.
// notification in top left corner
// rape started
public static void BeeingRapedAlert(Pawn rapist, Pawn target)
{
if (target.IsDesignatedComfort() && rapist.jobs.curDriver.GetType() == typeof(JobDriver_RapeComfortPawn))
if (!RJWPreferenceSettings.ShowForCP)
return;
if (target.IsDesignatedComfort() && rapist.jobs.curDriver.GetType() == typeof(JobDriver_Breeding))
if (target.IsDesignatedBreeding())
if (!RJWPreferenceSettings.ShowForBreeding)
return;
bool silent = false;
switch (RJWPreferenceSettings.rape_alert)
{
case RJWPreferenceSettings.RapeAlert.Enabled:
break;
case RJWPreferenceSettings.RapeAlert.Humanlikes:
if (!xxx.is_human(target))
return;
break;
case RJWPreferenceSettings.RapeAlert.Colonists:
if (!target.IsColonist)
return;
break;
case RJWPreferenceSettings.RapeAlert.Silent:
silent = true;
break;
default:
return;
}
if (!silent)
{
Messages.Message(xxx.get_pawnname(target) + " is getting raped.", target, MessageTypeDefOf.NegativeEvent);
}
else
{
Messages.Message(xxx.get_pawnname(target) + " is getting raped.", target, MessageTypeDefOf.SilentInput);
}
}
// Quick method that return a body part by name. Used for checking if a pawn has a specific body part, etc.
public static BodyPartRecord GetPawnBodyPart(Pawn pawn, string bodyPart)
{
return pawn.RaceProps.body.AllParts.Find(x => x.def == DefDatabase<BodyPartDef>.GetNamed(bodyPart));
}
public static void CumFilthGenerator(Pawn pawn)
{
if (pawn == null) return;
if (pawn.Dead) return;
if (xxx.is_slime(pawn)) return;
if (!RJWSettings.cum_filth) return;
// Larger creatures, larger messes.
float pawn_cum = Math.Min(80 / ScaleToHumanAge(pawn), 2.0f) * pawn.BodySize;
// Increased output if the pawn has the Messy quirk.
if (xxx.has_quirk(pawn, "Messy"))
pawn_cum *= 2.0f;
var partsProducingFluid = pawn.GetGenitalsList().OfType<ISexPartHediff>().Where(part => part.Def.produceFluidOnOrgasm);
foreach (var part in partsProducingFluid)
{
HediffDef_SexPart def = part.Def;
HediffComp_SexPart comp = part.GetPartComp();
SexFluidDef fluid = comp.Fluid;
if (fluid?.filth == null)
{
continue;
}
int filthCount = (int)(pawn_cum * comp.FluidAmount);
if (fluid.alwaysProduceFilth && filthCount < 1 )
{
filthCount = 1;
}
FilthMaker.TryMakeFilth(pawn.PositionHeld, pawn.MapHeld, fluid.filth, pawn.LabelIndefinite(), filthCount, FilthSourceFlags.Pawn);
}
}
// The pawn may or may not clean up the mess after fapping.
[SyncMethod]
public static bool ConsiderCleaning(Pawn fapper)
{
if (!RJWSettings.cum_filth) return false;
if (!xxx.has_traits(fapper) || fapper.story == null) return false;
if (fapper.WorkTagIsDisabled(WorkTags.Cleaning)) return false;
float do_cleaning = 0.5f; // 50%
if (!fapper.PositionHeld.Roofed(fapper.Map))
do_cleaning -= 0.25f; // Less likely to clean if outdoors.
if (xxx.CTIsActive && fapper.story.traits.HasTrait(xxx.RCT_NeatFreak))
do_cleaning += 1.00f;
if (xxx.has_quirk(fapper, "Messy"))
do_cleaning -= 0.75f;
switch (fapper.needs?.rest?.CurCategory)
{
case RestCategory.Exhausted:
do_cleaning -= 0.5f;
break;
case RestCategory.VeryTired:
do_cleaning -= 0.3f;
break;
case RestCategory.Tired:
do_cleaning -= 0.1f;
break;
case RestCategory.Rested:
do_cleaning += 0.3f;
break;
}
if (fapper.story.traits.DegreeOfTrait(VanillaTraitDefOf.NaturalMood) == -2) // Depressive
do_cleaning -= 0.3f;
if (fapper.story.traits.DegreeOfTrait(TraitDefOf.Industriousness) == 2) // Industrious
do_cleaning += 1.0f;
else if (fapper.story.traits.DegreeOfTrait(TraitDefOf.Industriousness) == 1) // Hard worker
do_cleaning += 0.5f;
else if (fapper.story.traits.DegreeOfTrait(TraitDefOf.Industriousness) == -1) // Lazy
do_cleaning -= 0.5f;
else if (fapper.story.traits.DegreeOfTrait(TraitDefOf.Industriousness) == -2) // Slothful
do_cleaning -= 1.0f;
if (xxx.is_ascetic(fapper))
do_cleaning += 0.2f;
//Rand.PopState();
//Rand.PushState(RJW_Multiplayer.PredictableSeed());
return Rand.Chance(do_cleaning);
}
/// <summary>Handles after-sex trait and thought gain, and fluid creation. Initiator of the act (whore, rapist, female zoophile, etc) should be first.</summary>
[SyncMethod]
public static void Aftersex(SexProps props)
{
if (props.sexType == xxx.rjwSextype.Masturbation)
{
AfterMasturbation(props);
return;
}
bool bothInMap = false;
if (!props.partner.Dead)
bothInMap = props.pawn.Map != null && props.partner.Map != null; //Added by Hoge. false when called this function for despawned pawn: using for background rape like a kidnappee
//Rand.PopState();
//Rand.PushState(RJW_Multiplayer.PredictableSeed());
if (bothInMap)
{
//Catch-all timer increase, for ensuring that pawns don't get stuck repeating jobs.
if (!props.isCoreLovin)
{
props.pawn.rotationTracker.Face(props.partner.DrawPos);
props.pawn.rotationTracker.FaceCell(props.partner.Position);
}
if (!props.partner.Dead)
{
if (!props.isCoreLovin)
{
props.partner.rotationTracker.Face(props.pawn.DrawPos);
props.partner.rotationTracker.FaceCell(props.pawn.Position);
}
if (RJWSettings.sounds_enabled)
{
if (props.isRape)
{
if (Rand.Value > 0.30f)
LifeStageUtility.PlayNearestLifestageSound(props.partner, (ls) => ls.soundAngry, null, null, 1.2f);
else
LifeStageUtility.PlayNearestLifestageSound(props.partner, (ls) => ls.soundCall, g => g.soundCall, null, 1.2f);
props.pawn.Drawer.Notify_MeleeAttackOn(props.partner);
props.partner.stances.stagger.StaggerFor(Rand.Range(10, 300));
}
else
LifeStageUtility.PlayNearestLifestageSound(props.partner, (ls) => ls.soundCall, g => g.soundCall,null);
}
if (props.sexType == xxx.rjwSextype.Vaginal || props.sexType == xxx.rjwSextype.DoublePenetration)
if (xxx.is_Virgin(props.partner))
{
//TODO: bind virginity to parts of pawn
/*
string thingdef_penis_name = Genital_Helper.get_penis_all(pawn)?.def.defName ?? "";
ThingDef thingdef_penis = null;
Log.Message("SexUtility::thingdef_penis_name " + thingdef_penis_name);
Log.Message("SexUtility::thingdef_penis 1 " + thingdef_penis);
if (thingdef_penis_name != "")
thingdef_penis = (from x in DefDatabase<ThingDef>.AllDefs where x.defName == thingdef_penis_name select x).RandomElement();
Log.Message("SexUtility::thingdef_penis 2 " + thingdef_penis);
partner.TakeDamage(new DamageInfo(DamageDefOf.Stab, 1, 999, -1.0f, null, xxx.genitals, thingdef_penis));
*/
}
}
if (RJWSettings.sounds_enabled && props.isCoreLovin)
SoundDef.Named("Cum").PlayOneShot(!props.partner.Dead
? new TargetInfo(props.partner.Position, props.pawn.Map)
: new TargetInfo(props.pawn.Position, props.pawn.Map));
if (props.isRape)
{
if (Rand.Value > 0.30f)
LifeStageUtility.PlayNearestLifestageSound(props.pawn, (ls) => ls.soundAngry, null,null, 1.2f);
else
LifeStageUtility.PlayNearestLifestageSound(props.pawn, (ls) => ls.soundCall, g => g.soundCall,null, 1.2f);
}
else
LifeStageUtility.PlayNearestLifestageSound(props.pawn, (ls) => ls.soundCall, g => g.soundCall, null);
}
if (props.usedCondom)
{
if (CondomUtility.UsedCondom != null)
GenSpawn.Spawn(CondomUtility.UsedCondom, props.pawn.Position, props.pawn.Map);
CondomUtility.useCondom(props.pawn);
CondomUtility.useCondom(props.partner);
}
else
{
if (props.isCoreLovin) // non core handled by jobdriver
{
//apply cum to floor:
CumFilthGenerator(props.pawn);
CumFilthGenerator(props.partner);
PregnancyHelper.impregnate(props);
TransferNutritionCore(props);
}
}
List<Trait> newInitiatorTraits = new(), newReceiverTraits = new();
if (props.isRape && !props.partner.Dead)
AfterSexUtility.processBrokenPawn(props.partner, newReceiverTraits);
//Satisfy(pawn, partner, sextype, rape);
//TODO: below is fucked up, unfuck it someday
AfterSexUtility.UpdateRecords(props);
GiveTraits(props, newInitiatorTraits);
GiveTraits(props.GetForPartner(), newReceiverTraits);
if (RJWSettings.sendTraitGainLetters)
{
SendTraitGainLetter(props.pawn, newInitiatorTraits);
SendTraitGainLetter(props.partner, newReceiverTraits);
}
}
// <summary>Solo acts.</summary>
public static void AfterMasturbation(SexProps props)
{
IncreaseTicksToNextLovin(props.pawn);
//apply cum to floor:
CumFilthGenerator(props.pawn);
AfterSexUtility.UpdateRecords(props);
// No traits from solo. Enable if some are edded. (Voyerism?)
//check_trait_gain(pawn);
}
// Scales alien lifespan to human age.
// Some aliens have broken lifespans, that can be manually corrected here.
public static int ScaleToHumanAge(Pawn pawn, int humanLifespan = 80)
{
float pawnAge = pawn.ageTracker.AgeBiologicalYearsFloat;
float pawnLifespan = pawn.RaceProps.lifeExpectancy;
if (pawn.def.defName == "Human") return (int)pawnAge; // Human, no need to scale anything.
// Xen races, all broken and need a fix.
if (pawn.def.defName.ContainsAny("Alien_Sergal", "Alien_SergalNME", "Alien_Xenn", "Alien_Racc", "Alien_Ferrex", "Alien_Wolvx", "Alien_Frijjid", "Alien_Fennex") && pawnLifespan >= 2000f)
{
pawnAge = Math.Min(pawnAge, 80f); // Clamp to 80.
pawnLifespan = 80f;
}
if (pawn.def.defName.ContainsAny("Alien_Gnoll", "Alien_StripedGnoll") && pawnLifespan >= 2000f)
{
pawnAge = Math.Min(pawnAge, 60f); // Clamp to 60.
pawnLifespan = 60f; // Mature faster than humans.
}
// Immortal races that mature at similar rate to humans.
if (pawn.def.defName.ContainsAny("LF_Dragonia", "LotRE_ElfStandardRace", "Alien_Crystalloid", "Alien_CrystalValkyrie"))
{
pawnAge = Math.Min(pawnAge, 40f); // Clamp to 40 - never grow 'old'.
pawnLifespan = 80f;
}
float age_scaling = humanLifespan / pawnLifespan;
float scaled_age = pawnAge * age_scaling;
if (scaled_age < 1)
scaled_age = 1;
return (int)scaled_age;
}
// Used in complex impregnation calculation. Pawns/animals with similar parts have better compatibility.
public static float BodySimilarity(Pawn pawn, Pawn partner)
{
float size_adjustment = Mathf.Lerp(0.3f, 1.05f, 1.0f - Math.Abs(pawn.BodySize - partner.BodySize));
//ModLog.Message(" Size adjustment: " + size_adjustment);
List<BodyPartDef> pawn_partlist = new List<BodyPartDef> { };
List<BodyPartDef> pawn_mismatched = new List<BodyPartDef> { };
List<BodyPartDef> partner_mismatched = new List<BodyPartDef> { };
//ModLog.Message("Checking compatibility for " + xxx.get_pawnname(pawn) + " and " + xxx.get_pawnname(partner));
bool pawnHasHands = pawn.health.hediffSet.GetNotMissingParts().Any(part => part.IsInGroup(BodyPartGroupDefOf.RightHand) || part.IsInGroup(BodyPartGroupDefOf.LeftHand));
foreach (BodyPartRecord part in pawn.RaceProps.body.AllParts)
{
pawn_partlist.Add(part.def);
}
float pawn_count = pawn_partlist.Count();
foreach (BodyPartRecord part in partner.RaceProps.body.AllParts)
{
partner_mismatched.Add(part.def);
}
float partner_count = partner_mismatched.Count();
foreach (BodyPartDef part in pawn_partlist)
{
if (partner_mismatched.Contains(part))
{
pawn_mismatched.Add(part);
partner_mismatched.Remove(part);
}
}
float pawn_mismatch = pawn_mismatched.Count() / pawn_count;
float partner_mismatch = partner_mismatched.Count() / partner_count;
//ModLog.Message("Body type similarity for " + xxx.get_pawnname(pawn) + " and " + xxx.get_pawnname(partner) + ": " + Math.Round(((pawn_mismatch + partner_mismatch) * 50) * size_adjustment, 1) + "%");
return ((pawn_mismatch + partner_mismatch) / 2) * size_adjustment;
}
public static void SatisfyPersonal(SexProps props, float satisfaction = 0.4f)
{
Pawn pawn = props.pawn;
Pawn partner = props.partner;
//--Log.Message("xxx::satisfy( " + pawn_name + ", " + partner_name + ", " + violent + "," + isCoreLovin + " ) - modifying partner satisfaction");
var sex_need = pawn?.needs?.TryGetNeed<Need_Sex>();
if (sex_need == null) return;
float Trait_Satisfaction = 1f;
float Quirk_Satisfaction = 1f;
float Stat_Satisfaction = 0f;
float Circumstances_Satisfaction = 0f; // violence/broken
float joysatisfaction = satisfaction;
// Bonus satisfaction from traits
if (pawn != null && partner != null)
{
if (xxx.is_animal(partner) && xxx.is_zoophile(pawn))
{
Trait_Satisfaction += 0.5f;
}
if (partner.Dead && xxx.is_necrophiliac(pawn))
{
Trait_Satisfaction += 0.5f;
}
}
// Calculate bonus satisfaction from quirks
var quirkCount = Quirk.CountSatisfiedQuirks(props);
Quirk_Satisfaction += quirkCount * base_sat_per_quirk;
// Apply sex satisfaction stat (min 0.1 default 1) as a modifier to total satisfaction
Stat_Satisfaction += Math.Max(xxx.get_sex_satisfaction(pawn), 0.1f);
// Apply extra multiplier for special/violence circumstances
Circumstances_Satisfaction += get_satisfaction_circumstance_multiplier(props);
satisfaction *= Trait_Satisfaction * Quirk_Satisfaction * Stat_Satisfaction;
joysatisfaction = satisfaction;
satisfaction *= Circumstances_Satisfaction;
if (!RJWSettings.Disable_RecreationDrain)
joysatisfaction *= (Circumstances_Satisfaction - 1);
else
joysatisfaction *= Circumstances_Satisfaction;
//Log.Message("SatisfyPersonal( " + pawn + ", " + satisfaction + " ) - setting pawn sexneed");
sex_need.CurLevel += satisfaction;
if (quirkCount > 0)
{
Quirk.AddThought(pawn);
}
var joy_need = pawn.needs.TryGetNeed<Need_Joy>();
if (joy_need == null) return;
joysatisfaction *= joysatisfaction > 0 ? 0.5f : 1f; // convert half of positive satisfaction to joy
//Log.Message("SatisfyPersonal( " + pawn + ", " + joysatisfaction + " ) - setting pawn joyneed");
pawn.needs.joy.CurLevel += joysatisfaction;
//add Ahegao
//sex&joy > 95%
//sex&broken
var lev = sex_need.CurLevel;
if (lev >= sex_need.thresh_ahegao() &&
(joy_need.CurLevelPercentage > sex_need.thresh_ahegao()) ||
(AfterSexUtility.BodyIsBroken(pawn) && pawn.health.hediffSet.GetFirstHediffOfDef(xxx.feelingBroken)?.CurStageIndex >= 3))
{
var thoughtDef = DefDatabase<ThoughtDef>.GetNamed("RJW_Ahegao");
pawn.needs.mood.thoughts.memories.TryGainMemory(thoughtDef);
}
}
[SyncMethod]
public static void GiveTraits(SexProps props, List<Trait> newTraits)
{
var pawn = props.pawn;
var partner = props.partner;
if (!xxx.has_traits(pawn) || pawn.records.GetValue(xxx.CountOfSex) <= 10)
{
return;
}
GiveQuirkTraits(props, newTraits, 0.05f);
if (props.IsInitiator())
{
if (RJWSettings.AddTrait_Rapist && !xxx.is_rapist(pawn) && !xxx.is_masochist(pawn) && props.isRape && pawn.records.GetValue(xxx.CountOfRapedHumanlikes) > 0.12 * pawn.records.GetValue(xxx.CountOfSex))
{
var chance = 0.5f;
if (xxx.is_kind(pawn)) chance -= 0.25f;
if (xxx.is_prude(pawn)) chance -= 0.25f;
if (xxx.is_zoophile(pawn)) chance -= 0.25f; // Less interested in raping humanlikes.
if (xxx.is_ascetic(pawn)) chance -= 0.2f;
if (xxx.is_bloodlust(pawn)) chance += 0.2f;
if (xxx.is_psychopath(pawn)) chance += 0.25f;
if (Rand.Chance(chance))
{
Trait rapist = new Trait(xxx.rapist);
pawn.story.traits.GainTrait(rapist);
newTraits.Add(rapist);
//--Log.Message(xxx.get_pawnname(pawn) + " aftersex, not rapist, adding rapist trait");
}
}
if (RJWSettings.AddTrait_Necrophiliac && !xxx.is_necrophiliac(pawn) && partner.Dead && pawn.records.GetValue(xxx.CountOfSexWithCorpse) > 0.5 * pawn.records.GetValue(xxx.CountOfSex))
{
Trait necropphiliac = new Trait(xxx.necrophiliac);
pawn.story.traits.GainTrait(necropphiliac);
newTraits.Add(necropphiliac);
//Log.Message(xxx.get_pawnname(necro) + " aftersex, not necro, adding necro trait");
}
}
if (RJWSettings.AddTrait_Zoophiliac && !xxx.is_zoophile(pawn) && xxx.is_animal(partner)
&& (pawn.records.GetValue(xxx.CountOfSexWithAnimals) + pawn.records.GetValue(xxx.CountOfSexWithInsects) > 0.5 * pawn.records.GetValue(xxx.CountOfSex)))
{
Trait zoophile = new Trait(xxx.zoophile);
pawn.story.traits.GainTrait(zoophile);
newTraits.Add(zoophile);
MemoryThoughtHandler memories = pawn.needs.mood.thoughts.memories;
foreach (ThoughtDef memory in new[] {xxx.got_bred, xxx.got_anal_bred, xxx.got_groped, xxx.got_licked})
{
memories.RemoveMemoriesOfDef(memory);
}
//--Log.Message(xxx.get_pawnname(pawn) + " aftersex, not zoo, adding zoo trait");
}
if (RJWSettings.AddTrait_Nymphomaniac && !xxx.is_nympho(pawn))
{
if (pawn.health.hediffSet.HasHediff(RJWHediffDefOf.HumpShroomAddiction) && pawn.health.hediffSet.HasHediff(RJWHediffDefOf.HumpShroomEffect))
{
Trait nymphomaniac = new Trait(xxx.nymphomaniac);
pawn.story.traits.GainTrait(nymphomaniac);
newTraits.Add(nymphomaniac);
//Log.Message(xxx.get_pawnname(pawn) + " is HumpShroomAddicted, not nymphomaniac, adding nymphomaniac trait");
}
}
}
[SyncMethod]
private static void GiveQuirkTraits(SexProps props, List<Trait> newTraits, float traitGainChance = 0.05f)
{
var pawn = props.pawn;
if (RJWPreferenceSettings.PlayerIsFootSlut && !pawn.Has(Quirk.Podophile))
{
if (props.sexType == xxx.rjwSextype.Footjob)
if (props.IsSubmissive())
{
if (Rand.Chance(traitGainChance) || pawn.story.traits.HasTrait(xxx.footSlut))
{
pawn.Add(Quirk.Podophile);
if (RJWSettings.AddTrait_FootSlut)
{
Trait footSlut = new Trait(xxx.footSlut);
pawn.story.traits.GainTrait(footSlut);
newTraits.Add(footSlut);
}
}
}
}
if (RJWPreferenceSettings.PlayerIsCumSlut && !pawn.Has(Quirk.Cumslut))
{
if (props.sexType == xxx.rjwSextype.Fellatio)
if (props.IsSubmissive())
{
if (Rand.Chance(traitGainChance) || pawn.story.traits.HasTrait(xxx.cumSlut))
{
pawn.Add(Quirk.Cumslut);
if (RJWSettings.AddTrait_CumSlut)
{
Trait cumSlut = new Trait(xxx.cumSlut);
pawn.story.traits.GainTrait(cumSlut);
newTraits.Add(cumSlut);
}
}
}
}
if (RJWPreferenceSettings.PlayerIsButtSlut && !pawn.Has(Quirk.Buttslut))
{
if (props.sexType == xxx.rjwSextype.Anal)
if (props.IsSubmissive())
{
if (Rand.Chance(traitGainChance) || pawn.story.traits.HasTrait(xxx.buttSlut))
{
pawn.Add(Quirk.Buttslut);
if (RJWSettings.AddTrait_ButtSlut)
{
Trait buttSlut = new Trait(xxx.buttSlut);
pawn.story.traits.GainTrait(buttSlut);
newTraits.Add(buttSlut);
}
}
}
}
}
private static void SendTraitGainLetter(Pawn pawn, List<Trait> newTraits)
{
if (newTraits.Count == 0 || !PawnUtility.ShouldSendNotificationAbout(pawn))
{
return;
}
TaggedString letterLabel;
TaggedString letterDescription;
if (newTraits.Count == 1)
{
string traitLabel = newTraits[0].Label;
string letterLabelKey = TranslationKeyFor("LetterLabelGainedTraitFromSex", newTraits[0]);
letterLabel = letterLabelKey.Translate(traitLabel.Named("TRAIT"), pawn.Named("PAWN")).CapitalizeFirst();
string letterDescriptionKey = TranslationKeyFor("GainedTraitFromSex", newTraits[0]);
letterDescription = letterDescriptionKey.Translate(traitLabel.Named("TRAIT"), pawn.Named("PAWN")).CapitalizeFirst();
}
else
{
letterLabel = "LetterLabelGainedMultipleTraitsFromSex".Translate(pawn.Named("PAWN"));
letterDescription = "GainedMultipleTraitsFromSex".Translate(pawn.Named("PAWN"));
letterDescription += "\n";
foreach (var trait in newTraits)
{
letterDescription += "\n" + "GainedMultipleTraitsFromSexListItem".Translate(trait.LabelCap);
}
}
Find.LetterStack.ReceiveLetter(letterLabel, letterDescription, LetterDefOf.NeutralEvent, pawn);
string TranslationKeyFor(string stem, Trait trait)
{
string traitKey = stem + trait.def.defName;
string traitKeyWithDegree = traitKey + trait.Degree;
if (traitKeyWithDegree.CanTranslate())
{
return traitKeyWithDegree;
}
if (traitKey.CanTranslate())
{
return traitKey;
}
return stem;
}
}
// Checks if enough time has passed from previous lovin'.
public static bool ReadyForLovin(Pawn pawn)
{
return Find.TickManager.TicksGame > pawn.mindState.canLovinTick;
}
// Checks if enough time has passed from previous search for a hookup.
// Checks if hookups allowed during working hours, exlcuding nymphs
public static bool ReadyForHookup(Pawn pawn)
{
if (!xxx.is_nympho(pawn) && RJWHookupSettings.NoHookupsDuringWorkHours && ((pawn.timetable != null) ? pawn.timetable.CurrentAssignment : TimeAssignmentDefOf.Anything) == TimeAssignmentDefOf.Work) return false;
return Find.TickManager.TicksGame > CompRJW.Comp(pawn).NextHookupTick;
}
private static void IncreaseTicksToNextLovin(Pawn pawn)
{
if (pawn == null || pawn.Dead) return;
int currentTime = Find.TickManager.TicksGame;
if (pawn.mindState.canLovinTick <= currentTime)
pawn.mindState.canLovinTick = currentTime + GenerateMinTicksToNextLovin(pawn);
}
[SyncMethod]
public static int GenerateMinTicksToNextLovin(Pawn pawn)
{
if (DebugSettings.alwaysDoLovin) return 100;
//Rand.PopState();
//Rand.PushState(RJW_Multiplayer.PredictableSeed());
float tick = 1.0f;
// Nymphs automatically get the tick increase from the trait influence on sex drive.
if (xxx.is_animal(pawn))
{
//var mateMtbHours = pawn.RaceProps.mateMtbHours / 24 * GenDate.TicksPerDay;
//if (mateMtbHours > 0)
// interval = mateMtbHours
if (RJWSettings.Animal_mating_cooldown == 0)
tick = 0.75f;
else
return RJWSettings.Animal_mating_cooldown * 2500;
}
else if (xxx.is_prude(pawn))
tick = 1.5f;
if (pawn.Has(Quirk.Vigorous))
tick *= 0.8f;
float sex_drive = xxx.get_sex_drive(pawn);
if (sex_drive <= 0.05f)
sex_drive = 0.05f;
float interval = AgeConfigDef.Instance.lovinIntervalHoursByAge.Evaluate(ScaleToHumanAge(pawn));
float rinterval = Math.Max(0.5f, Rand.Gaussian(interval, 0.3f));
return (int)(tick * rinterval * (2500.0f / sex_drive));
}
public static void IncreaseTicksToNextHookup(Pawn pawn)
{
if (pawn == null || pawn.Dead)
return;
// There are 2500 ticks per rimworld hour. Sleeping an hour between checks seems like a good start.
// We could get fancier and weight it by sex drive and stuff, but would people even notice?
const int TicksBetweenHookups = 2500;
int currentTime = Find.TickManager.TicksGame;
CompRJW.Comp(pawn).NextHookupTick = currentTime + TicksBetweenHookups;
}
/// <summary>
/// <para>Determines the sex type and handles the log output.</para>
/// <para>`props.pawn` should be initiator of the act (rapist, whore, etc).</para>
/// <para>`props.partner` should be the target.</para>
/// </summary>
public static void ProcessSex(SexProps props)
{
//Log.Message("usedCondom=" + usedCondom);
if (props.pawn == null || props.partner == null)
{
if (props.pawn == null)
ModLog.Error("[SexUtility] ERROR: pawn is null.");
if (props.partner == null)
ModLog.Error("[SexUtility] ERROR: partner is null.");
return;
}
IncreaseTicksToNextLovin(props.pawn);
IncreaseTicksToNextLovin(props.partner);
Aftersex(props);
AfterSexUtility.think_about_sex(props);
}
[SyncMethod]
public static SexProps SelectSextype(Pawn pawn, Pawn partner, bool rape, bool whoring)
{
var SP = new SexProps();
SP.pawn = pawn;
SP.partner = partner;
SP.isRape = rape;
SP.isWhoring = whoring;
//Caufendra's magic is happening here
InteractionInputs inputs = new InteractionInputs()
{
Initiator = pawn,
Partner = partner,
IsRape = rape,
IsWhoring = whoring
};
//this should be added as a static readonly but ... since the class is so big,
//it's probably best not to overload the static constructor
ILewdInteractionService lewdInteractionService = LewdInteractionService.Instance;
InteractionOutputs outputs = lewdInteractionService.GenerateInteraction(inputs);
SP.sexType = outputs.Generated.RjwSexType;
SP.rulePack = outputs.Generated.RulePack.defName;
SP.dictionaryKey = outputs.Generated.InteractionDef.Interaction;
return SP;
}
public static void LogSextype(Pawn giving, Pawn receiving, string rulepack, InteractionDef dictionaryKey)
{
List<RulePackDef> extraSentencePacks = new List<RulePackDef>();
if (!rulepack.NullOrEmpty())
extraSentencePacks.Add(RulePackDef.Named(rulepack));
LogSextype(giving, receiving, extraSentencePacks, dictionaryKey);
}
public static void LogSextype(Pawn giving, Pawn receiving, List<RulePackDef> extraSentencePacks, InteractionDef dictionaryKey)
{
if (extraSentencePacks.NullOrEmpty())
{
extraSentencePacks = new List<RulePackDef>();
string extraSentenceRulePack = SexRulePackGet(dictionaryKey);
if (!extraSentenceRulePack.NullOrEmpty())
extraSentencePacks.Add(RulePackDef.Named(extraSentenceRulePack));
}
PlayLogEntry_Interaction playLogEntry = new PlayLogEntry_Interaction(dictionaryKey, giving, receiving, extraSentencePacks);
Find.PlayLog.Add(playLogEntry);
}
[SyncMethod]
public static string SexRulePackGet(InteractionDef dictionaryKey)
{
var extension = Modules.Interactions.Helpers.InteractionHelper.GetWithExtension(dictionaryKey).Extension;
string extraSentenceRulePack = "";
if (!extension.rulepack_defs.NullOrEmpty())
{
extraSentenceRulePack = extension.rulepack_defs.RandomElement();
}
try
{
if (RulePackDef.Named(extraSentenceRulePack) != null)
{
}
}
catch
{
ModLog.Warning("RulePackDef " + extraSentenceRulePack + " for " + dictionaryKey + " not found");
extraSentenceRulePack = "";
}
return extraSentenceRulePack;
}
public static xxx.rjwSextype rjwSextypeGet(InteractionDef dictionaryKey)
{
var extension = Modules.Interactions.Helpers.InteractionHelper.GetWithExtension(dictionaryKey).Extension;
var sextype = xxx.rjwSextype.None;
if (!extension.rjwSextype.NullOrEmpty())
sextype = ParseHelper.FromString<xxx.rjwSextype>(extension.rjwSextype);
if (RJWSettings.DevMode) ModLog.Message("rjwSextypeGet:dictionaryKey " + dictionaryKey + " sextype " + sextype);
return sextype;
}
[SyncMethod]
public static void Sex_Beatings(SexProps props)
{
Pawn pawn = props.pawn;
Pawn partner = props.partner;
if ((xxx.is_animal(pawn) && xxx.is_animal(partner)))
return;
//dont remember what it does, probably manhunter stuff or not? disable and wait reports
//if (!xxx.is_human(pawn))
// return;
//If a pawn is incapable of violence/has low melee, they most likely won't beat their partner
if (pawn.skills?.GetSkill(SkillDefOf.Melee).Level < 1)
return;
//Rand.PopState();
//Rand.PushState(RJW_Multiplayer.PredictableSeed());
float rand_value = Rand.Value;
//float rand_value = RJW_Multiplayer.RJW_MP_RAND();
float victim_pain = partner.health.hediffSet.PainTotal;
// bloodlust makes the aggressor more likely to hit the prisoner
float beating_chance = xxx.config.base_chance_to_hit_prisoner * (xxx.is_bloodlust(pawn) ? 1.5f : 1.0f);
// psychopath makes the aggressor more likely to hit the prisoner past the significant_pain_threshold
float beating_threshold = xxx.is_psychopath(pawn) ? xxx.config.extreme_pain_threshold : pawn.HostileTo(partner) ? xxx.config.significant_pain_threshold : xxx.config.minor_pain_threshold;
//--Log.Message("roll_to_hit: rand = " + rand_value + ", beating_chance = " + beating_chance + ", victim_pain = " + victim_pain + ", beating_threshold = " + beating_threshold);
if ((victim_pain < beating_threshold && rand_value < beating_chance) || (rand_value < (beating_chance / 2) && xxx.is_bloodlust(pawn)))
{
Sex_Beatings_Dohit(pawn, partner, props.isRapist);
}
}
[SyncMethod]
public static void Sex_Beatings_Dohit(Pawn pawn, Pawn partner, bool isRape = false)
{
//--Log.Message(" done told her twice already...");
if (InteractionUtility.TryGetRandomVerbForSocialFight(pawn, out Verb v))
{
//Log.Message(" v. : " + v);
//Log.Message(" v.GetDamageDef : " + v.GetDamageDef());
//Log.Message(" v.v.tool - " + v.tool.label);
//Log.Message(" v.v.tool.power base - " + v.tool.power);
var orgpower = v.tool.power;
//in case something goes wrong
try
{
//Log.Message(" v.v.tool.power base - " + v.tool.power);
if (RJWSettings.gentle_rape_beating || !isRape)
{
v.tool.power = 0;
//partner.stances.stunner.StunFor(600, pawn);
}
//Log.Message(" v.v.tool.power mod - " + v.tool.power);
var guilty = true;
if (!pawn.guilt.IsGuilty)
{
guilty = false;
}
pawn.meleeVerbs.TryMeleeAttack(partner, v);
if (pawn.guilt.IsGuilty && !guilty)
pawn.guilt.Notify_Guilty(0);
}
catch
{ }
v.tool.power = orgpower;
//Log.Message(" v.v.tool.power reset - " + v.tool.power);
}
}
// Overrides the current clothing. Defaults to nude, with option to keep headgear on.
public static void DrawNude(Pawn pawn, bool keep_hat_on = false)
{
if (!xxx.is_human(pawn)) return;
if (pawn.Map != Find.CurrentMap) return;
if (RJWPreferenceSettings.sex_wear == RJWPreferenceSettings.Clothing.Clothed) return;
var comp = CompRJW.Comp(pawn);
if(comp == null) return;
if (comp.drawNude != true)
{
comp.drawNude = true;
var renderer = pawn.Drawer?.renderer;
if(renderer != null)
renderer.SetAllGraphicsDirty();
}
comp.keep_hat_on = keep_hat_on;
}
public static void reduce_rest(Pawn pawn, float x = 1f)
{
if (pawn == null || x <= 0) return;
if (pawn.Has(Quirk.Vigorous)) x -= x / 2;
Need_Rest need_rest = pawn.needs.TryGetNeed<Need_Rest>();
if (need_rest == null)
return;
need_rest.CurLevel -= need_rest.RestFallPerTick * x;
}
public static void OffsetPsyfocus(Pawn pawn, float x = 0)//0-1
{
if (ModsConfig.RoyaltyActive)
{
//pawn.psychicEntropy.Notify_Meditated();
if (pawn.HasPsylink)
{
pawn.psychicEntropy.OffsetPsyfocusDirectly(x);
}
}
}
public static void TransferFluids(SexProps props)
{
Pawn pawn = props.pawn, partner = props.partner;
if (partner == null)
{
return;
}
bool receivedOral = false;
var possibleFluidParts = Enumerable.Empty<ILewdablePart>();
var partnerOrifices = Enumerable.Empty<ILewdablePart>();
InteractionWithExtension interaction = InteractionHelper.GetWithExtension(props.dictionaryKey);
// Checking each sex type individually somehow manages to be less of a pain than figuring out what goes
// where from the fancier InteractionWithExtension.
// This too is the perversity of RimJobWorld.
if (props.sexType == SexType.Rimming)
{
if (interaction.DominantHasFamily(GenitalFamily.Anus)
|| (props.isReceiver && interaction.SubmissiveHasFamily(GenitalFamily.Anus)))
{
receivedOral = true;
possibleFluidParts = PartHelper.FindParts(pawn, GenitalFamily.Anus);
}
}
else if (props.sexType == SexType.Cunnilingus)
{
if (interaction.DominantHasFamily(GenitalFamily.Vagina)
|| (props.isReceiver && interaction.SubmissiveHasFamily(GenitalFamily.Vagina)))
{
receivedOral = true;
possibleFluidParts = PartHelper.FindParts(pawn, GenitalFamily.Vagina);
}
}
else if (props.sexType == SexType.Fellatio)
{
if (interaction.DominantHasTag(GenitalTag.CanPenetrate) || interaction.DominantHasFamily(GenitalFamily.Penis)
|| (props.isReceiver
&& (interaction.SubmissiveHasTag(GenitalTag.CanPenetrate) || interaction.SubmissiveHasFamily(GenitalFamily.Penis))))
{
receivedOral = true;
possibleFluidParts = PartHelper.FindParts(pawn, GenitalTag.CanPenetrate);
}
}
else if (props.sexType == SexType.DoublePenetration)
{
if (interaction.DominantHasTag(GenitalTag.CanPenetrate)
|| (props.isReceiver && interaction.SubmissiveHasTag(GenitalTag.CanPenetrate)))
{
partnerOrifices = PartHelper.FindParts(partner, GenitalTag.CanBePenetrated);
possibleFluidParts = PartHelper.FindParts(pawn, GenitalTag.CanPenetrate);
}
}
else if (props.sexType == SexType.Vaginal)
{
if (interaction.DominantHasTag(GenitalTag.CanPenetrate) || interaction.DominantHasFamily(GenitalFamily.Penis)
|| (props.isReceiver
&& (interaction.SubmissiveHasTag(GenitalTag.CanPenetrate) || interaction.SubmissiveHasFamily(GenitalFamily.Penis))))
{
possibleFluidParts = PartHelper.FindParts(pawn, GenitalTag.CanPenetrate);
partnerOrifices = PartHelper.FindParts(partner, GenitalFamily.Vagina)
.Concat(PartHelper.FindParts(partner, GenitalFamily.FemaleOvipositor));
}
}
else if (props.sexType == SexType.Anal)
{
if (interaction.DominantHasTag(GenitalTag.CanPenetrate)
|| (props.isReceiver && interaction.SubmissiveHasTag(GenitalTag.CanPenetrate)))
{
possibleFluidParts = PartHelper.FindParts(pawn, GenitalTag.CanPenetrate);
partnerOrifices = PartHelper.FindParts(partner, GenitalFamily.Anus);
}
}
else if (props.sexType == SexType.Scissoring)
{
possibleFluidParts = PartHelper.FindParts(pawn, GenitalFamily.Vagina)
.Concat(PartHelper.FindParts(pawn, GenitalFamily.FemaleOvipositor));
partnerOrifices = PartHelper.FindParts(partner, GenitalFamily.Vagina)
.Concat(PartHelper.FindParts(partner, GenitalFamily.FemaleOvipositor));
}
else if (props.sexType == SexType.Sixtynine)
{
receivedOral = true;
possibleFluidParts = PartHelper.FindParts(pawn, GenitalTag.CanPenetrate)
.Concat(PartHelper.FindParts(pawn, GenitalFamily.Vagina));
}
if (possibleFluidParts.Any())
{
var fluidParts = possibleFluidParts.OfType<RJWLewdablePart>()
.Select(lp => lp.Part)
.Where(p => p.Def.fluid != null && p.Def.produceFluidOnOrgasm);
float nutritionLost = 0f;
//if (receivedOral && !props.isReceiver)
if (receivedOral)
{
foreach (var part in fluidParts)
{
IngestFluids(partner, pawn, part, null, ref nutritionLost);
}
}
else
{
foreach (var part in fluidParts.Where(p => p.Def.fluid.ingestThroughAnyOrifice))
{
foreach (var orifice in partnerOrifices.Cast<RJWLewdablePart>())
{
IngestFluids(partner, pawn, part, orifice.Part, ref nutritionLost);
}
}
}
}
if (pawn != partner && pawn.needs != null && partner.needs != null)
{
TransferNutritionSucc(props);
}
}
public static void IngestFluids(Pawn receiver, Pawn giver, ISexPartHediff fromPart, ISexPartHediff toPart, ref float totalNutritionLost)
{
const float maxNutritionLoss = 0.15f;
Need_Food receiverFood = receiver.needs?.food, giverFood = giver.needs?.food;
var fluid = fromPart.GetPartComp().Fluid;
float baseAmount = fromPart.GetPartComp().FluidAmount;
float amountIngested;
// Deduct nutrition from giver
if (giverFood != null && fluid.baseNutritionCost != 0)
{
float nutritionCost = Math.Min(baseAmount * fluid.baseNutritionCost, giverFood.CurLevel);
amountIngested = nutritionCost / fluid.baseNutritionCost;
if (totalNutritionLost < giverFood.MaxLevel * maxNutritionLoss)
{
totalNutritionLost += nutritionCost;
giverFood.CurLevel -= Math.Min(giverFood.MaxLevel * maxNutritionLoss, nutritionCost);
}
}
else
{
amountIngested = baseAmount;
}
if (fluid.quenchesThirst)
{
TransferThirst(giver, receiver);
}
if (fluid.consumable != null)
{
var thing = ThingMaker.MakeThing(fluid.consumable);
thing.stackCount = (int) Math.Max(amountIngested * fluid.consumableFluidRatio, 1f);
thing.Ingested(receiver, 1000f);
}
else
{
if (receiverFood != null)
{
receiverFood.CurLevel += amountIngested * fluid.baseNutrition;
}
}
if (fluid.ingestionDoers != null)
{
foreach (var doer in fluid.ingestionDoers)
{
doer.Ingested(receiver, fluid, amountIngested, fromPart, toPart);
}
}
}
// Takes the nutrition away from the one penetrating(probably) and injects it to the one on the receiving end
// As with everything in the mod, this could be greatly extended, current focus though is to prevent starvation
// of those caught in a huge horde of rappers (that may happen with some mods). Currently only used by core lovin'.
public static void TransferNutritionCore(SexProps props)
{
//Log.Message("xxx::TransferNutrition:: " + xxx.get_pawnname(pawn) + " => " + xxx.get_pawnname(partner));
if (props.partner?.needs == null)
{
//Log.Message("xxx::TransferNutrition() failed due to lack of transfer equipment or pawn ");
return;
}
if (props.pawn?.needs == null)
{
//Log.Message("xxx::TransferNutrition() failed due to lack of transfer equipment or pawn ");
return;
}
TransferNutritionSucc(props);
//transfer nutrition from presumanbly "giver" to partner
if (props.sexType == xxx.rjwSextype.Sixtynine ||
props.sexType == xxx.rjwSextype.Oral ||
props.sexType == xxx.rjwSextype.Cunnilingus ||
props.sexType == xxx.rjwSextype.Fellatio)
{
Pawn pawn = props.pawn;
Pawn partner = props.partner;
Pawn giver, receiver;
List<Hediff> pawnparts = pawn.GetGenitalsList();
List<Hediff> partnerparts = partner.GetGenitalsList();
bool didTransfer = false;
if (props.sexType == xxx.rjwSextype.Sixtynine || Genital_Helper.has_penis_fertile(pawn, pawnparts) || Genital_Helper.has_ovipositorF(pawn, pawnparts))
{
giver = pawn;
receiver = partner;
Need_Food need = giver.needs.TryGetNeed<Need_Food>();
if (need == null)
{
//Log.Message("TransferNutrition() " + xxx.get_pawnname(giver) + " doesn't track nutrition in itself, probably shouldn't feed the others");
return;
}
float nutrition_amount = Math.Min(need.MaxLevel / 15f, need.CurLevel); //body size is taken into account implicitly by need.MaxLevel
giver.needs.food.CurLevel = need.CurLevel - nutrition_amount;
//Log.Message("TransferNutrition() " + xxx.get_pawnname(giver) + " sent " + nutrition_amount + " of nutrition");
if (receiver.needs?.TryGetNeed<Need_Food>() != null)
{
//Log.Message("xxx::TransferNutrition() " + xxx.get_pawnname(receiver) + " can receive");
receiver.needs.food.CurLevel += nutrition_amount;
}
TransferThirst(giver, receiver);
didTransfer = true;
}
if (props.sexType == xxx.rjwSextype.Sixtynine || (!didTransfer && (Genital_Helper.has_penis_fertile(partner, partnerparts) || Genital_Helper.has_ovipositorF(partner, partnerparts))))
{
giver = partner;
receiver = pawn;
Need_Food need = giver.needs?.TryGetNeed<Need_Food>();
if (need == null)
{
//Log.Message("TransferNutrition() " + xxx.get_pawnname(giver) + " doesn't track nutrition in itself, probably shouldn't feed the others");
return;
}
float nutrition_amount = Math.Min(need.MaxLevel / 15f, need.CurLevel); //body size is taken into account implicitly by need.MaxLevel
giver.needs.food.CurLevel = need.CurLevel - nutrition_amount;
//Log.Message("TransferNutrition() " + xxx.get_pawnname(giver) + " sent " + nutrition_amount + " of nutrition");
if (receiver.needs?.TryGetNeed<Need_Food>() != null)
{
//Log.Message("TransferNutrition() " + xxx.get_pawnname(receiver) + " can receive");
receiver.needs.food.CurLevel += nutrition_amount;
}
TransferThirst(giver, receiver);
}
}
}
public static void TransferThirst(Pawn pawn, Pawn receiver)
{
if (xxx.DubsBadHygieneIsActive)
{
Need DBHThirst = receiver.needs?.AllNeeds.Find(x => x.def == xxx.DBHThirst);
if (DBHThirst != null)
{
//Log.Message("TransferThirst() " + xxx.get_pawnname(receiver) + " decreasing thirst");
receiver.needs.TryGetNeed(DBHThirst.def).CurLevel += 0.1f;
}
}
}
public static void TransferNutritionSucc(SexProps props)
{
//succubus mana and rest regen stuff
if (props.sexType == xxx.rjwSextype.Oral ||
props.sexType == xxx.rjwSextype.Cunnilingus ||
props.sexType == xxx.rjwSextype.Fellatio ||
props.sexType == xxx.rjwSextype.Vaginal ||
props.sexType == xxx.rjwSextype.Anal ||
props.sexType == xxx.rjwSextype.DoublePenetration)
{
if (xxx.has_traits(props.partner))
{
bool gainrest = false;
if (xxx.RoMIsActive && (props.partner.story.traits.HasTrait(xxx.Succubus) || props.partner.story.traits.HasTrait(xxx.Warlock)))
{
Need TM_Mana = props.partner?.needs?.AllNeeds.Find(x => x.def == xxx.TM_Mana);
if (TM_Mana != null)
{
//Log.Message("TransferNutritionSucc() " + xxx.get_pawnname(partner) + " increase mana");
props.partner.needs.TryGetNeed(TM_Mana.def).CurLevel += 0.1f;
}
gainrest = true;
}
if (xxx.NightmareIncarnationIsActive)
{
foreach (var x in props.partner.AllComps?.Where(x => x.props?.ToString() == "NightmareIncarnation.CompProperties_SuccubusRace"))
{
Need NI_Need_Mana = props.partner?.needs?.AllNeeds.Find(x => x.def == xxx.NI_Need_Mana);
if (NI_Need_Mana != null)
{
//Log.Message("TransferNutritionSucc() " + xxx.get_pawnname(partner) + " increase mana");
props.partner.needs.TryGetNeed(NI_Need_Mana.def).CurLevel += 0.1f;
}
gainrest = true;
break;
}
}
if (gainrest)
{
Need_Rest need1 = props.pawn.needs?.TryGetNeed<Need_Rest>();
Need_Rest need2 = props.partner.needs?.TryGetNeed<Need_Rest>();
if (need1 != null && need2 != null)
{
//Log.Message("TransferNutritionSucc() " + xxx.get_pawnname(partner) + " increase rest");
props.partner.needs.TryGetNeed(need2.def).CurLevel += 0.25f;
//Log.Message("TransferNutritionSucc() " + xxx.get_pawnname(pawn) + " decrease rest");
props.pawn.needs.TryGetNeed(need1.def).CurLevel -= 0.25f;
}
}
}
if (xxx.has_traits(props.pawn))
{
bool gainrest = false;
if (xxx.RoMIsActive && (props.pawn.story.traits.HasTrait(xxx.Succubus) || props.pawn.story.traits.HasTrait(xxx.Warlock)))
{
Need TM_Mana = props.pawn?.needs?.AllNeeds.Find(x => x.def == xxx.TM_Mana);
if (TM_Mana != null)
{
//Log.Message("TransferNutritionSucc() " + xxx.get_pawnname(pawn) + " increase mana");
props.pawn.needs.TryGetNeed(TM_Mana.def).CurLevel += 0.1f;
}
}
if (xxx.NightmareIncarnationIsActive)
{
foreach (var x in props.pawn.AllComps?.Where(x => x.props?.ToString() == "NightmareIncarnation.CompProperties_SuccubusRace"))
{
Need NI_Need_Mana = props.pawn?.needs?.AllNeeds.Find(x => x.def == xxx.NI_Need_Mana);
if (NI_Need_Mana != null)
{
//Log.Message("TransferNutritionSucc() " + xxx.get_pawnname(partner) + " increase mana");
props.pawn.needs.TryGetNeed(NI_Need_Mana.def).CurLevel += 0.1f;
}
gainrest = true;
break;
}
}
if (gainrest)
{
Need_Rest need1 = props.partner.needs.TryGetNeed<Need_Rest>();
Need_Rest need2 = props.pawn.needs.TryGetNeed<Need_Rest>();
if (need1 != null && need2 != null)
{
//Log.Message("TransferNutritionSucc() " + xxx.get_pawnname(pawn) + " increase rest");
props.pawn.needs.TryGetNeed(need2.def).CurLevel += 0.25f;
//Log.Message("TransferNutritionSucc() " + xxx.get_pawnname(partner) + " decrease rest");
props.partner.needs.TryGetNeed(need1.def).CurLevel -= 0.25f;
}
}
}
}
}
public static float get_broken_consciousness_debuff(Pawn pawn)
{
if (pawn == null)
{
return 1.0f;
}
try
{
Hediff broken = pawn.health.hediffSet.GetFirstHediffOfDef(xxx.feelingBroken);
foreach (PawnCapacityModifier capMod in broken.CapMods)
{
if (capMod.capacity == PawnCapacityDefOf.Consciousness)
{
if (RJWSettings.DevMode) ModLog.Message("Broken Pawn Consciousness factor: " + capMod.postFactor);
return capMod.postFactor;
}
}
// fallback
return 1.0f;
}
catch (NullReferenceException)
{
//Log.Warning(e.ToString());
return 1f;
}
}
public static float get_satisfaction_circumstance_multiplier(SexProps props)
{
// Get a multiplier for satisfaction that should apply on top of the sex satisfaction stat
// This is mostly for traits that only affect satisfaction in some circumstances
Pawn pawn = props.pawn;
Boolean isViolentSex = props.isRape;
float multiplier = 1.0f;
if (xxx.is_human(pawn))
{
// Negate consciousness debuffs for broken pawns (counters the sex satisfaction score being affected by low consciousness)
multiplier = (1.0f / get_broken_consciousness_debuff(pawn));
// Multiplier bonus for violent traits and violent sex
if (!props.isReceiver)
{
// Rapists/Bloodlusts get 50% more satisfaction from violent encounters, and less from non-violent
if (isViolentSex)
{
if (xxx.is_rapist(pawn) || xxx.is_bloodlust(pawn) || xxx.is_psychopath(pawn))
multiplier += 0.5f;
else
multiplier -= 0.2f;
}
else
{
if (xxx.is_rapist(pawn) || xxx.is_bloodlust(pawn))
multiplier -= 0.2f;
else
multiplier += 0.2f;
}
}
else if (props.isReceiver)
{
// Masochists get 50% more satisfaction from receiving violent sex and 20% less from normal sex
if (isViolentSex)
{
if (xxx.is_masochist(pawn))
multiplier += 0.5f;
else
multiplier -= 0.2f;
}
else
{
if (xxx.is_masochist(pawn))
multiplier -= 0.2f;
else
multiplier += 0.2f;
}
// Multiplier for broken pawns
if (isViolentSex && AfterSexUtility.BodyIsBroken(pawn))
{
// Add bonus satisfaction based on stage
switch (pawn.health.hediffSet.GetFirstHediffOfDef(xxx.feelingBroken).CurStageIndex)
{
case 0:
break;
case 1:
// 50% bonus for stage 2
//multiplier += 0.5f;
break;
case 2:
// 100% bonus for stage 2
multiplier += 1.0f;
break;
}
}
}
//ModLog.Message("Sex satisfaction multiplier: " + multiplier);
}
return multiplier;
}
}
}
| Korth95/rjw | 1.5/Source/Common/Helpers/SexUtility.cs | C# | mit | 50,323 |
using Multiplayer.API;
using Verse;
namespace rjw
{
public static class Sexualizer
{
static void SexualizeSingleGenderPawn(Pawn pawn)
{
// Single gender is futa without the female gender change.
SexPartAdder.add_genitals(pawn, null, Gender.Male);
SexPartAdder.add_genitals(pawn, null, Gender.Female);
SexPartAdder.add_breasts(pawn, null, Gender.Female);
SexPartAdder.add_anus(pawn, null);
}
static void SexualizeGenderlessPawn(Pawn pawn)
{
if (RJWSettings.GenderlessAsFuta && !xxx.is_mechanoid(pawn) && (pawn.RaceProps.Animal || pawn.RaceProps.Humanlike))
{
if (RJWSettings.DevMode)
ModLog.Message(" SexualizeGenderlessPawn() - genderless pawn, treating Genderless pawn As Futa" + xxx.get_pawnname(pawn));
//set gender to female for futas
pawn.gender = Gender.Female;
SexPartAdder.add_genitals(pawn, null, Gender.Male);
SexPartAdder.add_genitals(pawn, null, Gender.Female);
SexPartAdder.add_breasts(pawn, null, Gender.Female);
SexPartAdder.add_anus(pawn, null);
}
else
{
if (RJWSettings.DevMode)
ModLog.Message(" SexualizeGenderlessPawn() - unable to sexualize genderless pawn " + xxx.get_pawnname(pawn) + " gender: " + pawn.gender);
}
}
[SyncMethod]
static void SexualizeGenderedPawn(Pawn pawn)
{
//apply normal gender
SexPartAdder.add_genitals(pawn, null, pawn.gender);
//apply futa gender
//if (pawn.gender == Gender.Female) // changing male to futa will break pawn generation due to relations
if (pawn.Faction != null && !xxx.is_animal(pawn)) //null faction throws error
{
//ModLog.Message(" SexualizeGenderedPawn( " + xxx.get_pawnname(pawn) + " ) techLevel: " + (int)pawn.Faction.def.techLevel);
//ModLog.Message(" SexualizeGenderedPawn( " + xxx.get_pawnname(pawn) + " ) techLevel: " + pawn.Faction.Name);
//natives/spacer futa
float chance = (int)pawn.Faction.def.techLevel < 5 ? RJWSettings.futa_natives_chance : RJWSettings.futa_spacers_chance;
//nymph futa gender
chance = xxx.is_nympho(pawn) ? RJWSettings.futa_nymph_chance : chance;
// ModLog.Message($"SexualizeGenderedPawn {chance} from {RJWSettings.futa_nymph_chance} {RJWSettings.futa_natives_chance} {RJWSettings.futa_spacers_chance}");
if (Rand.Chance(chance))
{
//make futa
if (pawn.gender == Gender.Female && RJWSettings.FemaleFuta)
SexPartAdder.add_genitals(pawn, null, Gender.Male);
//make trap
else if (pawn.gender == Gender.Male && RJWSettings.MaleTrap)
SexPartAdder.add_breasts(pawn, null, Gender.Female);
}
}
SexPartAdder.add_breasts(pawn, null, pawn.gender);
SexPartAdder.add_anus(pawn, null);
}
[SyncMethod]
public static void sexualize_pawn(Pawn pawn)
{
//ModLog.Message(" sexualize_pawn( " + xxx.get_pawnname(pawn) + " ) called");
if (pawn == null)
{
return;
}
//override pawn
if (RacePartDef_Helper.TryRacePartDef_partAdders(pawn))
return;
if (RaceGroupDef_Helper.TryGetRaceGroupDef(pawn, out var raceGroupDef) &&
raceGroupDef.hasSingleGender)
{
if (RJWSettings.DevMode)
ModLog.Message($"sexualize_pawn() - sexualizing single gender pawn {xxx.get_pawnname(pawn)} race: {raceGroupDef.defName}");
SexualizeSingleGenderPawn(pawn);
}
else if (pawn.RaceProps.hasGenders)
{
SexualizeGenderedPawn(pawn);
}
else
{
if (Current.ProgramState == ProgramState.Playing) // DO NOT run at world generation, throws error in generating relationship stuff
{
SexualizeGenderlessPawn(pawn);
return;
}
}
if (!pawn.Dead)
{
//Add ticks at generation, so pawns don't instantly start lovin' when generated (esp. on scenario start).
//if (xxx.RoMIsActive && pawn.health.hediffSet.HasHediff(HediffDef.Named("TM_ShapeshiftHD"))) // Rimworld of Magic's polymorph/shapeshift
// pawn.mindState.canLovinTick = Find.TickManager.TicksGame + (int)(SexUtility.GenerateMinTicksToNextLovin(pawn) * Rand.Range(0.01f, 0.05f));
if (!xxx.is_insect(pawn))
pawn.mindState.canLovinTick = Find.TickManager.TicksGame + (int)(SexUtility.GenerateMinTicksToNextLovin(pawn) * Rand.Range(0.1f, 1.0f));
else
pawn.mindState.canLovinTick = Find.TickManager.TicksGame + (int)(SexUtility.GenerateMinTicksToNextLovin(pawn) * Rand.Range(0.01f, 0.2f));
//ModLog.Message(" sexualize_pawn( " + xxx.get_pawnname(pawn) + " ) add sexneed");
if (pawn.RaceProps.Humanlike)
{
var sex_need = pawn.needs.TryGetNeed<Need_Sex>();
if (pawn.Faction != null && !(pawn.Faction?.IsPlayer ?? false) && sex_need != null)
{
sex_need.CurLevel = Rand.Range(0.01f, 0.75f);
}
}
}
}
}
}
| Korth95/rjw | 1.5/Source/Common/Helpers/Sexualizer.cs | C# | mit | 4,679 |
using System.Collections.Generic;
using Verse;
using RimWorld;
using System.Linq;
namespace rjw
{
public static class SurgeryHelper
{
// Quick and dirty method to guess whether the player is harvesting the genitals or amputating them
// due to infection. The core code can't do this properly because it considers the private part
// hediffs as "unclean".
public static bool IsHarvest(Pawn p, BodyPartRecord part)
{
foreach (Hediff hed in p.health.hediffSet.hediffs)
{
if ((hed.Part?.def == part.def) && hed.def.isBad && (hed.Severity >= 0.70f))
return false;
}
return true;
}
/// <summary>
/// Spawn a part from its hediff and do the same for all sub-parts (unless we're on the main body part).
/// Also removes part hediffs so the BodyPartRecord can count as 'clean' for the purposes of core part spawning logic.
/// </summary>
/// <remarks>
/// This is currently overkill as parts are forced to only appear on specific BodyPartRecords without sub-parts,
/// but hopefully someday someone will make a submod featuring a race with dicktongued mouth-pussies or something
/// and then you will see.
/// <para>Then you will all see.</para>
/// </remarks>
public static void RemoveAndSpawnSexParts(Pawn surgeon, Pawn patient, BodyPartRecord part, bool isReplacement)
{
List<Hediff> parts = patient.health.hediffSet.hediffs.Where(h => h.part == part && h is ISexPartHediff).ToList();
foreach (var partHediff in parts)
{
Thing removedPart = SexPartAdder.recipePartRemover(partHediff);
patient.health.RemoveHediff(partHediff);
if (removedPart != null)
{
if (surgeon?.Map != null)
{
GenSpawn.Spawn(removedPart, surgeon.Position, surgeon.Map);
}
else if (patient.Map != null)
{
GenSpawn.Spawn(removedPart, patient.Position, patient.Map);
}
}
if (isReplacement)
{
partHediff.Notify_SurgicallyReplaced(surgeon);
}
else
{
partHediff.Notify_SurgicallyRemoved(surgeon);
}
}
if (part.IsCorePart)
{
return;
}
foreach (var subPart in part.parts)
{
RemoveAndSpawnSexParts(surgeon, patient, subPart, isReplacement);
}
}
}
} | Korth95/rjw | 1.5/Source/Common/Helpers/SurgeryHelper.cs | C# | mit | 2,210 |
using System;
using System.Diagnostics;
using UnityEngine;
using Verse;
namespace rjw
{
public static class Logger
{
private static readonly LogMessageQueue messageQueueRJW = new LogMessageQueue();
public static void Message(string text)
{
bool DevModeEnabled = RJWSettings.DevMode;
if (!DevModeEnabled) return;
UnityEngine.Debug.Log(text);
messageQueueRJW.Enqueue(new LogMessage(LogMessageType.Message, text, StackTraceUtility.ExtractStackTrace()));
}
public static void Warning(string text)
{
bool DevModeEnabled = RJWSettings.DevMode;
if (!DevModeEnabled) return;
UnityEngine.Debug.Log(text);
messageQueueRJW.Enqueue(new LogMessage(LogMessageType.Warning, text, StackTraceUtility.ExtractStackTrace()));
}
public static void Error(string text)
{
bool DevModeEnabled = RJWSettings.DevMode;
if (!DevModeEnabled) return;
UnityEngine.Debug.Log(text);
messageQueueRJW.Enqueue(new LogMessage(LogMessageType.Error, text, StackTraceUtility.ExtractStackTrace()));
}
public static TimeSpan Time(Action action)
{
Stopwatch stopwatch = Stopwatch.StartNew();
action();
stopwatch.Stop();
return stopwatch.Elapsed;
}
}
}
| Korth95/rjw | 1.5/Source/Common/Logger.cs | C# | mit | 1,190 |
using Verse;
namespace rjw
{
public class MapCom_Injector : MapComponent
{
public bool injected_designator = false;
public bool triggered_after_load = false;
public MapCom_Injector(Map m) : base(m)
{
}
public override void MapComponentUpdate()
{
}
public override void MapComponentTick()
{
}
public override void MapComponentOnGUI()
{
var currently_visible = Find.CurrentMap == map;
if ((!injected_designator) && currently_visible)
{
//Find.ReverseDesignatorDatabase.AllDesignators.Add(new Designator_ComfortPrisoner());
//Find.ReverseDesignatorDatabase.AllDesignators.Add(new Designator_Breed());
injected_designator = true;
}
else if (injected_designator && (!currently_visible))
injected_designator = false;
}
public override void ExposeData()
{
}
}
} | Korth95/rjw | 1.5/Source/Common/MapCom_Injector.cs | C# | mit | 833 |
using System;
using Verse;
namespace rjw
{
public sealed class MiscTranslationDef : Def
{
public Type targetClass;
public string stringA = null;
public string stringB = null;
public string stringC = null;
private void Assert(bool check, string errorMessage)
{
if (!check)
{
ModLog.Error($"Invalid data in MiscTranslationDef {defName}: {errorMessage}");
}
}
public override void PostLoad()
{
Assert(targetClass != null, "targetClass field must be set");
}
public override void ResolveReferences()
{
base.ResolveReferences();
}
}
} | Korth95/rjw | 1.5/Source/Common/MiscTranslationDef.cs | C# | mit | 584 |
using Verse;
namespace rjw
{
public static class ModLog
{
/// <summary>
/// Logs the given message with [SaveStorage.ModId] appended.
/// </summary>
public static void Error(string message)
{
Log.Error($"[{SaveStorage.ModId}] {message}");
}
/// <summary>
/// Logs the given message with [SaveStorage.ModId] appended.
/// </summary>
public static void Message(string message)
{
Log.Message($"[{SaveStorage.ModId}] {message}");
}
/// <summary>
/// Logs the given message with [SaveStorage.ModId] appended.
/// </summary>
public static void Warning(string message)
{
Log.Warning($"[{SaveStorage.ModId}] {message}");
}
}
}
| Korth95/rjw | 1.5/Source/Common/ModLog.cs | C# | mit | 673 |
using RimWorld;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Verse;
namespace rjw
{
public static class PawnExtensions
{
public static bool RaceHasFertility(this Pawn pawn)
{
// True by default.
if (RaceGroupDef_Helper.TryGetRaceGroupDef(pawn, out var raceGroupDef))
return raceGroupDef.hasFertility;
return true;
}
public static bool RaceHasPregnancy(this Pawn pawn)
{
// True by default.
if (RaceGroupDef_Helper.TryGetRaceGroupDef(pawn, out var raceGroupDef))
return raceGroupDef.hasPregnancy;
return true;
}
public static bool RaceHasOviPregnancy(this Pawn pawn)
{
// False by default.
if (RaceGroupDef_Helper.TryGetRaceGroupDef(pawn, out var raceGroupDef))
return raceGroupDef.oviPregnancy;
return false;
}
public static bool RaceImplantEggs(this Pawn pawn)
{
// False by default.
if (RaceGroupDef_Helper.TryGetRaceGroupDef(pawn, out var raceGroupDef))
return raceGroupDef.ImplantEggs;
return false;
}
public static bool RaceHasSexNeed(this Pawn pawn)
{
// True by default.
if (RaceGroupDef_Helper.TryGetRaceGroupDef(pawn, out var raceGroupDef))
return raceGroupDef.hasSexNeed;
return true;
}
public static bool TryAddRacePart(this Pawn pawn, SexPartType sexPartType)
{
return RaceGroupDef_Helper.TryAddRacePart(pawn, sexPartType);
}
public static bool Has(this Pawn pawn, Quirk quirk)
{
return xxx.has_quirk(pawn, quirk.Key);
}
public static bool Has(this Pawn pawn, RaceTag tag)
{
if (RaceGroupDef_Helper.TryGetRaceGroupDef(pawn, out var raceGroupDef))
{
return raceGroupDef.tags != null && raceGroupDef.tags.Contains(tag.Key);
}
else
{
return tag.DefaultWhenNoRaceGroupDef(pawn);
}
}
public static void Add(this Pawn pawn, Quirk quirk)
{
QuirkAdder.Add(pawn, quirk);
}
public static bool IsSexyRobot(this Pawn pawn)
{
return AndroidsCompatibility.IsAndroid(pawn);
}
// In theory I think this should involve RaceGroupDef.
public static bool IsUnsexyRobot(this Pawn pawn)
{
return !IsSexyRobot(pawn)
&& (xxx.is_mechanoid(pawn) || pawn.kindDef.race.defName.ToLower().Contains("droid"));
}
public static bool IsAnimal(this Pawn pawn)
{
return xxx.is_animal(pawn);
}
public static bool IsHuman(this Pawn pawn)
{
return xxx.is_human(pawn);
}
public static bool IsPoly(this Pawn pawn)
{
if (!pawn.IsHuman())
{
return true;
}
if (pawn.IsIdeologicallyPoly())
{
return true;
}
if (pawn.story?.traits == null)
{
return false;
}
if (xxx.AnyPolyamoryModIsActive && pawn.story.traits.HasTrait(xxx.polyamorous))
{
return true;
}
if (xxx.AnyPolygamyModIsActive && pawn.story.traits.HasTrait(xxx.polygamous))
{
return true;
}
return false;
}
public static bool IsVisiblyPregnant(this Pawn pawn)
{
return pawn.IsPregnant(true);
}
public static bool IsPregnant(this Pawn pawn, bool mustBeVisible = false)
{
var set = pawn.health.hediffSet;
return set.HasHediff(HediffDefOf.PregnantHuman, mustBeVisible) ||
set.HasHediff(HediffDefOf.Pregnant, mustBeVisible) ||
Hediff_BasePregnancy.KnownPregnancies().Any(x => set.HasHediff(HediffDef.Named(x), mustBeVisible));
}
public static List<Hediff> GetGenitalsList(this Pawn pawn)
{
List<Hediff> set;
try//error at world gen
{
set = pawn.GetRJWPawnData().genitals;
if (set.NullOrEmpty())
{
var partBPR = Genital_Helper.get_genitalsBPR(pawn);
set = Genital_Helper.get_PartsHediffList(pawn, partBPR);
pawn.GetRJWPawnData().genitals = set;
}
}
catch
{
var partBPR = Genital_Helper.get_genitalsBPR(pawn);
set = Genital_Helper.get_PartsHediffList(pawn, partBPR);
}
return set;
}
public static List<Hediff> GetBreastList(this Pawn pawn)
{
List<Hediff> set;
try//error at world gen
{
set = pawn.GetRJWPawnData().breasts;
if (set.NullOrEmpty())
{
var partBPR = Genital_Helper.get_breastsBPR(pawn);
set = Genital_Helper.get_PartsHediffList(pawn, partBPR);
pawn.GetRJWPawnData().breasts = set;
}
}
catch
{
var partBPR = Genital_Helper.get_breastsBPR(pawn);
set = Genital_Helper.get_PartsHediffList(pawn, partBPR);
}
return set;
}
public static List<Hediff> GetAnusList(this Pawn pawn)
{
List<Hediff> set;
try//error at world gen
{
set = pawn.GetRJWPawnData().anus;
if (set.NullOrEmpty())
{
var partBPR = Genital_Helper.get_anusBPR(pawn);
set = Genital_Helper.get_PartsHediffList(pawn, partBPR);
pawn.GetRJWPawnData().anus = set;
}
}
catch
{
var partBPR = Genital_Helper.get_anusBPR(pawn);
set = Genital_Helper.get_PartsHediffList(pawn, partBPR);
}
return set;
}
public static List<Hediff> GetTorsoList(this Pawn pawn)
{
List<Hediff> set;
try//error at world gen
{
set = pawn.GetRJWPawnData().torso;
if (set.NullOrEmpty())
{
var partBPR = Genital_Helper.get_torsoBPR(pawn);
set = Genital_Helper.get_PartsHediffList(pawn, partBPR);
pawn.GetRJWPawnData().torso = set;
}
}
catch
{
var partBPR = Genital_Helper.get_torsoBPR(pawn);
set = Genital_Helper.get_PartsHediffList(pawn, partBPR);
}
return set;
}
public static SexProps GetRMBSexPropsCache(this Pawn pawn)
{
SexProps set;
set = pawn.GetRJWPawnData().SexProps;
return set;
}
public static PawnData GetRJWPawnData(this Pawn pawn)
{
return SaveStorage.DataStore.GetPawnData(pawn);
}
}
}
| Korth95/rjw | 1.5/Source/Common/PawnExtensions.cs | C# | mit | 5,633 |
using RimWorld;
using System.Collections.Generic;
using System.Linq;
using Verse;
using Verse.AI;
namespace rjw.RMB
{
/// <summary>
/// Generator of RMB categories for bestiality
/// </summary>
static class RMB_Bestiality
{
/// <summary>
/// Add bestiality and reverse bestiality options to <paramref name="opts"/>
/// </summary>
/// <param name="pawn">Selected pawn</param>
/// <param name="opts">List of RMB options</param>
/// <param name="target">Target of the right click</param>
public static void AddFloatMenuOptions(Pawn pawn, List<FloatMenuOption> opts, LocalTargetInfo target)
{
AcceptanceReport canCreateEntries = DoBasicChecks(pawn, target.Pawn);
if (!canCreateEntries)
{
if (RJWSettings.DevMode && !canCreateEntries.Reason.NullOrEmpty())
opts.Add(new FloatMenuOption(canCreateEntries.Reason, null));
return;
}
canCreateEntries = DoChecks(pawn, target.Pawn);
if (!canCreateEntries)
{
opts.Add(new FloatMenuOption("RJW_RMB_Bestiality".Translate(target.Pawn) + ": " + canCreateEntries.Reason, null));
return;
}
FloatMenuOption opt = GenerateCategoryOption(pawn, target);
if (opt != null)
opts.Add(opt);
opt = GenerateCategoryOption(pawn, target, true);
if (opt != null)
opts.Add(opt);
}
/// <summary>
/// Check for the things that should be obvious to the player or does not change for particular pawns.
/// </summary>
/// <returns>
/// AcceptanceReport. Reason is an untranslated string and should only be shown in the DevMode
/// </returns>
private static AcceptanceReport DoBasicChecks(Pawn pawn, Pawn target)
{
if (!RJWSettings.bestiality_enabled)
{
return "No bestiality: Disabled by the mod settings";
}
if (target.Downed)
{
return "No bestiality: Target is downed";
}
if (target.HostileTo(pawn))
{
return "No bestiality: Target is hostile";
}
if (!xxx.can_be_fucked(target) && !xxx.can_fuck(target))
{
return "No bestiality: Target can't have sex";
}
if (target.Faction != pawn.Faction)
{
return "No bestiality: Target must belong to pawn's faction";
}
return true;
}
/// <summary>
/// Check for the things that can change for particular pawns.
/// </summary>
/// <returns>
/// AcceptanceReport. Reason is a translated string and should not be null.
/// </returns>
private static AcceptanceReport DoChecks(Pawn pawn, Pawn target)
{
if (!pawn.IsDesignatedHero() && !pawn.IsHeroOwner())
{
int opinionOf = pawn.relations.OpinionOf(target);
if (opinionOf < RJWHookupSettings.MinimumRelationshipToHookup)
{
if (!(opinionOf > 0 && xxx.is_nympho(pawn)))
{
return "RJW_RMB_ReasonLowOpinionOfTarget".Translate();
}
}
if (SexAppraiser.would_fuck(pawn, target) < 0.1f)
{
return "RJW_RMB_ReasonUnappealingTarget".Translate();
}
}
if ((pawn.ownership.OwnedBed == null) && (target.ownership.OwnedBed == null))
{
return "RJW_RMB_ReasonNeedBed".Translate();
}
if ((!pawn.CanReach(target.ownership.OwnedBed, PathEndMode.OnCell, Danger.Some)) && (pawn.ownership.OwnedBed == null))
{
return "RJW_RMB_ReasonCantReachBed".Translate();
}
if ((!target.CanReach(pawn.ownership.OwnedBed, PathEndMode.OnCell, Danger.Some)) && (target.ownership.OwnedBed == null))
{
return "RJW_RMB_ReasonCantReachBed".Translate();
}
return true;
}
/// <summary>
/// Generate one FloatMenuOption
/// </summary>
/// <param name="pawn"></param>
/// <param name="target"></param>
/// <param name="reverse"></param>
/// <returns>Category-level item that opens a sub-menu on click</returns>
private static FloatMenuOption GenerateCategoryOption(Pawn pawn, LocalTargetInfo target, bool reverse = false)
{
string text = null;
if (reverse)
{
text = "RJW_RMB_Bestiality_Reverse".Translate(target.Pawn);
}
else
{
text = "RJW_RMB_Bestiality".Translate(target.Pawn);
}
return FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(text, delegate ()
{
JobDef job = xxx.bestialityForFemale;
var validinteractions = RMB_Menu.GenerateNonSoloSexRoleOptions(pawn, target, job, false, reverse);
if (validinteractions.Any())
FloatMenuUtility.MakeMenu(validinteractions, (FloatMenuOption opt) => opt.Label, (FloatMenuOption opt) => opt.action);
else
Messages.Message("No valid interactions found for " + text, MessageTypeDefOf.RejectInput, false);
}, MenuOptionPriority.High), pawn, target);
}
}
} | Korth95/rjw | 1.5/Source/Common/RMB/RMB_Bestiality.cs | C# | mit | 4,562 |
using RimWorld;
using System.Collections.Generic;
using System.Linq;
using Verse;
using rjw.Modules.Interactions;
using rjw.Modules.Interactions.Implementation;
namespace rjw.RMB
{
/// <summary>
/// Generator of RMB categories for masturbation.
///
/// Unlike the two-pawn options, masturbation menu is two has 3 levels:
/// Masturbate -> Masturbate on bed
/// Masturbate at (tile) -> Interaction 1
/// Masturbate here Interaction 2
/// etc.
/// </summary>
static class RMB_Masturbate
{
/// <summary>
/// Add masturbation option to <paramref name="opts"/>
/// </summary>
/// <param name="pawn">Selected pawn</param>
/// <param name="opts">List of RMB options</param>
/// <param name="target">Target of the right click</param>
public static void AddFloatMenuOptions(Pawn pawn, List<FloatMenuOption> opts, LocalTargetInfo target)
{
FloatMenuOption opt = GenerateCategoryOption(pawn, target);
if (opt != null)
opts.Add(opt);
}
/// <summary>
/// Generate one FloatMenuOption
/// </summary>
/// <param name="pawn"></param>
/// <param name="target"></param>
/// <param name="reverse"></param>
/// <returns>Category-level item that opens a sub-menu on click</returns>
private static FloatMenuOption GenerateCategoryOption(Pawn pawn, LocalTargetInfo target)
{
return FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("RJW_RMB_Masturbate".Translate(), delegate ()
{
FloatMenuUtility.MakeMenu(GenerateSoloSexRoleOptions(pawn, target).Where(x => x.action != null), (FloatMenuOption opt) => opt.Label, (FloatMenuOption opt) => opt.action);
}, MenuOptionPriority.High), pawn, target);
}
/// <summary>
/// Generates sub-menu options for a solo pawn
/// </summary>
/// <param name="pawn">Initiator pawn</param>
/// <param name="target">Place to masturbate</param>
/// <returns>A list of menu options, where each item represents a possible masturbation type</returns>
private static List<FloatMenuOption> GenerateSoloSexRoleOptions(Pawn pawn, LocalTargetInfo target)
{
List<FloatMenuOption> opts = new();
FloatMenuOption option = null;
option = new FloatMenuOption("RJW_RMB_Masturbate_Bed".Translate(), delegate ()
{
Find.Targeter.BeginTargeting(TargetParemetersMasturbationChairOrBed(target), (LocalTargetInfo targetThing) =>
{
FloatMenuUtility.MakeMenu(GenerateSoloSexPoseOptions(pawn, targetThing), (FloatMenuOption opt) => opt.Label, (FloatMenuOption opt) => opt.action);
});
}, MenuOptionPriority.High);
opts.Add(FloatMenuUtility.DecoratePrioritizedTask(option, pawn, target));
option = new FloatMenuOption("RJW_RMB_Masturbate_At".Translate(), delegate ()
{
Find.Targeter.BeginTargeting(TargetParemetersMasturbationLoc(target), (LocalTargetInfo targetThing) =>
{
FloatMenuUtility.MakeMenu(GenerateSoloSexPoseOptions(pawn, targetThing), (FloatMenuOption opt) => opt.Label, (FloatMenuOption opt) => opt.action);
});
}, MenuOptionPriority.High);
opts.Add(FloatMenuUtility.DecoratePrioritizedTask(option, pawn, target));
option = new FloatMenuOption("RJW_RMB_Masturbate_Here".Translate(), delegate ()
{
FloatMenuUtility.MakeMenu(GenerateSoloSexPoseOptions(pawn, target), (FloatMenuOption opt) => opt.Label, (FloatMenuOption opt) => opt.action);
}, MenuOptionPriority.High);
opts.Add(FloatMenuUtility.DecoratePrioritizedTask(option, pawn, target));
return opts;
}
private static TargetingParameters TargetParemetersMasturbationChairOrBed(LocalTargetInfo target)
{
return new TargetingParameters()
{
canTargetBuildings = true,
mapObjectTargetsMustBeAutoAttackable = false,
validator = (TargetInfo target) =>
{
if (!target.HasThing)
return false;
if (target.Thing is not Building building)
return false;
if (building.def.building.isSittable)
return true;
if (building is Building_Bed)
return true;
return false;
}
};
}
public static TargetingParameters TargetParemetersMasturbationLoc(LocalTargetInfo target)
{
return new TargetingParameters()
{
canTargetLocations = true,
mapObjectTargetsMustBeAutoAttackable = false,
validator = (TargetInfo target) =>
{
if (!target.HasThing)
return true;
return false;
}
};
}
/// <summary>
/// Generates sub-sub-menu options for a solo pawn
/// </summary>
/// <param name="pawn">Initiator pawn</param>
/// <param name="target">Place to masturbate</param>
/// <returns>A list of menu options, where each item represents a possible masturbation interaction</returns>
public static List<FloatMenuOption> GenerateSoloSexPoseOptions(Pawn pawn, LocalTargetInfo target)
{
List<FloatMenuOption> opts = new();
FloatMenuOption option = null;
ILewdInteractionValidatorService service = LewdInteractionValidatorService.Instance;
foreach (InteractionDef d in SexUtility.SexInterractions)
{
var interaction = Modules.Interactions.Helpers.InteractionHelper.GetWithExtension(d);
if (interaction.Extension.rjwSextype != xxx.rjwSextype.Masturbation.ToStringSafe())
continue;
if (!service.IsValid(d, pawn, pawn))
continue;
string label = interaction.Extension.RMBLabel.CapitalizeFirst();
if (RJWSettings.DevMode)
label += $" ( defName: {d.defName} )";
option = new FloatMenuOption(label, delegate ()
{
RMB_Menu.HaveSex(pawn, xxx.Masturbate, target, d);
}, MenuOptionPriority.High);
opts.Add(FloatMenuUtility.DecoratePrioritizedTask(option, pawn, target));
}
if (RJWSettings.DevMode && opts.NullOrEmpty())
{
opts.Add(new FloatMenuOption("No interactions found", null));
}
return opts;
}
}
} | Korth95/rjw | 1.5/Source/Common/RMB/RMB_Masturbate.cs | C# | mit | 5,808 |
using RimWorld;
using System.Collections.Generic;
using Verse;
using Multiplayer.API;
using Verse.AI;
namespace rjw.RMB
{
/// <summary>
/// Generator of RMB categories for Biotech Mechanitor
/// </summary>
static class RMB_Mechanitor
{
public static void AddFloatMenuOptions(Pawn pawn, List<FloatMenuOption> opts, LocalTargetInfo target)
{
if (!ModsConfig.BiotechActive)
{
return;
}
FloatMenuOption opt = GenerateCategoryOption(pawn, target);
if (opt != null)
opts.Add(opt);
}
private static FloatMenuOption GenerateCategoryOption(Pawn pawn, LocalTargetInfo target)
{
if (MechanitorUtility.IsMechanitor(pawn))
{
if (target.Pawn?.IsVisiblyPregnant() == true)
{
Hediff_MechanoidPregnancy pregnancy = (Hediff_MechanoidPregnancy)target.Pawn.health.hediffSet.GetFirstHediffOfDef(HediffDef.Named("RJW_pregnancy_mech"));
if (pregnancy != null)
{
if (pregnancy.is_checked && !pregnancy.is_hacked)
{
return FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("RJW_RMB_HackMechPregnancy".Translate(), delegate ()
{
HackMechPregnancy(pawn, target);
}, MenuOptionPriority.High), pawn, target);
}
}
}
}
//else if (pawn.IsColonyMechPlayerControlled)
//{
//mechimplant
// option = FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("RJW_RMB_Masturbate".Translate(), delegate ()
// {
// FloatMenuUtility.MakeMenu(GenerateSoloSexPoseOptions(pawn, target), (FloatMenuOption opt) => opt.Label, (FloatMenuOption opt) => opt.action);
// }, MenuOptionPriority.High), pawn, target);
// opts.AddDistinct(option);
//}
return null;
}
[SyncMethod] // Not sure it is needed
static void HackMechPregnancy(Pawn pawn, LocalTargetInfo target)
{
Job job = JobMaker.MakeJob(DefDatabase<JobDef>.GetNamed("RJW_HackMechPregnancy"), target.Pawn);
pawn.jobs.TryTakeOrderedJob(job, JobTag.Misc);
}
}
} | Korth95/rjw | 1.5/Source/Common/RMB/RMB_Mechanitor.cs | C# | mit | 1,978 |
using RimWorld;
using System.Collections.Generic;
using UnityEngine;
using Verse;
using Verse.AI;
using Multiplayer.API;
using rjw.Modules.Interactions.Enums;
using rjw.Modules.Interactions;
using rjw.Modules.Interactions.Implementation;
using rjw.Modules.Interactions.Objects;
namespace rjw.RMB
{
static class RMB_Menu
{
/// <summary>
/// TargetingParameters for all things that can have RMB options
/// </summary>
private static TargetingParameters ForRmbOptions
{
get
{
if (targetParametersCache == null)
{
targetParametersCache = new TargetingParameters()
{
canTargetHumans = true,
canTargetAnimals = true,
canTargetItems = true,
mapObjectTargetsMustBeAutoAttackable = false,
};
}
return targetParametersCache;
}
}
/// <summary>
/// Don't use this directly, use <see cref="ForRmbOptions"/> instead
/// </summary>
private static TargetingParameters targetParametersCache = null;
/// <summary>
/// Adds RJW floating menu options to <paramref name="opts"/> list
/// </summary>
/// <param name="pawn">Selected pawn</param>
/// <param name="opts">Full menu options list, vanilla options included. Do not clear it, please</param>
/// <param name="clickPos">Where player clicked in the world</param>
public static void AddSexFloatMenuOptions(Pawn pawn, List<FloatMenuOption> opts, Vector3 clickPos)
{
AcceptanceReport canControlPawn = CanControlPawn(pawn);
if (!canControlPawn)
{
if (RJWSettings.DevMode)
opts.Add(new FloatMenuOption($"No interactions: {canControlPawn.Reason}", null));
return;
}
// Find valid targets for sex.
IEnumerable<LocalTargetInfo> validTargets = GenUI.TargetsAt(clickPos, ForRmbOptions);
foreach (LocalTargetInfo target in validTargets)
{
if (target == null)
{
continue;
}
if (target.Pawn != null)
{
Pawn targetPawn = target.Pawn;
if (!targetPawn.Spawned)
{
if (RJWSettings.DevMode)
opts.Add(new FloatMenuOption($"No interactions for {targetPawn}: Pawn not spawned", null));
continue;
}
if (targetPawn.Drafted)
{
if (RJWSettings.DevMode)
opts.Add(new FloatMenuOption($"No interactions for {targetPawn}: Pawn is drafted", null));
continue;
}
if (targetPawn.IsHiddenFromPlayer())
{
if (RJWSettings.DevMode)
opts.Add(new FloatMenuOption($"No interactions for {targetPawn}: Pawn is hidden", null));
continue;
}
}
// Ensure target is reachable.
if (!pawn.CanReach(target, PathEndMode.ClosestTouch, Danger.Deadly))
{
//option = new FloatMenuOption("CannotReach".Translate(target.Thing.LabelCap, target.Thing) + " (" + "NoPath".Translate() + ")", null);
continue;
}
AddFloatMenuOptionsForTarget(pawn, opts, target);
}
}
/// <summary>
/// Check if <paramref name="pawn"/> can be controlled by the player
/// </summary>
/// <returns>
/// AcceptanceReport. Reason is an untranslated string and should only be shown in the DevMode
/// </returns>
private static AcceptanceReport CanControlPawn(Pawn pawn)
{
// If the pawn in question cannot take jobs, don't bother.
if (pawn.jobs == null)
return "Cannot take jobs";
// If the pawn is drafted - quit.
if (pawn.Drafted)
return "Drafted";
// Getting raped - no control
if (pawn.jobs.curDriver is JobDriver_SexBaseRecieverRaped)
return "Getting raped";
//is colonist?, is hospitality colonist/guest?, no control for guests
if (!pawn.IsFreeColonist || pawn.Faction == null || pawn.GetExtraHomeFaction(null) != null)
return "Not a colonist";
//not hero mode or override_control - quit
if (!(RJWSettings.RPG_hero_control || RJWSettings.override_control))
return "Enable hero mode or direct control";
bool isHero = false; //is hero
bool otherPlayerHero = false; //not owned hero? maybe prison check etc in future
if (RJWSettings.RPG_hero_control)
{
isHero = pawn.IsDesignatedHero();
otherPlayerHero = isHero && !pawn.IsHeroOwner();
}
else if (!RJWSettings.override_control)
return "Not a hero, direct control disabled";
//not hero, not override_control - quit
if (!isHero && !RJWSettings.override_control)
return "Not a hero";
//not owned hero - quit
if (isHero && otherPlayerHero)
return "Not owned hero";
if (pawn.IsPrisoner) // Removed slave restrictions - we can draft slaves, so why not control them directly?
return "Prisoner";
return true;
}
/// <summary>
/// Adds RJW floating menu options to <paramref name="opts"/> list
/// </summary>
/// <param name="pawn">Selected pawn</param>
/// <param name="opts">Full menu options list, vanilla options included. Do not clear it, please</param>
/// <param name="target">Pawn or item player clicked on</param>
private static void AddFloatMenuOptionsForTarget(Pawn pawn, List<FloatMenuOption> opts, LocalTargetInfo target)
{
RMB_Mechanitor.AddFloatMenuOptions(pawn, opts, target);
if (pawn == target)
{
RMB_Masturbate.AddFloatMenuOptions(pawn, opts, target);
}
else if (target.Pawn != null)
{
if (xxx.is_human(target.Pawn))
{
RMB_Sex.AddFloatMenuOptions(pawn, opts, target);
}
if (xxx.is_animal(target.Pawn))
{
RMB_Bestiality.AddFloatMenuOptions(pawn, opts, target);
RMB_RapeAnimal.AddFloatMenuOptions(pawn, opts, target);
}
else
{
RMB_Rape.AddFloatMenuOptions(pawn, opts, target);
}
RMB_Socialize.AddFloatMenuOptions(pawn, opts, target);
}
else if (target.Thing is Corpse)
{
RMB_Necro.AddFloatMenuOptions(pawn, opts, target);
}
}
/// <summary>
/// Generates sub-menu options for two pawns
/// </summary>
/// <param name="pawn">Initiator pawn</param>
/// <param name="target">Reciever pawn or corpse</param>
/// <param name="job"></param>
/// <param name="rape"></param>
/// <param name="reverse"></param>
/// <returns>A list of menu options, where each item represents a possible interaction</returns>
public static List<FloatMenuOption> GenerateNonSoloSexRoleOptions(Pawn pawn, LocalTargetInfo target, JobDef job, bool rape, bool reverse = false)
{
List<FloatMenuOption> opts = new();
Pawn partner = target.Pawn;
if (target.Thing is Corpse corpse)
{
partner = corpse.InnerPawn;
}
InteractionTag mainTag = InteractionTag.Consensual; //sex
if (xxx.is_animal(partner))
{
mainTag = InteractionTag.Bestiality; //bestiality/breeding
}
else if (rape)
{
mainTag = InteractionTag.Rape; //rape
}
ILewdInteractionValidatorService service = LewdInteractionValidatorService.Instance;
foreach (InteractionDef d in SexUtility.SexInterractions)
{
var interaction = Modules.Interactions.Helpers.InteractionHelper.GetWithExtension(d);
if (interaction.Extension.rjwSextype == xxx.rjwSextype.None.ToStringSafe())
continue;
if (interaction.Extension.rjwSextype == xxx.rjwSextype.Masturbation.ToStringSafe())
continue;
if (!interaction.HasInteractionTag(mainTag))
continue;
if (reverse != interaction.HasInteractionTag(InteractionTag.Reverse))
continue;
if (!service.IsValid(d, pawn, partner))
continue;
string label = interaction.Extension.RMBLabel.CapitalizeFirst();
if (RJWSettings.DevMode)
label += $" ( defName: {d.defName} )";
FloatMenuOption option = new(label, delegate () { HaveSex(pawn, job, target, d); }, MenuOptionPriority.High);
opts.Add(FloatMenuUtility.DecoratePrioritizedTask(option, pawn, target));
}
if (RJWSettings.DevMode && opts.NullOrEmpty())
{
opts.Add(new FloatMenuOption("No interactions found", null));
}
return opts;
}
//multiplayer synch actions
/// <summary>
/// Stops current job of the <paramref name="pawn"/> and starts new sex job
/// </summary>
/// <param name="pawn"></param>
/// <param name="jobDef"></param>
/// <param name="target">Reciever pawn or corpse</param>
/// <param name="interactionDef">Sex interaction def</param>
[SyncMethod]
public static void HaveSex(Pawn pawn, JobDef jobDef, LocalTargetInfo target, InteractionDef interactionDef)
{
Pawn partner;
if (target.Thing is Corpse corpse)
{
partner = corpse.InnerPawn;
}
else if (target.Pawn == null || pawn == target.Pawn) // masturbation
{
partner = pawn;
}
else
{
partner = target.Pawn;
}
InteractionWithExtension interaction = Modules.Interactions.Helpers.InteractionHelper.GetWithExtension(interactionDef);
bool rape = interaction.HasInteractionTag(InteractionTag.Rape);
Job job;
if (jobDef == xxx.casual_sex)
{
job = new Job(jobDef, target, partner.CurrentBed());
}
else if (jobDef == xxx.bestialityForFemale)
{
if (target.Pawn.ownership.OwnedBed == null) //Check if Partner have bed
job = new Job(jobDef, target, pawn.ownership.OwnedBed); //Go to Pawn bed if partner don't have bed assigned
else job = new Job(jobDef, target, target.Pawn.ownership.OwnedBed); //If Partner have bed - go to partner
}
else if (jobDef == xxx.Masturbate)
{
job = new Job(jobDef, pawn, null, target.Cell);
}
else
{
job = new Job(jobDef, target);
}
var SP = new SexProps
{
pawn = pawn,
partner = partner,
sexType = SexUtility.rjwSextypeGet(interactionDef),
isRape = rape,
isRapist = rape,
canBeGuilty = false, //pawn.IsHeroOwner();//TODO: fix for MP someday
dictionaryKey = interactionDef,
rulePack = SexUtility.SexRulePackGet(interactionDef)
};
pawn.GetRJWPawnData().SexProps = SP;
pawn.jobs.EndCurrentJob(JobCondition.InterruptForced);
pawn.jobs.TryTakeOrderedJob(job);
}
}
} | Korth95/rjw | 1.5/Source/Common/RMB/RMB_Menu.cs | C# | mit | 9,816 |
using RimWorld;
using System.Collections.Generic;
using System.Linq;
using Verse;
using System;
namespace rjw.RMB
{
/// <summary>
/// Generator of RMB categories for necrophilia
/// </summary>
static class RMB_Necro
{
/// <summary>
/// Add necrophilia and reverse necrophilia options to <paramref name="opts"/>
/// </summary>
/// <param name="pawn">Selected pawn</param>
/// <param name="opts">List of RMB options</param>
/// <param name="target">Target of the right click</param>
public static void AddFloatMenuOptions(Pawn pawn, List<FloatMenuOption> opts, LocalTargetInfo target)
{
if (target.Thing is not Corpse corpse)
{
return;
}
AcceptanceReport canCreateEntries = DoBasicChecks(pawn, corpse);
if (!canCreateEntries)
{
if (RJWSettings.DevMode && !canCreateEntries.Reason.NullOrEmpty())
opts.Add(new FloatMenuOption(canCreateEntries.Reason, null));
return;
}
canCreateEntries = DoChecks(pawn, corpse);
if (!canCreateEntries)
{
opts.Add(new FloatMenuOption("RJW_RMB_RapeCorpse".Translate(corpse) + ": " + canCreateEntries.Reason, null));
return;
}
FloatMenuOption opt = GenerateCategoryOption(pawn, target);
if (opt != null)
opts.Add(opt);
opt = GenerateCategoryOption(pawn, target, true);
if (opt != null)
opts.Add(opt);
}
/// <summary>
/// Check for the things that should be obvious to the player or does not change for particular pawns.
/// </summary>
/// <returns>
/// AcceptanceReport. Reason is an untranslated string and should only be shown in the DevMode
/// </returns>
private static AcceptanceReport DoBasicChecks(Pawn pawn, Corpse target)
{
if (!RJWSettings.necrophilia_enabled)
{
return "No necro: Disabled by the mod settings";
}
if (target.InnerPawn == null || target.InnerPawn == pawn)
{
return false;
}
if (!xxx.can_rape(pawn, true))
{
return "No necro: Pawn can't rape";
}
return true;
}
/// <summary>
/// Check for the things that can change for particular pawns.
/// </summary>
/// <returns>
/// AcceptanceReport. Reason is a translated string and should not be null.
/// </returns>
private static AcceptanceReport DoChecks(Pawn pawn, Corpse target)
{
if (!pawn.IsDesignatedHero() && !pawn.IsHeroOwner())
{
if (SexAppraiser.would_fuck(pawn, target.InnerPawn) < 0.1f)
{
return "RJW_RMB_ReasonUnappealingTarget".Translate();
}
}
return true;
}
/// <summary>
/// Generate one FloatMenuOption
/// </summary>
/// <param name="pawn"></param>
/// <param name="target"></param>
/// <param name="reverse"></param>
/// <returns>Category-level item that opens a sub-menu on click</returns>
private static FloatMenuOption GenerateCategoryOption(Pawn pawn, LocalTargetInfo target, bool reverse = false)
{
string text = null;
Corpse corpse = target.Thing as Corpse;
if (reverse)
{
text = "RJW_RMB_RapeCorpse_Reverse".Translate(corpse);
}
else
{
text = "RJW_RMB_RapeCorpse".Translate(corpse);
}
Action action = delegate ()
{
JobDef job = xxx.RapeCorpse;
var validinteractions = RMB_Menu.GenerateNonSoloSexRoleOptions(pawn, target, job, true, reverse);
if (validinteractions.Any())
FloatMenuUtility.MakeMenu(validinteractions, (FloatMenuOption opt) => opt.Label, (FloatMenuOption opt) => opt.action);
else
Messages.Message("No valid interactions found for " + text, MessageTypeDefOf.RejectInput, false);
};
return FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(text, action, MenuOptionPriority.High), pawn, target);
}
}
}
| Korth95/rjw | 1.5/Source/Common/RMB/RMB_Necro.cs | C# | mit | 3,663 |
using RimWorld;
using System.Collections.Generic;
using System.Linq;
using Verse;
using System;
namespace rjw.RMB
{
/// <summary>
/// Generator of RMB categories for rape
/// </summary>
static class RMB_Rape
{
/// <summary>
/// Add rape and reverse rape options to <paramref name="opts"/>
/// </summary>
/// <param name="pawn">Selected pawn</param>
/// <param name="opts">List of RMB options</param>
/// <param name="target">Target of the right click</param>
public static void AddFloatMenuOptions(Pawn pawn, List<FloatMenuOption> opts, LocalTargetInfo target)
{
AcceptanceReport canCreateEntries = DoBasicChecks(pawn, target.Pawn);
if (!canCreateEntries)
{
if (RJWSettings.DevMode && !canCreateEntries.Reason.NullOrEmpty())
opts.Add(new FloatMenuOption(canCreateEntries.Reason, null));
return;
}
canCreateEntries = DoChecks(pawn, target.Pawn);
if (!canCreateEntries)
{
opts.Add(new FloatMenuOption("RJW_RMB_Rape".Translate(target.Pawn) + ": " + canCreateEntries.Reason, null));
return;
}
FloatMenuOption opt = GenerateCategoryOption(pawn, target);
if (opt != null)
opts.Add(opt);
opt = GenerateCategoryOption(pawn, target, true);
if (opt != null)
opts.Add(opt);
}
/// <summary>
/// Check for the things that should be obvious to the player or does not change for particular pawns.
/// </summary>
/// <returns>
/// AcceptanceReport. Reason is an untranslated string and should only be shown in the DevMode
/// </returns>
private static AcceptanceReport DoBasicChecks(Pawn pawn, Pawn target)
{
if (!RJWSettings.rape_enabled)
{
return "No rape: Disabled by the mod settings";
}
if (!xxx.can_rape(pawn, true))
{
return "No rape: Pawn can't rape";
}
if (!xxx.can_be_fucked(target))
{
return "No rape: Target can't have sex";
}
if (target.HostileTo(pawn) && !target.Downed)
{
return "No rape: Hostile must be downed";
}
return true;
}
/// <summary>
/// Check for the things that can change for particular pawns.
/// </summary>
/// <returns>
/// AcceptanceReport. Reason is a translated string and should not be null.
/// </returns>
private static AcceptanceReport DoChecks(Pawn pawn, Pawn target)
{
if (!pawn.IsDesignatedHero() && !pawn.IsHeroOwner())
{
if (SexAppraiser.would_fuck(pawn, target) < 0.1f)
return "RJW_RMB_ReasonUnappealingTarget".Translate();
}
return true;
}
/// <summary>
/// Generate one FloatMenuOption
/// </summary>
/// <param name="pawn"></param>
/// <param name="target"></param>
/// <param name="reverse"></param>
/// <returns>Category-level item that opens a sub-menu on click</returns>
private static FloatMenuOption GenerateCategoryOption(Pawn pawn, LocalTargetInfo target, bool reverse = false)
{
string text = null;
if (reverse)
{
text = "RJW_RMB_Rape_Reverse".Translate(target.Pawn);
}
else
{
text = "RJW_RMB_Rape".Translate(target.Pawn);
}
Action action = null;
if (target.Pawn.HostileTo(pawn))
{
action = delegate ()
{
JobDef job = xxx.RapeEnemy;
var validinteractions = RMB_Menu.GenerateNonSoloSexRoleOptions(pawn, target, job, true, reverse);
if (validinteractions.Any())
FloatMenuUtility.MakeMenu(validinteractions, (FloatMenuOption opt) => opt.Label, (FloatMenuOption opt) => opt.action);
else
Messages.Message("No valid interactions found for " + text, MessageTypeDefOf.RejectInput, false);
};
}
else if (target.Pawn.IsDesignatedComfort())
{
action = delegate ()
{
JobDef job = xxx.RapeCP;
var validinteractions = RMB_Menu.GenerateNonSoloSexRoleOptions(pawn, target, job, true, reverse);
if (validinteractions.Any())
FloatMenuUtility.MakeMenu(validinteractions, (FloatMenuOption opt) => opt.Label, (FloatMenuOption opt) => opt.action);
else
Messages.Message("No valid interactions found for " + text, MessageTypeDefOf.RejectInput, false);
};
}
else if (xxx.can_get_raped(target.Pawn) && (xxx.get_vulnerability(target.Pawn) >= xxx.get_vulnerability(pawn)))
{
action = delegate ()
{
JobDef job = xxx.RapeRandom;
var validinteractions = RMB_Menu.GenerateNonSoloSexRoleOptions(pawn, target, job, true, reverse);
if (validinteractions.Any())
FloatMenuUtility.MakeMenu(validinteractions, (FloatMenuOption opt) => opt.Label, (FloatMenuOption opt) => opt.action);
else
Messages.Message("No valid interactions found for " + text, MessageTypeDefOf.RejectInput, false);
};
}
else
{
if (RJWSettings.DevMode && !reverse)
{
return new FloatMenuOption("No rape: Target not hostile, not CP, can't be raped, or not vulnerable enough", null);
}
return null;
}
return FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(text, action, MenuOptionPriority.High), pawn, target);
}
}
}
| Korth95/rjw | 1.5/Source/Common/RMB/RMB_Rape.cs | C# | mit | 4,968 |
using RimWorld;
using System.Collections.Generic;
using System.Linq;
using Verse;
using System;
namespace rjw.RMB
{
/// <summary>
/// Generator of RMB categories for breeding
/// </summary>
static class RMB_RapeAnimal
{
/// <summary>
/// Add breeding and reverse breeding options to <paramref name="opts"/>
/// </summary>
/// <param name="pawn">Selected pawn</param>
/// <param name="opts">List of RMB options</param>
/// <param name="target">Target of the right click</param>
public static void AddFloatMenuOptions(Pawn pawn, List<FloatMenuOption> opts, LocalTargetInfo target)
{
AcceptanceReport canCreateEntries = DoBasicChecks(pawn, target.Pawn);
if (!canCreateEntries)
{
if (RJWSettings.DevMode && !canCreateEntries.Reason.NullOrEmpty())
opts.Add(new FloatMenuOption(canCreateEntries.Reason, null));
return;
}
canCreateEntries = DoChecks(pawn, target.Pawn);
if (!canCreateEntries)
{
opts.Add(new FloatMenuOption("RJW_RMB_RapeAnimal".Translate(target.Pawn) + ": " + canCreateEntries.Reason, null));
return;
}
FloatMenuOption opt = GenerateCategoryOption(pawn, target);
if (opt != null)
opts.Add(opt);
opt = GenerateCategoryOption(pawn, target, true);
if (opt != null)
opts.Add(opt);
}
/// <summary>
/// Check for the things that should be obvious to the player or does not change for particular pawns.
/// </summary>
/// <returns>
/// AcceptanceReport. Reason is an untranslated string and should only be shown in the DevMode
/// </returns>
private static AcceptanceReport DoBasicChecks(Pawn pawn, Pawn target)
{
if (!RJWSettings.rape_enabled)
{
return "No breeding: Rape is disabled by the mod settings";
}
if (!RJWSettings.bestiality_enabled)
{
return "No breeding: Bestiality is disabled by the mod settings";
}
if (!xxx.can_rape(pawn, true))
{
return "No breeding: Pawn can't rape";
}
if (!xxx.can_be_fucked(target))
{
return "No breeding: Target can't have sex";
}
if (target.HostileTo(pawn) && !target.Downed)
{
return "No breeding: Hostile must be downed";
}
return true;
}
/// <summary>
/// Check for the things that can change for particular pawns.
/// </summary>
/// <returns>
/// AcceptanceReport. Reason is a translated string and should not be null.
/// </returns>
private static AcceptanceReport DoChecks(Pawn pawn, Pawn target)
{
if (!pawn.IsDesignatedHero() && !pawn.IsHeroOwner())
{
if (SexAppraiser.would_fuck(pawn, target) < 0.1f)
return "RJW_RMB_ReasonUnappealingTarget".Translate();
}
return true;
}
/// <summary>
/// Generate one FloatMenuOption
/// </summary>
/// <param name="pawn"></param>
/// <param name="target"></param>
/// <param name="reverse"></param>
/// <returns>Category-level item that opens a sub-menu on click</returns>
private static FloatMenuOption GenerateCategoryOption(Pawn pawn, LocalTargetInfo target, bool reverse = false)
{
string text = null;
if (reverse)
{
text = "RJW_RMB_RapeAnimal_Reverse".Translate(target.Pawn);
}
else
{
text = "RJW_RMB_RapeAnimal".Translate(target.Pawn);
}
Action action = null;
if (target.Pawn.HostileTo(pawn))
{
// Needs testing
// Before separation from RMB_Rape animals, in theory, could get here.
// But would the RapeEnemy job driver work properly?
// Or maybe downed animals loose hostile status?
action = delegate ()
{
JobDef job = xxx.RapeEnemy;
var validinteractions = RMB_Menu.GenerateNonSoloSexRoleOptions(pawn, target, job, true, reverse);
if (validinteractions.Any())
FloatMenuUtility.MakeMenu(validinteractions, (FloatMenuOption opt) => opt.Label, (FloatMenuOption opt) => opt.action);
else
Messages.Message("No valid interactions found for " + text, MessageTypeDefOf.RejectInput, false);
};
}
else if (!xxx.can_fuck(pawn))
{
if (RJWSettings.DevMode && !reverse)
{
return new FloatMenuOption("No breeding: Pawn can't fuck", null);
}
return null;
}
else
{
action = delegate ()
{
JobDef job = xxx.bestiality;
var validinteractions = RMB_Menu.GenerateNonSoloSexRoleOptions(pawn, target, job, true, reverse);
if (validinteractions.Any())
FloatMenuUtility.MakeMenu(validinteractions, (FloatMenuOption opt) => opt.Label, (FloatMenuOption opt) => opt.action);
else
Messages.Message("No valid interactions found for " + text, MessageTypeDefOf.RejectInput, false);
};
}
return FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(text, action, MenuOptionPriority.High), pawn, target);
}
}
}
| Korth95/rjw | 1.5/Source/Common/RMB/RMB_RapeAnimal.cs | C# | mit | 4,723 |
using RimWorld;
using System.Collections.Generic;
using System.Linq;
using Verse;
namespace rjw.RMB
{
/// <summary>
/// Generator of RMB categories for "normal" sex
/// </summary>
static class RMB_Sex
{
/// <summary>
/// Add have sex and reverse sex options to <paramref name="opts"/>
/// </summary>
/// <param name="pawn">Selected pawn</param>
/// <param name="opts">List of RMB options</param>
/// <param name="target">Target of right click</param>
public static void AddFloatMenuOptions(Pawn pawn, List<FloatMenuOption> opts, LocalTargetInfo target)
{
AcceptanceReport canCreateEntries = DoBasicChecks(pawn, target.Pawn);
if (!canCreateEntries)
{
if (RJWSettings.DevMode && !canCreateEntries.Reason.NullOrEmpty())
opts.Add(new FloatMenuOption(canCreateEntries.Reason, null));
return;
}
canCreateEntries = DoChecks(pawn, target.Pawn);
if (!canCreateEntries)
{
opts.Add(new FloatMenuOption("RJW_RMB_Sex".Translate(target.Pawn) + ": " + canCreateEntries.Reason, null));
return;
}
FloatMenuOption opt = GenerateCategoryOption(pawn, target);
if (opt != null)
opts.Add(opt);
opt = GenerateCategoryOption(pawn, target, true);
if (opt != null)
opts.Add(opt);
}
/// <summary>
/// Check for the things that should be obvious to the player or does not change for particular pawns.
/// </summary>
/// <returns>
/// AcceptanceReport. Reason is an untranslated string and should only be shown in the DevMode
/// </returns>
private static AcceptanceReport DoBasicChecks(Pawn pawn, Pawn target)
{
if (target.Downed)
{
return "No sex: Target downed";
}
if (target.HostileTo(pawn))
{
return "No sex: Target hostile";
}
if (!xxx.can_be_fucked(target) && !xxx.can_fuck(target))
{
return "No sex: Target can't have sex";
}
return true;
}
/// <summary>
/// Check for the things that can change for particular pawns.
/// </summary>
/// <returns>
/// AcceptanceReport. Reason is a translated string and should not be null.
/// </returns>
private static AcceptanceReport DoChecks(Pawn pawn, Pawn target)
{
int opinionOf;
if (!pawn.IsDesignatedHero() && !pawn.IsHeroOwner())
{
opinionOf = pawn.relations.OpinionOf(target);
if (opinionOf < RJWHookupSettings.MinimumRelationshipToHookup)
{
if (!(opinionOf > 0 && xxx.is_nympho(pawn)))
{
return "RJW_RMB_ReasonLowOpinionOfTarget".Translate();
}
}
if (SexAppraiser.would_fuck(pawn, target) < 0.1f)
{
return "RJW_RMB_ReasonUnappealingTarget".Translate();
}
}
opinionOf = target.relations.OpinionOf(pawn);
if (opinionOf < RJWHookupSettings.MinimumRelationshipToHookup)
{
if (!(opinionOf > 0 && xxx.is_nympho(target)))
{
return "RJW_RMB_ReasonLowOpinionOfPawn".Translate();
}
}
if (SexAppraiser.would_fuck(target, pawn) < 0.1f)
{
return "RJW_RMB_ReasonUnappealingPawn".Translate();
}
return true;
}
/// <summary>
/// Generate one FloatMenuOption
/// </summary>
/// <param name="pawn"></param>
/// <param name="target"></param>
/// <param name="reverse"></param>
/// <returns>Category-level item that opens a sub-menu on click</returns>
private static FloatMenuOption GenerateCategoryOption(Pawn pawn, LocalTargetInfo target, bool reverse = false)
{
string text = null;
if (reverse)
{
text = "RJW_RMB_Sex_Reverse".Translate(target.Pawn);
}
else
{
text = "RJW_RMB_Sex".Translate(target.Pawn);
}
return FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(text, delegate ()
{
JobDef job = null;
if (target.Pawn.InBed())
job = xxx.casual_sex;
else
job = xxx.quick_sex;
var validinteractions = RMB_Menu.GenerateNonSoloSexRoleOptions(pawn, target, job, false, reverse);
if (validinteractions.Any())
FloatMenuUtility.MakeMenu(validinteractions, (FloatMenuOption opt) => opt.Label, (FloatMenuOption opt) => opt.action);
else
Messages.Message("No valid interactions found for " + text, MessageTypeDefOf.RejectInput, false);
}, MenuOptionPriority.High), pawn, target);
}
}
} | Korth95/rjw | 1.5/Source/Common/RMB/RMB_Sex.cs | C# | mit | 4,195 |
using RimWorld;
using System.Collections.Generic;
using System.Linq;
using Verse;
using Multiplayer.API;
namespace rjw
{
/// <summary>
/// Generator of RMB categories for socializing
/// </summary>
static class RMB_Socialize
{
/// <summary>
/// Add socialize option to <paramref name="opts"/>
/// </summary>
/// <param name="pawn">Selected pawn</param>
/// <param name="opts">List of RMB options</param>
/// <param name="target">Target of right click</param>
public static void AddFloatMenuOptions(Pawn pawn, List<FloatMenuOption> opts, LocalTargetInfo target)
{
AcceptanceReport canCreateEntries = DoBasicChecks(pawn, target.Pawn);
if (!canCreateEntries)
{
if (RJWSettings.DevMode && !canCreateEntries.Reason.NullOrEmpty())
opts.Add(new FloatMenuOption(canCreateEntries.Reason, null));
return;
}
FloatMenuOption opt = GenerateCategoryOption(pawn, target);
if (opt != null)
opts.Add(opt);
}
/// <summary>
/// Check for the things that should be obvious to the player or does not change for particular pawns.
/// </summary>
/// <returns>
/// AcceptanceReport. Reason is an untranslated string and should only be shown in the DevMode
/// </returns>
private static AcceptanceReport DoBasicChecks(Pawn pawn, Pawn target)
{
if (!pawn.interactions.CanInteractNowWith(target))
{
return $"No socialize: cannot interact with {target.NameShortColored} now";
}
return true;
}
private static FloatMenuOption GenerateCategoryOption(Pawn pawn, LocalTargetInfo target)
{
return FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("RJW_RMB_Social".Translate(target.Pawn), delegate ()
{
FloatMenuUtility.MakeMenu(GenerateSocialOptions(pawn, target).Where(x => x.action != null), (FloatMenuOption opt) => opt.Label, (FloatMenuOption opt) => opt.action);
}, MenuOptionPriority.High), pawn, target);
}
/// <summary>
/// Generates sub-menu options for socializing
/// </summary>
/// <param name="pawn">Initiator pawn</param>
/// <param name="target">Target pawn</param>
/// <returns>A list of menu options, where each item represents a possible interaction</returns>
private static List<FloatMenuOption> GenerateSocialOptions(Pawn pawn, LocalTargetInfo target)
{
List<FloatMenuOption> opts = new List<FloatMenuOption>();
FloatMenuOption option = null;
option = FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("RJW_RMB_Insult".Translate(), delegate ()
{
Socialize(pawn, target, InteractionDefOf.Insult);
}, MenuOptionPriority.High), pawn, target);
opts.Add(option);
if (!pawn.HostileTo(target.Pawn))
{
option = FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("RJW_RMB_SocialFight".Translate(), delegate ()
{
SocializeFight(pawn, target);
}, MenuOptionPriority.High), pawn, target);
opts.Add(option);
option = FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("RJW_RMB_Chat".Translate(), delegate ()
{
Socialize(pawn, target, InteractionDefOf.Chitchat);
}, MenuOptionPriority.High), pawn, target);
opts.Add(option);
// OP shit +12 relations, enable in cheat menu
if (RJWSettings.Allow_RMB_DeepTalk)
{
option = FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("RJW_RMB_DeepTalk".Translate(), delegate ()
{
pawn.interactions.TryInteractWith(target.Pawn, InteractionDefOf.DeepTalk);
}, MenuOptionPriority.High), pawn, target);
opts.Add(option);
}
if (!LovePartnerRelationUtility.LovePartnerRelationExists(pawn, target.Pawn))
{
option = FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("RJW_RMB_RomanceAttempt".Translate(), delegate ()
{
Socialize(pawn, target, InteractionDefOf.RomanceAttempt);
}, MenuOptionPriority.High), pawn, target);
opts.Add(option);
}
if (pawn.relations.DirectRelationExists(PawnRelationDefOf.Lover, target.Pawn) || pawn.relations.DirectRelationExists(PawnRelationDefOf.Fiance, target.Pawn))
{
option = FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("RJW_RMB_MarriageProposal".Translate(), delegate ()
{
Socialize(pawn, target, InteractionDefOf.MarriageProposal);
}, MenuOptionPriority.High), pawn, target);
opts.Add(option);
}
}
return opts;
}
//multiplayer synch actions
/// <summary>
/// Stops current job of the <paramref name="pawn"/> and starts a social fight
/// </summary>
/// <param name="pawn">Initiator</param>
/// <param name="target">Target pawn</param>
[SyncMethod]
static void SocializeFight(Pawn pawn, LocalTargetInfo target)
{
pawn.interactions.StartSocialFight(target.Pawn);
}
/// <summary>
/// Stops current job of the <paramref name="pawn"/> and starts an interaction
/// </summary>
/// <param name="pawn">Initiator</param>
/// <param name="target">Target pawn</param>
/// <param name="interaction">Interaction def</param>
[SyncMethod]
static void Socialize(Pawn pawn, LocalTargetInfo target, InteractionDef interaction)
{
pawn.interactions.TryInteractWith(target.Pawn, interaction);
}
}
} | Korth95/rjw | 1.5/Source/Common/RMB/RMB_Socialize.cs | C# | mit | 5,183 |
using HarmonyLib;
using Multiplayer.API;
using RimWorld;
using rjw.Modules.Shared.Extensions;
using rjw.Modules.Shared.Helpers;
using rjw.Modules.Shared.Logs;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using Verse;
using Verse.AI;
namespace rjw
{
/// <summary>
/// Responsible for judging the sexiness of potential partners.
/// </summary>
public static class SexAppraiser
{
private static ILog _log = LogManager.GetLogger(nameof(SexAppraiser));
public const float base_sat_per_fuck = 0.40f;
public const float base_attraction = 0.60f;
public const float no_partner_ability = 0.8f;
static readonly SimpleCurve fuckability_per_reserved = new SimpleCurve
{
new CurvePoint(0f, 1.0f),
new CurvePoint(0.3f, 0.4f),
new CurvePoint(1f, 0.2f)
};
/// <summary>
/// Returns boolean, no more messing around with floats.
/// Just a simple 'Would rape? True/false'.
/// </summary>
[SyncMethod]
public static bool would_rape(Pawn rapist, Pawn rapee)
{
float rape_factor = 0.3f; // start at 30%
float vulnerabilityFucker = xxx.get_vulnerability(rapist); //0 to 3
float vulnerabilityPartner = xxx.get_vulnerability(rapee); //0 to 3
// More inclined to rape someone from another faction.
if (rapist.HostileTo(rapee) || rapist.Faction != rapee.Faction)
rape_factor += 0.25f;
// More inclined to rape if the target is designated as CP.
if (rapee.IsDesignatedComfort())
rape_factor += 0.25f;
// More inclined to rape when horny.
Need_Sex horniness = rapist.needs.TryGetNeed<Need_Sex>();
if (!xxx.is_animal(rapist) && horniness?.CurLevel <= horniness?.thresh_horny())
{
rape_factor += 0.25f;
}
if (xxx.is_animal(rapist))
{
if (vulnerabilityFucker < vulnerabilityPartner)
rape_factor -= 0.1f;
else
rape_factor += 0.25f;
}
else if (xxx.is_animal(rapee))
{
if (xxx.is_zoophile(rapist))
rape_factor += 0.5f;
else
rape_factor -= 0.2f;
}
else
{
rape_factor *= 0.5f + Mathf.InverseLerp(vulnerabilityFucker, 3f, vulnerabilityPartner);
}
if (rapist.health.hediffSet.HasHediff(HediffDef.Named("AlcoholHigh")))
rape_factor *= 1.25f; //too drunk to care
// Increase factor from traits.
if (xxx.is_rapist(rapist))
rape_factor *= 1.5f;
if (xxx.is_nympho(rapist))
rape_factor *= 1.25f;
if (xxx.is_bloodlust(rapist))
rape_factor *= 1.2f;
if (xxx.is_psychopath(rapist))
rape_factor *= 1.2f;
if (xxx.is_masochist(rapee))
rape_factor *= 1.2f;
// Lower factor from traits.
if (xxx.is_masochist(rapist))
rape_factor *= 0.8f;
if (rapist.needs?.joy != null && rapist.needs.joy.CurLevel < 0.1f) // The rapist is really bored...
rape_factor *= 1.2f;
//Rand.PopState();
//Rand.PushState(RJW_Multiplayer.PredictableSeed());
if (rapist.relations == null || xxx.is_animal(rapist)) return Rand.Chance(rape_factor);
float opinion = rapist.relations.OpinionOf(rapee);
//remove Pretty trait bonus
//ThoughtWorker_Pretty
float beauty = rapee.GetStatValue(StatDefOf.PawnBeauty, true) * 20f;
opinion -= beauty;
// Won't rape friends, unless rapist or psychopath.
if (xxx.is_kind(rapist))
{ //<-80: 1f /-40: 0.5f / 0+: 0f
rape_factor *= 1f - Mathf.Pow(GenMath.InverseLerp(-80, 0, opinion), 2);
}
else if (xxx.is_rapist(rapist) || xxx.is_psychopath(rapist))
{ //<40: 1f /80: 0.5f / 120+: 0f
opinion -= beauty;
rape_factor *= 1f - Mathf.Pow(GenMath.InverseLerp(40, 120, opinion), 2); // This can never be 0, since opinion caps at 100.
}
else
{ //<-60: 1f /-20: 0.5f / 40+: 0f
opinion -= beauty;
rape_factor *= 1f - Mathf.Pow(GenMath.InverseLerp(-60, 40, opinion), 2);
}
//Log.Message("rjw::xxx rape_factor for " + get_pawnname(rapee) + " is " + rape_factor);
return Rand.Chance(rape_factor);
}
public static float would_fuck(Pawn fucker, Corpse fucked, bool invert_opinion = false, bool ignore_bleeding = false, bool ignore_gender = false)
{
CompRottable comp = fucked.GetComp<CompRottable>();
//--Log.Message("rotFactor:" + rotFactor);
// Things that don't rot, such as mechanoids and weird mod-added stuff such as Rimworld of Magic's elementals.
if (comp == null)
{
// Trying to necro the weird mod-added stuff causes an error, so skipping those for now.
return 0.0f;
}
float maxRot = ((CompProperties_Rottable)comp.props).TicksToDessicated;
float rotFactor = (maxRot - comp.RotProgress) / maxRot;
//--Log.Message("rotFactor:" + rotFactor);
return would_fuck(fucker, fucked.InnerPawn, invert_opinion, ignore_bleeding, ignore_gender) * rotFactor;
}
public static float would_fuck_animal(Pawn pawn, Pawn target, bool invert_opinion = false, bool ignore_bleeding = false, bool ignore_gender = false)
{
float wildness_modifier = 1.0f;
List<float> size_preference = new List<float>() { pawn.BodySize * 0.75f, pawn.BodySize * 1.6f };
float fuc = would_fuck(pawn, target, invert_opinion, ignore_bleeding, ignore_gender); // 0.0 to ~3.0, orientation checks etc.
if (fuc < 0.1f)
{ // Would not fuck
return 0;
}
if (xxx.has_quirk(pawn, "Teratophile"))
{ // Teratophiles prefer more 'monstrous' partners.
size_preference[0] = pawn.BodySize * 0.8f;
size_preference[1] = pawn.BodySize * 2.0f;
wildness_modifier = 0.3f;
}
if (Quirk.FeatherLover.IsSatisfiedBy(pawn, target) || Quirk.FurLover.IsSatisfiedBy(pawn, target) || Quirk.FeatherLover.IsSatisfiedBy(pawn, target) || Quirk.ScaleLover.IsSatisfiedBy(pawn, target) || Quirk.ChitinLover.IsSatisfiedBy(pawn, target))
{ // Will care less about size difference if fetish is satisfied.
size_preference[0] *= 0.5f;
size_preference[1] *= 1.5f;
}
if (pawn.health.hediffSet.HasHediff(HediffDef.Named("AlcoholHigh")))
{
wildness_modifier = 0.5f; //Drunk and making poor judgments.
size_preference[1] *= 1.5f;
}
else if (pawn.health.hediffSet.HasHediff(HediffDef.Named("YayoHigh")))
{
wildness_modifier = 0.2f; //This won't end well.
size_preference[1] *= 2.5f;
}
var parts = pawn.GetGenitalsList();
if (Genital_Helper.has_vagina(pawn, parts) || Genital_Helper.has_anus(pawn))
{
if (!Genital_Helper.has_male_bits(pawn, parts))
{
size_preference[1] = pawn.BodySize * 1.3f;
}
}
if (xxx.is_animal(pawn))
{
size_preference[1] = pawn.BodySize * 1.3f;
wildness_modifier = 0.4f;
}
else if (xxx.has_traits(pawn))
{
if (pawn.story.traits.HasTrait(VanillaTraitDefOf.Tough) || pawn.story.traits.HasTrait(TraitDefOf.Brawler))
{
size_preference[1] += 0.2f;
wildness_modifier -= 0.2f;
}
else if (pawn.story.traits.HasTrait(TraitDefOf.Wimp))
{
size_preference[0] -= 0.2f;
size_preference[1] -= 0.2f;
wildness_modifier += 0.25f;
}
}
float wildness = target.RaceProps.wildness; // 0.0 to 1.0
float petness = target.RaceProps.petness; // 0.0 to 1.0
float distance = pawn.Position.DistanceTo(target.Position);
//ModLog.Message("would_fuck_animal:: base: " + fuc + ", wildness: " + wildness + ", petness: " + petness + ", distance: " + distance);
fuc = fuc + fuc * petness - fuc * wildness * wildness_modifier;
if (fuc < 0.1f)
{ // Would not fuck
return 0;
}
// Adjust by distance, nearby targets preferred.
fuc *= 1.0f - Mathf.Max(distance / 10000, 0.1f);
// Adjust by size difference.
if (target.BodySize < size_preference[0])
{
fuc *= Mathf.Lerp(0.1f, size_preference[0], target.BodySize);
}
else if (target.BodySize > size_preference[1])
{
fuc *= Mathf.Lerp(size_preference[1] * 10, size_preference[1], target.BodySize);
}
if (target.Faction != pawn.Faction)
{
//ModLog.Message("would_fuck_animal(NT):: base: " + fuc + ", bound1: " + fuc * 0.75f);
//ModLog.Message("would_fuck_animal(NT):: base: " + fuc + ", bound2: " + fuc + 0.25f);
fuc *= 0.75f; // Less likely to target wild animals.
}
else if (pawn.relations.DirectRelationExists(PawnRelationDefOf.Bond, target))
{
//ModLog.Message("would_fuck_animal(T):: base: " + fuc + ", bound1: " + fuc * 1.25f);
//ModLog.Message("would_fuck_animal(T):: base: " + fuc + ", bound2: " + fuc + 0.25f);
fuc *= 1.25f; // Bonded animals preferred.
}
if (target.IsVisiblyPregnant() && !Quirk.PregnancyFetish.IsSatisfiedBy(pawn, target))
{
fuc *= 0.75f; // Less likely to target pregnant animals if not PregnancyFetish.
}
if (Quirk.PlantLover.IsSatisfiedBy(pawn, target) || Quirk.FurLover.IsSatisfiedBy(pawn, target) || Quirk.FeatherLover.IsSatisfiedBy(pawn, target) || Quirk.ScaleLover.IsSatisfiedBy(pawn, target) || Quirk.ChitinLover.IsSatisfiedBy(pawn, target))
{ // Will preferr animals that satisfy fetish.
fuc *= 2f;
}
return fuc;
}
// Returns how fuckable 'fucker' thinks 'p' is on a scale from 0.0 to 1.0
public static float would_fuck(Pawn fucker, Pawn fucked, bool invert_opinion = false, bool ignore_bleeding = false, bool ignore_gender = false)
{
//--ModLog.Message("would_fuck("+xxx.get_pawnname(fucker)+","+xxx.get_pawnname(fucked)+","+invert_opinion.ToString()+") is called");
if (xxx.is_human(fucker) && !xxx.is_healthy_enough(fucker) && !xxx.is_psychopath(fucker)) // Not healthy enough to have sex, shouldn't have got this far.
{
_log.Debug($"{nameof(would_fuck)} - {fucker.GetName()} on {fucked.GetName()}");
_log.Debug("Not healthy enough");
return 0f;
}
if ((xxx.is_animal(fucker) || xxx.is_animal(fucked)) && (!xxx.is_animal(fucker) || !xxx.is_animal(fucked)) && !RJWSettings.bestiality_enabled)
{
_log.Debug($"{nameof(would_fuck)} - {fucker.GetName()} on {fucked.GetName()}");
_log.Debug("Animals disabled");
return 0f;
}
if (fucked.Dead && !RJWSettings.necrophilia_enabled)
{
_log.Debug($"{nameof(would_fuck)} - {fucker.GetName()} on {fucked.GetName()}");
_log.Debug("Necrophilia disabled");
return 0f;
}
if (fucker.Dead || fucker.Suspended || fucked.Suspended)
{
_log.Debug($"{nameof(would_fuck)} - {fucker.GetName()} on {fucked.GetName()}");
_log.Debug("Target unreachable");
return 0f;
}
if (xxx.is_starved(fucked) && fucked.Faction == fucker.Faction && !xxx.is_psychopath(fucker) && !xxx.is_rapist(fucker))
{
_log.Debug($"{nameof(would_fuck)} - {fucker.GetName()} on {fucked.GetName()}");
_log.Debug("Target is starving");
return 0f;
}
if (xxx.is_human(fucker) && !ignore_bleeding && !xxx.is_not_dying(fucked) && !xxx.is_psychopath(fucker) && !xxx.is_rapist(fucker) && !xxx.is_bloodlust(fucker))
{
_log.Debug($"{nameof(would_fuck)} - {fucker.GetName()} on {fucked.GetName()}");
_log.Debug("Target is dying");
return 0f;
}
if (!IsGenderOk(fucker, fucked))
{
_log.Debug($"{nameof(would_fuck)} - {fucker.GetName()} on {fucked.GetName()}");
_log.Debug("Genders not compatible");
return 0.0f;
}
int fucker_age = fucker.ageTracker.AgeBiologicalYears;
//string fucker_quirks = CompRJW.Comp(fucker).quirks.ToString();
int fucked_age = fucked.ageTracker.AgeBiologicalYears;
// --- Age checks ---
if (!IsAgeOk(fucker, fucked, fucker_age, fucked_age))
{
float scaledFuckerAge = AgeHelper.ScaleToHumanAge(fucker);
float scaledFuckedAge = AgeHelper.ScaleToHumanAge(fucked);
_log.Debug($"{nameof(would_fuck)} - {fucker.GetName()} on {fucked.GetName()}");
_log.Debug($"ages KO : original {fucker_age}/{fucked_age} - scaled {scaledFuckerAge}/{scaledFuckedAge}");
return 0.0f;
}
float age_factor = GetAgeFactor(fucker, fucked, fucked_age);
// --- Orientation checks ---
float orientation_factor = GetOrientationFactor(fucker, fucked, ignore_gender);
//retry vanilla if 0
if (orientation_factor == 0.0f)
{
orientation_factor = fucker.relations.SecondaryLovinChanceFactor(fucked);
//Log.Message("would_fuck() SecondaryLovinChanceFactor:" + orientation_factor);
if (orientation_factor <= 0)
return 0.0f;
}
// --- Body and appearance checks ---
float body_factor = GetBodyFactor(fucker, fucked);
// --- Opinion checks ---
float opinion_factor = GetOpinionFactor(fucker, fucked, invert_opinion);
float horniness_factor = GetHorninessFactor(fucker);
float reservedPercentage = (fucked.Dead ? 1f : fucked.ReservedCount()) / xxx.max_rapists_per_prisoner;
//Log.Message("would_fuck() reservedPercentage:" + reservedPercentage + "fuckability_per_reserved"+ fuckability_per_reserved.Evaluate(reservedPercentage));
//Log.Message("would_fuck() - horniness_factor = " + horniness_factor.ToString());
float prenymph_att = Mathf.InverseLerp(0f, 2.8f, base_attraction * orientation_factor * horniness_factor * age_factor * body_factor * opinion_factor);
float final_att = !(xxx.is_nympho(fucker) || fucker.health.hediffSet.HasHediff(RJWHediffDefOf.HumpShroomEffect)) ? prenymph_att : 0.2f + 0.8f * prenymph_att;
//Log.Message("would_fuck( " + xxx.get_pawnname(fucker) + ", " + xxx.get_pawnname(fucked) + " ) - prenymph_att = " + prenymph_att.ToString() + ", final_att = " + final_att.ToString());
//if (xxx.is_human(fucker) && xxx.is_human(fucked))
//{
// Log.Message($"{nameof(would_fuck)} - {fucker.GetName()} on {fucked.GetName()}");
// Log.Message($"[age {age_factor}] [orientation {orientation_factor}] [body {body_factor}] [opinion {opinion_factor}] [horniness {horniness_factor}] [final {final_att}]");
//}
return Mathf.Min(final_att, fuckability_per_reserved.Evaluate(reservedPercentage));
}
/// <summary>
/// rjw settings gender sex limiters homo/nohomo
/// </summary>
/// <param name="fucker"></param>
/// <param name="fucked"></param>
/// <returns></returns>
private static bool IsGenderOk(Pawn fucker, Pawn fucked)
{
if (fucker.gender == Gender.Male)
{
switch (RJWPreferenceSettings.Malesex)
{
case RJWPreferenceSettings.AllowedSex.All:
break;
case RJWPreferenceSettings.AllowedSex.Homo:
if (fucked.gender != Gender.Male)
return false;
break;
case RJWPreferenceSettings.AllowedSex.Nohomo:
if (fucked.gender == Gender.Male)
return false;
break;
}
}
if (fucker.gender == Gender.Female)
{
switch (RJWPreferenceSettings.FeMalesex)
{
case RJWPreferenceSettings.AllowedSex.All:
break;
case RJWPreferenceSettings.AllowedSex.Homo:
if (fucked.gender != Gender.Female)
return false;
break;
case RJWPreferenceSettings.AllowedSex.Nohomo:
if (fucked.gender == Gender.Female)
return false;
break;
}
}
return true;
}
private static float GetHorninessFactor(Pawn fucker)
{
float horniness_factor; // 1 to 1.6
{
float need_sex = xxx.need_some_sex(fucker);
switch (need_sex)
{
case 3:
horniness_factor = 1.6f;
break;
case 2:
horniness_factor = 1.3f;
break;
case 1:
horniness_factor = 1.1f;
break;
default:
horniness_factor = 1f;
break;
}
}
//Log.Message("would_fuck() - horniness_factor = " + horniness_factor.ToString());
return horniness_factor;
}
private static float GetOpinionFactor(Pawn fucker, Pawn fucked, bool invert_opinion)
{
float opinion_factor;
{
if (fucked.relations != null && fucker.relations != null && !xxx.is_animal(fucker) && !xxx.is_animal(fucked))
{
float opi = !invert_opinion ? fucker.relations.OpinionOf(fucked) : 100 - fucker.relations.OpinionOf(fucked); // -100 to 100
opinion_factor = 0.8f + (opi + 100.0f) * (.45f / 200.0f); // 0.8 to 1.25
}
else if ((xxx.is_animal(fucker) || xxx.is_animal(fucked)) && fucker.relations.DirectRelationExists(PawnRelationDefOf.Bond, fucked))
{
opinion_factor = 1.3f;
}
else
{
opinion_factor = 1.0f;
}
// More likely to take advantege of CP.
if (fucked.IsDesignatedComfort() || (fucked.IsDesignatedBreeding() && xxx.is_animal(fucker)))
opinion_factor += 0.25f;
else if (fucked.IsDesignatedService())
opinion_factor += 0.1f;
// Less picky if designated for whorin'.
if (fucker.IsDesignatedService())
opinion_factor += 0.1f;
if (Quirk.Sapiosexual.IsSatisfiedBy(fucker, fucked))
{
opinion_factor *= 1.4f;
}
}
//Log.Message("would_fuck() - opinion_factor = " + opinion_factor.ToString());
return opinion_factor;
}
private static float GetBodyFactor(Pawn fucker, Pawn fucked)
{
float body_factor; //0.4 to 1.6
{
if (fucker.health.hediffSet.HasHediff(HediffDef.Named("AlcoholHigh")))
{
if (!xxx.is_zoophile(fucker) && xxx.is_animal(fucked))
body_factor = 0.8f;
else
body_factor = 1.25f; //beer lens
}
else if (xxx.is_zoophile(fucker) && !xxx.is_animal(fucked))
{
body_factor = 0.7f;
}
else if (!xxx.is_zoophile(fucker) && xxx.is_animal(fucked))
{
body_factor = 0.45f;
}
else if (Quirk.Teratophile.IsSatisfiedBy(fucker, fucked))
{
body_factor = 1.4f;
}
else if (fucked.story != null)
{
if (fucked.story.bodyType == BodyTypeDefOf.Female) body_factor = 1.25f;
else if (fucked.story.bodyType == BodyTypeDefOf.Fat) body_factor = 1.0f;
else body_factor = 1.1f;
if (fucked.story.traits.HasTrait(TraitDefOf.CreepyBreathing))
body_factor *= 0.9f;
//if (fucked.story.traits.HasTrait(TraitDefOf.Beauty))
//{
// switch (fucked.story.traits.DegreeOfTrait(TraitDefOf.Beauty))
// {
// case 2: // Beautiful
// body_factor *= 1.25f;
// break;
// case 1: // Pretty
// body_factor *= 1.1f;
// break;
// case -1: // Ugly
// body_factor *= 0.8f;
// break;
// case -2: // Staggeringly Ugly
// body_factor *= 0.5f;
// break;
// }
//}
if (fucked.GetStatValue(StatDefOf.PawnBeauty) >= 2)
body_factor *= 1.25f;
else if (fucked.GetStatValue(StatDefOf.PawnBeauty) >= 1)
body_factor *= 1.1f;
else if (fucked.GetStatValue(StatDefOf.PawnBeauty) < 0)
if (fucked.GetStatValue(StatDefOf.PawnBeauty) >= -1)
body_factor *= 0.8f;
else
body_factor *= 0.5f;
if (RelationsUtility.IsDisfigured(fucked))
{
body_factor *= 0.8f;
}
// Nude target is more tempting.
if (!fucked.Dead && fucked.apparel.PsychologicallyNude && fucker.CanSee(fucked))
body_factor *= 1.1f;
}
else
{
body_factor = 1.1f;
}
if (Quirk.Somnophile.IsSatisfiedBy(fucker, fucked))
{
body_factor *= 1.25f;
}
if (Quirk.PregnancyFetish.IsSatisfiedBy(fucker, fucked))
{
body_factor *= 1.25f;
}
if (Quirk.ImpregnationFetish.IsSatisfiedBy(fucker, fucked))
{
body_factor *= 1.25f;
}
if (xxx.AlienFrameworkIsActive && !xxx.is_animal(fucker))
{
if (xxx.is_xenophile(fucker))
{
if (fucker.def.defName == fucked.def.defName)
body_factor *= 0.5f; // Same species, xenophile less interested.
}
else if (xxx.is_xenophobe(fucker))
{
if (fucker.def.defName != fucked.def.defName)
body_factor *= 0.25f; // Different species, xenophobe less interested.
}
}
if (fucked.Dead && !xxx.is_necrophiliac(fucker))
{
body_factor *= 0.5f;
}
}
//Log.Message("would_fuck() - body_factor = " + body_factor.ToString());
return body_factor;
}
private static float GetOrientationFactor(Pawn fucker, Pawn fucked, bool ignore_gender)
{
float orientation_factor; //0 or 1
{
orientation_factor = 1.0f;
if (!ignore_gender && !xxx.is_animal(fucker))
{
if (!CompRJW.CheckPreference(fucker, fucked))
{
//Log.Message("would_fuck( " + xxx.get_pawnname(fucker) + ", " + xxx.get_pawnname(fucked) + " )");
//Log.Message("would_fuck() - preference fail");
orientation_factor = 0.0f;
}
}
}
//Log.Message("would_fuck() - orientation_factor = " + orientation_factor.ToString());
return orientation_factor;
}
private static float GetAgeFactor(Pawn fucker, Pawn fucked, int p_age)
{
float age_factor;
age_factor = fucked.gender == Gender.Male
? AgeConfigDef.Instance.attractivenessByAgeMale.Evaluate(AgeHelper.ScaleToHumanAge(fucker))
: AgeConfigDef.Instance.attractivenessByAgeFemale.Evaluate(AgeHelper.ScaleToHumanAge(fucked));
//if (RJWSettings.DevMode) ModLog.Message("would_fuck() - age_factor = " + age_factor.ToString());
if (xxx.is_animal(fucker))
{
age_factor = 1.0f; //using flat factors, since human age is not comparable to animal ages
}
else if (xxx.is_animal(fucked))
{
if (p_age <= 1 && fucked.RaceProps.lifeExpectancy > 8)
age_factor = 0.5f;
else
age_factor = 1.0f;
//--Log.Message("would_fuck() - animal age_factor = " + age_factor.ToString());
}
if (Quirk.Gerontophile.IsSatisfiedBy(fucker, fucked))
{
age_factor = 1.0f;
}
return age_factor;
}
private static bool IsAgeOk(Pawn fucker, Pawn fucked, int fucker_age, int fucked_age)
{
bool age_ok = false;
{
if (xxx.is_mechanoid(fucker) || xxx.can_do_loving(fucker))
{
age_ok = true;
}
if (age_ok && (xxx.is_mechanoid(fucked) || xxx.can_do_loving(fucked)))
{
age_ok = true;
}
else
age_ok = false;
//Log.Message("IsAgeOk can_do_loving = " + age_ok.ToString());
if (age_ok && xxx.is_human(fucker) && xxx.is_human(fucked))
{
bool FuckerAgeOk = fucker.ageTracker.Growth == 1;
bool FuckedAgeOk = fucked.ageTracker.Growth == 1;
//Log.Message("fucker AdultMinAge " + fucker.ageTracker.CurLifeStage.defName);
//Log.Message("fucked AdultMinAge " + fucked.ageTracker.CurLifeStage.defName);
if (!FuckerAgeOk || !FuckedAgeOk)
{
//scaled ages
//float scaledFuckerAge = AgeHelper.ScaleToHumanAge(fucker);
//float scaledFuckedAge = AgeHelper.ScaleToHumanAge(fucked);
//age_ok = Math.Abs(scaledFuckerAge - scaledFuckedAge) < 2.05f;
//fixed racegroupdef ages
//if (!age_ok)
if (true)
{
if (!FuckerAgeOk)
{
if (!(fucker.ageTracker.CurLifeStage.defName.ToLower().Contains("adult")))
{
FuckerAgeOk = true;
}
if (fucker.GetRJWPawnData().RaceSupportDef?.adultAge != null && fucker.GetRJWPawnData().RaceSupportDef?.adultAge != 0)
{
var adultAge = fucker.GetRJWPawnData().RaceSupportDef.adultAge;
var pawnAge = fucker.ageTracker.AgeBiologicalYearsFloat;
if (adultAge <= pawnAge)
FuckerAgeOk = true;
else
FuckerAgeOk = false;
}
}
if (!FuckedAgeOk)
{
{
if (!(fucked.ageTracker.CurLifeStage.defName.ToLower().Contains("adult")))
{
FuckedAgeOk = true;
}
if (fucked.GetRJWPawnData().RaceSupportDef?.adultAge != null && fucked.GetRJWPawnData().RaceSupportDef?.adultAge != 0)
{
var adultAge = fucked.GetRJWPawnData().RaceSupportDef.adultAge;
var pawnAge = fucked.ageTracker.AgeBiologicalYearsFloat;
if (adultAge <= pawnAge)
FuckedAgeOk = true;
else
FuckedAgeOk = false;
}
}
}
//age_ok = FuckerAgeOk && FuckedAgeOk;
if (FuckerAgeOk && FuckedAgeOk)
return true;
if (!RJWSettings.AllowYouthSex)
return false;
}
}
//Log.Message(" AdultMinAge " + fucker.ageTracker.AdultMinAge);
}
}
//Log.Message("would_fuck() - age_ok = " + age_ok.ToString());
return age_ok;
}
static int ReservedCount(this Thing pawn)
{
int ret = 0;
if (pawn == null) return 0;
try
{
ReservationManager reserver = pawn.Map.reservationManager;
IList reservations = (IList)AccessTools.Field(typeof(ReservationManager), "reservations").GetValue(reserver);
if (reservations.Count == 0) return 0;
Type reserveType = reservations[0].GetType();
ret += (from object t in reservations
where t != null
let target = (LocalTargetInfo)AccessTools.Field(reserveType, "target").GetValue(t)
let claimant = (Pawn)AccessTools.Field(reserveType, "claimant").GetValue(t)
where target != null
where target.Thing != null
where target.Thing.ThingID == pawn.ThingID
select (int)AccessTools.Field(reserveType, "stackCount").GetValue(t)).Count();
}
catch (Exception e)
{
ModLog.Warning(e.ToString());
}
return ret;
}
}
}
| Korth95/rjw | 1.5/Source/Common/SexAppraiser.cs | C# | mit | 24,712 |
using System;
using System.Collections.Generic;
using UnityEngine;
using Verse;
using Verse.Sound;
using RimWorld;
using Multiplayer.API;
namespace rjw
{
[StaticConstructorOnStartup]
public class SexGizmo : Gizmo
{
public SexGizmo(Pawn __instance)
{
this.pawn = __instance;
//this.order = -100f;
this.LimitedTex = ContentFinder<Texture2D>.Get("UI/Icons/EntropyLimit/Limited", true);
this.UnlimitedTex = ContentFinder<Texture2D>.Get("UI/Icons/EntropyLimit/Unlimited", true);
this.AttackTex = ContentFinder<Texture2D>.Get("UI/Icons/HostilityResponse/Attack", true);
//this.LimitedTex = ContentFinder<Texture2D>.Get("UI/Icons/HostilityResponse/Ignore", true);
//this.UnlimitedTex = ContentFinder<Texture2D>.Get("UI/Icons/HostilityResponse/Attack", true);
//this.LimitedTex = ContentFinder<Texture2D>.Get("UI/Commands/AttackMelee", true);
//this.UnlimitedTex = ContentFinder<Texture2D>.Get("UI/Commands/AttackMelee", true);
}
public override GizmoResult GizmoOnGUI(Vector2 topLeft, float maxWidth, GizmoRenderParms parms)
{
if (pawn.jobs?.curDriver is JobDriver_Sex)
{
Rect rect = new Rect(topLeft.x, topLeft.y, this.GetWidth(maxWidth), 75f);
Rect rect2 = rect.ContractedBy(6f);
Widgets.DrawWindowBackground(rect);
//row1 label1 - Orgasm
Text.Font = GameFont.Small;
Rect rect3 = rect2;
rect3.y += 6f;
rect3.height = Text.LineHeight;
Widgets.Label(rect3, "RJW_SexGizmo_Orgasm".Translate());
//row2 label2 - Stamina
Rect rect4 = rect2;
rect4.y += 38f;
rect4.height = Text.LineHeight;
Widgets.Label(rect4, "RJW_SexGizmo_RestNeed".Translate());
//row1 meter bar fill up
Rect rect5 = rect2;
rect5.x += 63f;
rect5.y += 6f;
rect5.width = 100f;
rect5.height = 22f;
float orgasm = (pawn.jobs?.curDriver as JobDriver_Sex).OrgasmProgress;
//orgasm = sex_ticks;
Widgets.FillableBar(rect5, Mathf.Max(orgasm, 0f), SexGizmo.EntropyBarTex, SexGizmo.EmptyBarTex, true);
//row1 meter values
string label = (orgasm * 100).ToString("F0") + " / " + 100;
Text.Font = GameFont.Small;
Text.Anchor = TextAnchor.MiddleCenter;
Widgets.Label(rect5, label);
Text.Anchor = TextAnchor.UpperLeft;
Text.Font = GameFont.Tiny;
GUI.color = Color.white;
//row1 meter description
//Rect rect6 = rect2;
//rect6.width = 175f;
//rect6.height = 38f;
//TooltipHandler.TipRegion(rect6, delegate()
//{
// float f = this.tracker.EntropyValue / this.tracker.RecoveryRate;
// return string.Format("PawnTooltipPsychicEntropyStats".Translate(), new object[]
// {
// Mathf.Round(this.tracker.EntropyValue),
// Mathf.Round(this.tracker.MaxEntropy),
// this.tracker.RecoveryRate.ToString("0.#"),
// Mathf.Round(f)
// }) + "\n\n" + "PawnTooltipPsychicEntropyDesc".Translate();
//}, Gen.HashCombineInt(this.tracker.GetHashCode(), 133858));
//row2 meter bar fill
Rect rect7 = rect2;
rect7.x += 63f;
rect7.y += 38f;
rect7.width = 100f;
rect7.height = 22f;
if (pawn.needs?.TryGetNeed<Need_Rest>() != null)
Widgets.FillableBar(rect7, Mathf.Min(pawn.needs.TryGetNeed<Need_Rest>().CurLevel, 1f), SexGizmo.PsyfocusBarTex, SexGizmo.EmptyBarTex, true);
GUI.color = Color.white;
//toggles
if (!MP.IsInMultiplayer) //TODO: someday write mp synchronizers?
if (pawn.IsColonistPlayerControlled && pawn.CanChangeDesignationColonist())
{
//row1 toggle - SexOverdrive
if (pawn.jobs?.curDriver is JobDriver_SexBaseInitiator)
{
float num = 32f;
float num2 = 4f;
float num3 = rect2.height / 2f - num + num2;
float num4 = rect2.width - num;
Rect rect9 = new Rect(rect2.x + num4, rect2.y + num3, num, num);
if (Widgets.ButtonImage(rect9, !(pawn.jobs?.curDriver as JobDriver_Sex).neverendingsex ? this.LimitedTex : this.UnlimitedTex, true))
{
if (pawn.jobs?.curDriver is JobDriver_SexBaseInitiator)
{
(pawn.jobs?.curDriver as JobDriver_Sex).neverendingsex = !(pawn.jobs?.curDriver as JobDriver_Sex).neverendingsex;
if ((pawn.jobs?.curDriver as JobDriver_Sex).neverendingsex)
{
SoundDefOf.Tick_Low.PlayOneShotOnCamera(null);
}
else
{
SoundDefOf.Tick_High.PlayOneShotOnCamera(null);
}
}
}
TooltipHandler.TipRegionByKey(rect9, "RJW_SexGizmo_SexOverdriveTooltip");
}
//row2 toggle - HitPawn
if (pawn.jobs?.curDriver is JobDriver_SexBaseInitiator) //TODO: maybe allow for receiver control someday?
{
if ((pawn.jobs?.curDriver as JobDriver_Sex).Sexprops != null)
if ((pawn.jobs?.curDriver as JobDriver_Sex).Sexprops.isRapist) //TODO: beating interrupts loving, fix someday?
{
float num = 32f;
float num2 = 34f;
float num3 = rect2.height / 2f - num + num2;
float num4 = rect2.width - num;
Rect rect11 = new Rect(rect2.x + num4, rect2.y + num3, num, num);
if (Widgets.ButtonImage(rect11, AttackTex, true))
{
(pawn.jobs?.curDriver as JobDriver_Sex).beatonce = true;
//SexUtility.Sex_Beatings_Dohit(pawn, ((JobDriver_Sex)pawn.jobs?.curDriver).Partner, ((JobDriver_Sex)pawn.jobs?.curDriver).isRape);
SoundDefOf.Tick_High.PlayOneShotOnCamera(null);
}
TooltipHandler.TipRegionByKey(rect11, "RJW_SexGizmo_HitPawn");
}
}
}
}
return new GizmoResult(GizmoState.Clear);
}
public override float GetWidth(float maxWidth)
{
return 212f;
}
private Pawn pawn;
private Texture2D LimitedTex;
private Texture2D UnlimitedTex;
private Texture2D AttackTex;
private const string LimitedIconPath = "UI/Icons/EntropyLimit/Limited";
private const string UnlimitedIconPath = "UI/Icons/EntropyLimit/Unlimited";
private const string AttackIconPath = "UI/Icons/HostilityResponse/Attack";
private static readonly Color PainBoostColor = new Color(0.2f, 0.65f, 0.35f);
private static readonly Texture2D EntropyBarTex = SolidColorMaterials.NewSolidColorTexture(new Color(0.46f, 0.34f, 0.35f));
private static readonly Texture2D OverLimitBarTex = SolidColorMaterials.NewSolidColorTexture(new Color(0.75f, 0.2f, 0.15f));
private static readonly Texture2D PsyfocusBarTex = SolidColorMaterials.NewSolidColorTexture(new Color(0.34f, 0.42f, 0.43f));
private static readonly Texture2D EmptyBarTex = SolidColorMaterials.NewSolidColorTexture(new Color(0.03f, 0.035f, 0.05f));
}
}
| Korth95/rjw | 1.5/Source/Common/SexGizmo.cs | C# | mit | 6,579 |
namespace rjw
{
public enum SexPartType : byte
{
Anus = 0,
FemaleBreast = 1,
FemaleGenital = 2,
MaleBreast = 3,
MaleGenital = 4
}
}
| Korth95/rjw | 1.5/Source/Common/SexPartType.cs | C# | mit | 148 |
using System;
using Verse;
namespace rjw
{
public static class SexPartTypeExtensions
{
public static BodyPartDef GetBodyPartDef(this SexPartType sexPartType)
{
return sexPartType switch
{
SexPartType.Anus => xxx.anusDef,
SexPartType.FemaleBreast => xxx.breastsDef,
SexPartType.FemaleGenital => xxx.genitalsDef,
SexPartType.MaleBreast => xxx.breastsDef,
SexPartType.MaleGenital => xxx.genitalsDef,
_ => throw new ArgumentException($"Unrecognized sexPartType: {sexPartType}")
};
}
}
}
| Korth95/rjw | 1.5/Source/Common/SexPartTypeExtensions.cs | C# | mit | 529 |
using RimWorld;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace rjw
{
/// <summary>
/// Compares traits for equality but ignores forsed flag
/// </summary>
class TraitComparer : IEqualityComparer<Trait>
{
bool ignoreForced;
bool ignoreDegree;
public TraitComparer(bool ignoreDegree = false, bool ignoreForced = true)
{
this.ignoreDegree = ignoreDegree;
this.ignoreForced = ignoreForced;
}
public bool Equals(Trait x, Trait y)
{
return
x.def == y.def &&
(ignoreDegree || (x.Degree == y.Degree)) &&
(ignoreForced || (x.ScenForced == y.ScenForced));
}
public int GetHashCode(Trait obj)
{
return
(obj.def.GetHashCode() << 5) +
(ignoreDegree ? 0 : obj.Degree) +
((ignoreForced || obj.ScenForced) ? 0 : 0x10);
}
}
}
| Korth95/rjw | 1.5/Source/Common/TraitComparer.cs | C# | mit | 829 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace rjw
{
public static class Unprivater
{
internal const BindingFlags flags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
/// <summary>
/// T is for returned type. For instance-class fields
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fieldName"></param>
/// <param name="obj"></param>
/// <returns></returns>
public static T GetProtectedValue<T>(string fieldName, object obj)
{
var fieldinfo = obj.GetType().GetField(fieldName, flags);
var readData = fieldinfo.GetValue(obj);
if (readData is T)
{
return (T)readData;
}
else
{
try
{
return (T)Convert.ChangeType(readData, typeof(T));
}
catch (InvalidCastException)
{
return default(T);
}
}
}
public static bool SetProtectedValue(string fieldName, object obj, object value)
{
var fieldinfo = obj.GetType().GetField(fieldName, flags);
try
{
fieldinfo.SetValue(obj, value);
return true;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// T is for returned type. For instance-class properties ( [ get; thingies ] )
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fieldName"></param>
/// <param name="obj"></param>
/// <returns></returns>
public static T GetProtectedProperty<T>(string propertyName, object obj)
{
var propinfo = obj.GetType().GetProperty(propertyName, flags);
var getter = propinfo.GetGetMethod(nonPublic: true);
var readData = getter.Invoke(obj, null);
if (readData is T)
{
return (T)readData;
}
else
{
try
{
return (T)Convert.ChangeType(readData, typeof(T));
}
catch (InvalidCastException)
{
return default(T);
}
}
}
public static bool SetProtectedProperty(string propertyName, object obj, object value)
{
var propinfo = obj.GetType().GetProperty(propertyName, flags);
try
{
propinfo.SetValue(obj, value, null);
return true;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// T is for returned type. For static-class fields
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fieldName"></param>
/// <param name="t"></param>
/// <returns></returns>
public static T GetProtectedValue<T>(string fieldName, Type t)
{
var fieldinfo = t.GetField(fieldName, flags);
var readData = fieldinfo.GetValue(null);
if (readData is T)
{
return (T)readData;
}
else
{
try
{
return (T)Convert.ChangeType(readData, typeof(T));
}
catch (InvalidCastException)
{
return default(T);
}
}
}
public static bool SetProtectedValue(string fieldName, Type t, object value)
{
var fieldinfo = t.GetField(fieldName, flags);
try
{
fieldinfo.SetValue(null, value);
return true;
}
catch (Exception)
{
return false;
}
}
// needs testing, dunno if it works for statics
public static T GetProtectedProperty<T>(string propertyName, Type t)
{
var propinfo = t.GetProperty(propertyName, flags);
var getter = propinfo.GetGetMethod(nonPublic: true);
var readData = getter.Invoke(null, null);
if (readData is T)
{
return (T)readData;
}
else
{
try
{
return (T)Convert.ChangeType(readData, typeof(T));
}
catch (InvalidCastException)
{
return default(T);
}
}
}
}
}
| Korth95/rjw | 1.5/Source/Common/Unprivater.cs | C# | mit | 3,622 |
namespace rjw
{
/*This is useless for now.
public class Verb_Fuck : Verb
{
private const int TargetCooldown = 40;
protected override bool TryCastShot()
{
Pawn casterPawn = base.CasterPawn;
Thing thing = this.currentTarget.Thing;
casterpawn.rotationTracker.Face(thing.DrawPos);
this.SoundJuicy().PlayOneShot(new TargetInfo(thing.Position, casterPawn.Map, false));
casterPawn.Drawer.Notify_MeleeAttackOn(thing);
casterpawn.rotationTracker.FaceCell(thing.Position);
if (casterPawn.caller != null) {
casterPawn.caller.Notify_DidMeleeAttack();
}
return true;
}
private SoundDef SoundJuicy()
{
return SoundDef.Named ("Sex");
}
}
*/
} | Korth95/rjw | 1.5/Source/Common/Verb_Fuck.cs | C# | mit | 688 |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Diagnostics;
using HarmonyLib;
using RimWorld;
using UnityEngine;
using Verse;
using Verse.AI;
using Verse.AI.Group;
using Verse.Sound;
using Multiplayer.API;
using System.Collections.ObjectModel;
//using static RimWorld.Planet.CaravanInventoryUtility;
namespace rjw
{
public static class xxx
{
public static readonly BindingFlags ins_public_or_no = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
public static readonly config config = DefDatabase<config>.GetNamed("the_one");
//HARDCODED MAGIC USED ACROSS DOZENS OF FILES, this is as bad place to put it as any other
//Should at the very least be encompassed in the related designation type
public static readonly int max_rapists_per_prisoner = 6;
//CombatExtended
public static bool CombatExtendedIsActive;
public static HediffDef MuscleSpasms;
//RomanceDiversified
public static bool RomanceDiversifiedIsActive; //A dirty way to check if the mod is active
public static TraitDef straight;
public static TraitDef faithful;
public static TraitDef philanderer;
public static TraitDef polyamorous;
//Psychology
public static bool PsychologyIsActive;
public static TraitDef prude;
public static TraitDef lecher;
public static TraitDef polygamous;
//Other poly mods
public static bool AnyPolyamoryModIsActive;
public static bool AnyPolygamyModIsActive;
//[SYR] Individuality
public static bool IndividualityIsActive;
public static TraitDef SYR_CreativeThinker;
public static TraitDef SYR_Haggler;
//Rimworld of Magic
public static bool RoMIsActive;
public static TraitDef Succubus;
public static TraitDef Warlock;
public static NeedDef TM_Mana;
public static HediffDef TM_ShapeshiftHD;
//Nightmare Incarnation
public static bool NightmareIncarnationIsActive;
public static NeedDef NI_Need_Mana;
//Consolidated
public static bool CTIsActive;
public static TraitDef RCT_NeatFreak;
public static TraitDef RCT_Savant;
public static TraitDef RCT_Inventor;
public static TraitDef RCT_AnimalLover;
//SimpleSlavery
public static bool SimpleSlaveryIsActive;
public static HediffDef Enslaved;
//Dubs Bad Hygiene
public static bool DubsBadHygieneIsActive;
public static NeedDef DBHThirst;
//Alien Framework
public static bool AlienFrameworkIsActive;
public static TraitDef xenophobia; // Degrees: 1: xenophobe, -1: xenophile
//Immortals
public static bool ImmortalsIsActive;
public static HediffDef IH_Immortal;
//RJW-EX
public static bool RjwExIsActive;
public static HediffDef RjwEx_Armbinder;
//RJW Children
public static HediffDef RJW_BabyState = DefDatabase<HediffDef>.GetNamed("RJW_BabyState");
public static HediffDef RJW_NoManipulationFlag = DefDatabase<HediffDef>.GetNamed("RJW_NoManipulationFlag");
//rjw
public static readonly TraitDef nymphomaniac = DefDatabase<TraitDef>.GetNamed("Nymphomaniac");
public static readonly TraitDef rapist = DefDatabase<TraitDef>.GetNamed("Rapist");
public static readonly TraitDef masochist = DefDatabase<TraitDef>.GetNamed("Masochist");
public static readonly TraitDef necrophiliac = DefDatabase<TraitDef>.GetNamed("Necrophiliac");
public static readonly TraitDef zoophile = DefDatabase<TraitDef>.GetNamed("Zoophile");
public static readonly TraitDef footSlut = DefDatabase<TraitDef>.GetNamed("FootSlut");
public static readonly TraitDef cumSlut = DefDatabase<TraitDef>.GetNamed("CumSlut");
public static readonly TraitDef buttSlut = DefDatabase<TraitDef>.GetNamed("ButtSlut");
//The Hediff to prevent reproduction
public static readonly HediffDef sterilized = DefDatabase<HediffDef>.GetNamed("Sterilized");
//The Hediff for broken body(resulted from being raped as CP for too many times)
public static readonly HediffDef feelingBroken = DefDatabase<HediffDef>.GetNamed("FeelingBroken");
public static readonly HediffDef submitting = DefDatabase<HediffDef>.GetNamed("Hediff_Submitting");
public static PawnCapacityDef reproduction = DefDatabase<PawnCapacityDef>.GetNamed("RJW_Fertility");
//rjw Body parts
public static readonly BodyPartDef genitalsDef = DefDatabase<BodyPartDef>.GetNamed("Genitals");
public static readonly BodyPartDef breastsDef = DefDatabase<BodyPartDef>.GetNamed("Chest");
public static readonly BodyPartDef anusDef = DefDatabase<BodyPartDef>.GetNamed("Anus");
//aftersex thoughts
public static readonly ThoughtDef got_raped = DefDatabase<ThoughtDef>.GetNamed("GotRaped");
public static readonly ThoughtDef got_anal_raped = DefDatabase<ThoughtDef>.GetNamed("GotAnalRaped");
public static readonly ThoughtDef got_anal_raped_byfemale = DefDatabase<ThoughtDef>.GetNamed("GotAnalRapedByFemale");
public static readonly ThoughtDef got_raped_unconscious = DefDatabase<ThoughtDef>.GetNamed("GotRapedUnconscious");
public static readonly ThoughtDef masochist_got_raped_unconscious = DefDatabase<ThoughtDef>.GetNamed("MasochistGotRapedUnconscious");
public static readonly ThoughtDef got_bred = DefDatabase<ThoughtDef>.GetNamed("GotBredByAnimal");
public static readonly ThoughtDef got_anal_bred = DefDatabase<ThoughtDef>.GetNamed("GotAnalBredByAnimal");
public static readonly ThoughtDef got_licked = DefDatabase<ThoughtDef>.GetNamed("GotLickedByAnimal");
public static readonly ThoughtDef got_groped = DefDatabase<ThoughtDef>.GetNamed("GotGropedByAnimal");
public static readonly ThoughtDef masochist_got_raped = DefDatabase<ThoughtDef>.GetNamed("MasochistGotRaped");
public static readonly ThoughtDef masochist_got_anal_raped = DefDatabase<ThoughtDef>.GetNamed("MasochistGotAnalRaped");
public static readonly ThoughtDef masochist_got_anal_raped_byfemale = DefDatabase<ThoughtDef>.GetNamed("MasochistGotAnalRapedByFemale");
public static readonly ThoughtDef masochist_got_bred = DefDatabase<ThoughtDef>.GetNamed("MasochistGotBredByAnimal");
public static readonly ThoughtDef masochist_got_anal_bred = DefDatabase<ThoughtDef>.GetNamed("MasochistGotAnalBredByAnimal");
public static readonly ThoughtDef masochist_got_licked = DefDatabase<ThoughtDef>.GetNamed("MasochistGotLickedByAnimal");
public static readonly ThoughtDef masochist_got_groped = DefDatabase<ThoughtDef>.GetNamed("MasochistGotGropedByAnimal");
public static readonly ThoughtDef allowed_animal_to_breed = DefDatabase<ThoughtDef>.GetNamed("AllowedAnimalToBreed");
public static readonly ThoughtDef allowed_animal_to_lick = DefDatabase<ThoughtDef>.GetNamed("AllowedAnimalToLick");
public static readonly ThoughtDef allowed_animal_to_grope = DefDatabase<ThoughtDef>.GetNamed("AllowedAnimalToGrope");
public static readonly ThoughtDef zoophile_got_bred = DefDatabase<ThoughtDef>.GetNamed("ZoophileGotBredByAnimal");
public static readonly ThoughtDef zoophile_got_anal_bred = DefDatabase<ThoughtDef>.GetNamed("ZoophileGotAnalBredByAnimal");
public static readonly ThoughtDef zoophile_got_licked = DefDatabase<ThoughtDef>.GetNamed("ZoophileGotLickedByAnimal");
public static readonly ThoughtDef zoophile_got_groped = DefDatabase<ThoughtDef>.GetNamed("ZoophileGotGropedByAnimal");
public static readonly ThoughtDef hate_my_rapist = DefDatabase<ThoughtDef>.GetNamed("HateMyRapist");
public static readonly ThoughtDef kinda_like_my_rapist = DefDatabase<ThoughtDef>.GetNamed("KindaLikeMyRapist");
public static readonly ThoughtDef allowed_me_to_get_raped = DefDatabase<ThoughtDef>.GetNamed("AllowedMeToGetRaped");
public static readonly ThoughtDef stole_some_lovin = DefDatabase<ThoughtDef>.GetNamed("StoleSomeLovin");
public static readonly ThoughtDef bloodlust_stole_some_lovin = DefDatabase<ThoughtDef>.GetNamed("BloodlustStoleSomeLovin");
public static readonly ThoughtDef violated_corpse = DefDatabase<ThoughtDef>.GetNamed("ViolatedCorpse");
public static readonly ThoughtDef gave_virginity = DefDatabase<ThoughtDef>.GetNamed("FortunateGaveVirginity");
public static readonly ThoughtDef lost_virginity = DefDatabase<ThoughtDef>.GetNamed("UnfortunateLostVirginity");
public static readonly ThoughtDef took_virginity = DefDatabase<ThoughtDef>.GetNamed("TookVirginity");
public static readonly JobDef Masturbate = DefDatabase<JobDef>.GetNamed("RJW_Masturbate");
public static readonly JobDef casual_sex = DefDatabase<JobDef>.GetNamed("JoinInBed");
public static readonly JobDef knotted = DefDatabase<JobDef>.GetNamed("RJW_Knotted");
public static readonly JobDef gettin_loved = DefDatabase<JobDef>.GetNamed("GettinLoved");
public static readonly JobDef gettin_raped = DefDatabase<JobDef>.GetNamed("GettinRaped");
public static readonly JobDef gettin_bred = DefDatabase<JobDef>.GetNamed("GettinBred");
public static readonly JobDef RapeCP = DefDatabase<JobDef>.GetNamed("RapeComfortPawn");
public static readonly JobDef RapeEnemy = DefDatabase<JobDef>.GetNamed("RapeEnemy");
public static readonly JobDef RapeRandom = DefDatabase<JobDef>.GetNamed("RandomRape");
public static readonly JobDef RapeCorpse = DefDatabase<JobDef>.GetNamed("ViolateCorpse");
public static readonly JobDef bestiality = DefDatabase<JobDef>.GetNamed("Bestiality");
public static readonly JobDef bestialityForFemale = DefDatabase<JobDef>.GetNamed("BestialityForFemale");
public static readonly JobDef whore_inviting_visitors = DefDatabase<JobDef>.GetNamedSilentFail("WhoreInvitingVisitors");
public static readonly JobDef whore_is_serving_visitors = DefDatabase<JobDef>.GetNamedSilentFail("WhoreIsServingVisitors");
public static readonly JobDef animalMate = DefDatabase<JobDef>.GetNamed("RJW_Mate");
public static readonly JobDef animalBreed = DefDatabase<JobDef>.GetNamed("Breed");
public static readonly JobDef quick_sex = DefDatabase<JobDef>.GetNamed("Quickie");
public static readonly JobDef getting_quickie = DefDatabase<JobDef>.GetNamed("GettingQuickie");
public static readonly JobDef struggle_in_BondageGear = DefDatabase<JobDef>.GetNamed("StruggleInBondageGear");
public static readonly JobDef unlock_BondageGear = DefDatabase<JobDef>.GetNamed("UnlockBondageGear");
public static readonly JobDef give_BondageGear = DefDatabase<JobDef>.GetNamed("GiveBondageGear");
public static readonly FleckDef mote_noheart = DefDatabase<FleckDef>.GetNamed("Mote_NoHeart");
public static readonly StatDef sex_satisfaction = DefDatabase<StatDef>.GetNamed("SexSatisfaction");
public static readonly StatDef vulnerability_stat = DefDatabase<StatDef>.GetNamed("Vulnerability");
public static readonly StatDef sex_drive_stat = DefDatabase<StatDef>.GetNamed("SexFrequency");
public static readonly RecordDef GetRapedAsComfortPawn = DefDatabase<RecordDef>.GetNamed("GetRapedAsComfortPrisoner");
public static readonly RecordDef CountOfFappin = DefDatabase<RecordDef>.GetNamed("CountOfFappin");
public static readonly RecordDef CountOfSex = DefDatabase<RecordDef>.GetNamed("CountOfSex");
public static readonly RecordDef CountOfSexWithHumanlikes = DefDatabase<RecordDef>.GetNamed("CountOfSexWithHumanlikes");
public static readonly RecordDef CountOfSexWithAnimals = DefDatabase<RecordDef>.GetNamed("CountOfSexWithAnimals");
public static readonly RecordDef CountOfSexWithInsects = DefDatabase<RecordDef>.GetNamed("CountOfSexWithInsects");
public static readonly RecordDef CountOfSexWithOthers = DefDatabase<RecordDef>.GetNamed("CountOfSexWithOthers");
public static readonly RecordDef CountOfSexWithCorpse = DefDatabase<RecordDef>.GetNamed("CountOfSexWithCorpse");
public static readonly RecordDef CountOfRapedHumanlikes = DefDatabase<RecordDef>.GetNamed("CountOfRapedHumanlikes");
public static readonly RecordDef CountOfBeenRapedByHumanlikes = DefDatabase<RecordDef>.GetNamed("CountOfBeenRapedByHumanlikes");
public static readonly RecordDef CountOfRapedAnimals = DefDatabase<RecordDef>.GetNamed("CountOfRapedAnimals");
public static readonly RecordDef CountOfBeenRapedByAnimals = DefDatabase<RecordDef>.GetNamed("CountOfBeenRapedByAnimals");
public static readonly RecordDef CountOfRapedInsects = DefDatabase<RecordDef>.GetNamed("CountOfRapedInsects");
public static readonly RecordDef CountOfBeenRapedByInsects = DefDatabase<RecordDef>.GetNamed("CountOfBeenRapedByInsects");
public static readonly RecordDef CountOfRapedOthers = DefDatabase<RecordDef>.GetNamed("CountOfRapedOthers");
public static readonly RecordDef CountOfBeenRapedByOthers = DefDatabase<RecordDef>.GetNamed("CountOfBeenRapedByOthers");
public static readonly RecordDef CountOfBirthHuman = DefDatabase<RecordDef>.GetNamed("CountOfBirthHuman");
public static readonly RecordDef CountOfBirthAnimal = DefDatabase<RecordDef>.GetNamed("CountOfBirthAnimal");
public static readonly RecordDef CountOfBirthEgg = DefDatabase<RecordDef>.GetNamed("CountOfBirthEgg");
public static readonly MeditationFocusDef SexMeditationFocus = DefDatabase<MeditationFocusDef>.GetNamed("Sex");
public enum rjwSextype { None, Vaginal, Anal, Oral, Masturbation, DoublePenetration, Boobjob, Handjob, Footjob, Fingering, Scissoring, MutualMasturbation, Fisting, MechImplant, Rimming, Fellatio, Cunnilingus, Sixtynine }
public static readonly ReadOnlyCollection <rjwSextype> rjwSextypeCollection = Array.AsReadOnly((rjwSextype[])Enum.GetValues(typeof(rjwSextype)));
public static void bootstrap(Map m)
{
if (m.GetComponent<MapCom_Injector>() == null)
m.components.Add(new MapCom_Injector(m));
}
//<Summary>Simple method that quickly checks for match from a list.</Summary>
public static bool ContainsAny(this string haystack, params string[] needles) { return needles.Any(haystack.Contains); }
public static bool has_traits(Pawn pawn)
{
return pawn?.story?.traits != null;
}
public static bool has_quirk(Pawn pawn, string quirk)
{
return pawn != null && is_human(pawn) && CompRJW.Comp(pawn).quirks.ToString().Contains(quirk);
}
[SyncMethod]
public static string random_pick_a_trait(this Pawn pawn)
{
//Rand.PopState();
//Rand.PushState(RJW_Multiplayer.PredictableSeed());
return has_traits(pawn) ? pawn.story.traits.allTraits.RandomElement().def.defName : null;
}
public static bool is_psychopath(Pawn pawn)
{
return has_traits(pawn) && pawn.story.traits.HasTrait(TraitDefOf.Psychopath);
}
public static bool is_ascetic(Pawn pawn)
{
return has_traits(pawn) && pawn.story.traits.HasTrait(TraitDefOf.Ascetic);
}
public static bool is_bloodlust(Pawn pawn)
{
return has_traits(pawn) && pawn.story.traits.HasTrait(TraitDefOf.Bloodlust);
}
public static bool is_brawler(Pawn pawn)
{
return has_traits(pawn) && pawn.story.traits.HasTrait(TraitDefOf.Brawler);
}
public static bool is_kind(Pawn pawn)
{
return has_traits(pawn) && pawn.story.traits.HasTrait(TraitDefOf.Kind);
}
public static bool is_rapist(Pawn pawn)
{
return has_traits(pawn) && pawn.story.traits.HasTrait(rapist);
}
public static bool is_necrophiliac(Pawn pawn)
{
return has_traits(pawn) && pawn.story.traits.HasTrait(necrophiliac);
}
public static bool is_zoophile(Pawn pawn)
{
return has_traits(pawn) && pawn.story.traits.HasTrait(zoophile);
}
public static bool is_masochist(Pawn pawn)
{
return has_traits(pawn) && pawn.story.traits.HasTrait(TraitDef.Named("Masochist"));
}
/// <summary>
/// Returns true if the given pawn has the nymphomaniac trait.
/// This may or may not be a nymph pawnKind.
/// </summary>
public static bool is_nympho(Pawn pawn)
{
return has_traits(pawn) && pawn.story.traits.HasTrait(nymphomaniac);
}
public static bool is_slime(Pawn pawn)
{
string racename = pawn.kindDef.race.defName.ToLower();
//if (Prefs.DevMode) ModLog.Message(" is_slime " + xxx.get_pawnname(pawn) + " " + racename.Contains("slime"));
return racename.Contains("slime");
}
public static bool is_demon(Pawn pawn)
{
string racename = pawn.kindDef.race.defName.ToLower();
//if (Prefs.DevMode) ModLog.Message(" is_demon " + xxx.get_pawnname(pawn) + " " + racename.Contains("demon"));
return racename.Contains("demon");
}
public static bool is_asexual(Pawn pawn) => CompRJW.Comp(pawn).orientation == Orientation.Asexual;
public static bool is_bisexual(Pawn pawn) => CompRJW.Comp(pawn).orientation == Orientation.Bisexual;
public static bool is_homosexual(Pawn pawn) => (CompRJW.Comp(pawn).orientation == Orientation.Homosexual || CompRJW.Comp(pawn).orientation == Orientation.MostlyHomosexual);
public static bool is_heterosexual(Pawn pawn) => (CompRJW.Comp(pawn).orientation == Orientation.Heterosexual || CompRJW.Comp(pawn).orientation == Orientation.MostlyHeterosexual);
public static bool is_pansexual(Pawn pawn) => CompRJW.Comp(pawn).orientation == Orientation.Pansexual;
public static bool is_slave(Pawn pawn)
{
if (is_vanillaslave(pawn) || is_modslave(pawn))
return true;
else
return false;
}
public static bool is_vanillaslave(Pawn pawn)
{
if (pawn.IsSlave)//1.3
return true;
else
return false;
}
public static bool is_modslave(Pawn pawn)
{
if (SimpleSlaveryIsActive)
return pawn?.health.hediffSet.HasHediff(xxx.Enslaved) ?? false;
else
return false;
}
public static bool is_nympho_or_rapist_or_zoophile(Pawn pawn)
{
if (!has_traits(pawn)) { return false; }
return (is_rapist(pawn) || is_nympho(pawn) || is_zoophile(pawn));
}
//Humanoid Alien Framework traits
public static bool is_xenophile(Pawn pawn)
{
if (!has_traits(pawn) || !AlienFrameworkIsActive) { return false; }
return pawn.story.traits.DegreeOfTrait(xenophobia) == -1;
}
public static bool is_xenophobe(Pawn pawn)
{
if (!has_traits(pawn) || !AlienFrameworkIsActive) { return false; }
return pawn.story.traits.DegreeOfTrait(xenophobia) == 1;
}
public static bool is_whore(Pawn pawn)
{
if (!has_traits(pawn)) { return false; }
return pawn != null && pawn.IsDesignatedService() && !pawn.story.traits.HasTrait(TraitDefOf.Asexual);
//return (pawn != null && pawn.ownership != null && pawn.ownership.OwnedBed is Building_WhoreBed && (!xxx.RomanceDiversifiedIsActive || !pawn.story.traits.HasTrait(xxx.asexual)));
}
public static bool is_lecher(Pawn pawn)
{
if (!has_traits(pawn)) { return false; }
return RomanceDiversifiedIsActive && pawn.story.traits.HasTrait(philanderer) || PsychologyIsActive && pawn.story.traits.HasTrait(lecher);
}
public static bool is_prude(Pawn pawn)
{
if (!has_traits(pawn)) { return false; }
if (is_nympho(pawn)) { return false; }
if (pawn.IsIdeologicallyPrudish()) { return true; }
return RomanceDiversifiedIsActive && pawn.story.traits.HasTrait(faithful) || PsychologyIsActive && pawn.story.traits.HasTrait(prude);
}
public static bool is_animal(Pawn pawn)
{
return pawn?.RaceProps?.Animal ?? false;
}
public static bool is_insect(Pawn pawn)
{
if (pawn == null) return false;
bool isit = pawn.RaceProps.FleshType == FleshTypeDefOf.Insectoid
|| pawn.RaceProps.FleshType.corpseCategory.ToString().Contains("CorpsesInsect")
//genetic rim
|| pawn.RaceProps.FleshType.defName.Contains("GR_Insectoid");
//Log.Message("is_insect " + get_pawnname(pawn) + " - " + isit);
return isit;
}
public static bool is_mechanoid(Pawn pawn)
{
if (pawn == null) return false;
if (AndroidsCompatibility.IsAndroid(pawn)) return false;
bool isit = pawn.RaceProps.IsMechanoid
|| pawn.RaceProps.FleshType == FleshTypeDefOf.Mechanoid
|| pawn.RaceProps.FleshType.corpseCategory.ToString().Contains("CorpsesMechanoid")
//genetic rim
|| pawn.RaceProps.FleshType.defName.Contains("GR_Mechanoid")
//android tiers
|| pawn.RaceProps.FleshType.defName.Contains("MechanisedInfantry")
|| pawn.RaceProps.FleshType.defName.Contains("Android")
;
//Log.Message("is_mechanoid " + get_pawnname(pawn) + " - " + isit);
return isit;
}
public static bool is_tooluser(Pawn pawn)
{
return pawn.RaceProps.ToolUser;
}
public static bool is_human(Pawn pawn)
{
if (pawn == null) return false;
return pawn.RaceProps.Humanlike;
}
public static bool is_female(Pawn pawn)
{
return pawn.gender == Gender.Female;
}
public static bool is_male(Pawn pawn)
{
return pawn.gender == Gender.Male;
}
public static bool is_healthy(Pawn pawn)
{
return !pawn.Dead &&
pawn.health.capacities.CanBeAwake &&
pawn.health.hediffSet.BleedRateTotal <= 0.0f &&
pawn.health.hediffSet.PainTotal < config.significant_pain_threshold;
}
/// <summary>
/// not going to die soon
/// </summary>
/// <param name="pawn"></param>
/// <returns></returns>
public static bool is_healthy_enough(Pawn pawn)
{
return !pawn.Dead &&
pawn.health.capacities.CanBeAwake &&
pawn.health.hediffSet.BleedRateTotal <= 0.1f;
}
/// <summary>
/// pawn can initiate action or respond - whoring, etc
/// </summary>
public static bool IsTargetPawnOkay(Pawn pawn)
{
return xxx.is_healthy(pawn) && !pawn.Downed && !pawn.Suspended;
}
public static bool is_not_dying(Pawn pawn)
{
return !pawn.Dead &&
pawn.health.hediffSet.BleedRateTotal <= 0.3f;
}
public static bool is_starved(Pawn pawn)
{
return pawn?.needs?.food != null &&
pawn.needs.food.Starving;
}
public static float bleedingRate(Pawn pawn)
{
return pawn?.health?.hediffSet?.BleedRateTotal ?? 0f;
}
public static string get_pawnname(Pawn who)
{
//ModLog.Message("xxx::get_pawnname is "+ who.KindLabelDefinite());
//ModLog.Message("xxx::get_pawnname is "+ who.KindLabelIndefinite());
if (who == null) return "null";
string name = who.Label;
if (name != null)
{
if (who.Name?.ToStringShort != null)
name = who.Name.ToStringShort;
}
else
name = "noname";
return name;
}
public static bool is_gettin_rapedNow(Pawn pawn)
{
if (pawn?.jobs?.curDriver != null)
{
return pawn.jobs.curDriver.GetType() == typeof(JobDriver_SexBaseRecieverRaped);
}
return false;
}
//cells checks are cheap, pathing is expensive. Do pathing check last.)
public static float need_some_sex(Pawn pawn)
{
// 3=> always horny for non humanlikes
float horniness_degree = 3f;
Need_Sex need_sex = pawn.needs.TryGetNeed<Need_Sex>();
if (need_sex == null) return horniness_degree;
if (need_sex.CurLevel < need_sex.thresh_frustrated()) horniness_degree = 3f;
else if (need_sex.CurLevel < need_sex.thresh_horny()) horniness_degree = 2f;
else if (need_sex.CurLevel < need_sex.thresh_satisfied()) horniness_degree = 1f;
else horniness_degree = 0f;
return horniness_degree;
}
public enum SexNeed
{
Frustrated,
Horny,
Neutral,
Satisfied
};
public static SexNeed need_sex(Pawn pawn)
{
// 3=> always horny for non humanlikes, since they dont have need
Need_Sex need_sex = pawn.needs.TryGetNeed<Need_Sex>();
if (need_sex == null) return SexNeed.Frustrated;
if (RJWSettings.sexneed_fix)
return need_sex_fixed(pawn);
else
return need_sex_broken(pawn);
}
/// <summary>
/// Original rjw threshholds for sex
/// </summary>
/// <param name="pawn"></param>
/// <returns></returns>
private static SexNeed need_sex_broken(Pawn pawn)
{
Need_Sex need_sex = pawn.needs.TryGetNeed<Need_Sex>();
if (need_sex.CurLevel >= need_sex.thresh_satisfied())
return SexNeed.Satisfied;
else if (need_sex.CurLevel >= need_sex.thresh_neutral())
return SexNeed.Neutral;
else if (need_sex.CurLevel >= need_sex.thresh_horny())
return SexNeed.Horny;
else
return SexNeed.Frustrated;
}
private static SexNeed need_sex_fixed(Pawn pawn)
{
// 3=> always horny for non humanlikes
Need_Sex need_sex = pawn.needs.TryGetNeed<Need_Sex>();
if (need_sex.CurLevel <= need_sex.thresh_frustrated())
return SexNeed.Frustrated;
else if (need_sex.CurLevel <= need_sex.thresh_horny())
return SexNeed.Horny;
else if (need_sex.CurLevel <= need_sex.thresh_neutral())
return SexNeed.Neutral;
else
return SexNeed.Satisfied;
}
public static bool is_frustrated(Pawn pawn)
{
return need_sex(pawn) == SexNeed.Frustrated;
}
public static bool is_horny(Pawn pawn)
{
return need_sex(pawn) == SexNeed.Horny;
}
public static bool is_hornyorfrustrated(Pawn pawn)
{
return (need_sex(pawn) == SexNeed.Horny || need_sex(pawn) == SexNeed.Frustrated);
}
public static bool is_neutral(Pawn pawn)
{
return need_sex(pawn) == SexNeed.Neutral;
}
public static bool is_satisfied(Pawn pawn)
{
return need_sex(pawn) == SexNeed.Satisfied;
}
/// <summary> Checks to see if the pawn has any partners who don't have a Polyamorous/Polygamous trait or ideo; aka someone who'd get mad about sleeping around. </summary>
/// <returns> True if the pawn has at least one romantic partner who does not have a poly trait or ideo. False if no partners or all partners are poly. </returns>
public static bool HasNonPolyPartner(Pawn pawn, bool onCurrentMap = false)
{
if (pawn.relations == null) // probably droids or who knows what modded abomination
return false;
var partners = LovePartnerRelationUtility.ExistingLovePartners(pawn, allowDead: false).Select(rel => rel.otherPawn);
// If they don't have a partner at all we can bail right away.
if (!partners.Any())
return false;
foreach (var partner in partners)
{
// Stasised partners will never find out!
if (partner.Suspended)
continue;
// Neither does anyone on another map because cheating away from home is obviously never ever discovered
if (onCurrentMap) // check only on Current Map
if (pawn.Map == null || partner.Map == null || partner.Map != pawn.Map)
continue;
if (partner.IsPoly())
{
// We have a partner who has a poly trait or ideo! But they could have multiple partners so keep checking.
continue;
}
// We found a partner who isn't poly.
return true;
}
// If we got here then we checked every partner and all of them had a poly trait, so they don't have a non-poly partner.
return false;
}
public static Gender opposite_gender(Gender g)
{
switch (g)
{
case Gender.Male:
return Gender.Female;
case Gender.Female:
return Gender.Male;
default:
return Gender.None;
}
}
public static float get_sex_satisfaction(Pawn pawn)
{
try
{
return pawn.GetStatValue(xxx.sex_satisfaction, false);
}
catch (NullReferenceException)
//not seeded with stats, error for non humanlikes/corpses
//this and below should probably be rewritten to do calculations here
{
//Log.Warning(e.ToString());
return 1f;
}
}
public static float get_vulnerability(Pawn pawn)
{
try
{
return pawn.GetStatValue(vulnerability_stat, false);
}
catch (NullReferenceException)
//not seeded with stats, error for non humanlikes/corpses
{
//Log.Warning(e.ToString());
return 1f;
}
}
public static float get_sex_drive(Pawn pawn)
{
try
{
return pawn.GetStatValue(sex_drive_stat, false) * (pawn.GetRJWPawnData().raceSexDrive);
}
catch (NullReferenceException)
//not seeded with stats, error for non humanlikes/corpses
{
//Log.Warning(e.ToString());
return 1f;
}
}
public static bool IsSingleOrPartnersNotHere(Pawn pawn)
{
var relations = LovePartnerRelationUtility.ExistingLovePartners(pawn, allowDead: false);
if (!relations.Any())
{
return true;
}
return relations.All(rel => rel.otherPawn.Map != pawn.Map);
}
//base check
public static bool can_do_loving(Pawn pawn)
{
if (is_mechanoid(pawn))
return false;
if (is_human(pawn))
{
var humansex = true;
//Log.Message("can_do_loving pawn " + pawn.Name);
//Log.Message(" AgeBiologicalYears " + pawn.ageTracker.AgeBiologicalYears);
//Log.Message(" CurLifeStage " + pawn.ageTracker.CurLifeStage.defName);
//Log.Message(" reproductive " + pawn.ageTracker.CurLifeStage.reproductive);
//Log.Message(" Growth " + pawn.ageTracker.Growth);
//Log.Message(" Adult " + pawn.ageTracker.Adult);
//foreach ( var stage in pawn.RaceProps.lifeStageAges)
//{
// Log.Message(" lifeStage ");
// Log.Message(" def " + stage.def);
// Log.Message(" minAge " + stage.minAge);
// Log.Message(" reproductive " + stage.def.reproductive);
// Log.Message(" milkable " + stage.def.milkable);
// Log.Message(" shearable " + stage.def.shearable);
//}
//vanilla like races with lifestages?
if (!(pawn.ageTracker.CurLifeStage.defName.ToLower().Contains("humanliketeenager") || pawn.ageTracker.CurLifeStage.defName.ToLower().Contains("adult")))
{
}
//racesupport override
if (pawn.GetRJWPawnData().RaceSupportDef?.teenAge != null && pawn.GetRJWPawnData().RaceSupportDef?.teenAge != 0)
{
int age = pawn.ageTracker.AgeBiologicalYears;
if (age < pawn.GetRJWPawnData().RaceSupportDef.teenAge)
humansex = false;
}
//everything else
else if (!pawn.ageTracker.CurLifeStage.reproductive)
if (pawn.ageTracker.Growth < 1)
humansex = false;
if (!pawn.apparel.WornApparel.NullOrEmpty())
if (pawn.apparel.WornApparel.Where(x => x.def.defName.ToLower().Contains("warcasket")).Any())
humansex = false;
return humansex;
}
if (is_animal(pawn))
{
if (pawn.GetRJWPawnData().RaceSupportDef?.teenAge != null && pawn.GetRJWPawnData().RaceSupportDef?.teenAge != 0)
{
int age = pawn.ageTracker.AgeBiologicalYears;
int t = pawn.GetRJWPawnData().RaceSupportDef.teenAge;
if (age < t)
return false;
}
//CurLifeStage/Growth for insects since they are not reproductive
else if (!pawn.ageTracker.CurLifeStage.reproductive)
if (pawn.ageTracker.Growth < 1)
return false;
return true;
}
return false;
}
public static bool can_do_animalsex(Pawn pawn1, Pawn pawn2)
{
bool v = false;
if (xxx.is_animal(pawn1) && xxx.is_animal(pawn2))
if (RJWSettings.animal_on_animal_enabled)
v = true;
else if (RJWSettings.bestiality_enabled)
v = true;
return v;
}
public static bool can_masturbate(Pawn pawn)
{
if (!RJWPreferenceSettings.FapInArmbinders)
if (Genital_Helper.hands_blocked(pawn))
return false;
if (!RJWPreferenceSettings.FapInBelts)
if (Genital_Helper.genitals_blocked(pawn))
return false;
if (!xxx.can_be_fucked(pawn) && !xxx.can_fuck(pawn)) //TODO: should improve this someday
return false;
return true;
}
// Penetrative organ check.
public static bool can_fuck(Pawn pawn)
{
//this may cause problems with human mechanoids, like misc. bots or other custom race mechanoids
if (is_mechanoid(pawn))
return true;
if (!can_do_loving(pawn))
return false;
var parts = pawn.GetGenitalsList();
if (Genital_Helper.penis_blocked(pawn) || (!Genital_Helper.has_penis_fertile(pawn, parts) && !Genital_Helper.has_penis_infertile(pawn, parts) && !Genital_Helper.has_ovipositorF(pawn, parts))) return false;
return true;
}
// Orifice check.
public static bool can_be_fucked(Pawn pawn)
{
if (is_mechanoid(pawn))
return false;
if (!can_do_loving(pawn))
return false;
if (Genital_Helper.has_anus(pawn) && !Genital_Helper.anus_blocked(pawn))
return true;
if (Genital_Helper.has_vagina(pawn) && !Genital_Helper.vagina_blocked(pawn))
return true;
if (Genital_Helper.has_mouth(pawn) && !Genital_Helper.oral_blocked(pawn))
return true;
//not sure about below, when female rape male, need to check all code so meh
//if ((Genital_Helper.has_penis(pawn) || Genital_Helper.has_penis_infertile(pawn) || Genital_Helper.has_ovipositorF(pawn)) && !Genital_Helper.penis_blocked(pawn))
// return true;
//if (Genital_Helper.has_breasts(pawn) && !Genital_Helper.breasts_blocked(pawn))
// return true;
//if (pawn.health.hediffSet.GetNotMissingParts().Any(part => part.IsInGroup(BodyPartGroupDefOf.RightHand) || part.IsInGroup(BodyPartGroupDefOf.LeftHand)) && !Genital_Helper.hands_blocked(pawn))
// return true;
return false;
}
public static bool can_rape(Pawn pawn, bool forced = false)
{
if (!RJWSettings.rape_enabled)
return false;
if (is_mechanoid(pawn))
return true;
if (!(can_fuck(pawn) ||
(!is_male(pawn) && get_vulnerability(pawn) < RJWSettings.nonFutaWomenRaping_MaxVulnerability && can_be_fucked(pawn))))
return false;
if (is_human(pawn))
{
if (pawn.ageTracker.Growth < 1 && !pawn.ageTracker.CurLifeStage.reproductive)
return false;
if (RJWSettings.WildMode || forced)
return true;
return need_some_sex(pawn) > 0;
}
return true;
}
public static bool can_get_raped(Pawn pawn)
{
if (!RJWSettings.rape_enabled)
return false;
if (!can_be_fucked(pawn))
return false;
if (is_human(pawn))
{
if (pawn.ageTracker.Growth < 1 && !pawn.ageTracker.CurLifeStage.reproductive)
return false;
if (RJWSettings.WildMode)
return true;
if (!(RJWSettings.rapee_MinVulnerability_human >= 0 && get_vulnerability(pawn) > RJWSettings.rapee_MinVulnerability_human))
return false;
}
return true;
}
public static bool is_Virgin(Pawn pawn)
{
//if (RJWSettings.DevMode) ModLog.Message("xxx::is_Virgin check:" +get_pawnname(pawn));
if (pawn.relations != null)
if (pawn.relations.ChildrenCount > 0)
{
//if (RJWSettings.DevMode) ModLog.Message("xxx::is_Virgin " + " ChildrenCount " + pawn.relations.ChildrenCount);
return false;
}
if (!(
pawn.records.GetValue(GetRapedAsComfortPawn) == 0 &&
pawn.records.GetValue(CountOfSex) == 0 &&
pawn.records.GetValue(CountOfSexWithHumanlikes) == 0 &&
pawn.records.GetValue(CountOfSexWithAnimals) == 0 &&
pawn.records.GetValue(CountOfSexWithInsects) == 0 &&
pawn.records.GetValue(CountOfSexWithOthers) == 0 &&
pawn.records.GetValue(CountOfSexWithCorpse) == 0 &&
//pawn.records.GetValue(CountOfWhore) == 0 &&
pawn.records.GetValue(CountOfRapedHumanlikes) == 0 &&
pawn.records.GetValue(CountOfBeenRapedByHumanlikes) == 0 &&
pawn.records.GetValue(CountOfRapedAnimals) == 0 &&
pawn.records.GetValue(CountOfBeenRapedByAnimals) == 0 &&
pawn.records.GetValue(CountOfRapedInsects) == 0 &&
pawn.records.GetValue(CountOfBeenRapedByInsects) == 0 &&
pawn.records.GetValue(CountOfRapedOthers) == 0 &&
pawn.records.GetValue(CountOfBeenRapedByOthers) == 0 &&
pawn.records.GetAsInt(xxx.CountOfBirthHuman) == 0 &&
pawn.records.GetAsInt(xxx.CountOfBirthAnimal) == 0 &&
pawn.records.GetAsInt(xxx.CountOfBirthEgg) == 0
))
{
//if (RJWSettings.DevMode) ModLog.Message("xxx::is_Virgin " + "records check fail");
return false;
}
return true;
}
}
}
| Korth95/rjw | 1.5/Source/Common/xxx.cs | C# | mit | 34,954 |
using Verse;
using System.Linq;
using RimWorld;
namespace rjw
{
[StaticConstructorOnStartup]
public static class AddComp
{
static AddComp()
{
AddRJWComp();
}
/// <summary>
/// This automatically adds the comp to all races on startup.
/// </summary>
public static void AddRJWComp()
{
foreach (ThingDef thingDef in DefDatabase<ThingDef>.AllDefs.Where(thingDef =>
thingDef.race != null))
{
thingDef.comps.Add(new CompProperties_RJW());
//Log.Message("AddRJWComp to race " + thingDef.label);
}
foreach (PawnKindDef pawnKindDef in DefDatabase<PawnKindDef>.AllDefs.Where(pawnKindDef => pawnKindDef.race.race != null))
{
RaceGroupDef raceGroupDef = null;
if (RaceGroupDef_Helper.TryGetRaceGroupDef(pawnKindDef, out raceGroupDef))
{
//Log.Message("RaceGroupDef_Helper " + raceGroupDef.defName + " for " + pawnKindDef.race.defName);
if (raceGroupDef.oviPregnancy)
{
if (pawnKindDef.race.comps.Any(x => x is CompProperties_EggLayer))
{
//Log.Message(pawnKindDef.race.defName + " was already egglayer");
}
else
{
CompProperties_EggLayer eggProps = OviHelper.GenerateEggLayerProperties(pawnKindDef, raceGroupDef);
pawnKindDef.race.comps.Add(eggProps);
//Log.Message(pawnKindDef.race.defName + " is now egglayer and lays " + eggProps.eggFertilizedDef.defName + " eggs");
}
}
}
}
// For some reason eggs only grow if a pawn has a lifestage that is "milkable"
// This might not be ideal...
foreach (LifeStageDef lifeStage in DefDatabase<LifeStageDef>.AllDefs)
{
if (lifeStage.reproductive)
{
lifeStage.milkable = true;
}
}
}
}
} | Korth95/rjw | 1.5/Source/Comps/CompAdder.cs | C# | mit | 1,705 |
using System.Collections.Generic;
using Verse;
namespace rjw
{
public class CompProperties_RJW : CompProperties
{
public CompProperties_RJW()
{
compClass = typeof(CompRJW);
}
}
public class CompProperties_ThingBodyPart : CompProperties
{
public HediffDef_SexPart hediffDef;
public bool guessHediffFromThingDef;
public CompProperties_ThingBodyPart()
{
compClass = typeof(CompThingBodyPart);
}
public override IEnumerable<string> ConfigErrors(ThingDef parentDef)
{
foreach (string err in base.ConfigErrors(parentDef))
{
yield return err;
}
if (hediffDef == null && !guessHediffFromThingDef)
{
yield return "<hediffDef> must not be null.";
}
}
// TODO: Stop guessing hediff from defName!
public override void ResolveReferences(ThingDef parentDef)
{
base.ResolveReferences(parentDef);
if (hediffDef == null && guessHediffFromThingDef)
{
hediffDef = (HediffDef_SexPart)HediffDef.Named(parentDef.defName);
}
}
}
} | Korth95/rjw | 1.5/Source/Comps/CompProperties.cs | C# | mit | 998 |
#nullable enable
using Psychology;
using SyrTraits;
using System.Text;
using Verse;
using RimWorld;
using Multiplayer.API;
namespace rjw
{
public class CompRJW : ThingComp
{
/// <summary>
/// Core comp for genitalia and sexuality tracking.
/// </summary>
public CompRJW() { }
public CompProperties_RJW Props => (CompProperties_RJW)props;
public Orientation orientation = Orientation.None;
public StringBuilder quirks = new();
public string quirksave = ""; // Not the most elegant way to do this, but it minimizes the save bloat.
public int NextHookupTick;
private bool BootStrapTriggered = false;
public Need_Sex? sexNeed;
public bool drawNude = false;
public bool keep_hat_on = false;
/// <summary>
/// <para>Gets the pawn for this comp.</para>
/// <para>May return null if the comp's parent is somehow not a pawn.</para>
/// </summary>
private Pawn? pawn;
private Pawn? Pawn => parent is Pawn pawn ? pawn : null;
// This automatically checks that genitalia has been added to all freshly spawned pawns.
public override void PostSpawnSetup(bool respawningAfterLoad)
{
base.PostSpawnSetup(respawningAfterLoad);
if (pawn == null)
{
pawn = Pawn;
if (pawn == null) return;
}
if (pawn.kindDef.race.defName.Contains("AIRobot") // No genitalia/sexuality for roombas.
|| pawn.kindDef.race.defName.Contains("AIPawn") // ...nor MAI.
|| pawn.kindDef.race.defName.Contains("RPP_Bot")
|| pawn.kindDef.race.defName.Contains("PRFDrone") // Project RimFactory Revived drones
) return;
// No genitalia
//if (!pawn.RaceProps.body.AllParts.Exists(x => x.def == DefDatabase<BodyPartDef>.GetNamed("Genitals")))
// return;
if (Comp(pawn).orientation == Orientation.None)
{
Sexualize(pawn);
Sexualize(pawn, true);
}
//Log.Message("PostSpawnSetup for " + pawn?.Name);
}
public override void CompTick()
{
base.CompTick();
if (pawn == null)
{
pawn = Pawn;
if (pawn == null) return;
}
if (pawn.IsHashIntervalTick(1500) && !pawn.health.Dead)
// The `NeedInterval` function is called every 150 ticks but was formerly
// rate limited by a factor of 10. This will make the upkeep execute at
// the same interval.
{
if (sexNeed == null)
{
sexNeed = pawn.needs?.TryGetNeed<Need_Sex>();
}
if (sexNeed != null)
{
DoUpkeep(pawn, sexNeed);
}
}
}
/// <summary>
/// Performs some upkeep tasks originally handled in `Need_Sex.NeedInterval`.
/// </summary>
private void DoUpkeep(Pawn pawn, Need_Sex sexNeed)
{
if (pawn.Map == null) return;
if (xxx.is_asexual(pawn)) return;
var curLevel = sexNeed.CurLevel;
// Update psyfocus if the pawn is awake.
if (!RJWSettings.Disable_MeditationFocusDrain && pawn.Awake() && curLevel < sexNeed.thresh_frustrated())
SexUtility.OffsetPsyfocus(pawn, -0.01f);
//if (curLevel < sexNeed.thresh_horny())
// SexUtility.OffsetPsyfocus(pawn, -0.01f);
//if (curLevel < sexNeed.thresh_frustrated() || curLevel > sexNeed.thresh_ahegao())
// SexUtility.OffsetPsyfocus(pawn, -0.05f);
if (curLevel < sexNeed.thresh_horny() && (pawn.mindState.canLovinTick - Find.TickManager.TicksGame > 300))
pawn.mindState.canLovinTick = Find.TickManager.TicksGame + 300;
// This can probably all just go, since it's now a noop.
// But I don't know if some mod is patching `xxx.bootstrap` or something.
if (!BootStrapTriggered)
{
//--ModLog.Message("CompRJW::DoUpkeep::calling boostrap - pawn is " + xxx.get_pawnname(pawn));
xxx.bootstrap(pawn.Map);
BootStrapTriggered = true;
}
if (drawNude) {
bool isFucking = pawn.jobs?.curDriver is JobDriver_Sex;
if(!isFucking)
{
drawNude = false;
keep_hat_on = false;
}
}
}
public override void PostExposeData()
{
base.PostExposeData();
if (Pawn == null) return;
// Saves the data.
Scribe_Values.Look(ref orientation, "RJW_Orientation");
Scribe_Values.Look(ref quirksave, "RJW_Quirks", "");
Scribe_Values.Look(ref NextHookupTick, "RJW_NextHookupTick");
Scribe_Values.Look(ref drawNude, "RJW_drawNude");
Scribe_Values.Look(ref keep_hat_on, "RJW_keep_hat_on");
//Log.Message("PostExposeData for " + pawn?.Name);
// Restore quirk data from the truncated save version.
quirks = new StringBuilder(quirksave);
}
public static CompRJW Comp(Pawn pawn)
{
// Call CompRJW.Comp(pawn).<method> to check sexuality, etc.
return pawn.GetComp<CompRJW>();
}
public static void CopyPsychologySexuality(Pawn pawn)
{
try
{
int kinsey = pawn.TryGetComp<CompPsychology>().Sexuality.kinseyRating;
//Orientation originalOrientation = Comp(pawn).orientation;
if (!Genital_Helper.has_genitals(pawn) && (pawn.kindDef.race.defName.ToLower().Contains("droid") || pawn.kindDef.race.defName.ToLower().Contains("drone")))
Comp(pawn).orientation = Orientation.Asexual;
else if (kinsey == 0)
Comp(pawn).orientation = Orientation.Heterosexual;
else if (kinsey == 1)
Comp(pawn).orientation = Orientation.MostlyHeterosexual;
else if (kinsey == 2)
Comp(pawn).orientation = Orientation.LeaningHeterosexual;
else if (kinsey == 3)
Comp(pawn).orientation = Orientation.Bisexual;
else if (kinsey == 4)
Comp(pawn).orientation = Orientation.LeaningHomosexual;
else if (kinsey == 5)
Comp(pawn).orientation = Orientation.MostlyHomosexual;
else if (kinsey == 6)
Comp(pawn).orientation = Orientation.Homosexual;
else
Comp(pawn).orientation = Orientation.Asexual;
/*else
Log.Error("RJW::ERRROR - unknown kinsey scale value: " + kinsey);/*
/*if (Comp(pawn).orientation != originalOrientation)
Log.Message("RJW + Psychology: Inherited pawn " + xxx.get_pawnname(pawn) + " sexuality from Psychology - " + Comp(pawn).orientation);*/
}
catch
{
if (!pawn.IsAnimal())
ModLog.Warning("CopyPsychologySexuality " + pawn?.Name + ", def: " + pawn?.def?.defName + ", kindDef: " + pawn?.kindDef?.race.defName);
}
}
public static void CopyIndividualitySexuality(Pawn pawn)
{
try
{
CompIndividuality.Sexuality individualitySexuality = pawn.TryGetComp<CompIndividuality>().sexuality;
//Orientation originalOrientation = Comp(pawn).orientation;
if (individualitySexuality == CompIndividuality.Sexuality.Asexual)
Comp(pawn).orientation = Orientation.Asexual;
else if (!Genital_Helper.has_genitals(pawn) && (pawn.kindDef.race.defName.ToLower().Contains("droid") || pawn.kindDef.race.defName.ToLower().Contains("drone")))
Comp(pawn).orientation = Orientation.Asexual;
else if (individualitySexuality == CompIndividuality.Sexuality.Straight)
Comp(pawn).orientation = Orientation.Heterosexual;
else if (individualitySexuality == CompIndividuality.Sexuality.Bisexual)
Comp(pawn).orientation = Orientation.Bisexual;
else if (individualitySexuality == CompIndividuality.Sexuality.Gay)
Comp(pawn).orientation = Orientation.Homosexual;
else
Comp(pawn).orientation = Orientation.Asexual;
/*if (Comp(pawn).orientation != originalOrientation)
Log.Message("RJW + [SYR]Individuality: Inherited pawn " + xxx.get_pawnname(pawn) + " sexuality from Individuality - " + Comp(pawn).orientation);*/
}
catch
{
if (!pawn.IsAnimal())
ModLog.Warning("CopyIndividualitySexuality " + pawn?.Name + ", def: " + pawn?.def?.defName + ", kindDef: " + pawn?.kindDef?.race.defName);
}
}
public static void VanillaTraitCheck(Pawn pawn)
{
//Orientation originalOrientation = Comp(pawn).orientation;
if (pawn.story.traits.HasTrait(TraitDefOf.Asexual))
Comp(pawn).orientation = Orientation.Asexual;
else if (!Genital_Helper.has_genitals(pawn) && (pawn.kindDef.race.defName.ToLower().Contains("droid") || pawn.kindDef.race.defName.ToLower().Contains("drone")))
Comp(pawn).orientation = Orientation.Asexual;
else if (pawn.story.traits.HasTrait(TraitDefOf.Gay))
Comp(pawn).orientation = Orientation.Homosexual;
else if (pawn.story.traits.HasTrait(TraitDefOf.Bisexual))
Comp(pawn).orientation = Orientation.Bisexual;
else
Comp(pawn).orientation = Orientation.Heterosexual;
}
// The main method for adding genitalia and orientation.
public void Sexualize(Pawn pawn, bool reroll = false)
{
if (reroll)
{
Comp(pawn).orientation = Orientation.None;
if (xxx.has_quirk(pawn, "Fertile"))
{
Hediff fertility = pawn.health.hediffSet.GetFirstHediffOfDef(HediffDef.Named("IncreasedFertility"));
if (fertility != null)
pawn.health.RemoveHediff(fertility);
}
if (xxx.has_quirk(pawn, "Infertile"))
{
Hediff fertility = pawn.health.hediffSet.GetFirstHediffOfDef(HediffDef.Named("DecreasedFertility"));
if (fertility != null)
pawn.health.RemoveHediff(fertility);
}
quirks = new StringBuilder();
}
else if (Comp(pawn).orientation != Orientation.None)
return;
//roll random RJW orientation
Comp(pawn).orientation = xxx.is_animal(pawn) ? RollAnimalOrientation(pawn) : RollOrientation(pawn);
//Asexual nymp re-roll
//if (xxx.is_nympho(pawn))
// while (Comp(pawn).orientation == Orientation.Asexual)
// {
// Comp(pawn).orientation = RollOrientation();
// }
//Log.Message("Sexualizing pawn " + pawn?.Name + ", def: " + pawn?.def?.defName);
if (!reroll)
Sexualizer.sexualize_pawn(pawn);
//Log.Message("Orientation for pawn " + pawn?.Name + " is " + orientation);
if (xxx.has_traits(pawn) && Genital_Helper.has_genitals(pawn) && !(pawn.kindDef.race.defName.ToLower().Contains("droid") && !AndroidsCompatibility.IsAndroid(pawn)))
{
if (RJWPreferenceSettings.sexuality_distribution == RJWPreferenceSettings.Rjw_sexuality.Vanilla)
VanillaTraitCheck(pawn);
if (RJWPreferenceSettings.sexuality_distribution == RJWPreferenceSettings.Rjw_sexuality.Psychology)
CopyPsychologySexuality(pawn);
if (RJWPreferenceSettings.sexuality_distribution == RJWPreferenceSettings.Rjw_sexuality.SYRIndividuality)
CopyIndividualitySexuality(pawn);
}
else if (((pawn.kindDef.race.defName.ToLower().Contains("droid")) && !AndroidsCompatibility.IsAndroid(pawn)) || !Genital_Helper.has_genitals(pawn))
{
// Droids with no genitalia are set as asexual.
// If player later adds genitalia to the droid, the droid 'sexuality' gets rerolled.
Comp(pawn).orientation = Orientation.Asexual;
}
QuirkAdder.Generate(pawn);
if (quirks.Length == 0)
{
quirks.Append("None");
quirksave = quirks.ToString();
}
}
/// <summary>
/// check try vanilla traits/mods, check rjw genitals, futa check, some rng rolls
/// </summary>
/// <param name="pawn"></param>
/// <param name="partner"></param>
/// <returns></returns>
public static bool CheckPreference(Pawn pawn, Pawn partner)
{
if (RJWPreferenceSettings.sexuality_distribution == RJWPreferenceSettings.Rjw_sexuality.Vanilla)
{
if (xxx.has_traits(pawn))
VanillaTraitCheck(pawn);
if (xxx.has_traits(partner))
VanillaTraitCheck(partner);
}
if (RJWPreferenceSettings.sexuality_distribution == RJWPreferenceSettings.Rjw_sexuality.SYRIndividuality)
{
CopyIndividualitySexuality(pawn);
CopyIndividualitySexuality(partner);
}
if (RJWPreferenceSettings.sexuality_distribution == RJWPreferenceSettings.Rjw_sexuality.Psychology)
{
if (RJWPreferenceSettings.sexuality_distribution == RJWPreferenceSettings.Rjw_sexuality.Psychology)
CopyPsychologySexuality(pawn);
CopyPsychologySexuality(partner);
}
//if (xxx.is_mechanoid(pawn))
// return false;
if (Comp(pawn) is CompRJW rjwComp)
{
var ori = rjwComp.orientation;
if (ori == Orientation.Pansexual || ori == Orientation.Bisexual)
return true;
if (ori == Orientation.Asexual)
return false;
var pawnSex = GenderHelper.GetSex(pawn);
var partnerSex = GenderHelper.GetSex(partner);
var isHetero = GenderHelper.CanBeHetero(pawnSex, partnerSex);
var isHomo = GenderHelper.CanBeHomo(pawnSex, partnerSex);
// Oh you crazy futas. fuck all cuz horny!
if (isHetero && isHomo)
return true;
//RMB ui lag fixes in mp intead of [SyncMethod]
if (MP.IsInMultiplayer)
return RollOriMP(ori, isHetero, isHomo);
else
return RollOriSP(ori, isHetero, isHomo);
}
else
{
//ModLog.Message("Error, pawn:" + pawn + " doesn't have orientation comp, modded race?");
return false;
}
}
//no rng no lag
public static bool RollOriMP(Orientation ori, bool isHetero, bool isHomo)
{
switch (ori)
{
case Orientation.Heterosexual:
return !isHomo;
case Orientation.MostlyHeterosexual:
return (!isHomo);
case Orientation.LeaningHeterosexual:
return (!isHomo);
case Orientation.LeaningHomosexual:
return (!isHetero);
case Orientation.MostlyHomosexual:
return (!isHetero);
case Orientation.Homosexual:
return !isHetero;
default:
ModLog.Error("ERROR - tried to check preference for undetermined sexuality.");
return false;
}
}
//slight rng, but heavy ddos lag in MP with [SyncMethod]
public static bool RollOriSP(Orientation ori, bool isHetero, bool isHomo)
{
switch (ori)
{
case Orientation.Heterosexual:
return !isHomo;
case Orientation.MostlyHeterosexual:
return (!isHomo || Rand.Chance(0.2f));
case Orientation.LeaningHeterosexual:
return (!isHomo || Rand.Chance(0.6f));
case Orientation.LeaningHomosexual:
return (!isHetero || Rand.Chance(0.6f));
case Orientation.MostlyHomosexual:
return (!isHetero || Rand.Chance(0.2f));
case Orientation.Homosexual:
return !isHetero;
default:
ModLog.Error("ERROR - tried to check preference for undetermined sexuality.");
return false;
}
}
[SyncMethod]
public Orientation RollOrientation(Pawn pawn)
{
//Rand.PopState();
//Rand.PushState(RJW_Multiplayer.PredictableSeed());
float random = Rand.Range(0f, 1f);
float checkpoint = RJWPreferenceSettings.asexual_ratio / RJWPreferenceSettings.GetTotal();
float checkpoint_pan = checkpoint + (RJWPreferenceSettings.pansexual_ratio / RJWPreferenceSettings.GetTotal());
float checkpoint_het = checkpoint_pan + (RJWPreferenceSettings.heterosexual_ratio / RJWPreferenceSettings.GetTotal());
float checkpoint_bi = checkpoint_het + (RJWPreferenceSettings.bisexual_ratio / RJWPreferenceSettings.GetTotal());
float checkpoint_gay = checkpoint_bi + (RJWPreferenceSettings.homosexual_ratio / RJWPreferenceSettings.GetTotal());
if (random < checkpoint || !Genital_Helper.has_genitals(pawn))
return Orientation.Asexual;
else if (random < checkpoint_pan)
return Orientation.Pansexual;
else if (random < checkpoint_het)
return Orientation.Heterosexual;
else if (random < checkpoint_het + ((checkpoint_bi - checkpoint_het) * 0.33f))
return Orientation.MostlyHeterosexual;
else if (random < checkpoint_het + ((checkpoint_bi - checkpoint_het) * 0.66f))
return Orientation.LeaningHeterosexual;
else if (random < checkpoint_bi)
return Orientation.Bisexual;
else if (random < checkpoint_bi + ((checkpoint_gay - checkpoint_bi) * 0.33f))
return Orientation.LeaningHomosexual;
else if (random < checkpoint_bi + ((checkpoint_gay - checkpoint_bi) * 0.66f))
return Orientation.MostlyHomosexual;
else
return Orientation.Homosexual;
}
// Simpler system for animals, with most of them being heterosexual.
// Don't want to disturb player breeding projects by adding too many gay animals.
[SyncMethod]
public Orientation RollAnimalOrientation(Pawn pawn)
{
//Rand.PopState();
//Rand.PushState(RJW_Multiplayer.PredictableSeed());
float random = Rand.Range(0f, 1f);
if (random < 0.03f || !Genital_Helper.has_genitals(pawn))
return Orientation.Asexual;
else if (random < 0.85f)
return Orientation.Heterosexual;
else if (random < 0.96f)
return Orientation.Bisexual;
else
return Orientation.Homosexual;
}
}
}
| Korth95/rjw | 1.5/Source/Comps/CompRJW.cs | C# | mit | 16,129 |
using RimWorld;
namespace rjw
{
public class CompRJWHatcher : CompHatcher
{
}
} | Korth95/rjw | 1.5/Source/Comps/CompRJWHatcher.cs | C# | mit | 86 |
using RimWorld;
namespace rjw
{
public class CompRJWProperties_Hatcher : CompProperties_Hatcher
{
public CompRJWProperties_Hatcher()
{
this.compClass = typeof(CompRJWHatcher);
}
}
} | Korth95/rjw | 1.5/Source/Comps/CompRJWProperties_Hatcher.cs | C# | mit | 198 |
using System.Text;
using Verse;
using RimWorld;
using Multiplayer.API;
using System.Collections.Generic;
using rjw.Modules.Shared.Logs;
using System.Runtime.InteropServices;
using System.Linq;
namespace rjw
{
/// <summary>
/// Comp for things
/// </summary>
public class CompThingBodyPart : ThingComp
{
/// <summary>
/// Comp for rjw Thing parts.
/// </summary>
public HediffDef_SexPart hediffDef;
public string sizeLabel; //eventually replace with below, maybe
public float size; //base size when part created, someday alter by operation
private float? depth;
private float? maxGirth;
private float? length;
private float? girth;
private string cupSize;
public float originalOwnerSize;
public string originalOwnerRace; //race of 1st owner race
public string previousOwner; //erm
public SexFluidDef fluid; //cummies/milk - insectjelly/honey etc
public float fluidAmount; //amount of Milk/Ejaculation/Wetness
private bool initialised;
public CompProperties_ThingBodyPart Props => (CompProperties_ThingBodyPart)props;
/// <summary>
/// Thing/part size in label
/// </summary>
public override string TransformLabel(string label)
{
if (!initialised)
Init();
if (sizeLabel != "")
return $"{label} ({sizeLabel})";
return label;
}
public override string CompInspectStringExtra()
{
return InspectStringLines().ToLineList();
}
private IEnumerable<string> InspectStringLines()
{
if (length.HasValue)
{
yield return "RJW_PartInfo_length".Translate(length.Value.ToString("F1"));
}
if (girth.HasValue)
{
yield return "RJW_PartInfo_girth".Translate(girth.Value.ToString("F1"));
}
if (depth.HasValue && hediffDef.genitalFamily != GenitalFamily.FemaleOvipositor)
{
yield return "RJW_PartInfo_depth".Translate(depth.Value.ToString("F1"));
}
if (maxGirth.HasValue && hediffDef.genitalFamily != GenitalFamily.FemaleOvipositor)
{
yield return "RJW_PartInfo_maxGirth".Translate(maxGirth.Value.ToString("F1"));
}
if (cupSize != null)
{
yield return "RJW_PartInfo_braCup".Translate(cupSize);
}
if (fluid != null)
{
yield return "RJW_PartInfo_fluidTypeFluidAmountHeading".Translate(fluid.label, fluidAmount.ToString("F0")).CapitalizeFirst();
}
}
public override void PostExposeData()
{
base.PostExposeData();
Scribe_Defs.Look(ref hediffDef, "hediffDef");
Scribe_Defs.Look(ref fluid, "fluid");
Scribe_Values.Look(ref sizeLabel, "sizeLabel");
Scribe_Values.Look(ref size, "size");
Scribe_Values.Look(ref originalOwnerSize, "originalOwnerSize");
Scribe_Values.Look(ref originalOwnerRace, "originalOwnerRace");
Scribe_Values.Look(ref previousOwner, "previousOwner");
Scribe_Values.Look(ref fluidAmount, "fluidAmount");
Scribe_Values.Look(ref initialised, "initialised", defaultValue: true);
Scribe_Values.Look(ref cupSize, "cupSize");
Scribe_Values.Look(ref length, "length");
Scribe_Values.Look(ref depth, "depth");
Scribe_Values.Look(ref maxGirth, "maxGirth");
Scribe_Values.Look(ref girth, "girth");
}
public override IEnumerable<StatDrawEntry> SpecialDisplayStats()
{
// Absolutely terrible idea, but this check was originally in the description override as some kind of failsafe,
// so sticking it here for now so as not to break things
// TODO: Ensure this can be removed
if (!initialised)
{
Init();
}
// Chosen semi-arbitrarily. Change these if stat ordering seems janky.
int statOrder = StatDisplayOrder.Thing_BodyPartEfficiency + 10;
var implantCategory = StatCategoryDefOf.Implant;
var ownerCategory = RJWStatCategoryDefOf.OriginalPartOwner;
//yield return new StatDrawEntry(category, "RJW_StatEntry_PartSize".Translate(), size.ToString("F2"), "", statOrder++);
if (fluid != null)
{
yield return new StatDrawEntry(implantCategory, "RJW_StatEntry_Fluid".Translate(), fluid.LabelCap, "", statOrder++);
}
if (fluidAmount != 0)
{
string fluidAmountKey = hediffDef.genitalFamily switch
{
GenitalFamily.Penis or GenitalFamily.MaleOvipositor => "RJW_StatEntry_FluidAmount_ejaculation",
GenitalFamily.Vagina or GenitalFamily.Anus => "RJW_StatEntry_FluidAmount_wetness",
_ => "RJW_StatEntry_FluidAmount"
};
yield return new StatDrawEntry(implantCategory, fluidAmountKey.Translate(), fluidAmount.ToString("F2"), "", statOrder++);
}
if (length.HasValue)
{
yield return new StatDrawEntry(implantCategory, "RJW_StatEntry_PartLength".Translate(), length.Value.ToString("F2"), "", statOrder++);
}
if (girth.HasValue)
{
yield return new StatDrawEntry(implantCategory, "RJW_StatEntry_PartGirth".Translate(), girth.Value.ToString("F2"), "", statOrder++);
}
if (depth.HasValue)
{
yield return new StatDrawEntry(implantCategory, "RJW_StatEntry_PartDepth".Translate(), depth.Value.ToString("F2"), "", statOrder++);
}
if (maxGirth.HasValue)
{
yield return new StatDrawEntry(implantCategory, "RJW_StatEntry_PartMaxGirth".Translate(), maxGirth.Value.ToString("F2"), "", statOrder++);
}
if (cupSize != null)
{
yield return new StatDrawEntry(implantCategory, "RJW_StatEntry_PartCupSize".Translate(), cupSize, "", statOrder++);
}
if (!hediffDef.partTags.NullOrEmpty())
{
var tags = hediffDef.partTags;
yield return new StatDrawEntry(implantCategory, "RJW_StatEntry_PartTags".Translate(), tags.ToCommaList(), "", statOrder++);
}
// Ownership info
if (!previousOwner.NullOrEmpty())
{
yield return new StatDrawEntry(ownerCategory, "RJW_StatEntry_PreviousOwner".Translate(), previousOwner, "", 1);
}
if (!originalOwnerRace.NullOrEmpty())
{
yield return new StatDrawEntry(ownerCategory, "RJW_StatEntry_OriginalOwnerRace".Translate(), originalOwnerRace, "", 2);
}
if (originalOwnerSize > 0f)
{
yield return new StatDrawEntry(ownerCategory, "RJW_StatEntry_OriginalOwnerSize".Translate(), originalOwnerSize.ToString("F1"), "", 3);
}
}
public override void PostPostMake()
{
base.PostPostMake();
Init();
}
/// <summary>
/// fill comp data
/// </summary>
[SyncMethod]
private void Init(Pawn pawn = null)
{
// TODO: Maybe un-link this from ThingDef xml and instead set randomly or inherit from removed part
hediffDef = Props.hediffDef;
bool originalOwnerIsKnown = true;
if (pawn == null)
{
InitFromDef(hediffDef);
initialised = true;
}
else
{
Hediff hd = HediffMaker.MakeHediff(hediffDef, pawn);
HediffComp_SexPart hediffComp = hd.TryGetComp<HediffComp_SexPart>();
if (hediffComp != null)
{
InitFromComp(hediffComp, originalOwnerIsKnown);
}
}
}
public void InitFromComp(HediffComp_SexPart hediffComp, bool recordOriginalOwner = true)
{
hediffDef = hediffComp.Def;
fluid = hediffComp.Fluid;
fluidAmount = hediffComp.partFluidFactor;
size = hediffComp.Size;
sizeLabel = hediffDef.GetStandardSizeLabel(size);
if (!hediffDef.genitalTags.NullOrEmpty())
{
if (hediffDef.genitalTags.Contains(GenitalTag.CanPenetrate))
{
if (PartSizeCalculator.TryGetLength(hediffComp.parent, out float length))
{
this.length = length;
}
if (PartSizeCalculator.TryGetGirth(hediffComp.parent, out float girth))
{
this.girth = girth;
}
}
if (hediffDef.genitalTags.Contains(GenitalTag.CanBePenetrated))
{
if (PartSizeCalculator.TryGetLength(hediffComp.parent, out float depth))
{
this.depth = depth;
}
if (PartSizeCalculator.TryGetGirth(hediffComp.parent, out float maxGirth))
{
this.maxGirth = maxGirth;
}
}
}
if (PartSizeCalculator.TryGetCupSize(hediffComp.parent, out float numericCupSize))
{
cupSize = BraSizeConfigDef.GetCupSizeLabel(numericCupSize);
}
if (recordOriginalOwner)
{
originalOwnerSize = hediffComp.originalOwnerSize;
previousOwner = hediffComp.Pawn?.LabelNoCount;
if (hediffComp.Pawn.IsHuman() || hediffComp.Pawn.Name != null)
{
originalOwnerRace = hediffComp.Pawn?.kindDef.race.LabelCap;
}
}
initialised = true;
}
[SyncMethod]
private void InitFromDef(HediffDef_SexPart hediffDef)
{
this.hediffDef = hediffDef;
fluid = hediffDef.fluid;
var bodySize = DefDatabase<PawnKindDef>.GetRandom().RaceProps.baseBodySize;
size = hediffDef.GetRandomSize() * bodySize;
fluidAmount = hediffDef.GetRandomFluidAmount(bodySize, size);
sizeLabel = hediffDef.GetStandardSizeLabel(size);
if (!hediffDef.genitalTags.NullOrEmpty())
{
if (hediffDef.genitalTags.Contains(GenitalTag.CanPenetrate))
{
if (PartSizeCalculator.TryGetLength(hediffDef, size, out float length))
{
this.length = length;
}
if (PartSizeCalculator.TryGetGirth(hediffDef, size, out float girth))
{
this.girth = girth;
}
}
if (hediffDef.genitalTags.Contains(GenitalTag.CanBePenetrated))
{
if (PartSizeCalculator.TryGetLength(hediffDef, size, out float depth))
{
this.depth = depth;
}
if (PartSizeCalculator.TryGetGirth(hediffDef, size, out float maxGirth))
{
this.maxGirth = maxGirth;
}
}
}
if (PartSizeCalculator.TryGetCupSize(hediffDef, size, out float numericCupSize))
{
cupSize = BraSizeConfigDef.GetCupSizeLabel(numericCupSize);
}
}
}
} | Korth95/rjw | 1.5/Source/Comps/CompRJWThingBodyPart.cs | C# | mit | 9,577 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace rjw
{
public enum Orientation
{
None,
Asexual,
Pansexual,
Heterosexual,
MostlyHeterosexual,
LeaningHeterosexual,
Bisexual,
LeaningHomosexual,
MostlyHomosexual,
Homosexual
}
}
| Korth95/rjw | 1.5/Source/Comps/Orientation.cs | C# | mit | 298 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Verse;
using Verse.AI;
using RimWorld;
namespace rjw
{
public class Quirk
{
public static List<Quirk> All = new List<Quirk>();
public static readonly Quirk Breeder = new Quirk(
"Breeder",
"BreederQuirk");
public static readonly Quirk Endytophile = new Quirk(
"Endytophile",
"EndytophileQuirk",
(pawn, partner) => !partner.apparel.PsychologicallyNude,
sexProps => !sexProps.pawn.apparel.PsychologicallyNude
);
public static readonly Quirk Exhibitionist = new Quirk(
"Exhibitionist",
"ExhibitionistQuirk",
null,
SatisfiesExhibitionist
);
public static readonly Quirk Fertile = new Quirk(
"Fertile",
"FertileQuirk");
public static readonly Quirk Gerontophile = new Quirk(
"Gerontophile",
"GerontophileQuirk",
(pawn, partner) => SexUtility.ScaleToHumanAge(partner) > 55,
sexProps => sexProps.hasPartner() && SexUtility.ScaleToHumanAge(sexProps.partner) > 55
);
public static readonly Quirk ImpregnationFetish = new Quirk(
"Impregnation fetish",
"ImpregnationFetishQuirk",
(pawn, partner) =>
PregnancyHelper.CanImpregnate(pawn, partner)
|| PregnancyHelper.CanImpregnate(partner, pawn),
sexProps =>
sexProps.hasPartner()
&& (PregnancyHelper.CanImpregnate(sexProps.pawn, sexProps.partner, sexProps.sexType)
|| PregnancyHelper.CanImpregnate(sexProps.partner, sexProps.pawn, sexProps.sexType))
);
public static readonly Quirk Incubator = new Quirk(
"Incubator",
"IncubatorQuirk");
public static readonly Quirk Infertile = new Quirk(
"Infertile",
"InfertileQuirk");
public static readonly Quirk Messy = new Quirk(
"Messy",
"MessyQuirk");
public static readonly Quirk Podophile = new Quirk(
"Podophile",
"PodophileQuirk",
null,
sexProps => sexProps.hasPartner() && sexProps.sexType == xxx.rjwSextype.Footjob && sexProps.IsSubmissive()
);
public static readonly Quirk Cumslut = new Quirk(
"Cumslut",
"CumslutQuirk",
null,
sexProps => sexProps.hasPartner() && sexProps.sexType == xxx.rjwSextype.Fellatio && sexProps.IsSubmissive()
);
public static readonly Quirk Buttslut = new Quirk(
"Buttslut",
"ButtslutQuirk",
null,
sexProps => sexProps.hasPartner() && sexProps.sexType == xxx.rjwSextype.Anal && sexProps.IsSubmissive()
);
public static readonly Quirk PregnancyFetish = new Quirk(
"Pregnancy fetish",
"PregnancyFetishQuirk",
(pawn, partner) => partner.IsVisiblyPregnant(),
sexProps => sexProps.hasPartner() && sexProps.partner.IsVisiblyPregnant()
);
public static readonly Quirk Sapiosexual = new Quirk(
"Sapiosexual",
"SapiosexualQuirk",
(pawn, partner) => SatisfiesSapiosexual(partner),
null
);
public static readonly Quirk Somnophile = new Quirk(
"Somnophile",
"SomnophileQuirk",
(pawn, partner) => !partner.Awake(),
sexProps => sexProps.hasPartner() && !sexProps.partner.Awake()
);
public static readonly Quirk Teratophile = new Quirk(
"Teratophile",
"TeratophileQuirk",
(pawn, partner) => SatisfiesTeratophile(partner),
null
);
public static readonly Quirk Vigorous = new Quirk(
"Vigorous",
"VigorousQuirk");
// There might be too many of these I dunno.
// People have expressed "special interest" in some of them so I thought
// it would be cool to have them in the game but since people are weird you end up with a lot of fetishes.
public static readonly Quirk ChitinLover = MakeTagBasedQuirk("Chitin lover", "ChitinLoverQuirk", RaceTag.Chitin);
public static readonly Quirk DemonLover = MakeTagBasedQuirk("Demon lover", "DemonLoverQuirk", RaceTag.Demon);
public static readonly Quirk FeatherLover = MakeTagBasedQuirk("Feather lover", "FeatherLoverQuirk", RaceTag.Feathers);
public static readonly Quirk FurLover = MakeTagBasedQuirk("Fur lover", "FurLoverQuirk", RaceTag.Fur);
public static readonly Quirk PlantLover = MakeTagBasedQuirk("Plant lover", "PlantLoverQuirk", RaceTag.Plant);
public static readonly Quirk RobotLover = MakeTagBasedQuirk("Robot lover", "RobotLoverQuirk", RaceTag.Robot);
public static readonly Quirk ScaleLover = MakeTagBasedQuirk("Scale lover", "ScaleLoverQuirk", RaceTag.Scales);
public static readonly Quirk SkinLover = MakeTagBasedQuirk("Skin lover", "SkinLoverQuirk", RaceTag.Skin);
public static readonly Quirk SlimeLover = MakeTagBasedQuirk("Slime lover", "SlimeLoverQuirk", RaceTag.Slime);
public string Key { get; }
public string LocaliztionKey { get; }
// Hack, quirk generation logic should be in the quirk not based on flags on the quirk.
public RaceTag RaceTag { get; }
readonly Func<Pawn, Pawn, bool> PawnSatisfiesFunc;
readonly Func<SexProps, bool> SexSatisfiesFunc;
readonly Action<Pawn> AfterAddFunc;
public static Quirk MakeTagBasedQuirk(string key, string localizationKey, RaceTag tag)
{
return new Quirk(
key,
localizationKey,
(pawn, partner) => partner.Has(tag),
sexProps => sexProps.hasPartner() && sexProps.partner.Has(tag),
null,
tag);
}
public Quirk(
string key,
string localizationKey,
Func<Pawn, Pawn, bool> pawnSatisfies = null,
Func<SexProps, bool> sexSatisfies = null,
Action<Pawn> afterAdd = null,
RaceTag raceTag = null)
{
Key = key;
LocaliztionKey = localizationKey;
PawnSatisfiesFunc = pawnSatisfies;
SexSatisfiesFunc = sexSatisfies;
AfterAddFunc = afterAdd;
RaceTag = raceTag;
All.Add(this);
}
public bool IsSatisfiedBy(Pawn pawn, Pawn partner)
{
return pawn != null
&& partner != null
&& pawn.Has(this)
&& PawnSatisfiesFunc != null
&& PawnSatisfiesFunc(pawn, partner);
}
public static int CountSatisfiedQuirks(SexProps props)
{
Pawn pawn = props.pawn;
Pawn partner = props.partner;
var satisfies = All.Where(quirk =>
quirk.SexSatisfiesFunc != null
&& pawn.Has(quirk)
&& quirk.SexSatisfiesFunc(props));
return satisfies.Count();
}
public void DoAfterAdd(Pawn pawn)
{
AfterAddFunc?.Invoke(pawn);
}
public static bool SatisfiesExhibitionist(SexProps sexProps)
{
var zoo = xxx.is_zoophile(sexProps.pawn);
return sexProps.pawn.Map.mapPawns.AllPawnsSpawned.Any(x =>
x != sexProps.pawn
&& x != sexProps.partner
&& !x.Dead
&& (zoo || !xxx.is_animal(x))
&& x.CanSee(sexProps.pawn));
}
public static bool SatisfiesSapiosexual(Pawn partner)
{
if (!xxx.has_traits(partner)) return false;
return partner.story.traits.HasTrait(VanillaTraitDefOf.TooSmart)
|| (xxx.CTIsActive && partner.story.traits.HasTrait(xxx.RCT_Savant))
|| (xxx.IndividualityIsActive && partner.story.traits.HasTrait(xxx.SYR_CreativeThinker))
|| (xxx.CTIsActive && partner.story.traits.HasTrait(xxx.RCT_Inventor))
|| partner.story.traits.HasTrait(TraitDefOf.GreatMemory)
|| partner.story.traits.HasTrait(TraitDefOf.Transhumanist)
|| partner.skills.GetSkill(SkillDefOf.Intellectual).levelInt >= 15;
}
public static bool SatisfiesTeratophile(Pawn partner)
{
if (partner.story == null) return false;
var story = partner.story;
return RelationsUtility.IsDisfigured(partner)
|| story.bodyType == BodyTypeDefOf.Fat
|| story.traits.HasTrait(TraitDefOf.CreepyBreathing)
|| (story.traits.HasTrait(VanillaTraitDefOf.Beauty) && story.traits.DegreeOfTrait(VanillaTraitDefOf.Beauty) < 0)
|| partner.GetStatValue(StatDefOf.PawnBeauty) < 0;
}
public static void AddThought(Pawn pawn)
{
var thoughtDef = DefDatabase<ThoughtDef>.GetNamed("ThatsMyFetish");
pawn.needs.mood.thoughts.memories.TryGainMemory(thoughtDef);
}
}
}
| Korth95/rjw | 1.5/Source/Comps/Quirk.cs | C# | mit | 7,682 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Verse;
using Verse.AI;
using RimWorld;
using Multiplayer.API;
namespace rjw
{
public static class QuirkAdder
{
public static void Add(Pawn pawn, Quirk quirk, bool warnOnFail = false)
{
if (!pawn.Has(quirk))
{
var hasFertility = pawn.RaceHasFertility();
if (quirk == Quirk.Fertile && (!hasFertility || CompRJW.Comp(pawn).quirks.ToString().Contains(Quirk.Infertile.Key)))
{
if (warnOnFail)
{
ModLog.Warning($"Tried to add quirk {quirk} to {pawn.Name}, but either {pawn.def} does not have fertility or {pawn.Name} has a conflicting quirk");
}
return;
}
if (quirk == Quirk.Infertile && (!hasFertility || CompRJW.Comp(pawn).quirks.ToString().Contains(Quirk.Fertile.Key)))
{
if (warnOnFail)
{
ModLog.Warning($"Tried to add quirk {quirk} to {pawn.Name}, but either {pawn.def} does not have fertility or {pawn.Name} has a conflicting quirk");
}
return;
}
// No fair having a fetish for your own race.
// But tags don't conflict so having a fetish for robot plant dragons is fine.
if (quirk.RaceTag != null && pawn.Has(quirk.RaceTag))
{
if (warnOnFail)
{
ModLog.Warning($"Tried to add quirk {quirk} to {pawn.Name}, but {pawn} already has the associated race tag {quirk.RaceTag}");
}
return;
}
if (quirk == Quirk.Fertile)
{
var fertility = HediffDef.Named("IncreasedFertility");
if (fertility != null)
pawn.health.AddHediff(fertility);
}
if (quirk == Quirk.Infertile)
{
var infertility = HediffDef.Named("DecreasedFertility");
if (infertility != null)
pawn.health.AddHediff(infertility);
}
if ((quirk == Quirk.Buttslut && !RJWPreferenceSettings.PlayerIsButtSlut)
|| (quirk == Quirk.Podophile && !RJWPreferenceSettings.PlayerIsFootSlut)
|| (quirk == Quirk.Cumslut && !RJWPreferenceSettings.PlayerIsCumSlut))
{
if (warnOnFail)
{
ModLog.Warning($"Tried to add quirk {quirk} to {pawn.Name}, but all relevant sex types are pseudo-disabled (i.e. given minimum weight in settings)");
}
return;
}
CompRJW.Comp(pawn).quirks.AppendWithComma(quirk.Key);
CompRJW.Comp(pawn).quirksave = CompRJW.Comp(pawn).quirks.ToString();
quirk.DoAfterAdd(pawn);
}
}
public static void Remove(Pawn pawn, Quirk quirk)
{
if (pawn.Has(quirk))
{
if (quirk == Quirk.Fertile)
{
var fertility = HediffDef.Named("IncreasedFertility");
if (fertility != null)
pawn.health.RemoveHediff(pawn.health.hediffSet.GetFirstHediffOfDef(fertility));
}
if (quirk == Quirk.Infertile)
{
var infertility = HediffDef.Named("DecreasedFertility");
if (infertility != null)
pawn.health.RemoveHediff(pawn.health.hediffSet.GetFirstHediffOfDef(infertility));
}
//CompRJW.Comp(pawn).quirks.AppendWithComma(quirk.Key);
CompRJW.Comp(pawn).quirks.Replace(quirk.Key, null);
if (CompRJW.Comp(pawn).quirks.Length == 0)
CompRJW.Comp(pawn).quirks.Append("None");
CompRJW.Comp(pawn).quirksave = CompRJW.Comp(pawn).quirks.ToString();
}
}
public static void Clear(Pawn pawn)
{
Hediff fertility = pawn.health.hediffSet.GetFirstHediffOfDef(HediffDef.Named("IncreasedFertility"));
if (fertility != null)
pawn.health.RemoveHediff(fertility);
Hediff infertility = pawn.health.hediffSet.GetFirstHediffOfDef(HediffDef.Named("DecreasedFertility"));
if (infertility != null)
pawn.health.RemoveHediff(infertility);
CompRJW.Comp(pawn).quirks = new StringBuilder();
if (CompRJW.Comp(pawn).quirks.Length == 0)
CompRJW.Comp(pawn).quirks.Append("None");
CompRJW.Comp(pawn).quirksave = CompRJW.Comp(pawn).quirks.ToString();
}
public static void Generate(Pawn pawn)
{
if (!pawn.RaceHasSexNeed() || (pawn.kindDef.race.defName.ToLower().Contains("droid") && !AndroidsCompatibility.IsAndroid(pawn)))
{
return;
}
else if (pawn.IsAnimal())
{
GenerateForAnimal(pawn);
}
else
{
GenerateForHumanlike(pawn);
}
}
[SyncMethod]
static void GenerateForHumanlike(Pawn pawn)
{
var count = Rand.RangeInclusive(0, RJWPreferenceSettings.MaxQuirks);
var list = Quirk.All.ToList();
list.Shuffle();
// Some quirks may be hard for a given pawn to indulge in.
// For example a female homosexual will have a hard time satisfying an impregnation fetish.
// But rimworld is a weird place and you never know what the pawn will be capable of in the future.
// We still don't want straight up contradictory results like fertile + infertile.
var hasFertility = pawn.RaceHasFertility();
var actual = new List<Quirk>();
foreach (var quirk in list)
{
if (count == 0)
{
break;
}
// These special cases are sort of hacked in.
// In theory there should be a general way for the quirk itself to decide when it applies.
if (quirk == Quirk.Fertile && (!hasFertility || actual.Contains(Quirk.Infertile)))
{
continue;
}
if (quirk == Quirk.Infertile && (!hasFertility || actual.Contains(Quirk.Fertile)))
{
continue;
}
// Have to earn these.
if (quirk == Quirk.Breeder || quirk == Quirk.Incubator)
{
continue;
}
// No fair having a fetish for your own race.
// But tags don't conflict so having a fetish for robot plant dragons is fine.
if (quirk.RaceTag != null && pawn.Has(quirk.RaceTag))
{
continue;
}
count--;
actual.Add(quirk);
}
foreach (var quirk in actual)
{
pawn.Add(quirk);
}
}
[SyncMethod]
static void GenerateForAnimal(Pawn pawn)
{
if (Rand.Chance(0.1f))
{
pawn.Add(Quirk.Messy);
}
if (!pawn.RaceHasFertility())
{
return;
}
if (Rand.Chance(0.1f))
{
pawn.Add(Quirk.Fertile);
}
else if (Rand.Chance(0.1f))
{
pawn.Add(Quirk.Infertile);
}
}
}
}
| Korth95/rjw | 1.5/Source/Comps/QuirkAdder.cs | C# | mit | 5,992 |
using Verse;
using RimWorld;
using Verse.AI;
namespace rjw
{
/// <summary>
/// data for sex related stuff/outcome
/// </summary>
public class SexProps : IExposable
{
public Pawn pawn;
public Pawn partner;
public bool hasPartner() => partner != null && partner != pawn;
public xxx.rjwSextype sexType = xxx.rjwSextype.None;
public InteractionDef dictionaryKey = null;
public string rulePack = null;
public bool usedCondom = false;
public bool isRape = false;
public bool isReceiver = false;// as JobDriver_SexBaseReciever
public bool isRevese = false;// brainfuck with who fucks who, see impregnation for clarity with tags n shit?. interaction.HasInteractionTag(InteractionTag.Reverse)
public bool isRapist = false;
public bool isCoreLovin = false;//vanilla loving, skip some mechanics. should really clean this up someday
public bool isWhoring = false;
public bool canBeGuilty = true;// can initiator pawn be counted guilty for percepts, player initiated/rmb actrions = false
public int orgasms = 0; // The orgasms had by the pawn
public SexProps()
{
}
public bool IsInitiator() => !isReceiver;
public bool IsSubmissive() => (isReceiver && !isRevese) || (!isReceiver && isRevese);
public SexProps GetForPartner()
{
return new SexProps
{
pawn = partner,
partner = pawn,
sexType = sexType,
dictionaryKey = dictionaryKey,
rulePack = rulePack,
usedCondom = usedCondom,
isRape = isRape,
isReceiver = !isReceiver,
isRevese = isRevese,
isRapist = isRapist,
isCoreLovin = isCoreLovin,
isWhoring = isWhoring,
canBeGuilty = canBeGuilty,
orgasms = orgasms
};
}
public void ExposeData()
{
Scribe_References.Look(ref pawn, "pawn");
Scribe_References.Look(ref partner, "partner");
Scribe_Values.Look(ref sexType, "sexType");
Scribe_Defs.Look(ref dictionaryKey, "dictionaryKey");
Scribe_Values.Look(ref rulePack, "rulePack");
Scribe_Values.Look(ref usedCondom, "usedCondom");
Scribe_Values.Look(ref isRape, "isRape");
Scribe_Values.Look(ref isReceiver, "isReceiver");
Scribe_Values.Look(ref isRapist, "isRapist");
Scribe_Values.Look(ref isCoreLovin, "isCoreLovin");
Scribe_Values.Look(ref isWhoring, "isWhoring");
Scribe_Values.Look(ref canBeGuilty, "canBeGuilty");
Scribe_Values.Look(ref orgasms, "orgasms");
}
}
}
| Korth95/rjw | 1.5/Source/Comps/SexProps.cs | C# | mit | 2,382 |
using RimWorld;
namespace rjw
{
[DefOf]
public static class IssueDefOf
{
public static IssueDef Lovin;
static IssueDefOf()
{
DefOfHelper.EnsureInitializedInCtor(typeof(IssueDefOf));
}
}
}
| Korth95/rjw | 1.5/Source/DefOf/IssueDefOf.cs | C# | mit | 244 |
using RimWorld;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Verse;
namespace rjw
{
[DefOf]
public static class JobDefOf
{
static JobDefOf()
{
DefOfHelper.EnsureInitializedInCtor(typeof(JobDefOf));
}
public static JobDef RJW_AdjustParts;
}
}
| Korth95/rjw | 1.5/Source/DefOf/JobDefOf.cs | C# | mit | 354 |
using RimWorld;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Verse;
using Verse.AI;
namespace Rimlaser
{
public class JobDriver_AdjustParts : JobDriver
{
private Thing Gun => job.GetTarget(TargetIndex.A).Thing;
private IBeamColorThing BeamColorThing => job.GetTarget(TargetIndex.A).Thing as IBeamColorThing;
private Thing Prism => job.GetTarget(TargetIndex.B).Thing;
public override bool TryMakePreToilReservations(bool errorOnFailed)
{
if (BeamColorThing == null) return false;
return pawn.Reserve(Gun, job, 1, -1, null, errorOnFailed) && pawn.Reserve(Prism, job, 1, -1, null, errorOnFailed);
}
protected override IEnumerable<Toil> MakeNewToils()
{
this.FailOnDespawnedNullOrForbidden(TargetIndex.A);
yield return Toils_Goto.GotoThing(TargetIndex.B, PathEndMode.Touch).FailOnDespawnedNullOrForbidden(TargetIndex.B).FailOnSomeonePhysicallyInteracting(TargetIndex.B);
yield return Toils_Haul.StartCarryThing(TargetIndex.B, false, false, false);
yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch).FailOnDespawnedOrNull(TargetIndex.A);
Toil repair = Toils_General.Wait(75, TargetIndex.None);
repair.FailOnDespawnedOrNull(TargetIndex.A);
repair.FailOnCannotTouch(TargetIndex.A, PathEndMode.Touch);
repair.WithEffect(Gun.def.repairEffect, TargetIndex.A);
repair.WithProgressBarToilDelay(TargetIndex.A, false, -0.5f);
yield return repair;
yield return new Toil
{
initAction = delegate ()
{
BeamColorThing.BeamColor = pawn.CurJob.maxNumMeleeAttacks;
var targetInfo = new TargetInfo(Gun.Position, Map, false);
Effecter effecter = EffecterDefOf.Deflect_Metal.Spawn();
effecter.Trigger(targetInfo, targetInfo);
effecter.Cleanup();
this.Prism.Destroy(DestroyMode.Vanish);
}
};
yield break;
}
}
}
| Korth95/rjw | 1.5/Source/DefOf/JobDriver_AdjustParts.cs | C# | mit | 2,204 |
using RimWorld;
namespace rjw
{
[DefOf]
public static class PreceptDefOf
{
[MayRequireIdeology]
public static PreceptDef Lovin_Prohibited;
[MayRequireIdeology]
public static PreceptDef Lovin_Horrible;
[MayRequireIdeology]
public static PreceptDef Lovin_SpouseOnly_Strict;
[MayRequireIdeology]
public static PreceptDef Lovin_SpouseOnly_Moderate;
[MayRequireIdeology]
public static PreceptDef Lovin_SpouseOnly_Mild;
public static PreceptDef Lovin_Free;
[MayRequireIdeology]
public static PreceptDef Lovin_FreeApproved;
static PreceptDefOf()
{
DefOfHelper.EnsureInitializedInCtor(typeof(IssueDefOf));
}
}
}
| Korth95/rjw | 1.5/Source/DefOf/PreceptDefOf.cs | C# | mit | 690 |
using Verse;
using RimWorld;
namespace rjw
{
[DefOf]
public static class RJWHediffDefOf
{
public static HediffDef HumpShroomAddiction;
public static HediffDef HumpShroomEffect;
}
} | Korth95/rjw | 1.5/Source/DefOf/RJWHediffDefOf.cs | C# | mit | 214 |
using Verse;
using RimWorld;
namespace rjw
{
[DefOf]
public static class RJWStatCategoryDefOf
{
[DefAlias("RJW_OriginalPartOwner")]
public static StatCategoryDef OriginalPartOwner;
static RJWStatCategoryDefOf()
{
DefOfHelper.EnsureInitializedInCtor(typeof(RJWStatCategoryDefOf));
}
}
} | Korth95/rjw | 1.5/Source/DefOf/RJWStatCategoryDefOf.cs | C# | mit | 304 |
using RimWorld;
using Verse;
namespace rjw
{
[DefOf]
public static class RJW_RecipeDefOf
{
public static RecipeDef AttachPenis;
public static RecipeDef InstallPenis;
public static RecipeDef RemovePenis;
}
}
| Korth95/rjw | 1.5/Source/DefOf/RJW_RecipeDefOf.cs | C# | mit | 221 |
using Verse;
using RimWorld;
using Verse.AI;
namespace rjw
{
[DefOf]
public static class VanillaDutyDefOf
{
public static DutyDef EnterTransporter;
static VanillaDutyDefOf()
{
DefOfHelper.EnsureInitializedInCtor(typeof(VanillaDutyDefOf));
}
}
} | Korth95/rjw | 1.5/Source/DefOf/VanillaDutyDefOf.cs | C# | mit | 261 |
using Verse;
using RimWorld;
namespace rjw
{
[DefOf]
public static class VanillaRoomRoleDefOf
{
public static RoomRoleDef Laboratory;
public static RoomRoleDef DiningRoom;
public static RoomRoleDef RecRoom;
static VanillaRoomRoleDefOf()
{
DefOfHelper.EnsureInitializedInCtor(typeof(VanillaRoomRoleDefOf));
}
}
} | Korth95/rjw | 1.5/Source/DefOf/VanillaRoomRoleDefOf.cs | C# | mit | 335 |
using Verse;
using RimWorld;
namespace rjw
{
[DefOf]
public static class VanillaThoughtDefOf
{
public static ThoughtDef AteHumanlikeMeatAsIngredient;
static VanillaThoughtDefOf()
{
DefOfHelper.EnsureInitializedInCtor(typeof(VanillaThoughtDefOf));
}
}
} | Korth95/rjw | 1.5/Source/DefOf/VanillaThoughtDefOf.cs | C# | mit | 269 |
using Verse;
using RimWorld;
namespace rjw
{
[DefOf]
public static class VanillaTraitDefOf
{
public static TraitDef Tough;
public static TraitDef Nerves;
public static TraitDef Beauty;
public static TraitDef TooSmart;
public static TraitDef NaturalMood;
public static TraitDef Cannibal;
static VanillaTraitDefOf()
{
DefOfHelper.EnsureInitializedInCtor(typeof(VanillaTraitDefOf));
}
}
} | Korth95/rjw | 1.5/Source/DefOf/VanillaTraitDefOf.cs | C# | mit | 417 |
using Verse;
using RimWorld;
using Multiplayer.API;
namespace rjw
{
public static class PawnDesignations_Breedee
{
public static bool UpdateCanDesignateBreeding(this Pawn pawn)
{
//no permission to change designation for NON prisoner hero/ other player
if (!pawn.CanChangeDesignationPrisoner() && !pawn.CanChangeDesignationColonist())
return pawn.GetRJWPawnData().CanDesignateBreeding = false;
//no permission to change designation for prisoner hero/ self
if (!pawn.CanChangeDesignationPrisoner())
return pawn.GetRJWPawnData().CanDesignateBreeding = false;
//cant have penetrative sex
if (!xxx.can_be_fucked(pawn))
return pawn.GetRJWPawnData().CanDesignateBreeding = false;
if (RJWSettings.bestiality_enabled && xxx.is_human(pawn))
{
if (!pawn.IsDesignatedHero())
{
if ((xxx.is_zoophile(pawn) || (RJWSettings.override_RJW_designation_checks && !MP.IsInMultiplayer)) && pawn.IsColonist)
return pawn.GetRJWPawnData().CanDesignateBreeding = true;
}
else if (pawn.IsHeroOwner())
return pawn.GetRJWPawnData().CanDesignateBreeding = true;
if (pawn.IsPrisonerOfColony || xxx.is_slave(pawn))
return pawn.GetRJWPawnData().CanDesignateBreeding = true;
}
if (RJWSettings.animal_on_animal_enabled && xxx.is_animal(pawn)
&& pawn.Faction == Faction.OfPlayer)
return pawn.GetRJWPawnData().CanDesignateBreeding = true;
return pawn.GetRJWPawnData().CanDesignateBreeding = false;
}
public static bool CanDesignateBreeding(this Pawn pawn)
{
return pawn.GetRJWPawnData().CanDesignateBreeding;
}
public static void ToggleBreeding(this Pawn pawn)
{
pawn.UpdateCanDesignateBreeding();
if (pawn.CanDesignateBreeding())
{
if (!pawn.IsDesignatedBreeding())
DesignateBreeding(pawn);
else
UnDesignateBreeding(pawn);
}
}
public static bool IsDesignatedBreeding(this Pawn pawn)
{
if (pawn.GetRJWPawnData().Breeding)
{
if (!xxx.is_animal(pawn))
{
if (!RJWSettings.bestiality_enabled)
UnDesignateBreeding(pawn);
else if (!pawn.IsDesignatedHero())
if (!(xxx.is_zoophile(pawn) || pawn.IsPrisonerOfColony || xxx.is_slave(pawn)))
if (!(RJWSettings.WildMode || (RJWSettings.override_RJW_designation_checks && !MP.IsInMultiplayer)))
UnDesignateBreeding(pawn);
}
else
{
if (!RJWSettings.animal_on_animal_enabled)
UnDesignateBreeding(pawn);
else if (!pawn.Faction?.IsPlayer ?? false)
UnDesignateBreeding(pawn);
}
if (pawn.Dead)
pawn.UnDesignateBreeding();
}
return pawn.GetRJWPawnData().Breeding;
}
[SyncMethod]
public static void DesignateBreeding(this Pawn pawn)
{
DesignatorsData.rjwBreeding.AddDistinct(pawn);
pawn.GetRJWPawnData().Breeding = true;
}
[SyncMethod]
public static void UnDesignateBreeding(this Pawn pawn)
{
DesignatorsData.rjwBreeding.Remove(pawn);
pawn.GetRJWPawnData().Breeding = false;
}
}
}
| Korth95/rjw | 1.5/Source/Designators/Breedee.cs | C# | mit | 2,970 |
using Verse;
using RimWorld;
using Multiplayer.API;
namespace rjw
{
public static class PawnDesignations_Breeder
{
public static bool UpdateCanDesignateBreedingAnimal(this Pawn pawn)
{
//no permission to change designation for NON prisoner hero/ other player
if (!pawn.CanChangeDesignationPrisoner() && !pawn.CanChangeDesignationColonist())
return pawn.GetRJWPawnData().CanDesignateBreedingAnimal = false;
//no permission to change designation for prisoner hero/ self
if (!pawn.CanChangeDesignationPrisoner())
return pawn.GetRJWPawnData().CanDesignateBreedingAnimal = false;
//Log.Message("CanDesignateAnimal for " + xxx.get_pawnname(pawn) + " " + SaveStorage.bestiality_enabled);
//Log.Message("checking animal props " + (pawn.Faction?.IsPlayer.ToString()?? "tynanfag") + xxx.is_animal(pawn) + xxx.can_rape(pawn));
if ((RJWSettings.bestiality_enabled || RJWSettings.animal_on_animal_enabled)
&& xxx.is_animal(pawn)
&& xxx.can_fuck(pawn)
&& pawn.Faction == Faction.OfPlayer)
return pawn.GetRJWPawnData().CanDesignateBreedingAnimal = true;
return pawn.GetRJWPawnData().CanDesignateBreedingAnimal = false;
}
public static bool CanDesignateBreedingAnimal(this Pawn pawn)
{
return pawn.GetRJWPawnData().CanDesignateBreedingAnimal;
}
public static void ToggleBreedingAnimal(this Pawn pawn)
{
pawn.UpdateCanDesignateBreedingAnimal();
if (pawn.CanDesignateBreedingAnimal())
{
if (!pawn.IsDesignatedBreedingAnimal())
DesignateBreedingAnimal(pawn);
else
UnDesignateBreedingAnimal(pawn);
}
}
public static bool IsDesignatedBreedingAnimal(this Pawn pawn)
{
if (pawn.GetRJWPawnData().BreedingAnimal)
{
if (!pawn.Faction?.IsPlayer ?? false)
UnDesignateBreedingAnimal(pawn);
if (pawn.Dead)
pawn.UnDesignateBreedingAnimal();
}
return pawn.GetRJWPawnData().BreedingAnimal;
}
[SyncMethod]
public static void DesignateBreedingAnimal(this Pawn pawn)
{
DesignatorsData.rjwBreedingAnimal.AddDistinct(pawn);
pawn.GetRJWPawnData().BreedingAnimal = true;
}
[SyncMethod]
public static void UnDesignateBreedingAnimal(this Pawn pawn)
{
DesignatorsData.rjwBreedingAnimal.Remove(pawn);
pawn.GetRJWPawnData().BreedingAnimal = false;
}
}
}
| Korth95/rjw | 1.5/Source/Designators/Breeder.cs | C# | mit | 2,281 |
using Verse;
using Multiplayer.API;
namespace rjw
{
public static class PawnDesignations_Comfort
{
public static bool UpdateCanDesignateComfort(this Pawn pawn)
{
//rape disabled
if (!RJWSettings.rape_enabled)
return pawn.GetRJWPawnData().CanDesignateComfort = false;
//no permission to change designation for NON prisoner hero/ other player
if (!pawn.CanChangeDesignationPrisoner() && !pawn.CanChangeDesignationColonist())
return pawn.GetRJWPawnData().CanDesignateComfort = false;
//no permission to change designation for prisoner hero/ self
if (!pawn.CanChangeDesignationPrisoner())
return pawn.GetRJWPawnData().CanDesignateComfort = false;
//cant sex
if (!(xxx.can_fuck(pawn) || xxx.can_be_fucked(pawn)))
return pawn.GetRJWPawnData().CanDesignateComfort = false;
if (!pawn.IsDesignatedHero())
{
if ((xxx.is_masochist(pawn) || (RJWSettings.override_RJW_designation_checks && !MP.IsInMultiplayer)) && pawn.IsColonist)
return pawn.GetRJWPawnData().CanDesignateComfort = true;
}
else if (pawn.IsHeroOwner())
return pawn.GetRJWPawnData().CanDesignateComfort = true;
if (pawn.IsPrisonerOfColony || xxx.is_slave(pawn))
return pawn.GetRJWPawnData().CanDesignateComfort = true;
return pawn.GetRJWPawnData().CanDesignateComfort = false;
}
public static bool CanDesignateComfort(this Pawn pawn)
{
return pawn.GetRJWPawnData().CanDesignateComfort;
}
public static void ToggleComfort(this Pawn pawn)
{
pawn.UpdateCanDesignateComfort();
if (pawn.CanDesignateComfort())
{
if (!pawn.IsDesignatedComfort())
DesignateComfort(pawn);
else
UnDesignateComfort(pawn);
}
}
public static bool IsDesignatedComfort(this Pawn pawn)
{
if (pawn.GetRJWPawnData().Comfort)
{
if (!pawn.IsDesignatedHero())
{
if (!pawn.IsPrisonerOfColony)
if (!(xxx.is_masochist(pawn) || xxx.is_slave(pawn)))
{
if (!pawn.IsColonist)
UnDesignateComfort(pawn);
else if (!(RJWSettings.WildMode || (RJWSettings.override_RJW_designation_checks && !MP.IsInMultiplayer)))
UnDesignateComfort(pawn);
}
}
if (pawn.Dead)
pawn.UnDesignateComfort();
}
return pawn.GetRJWPawnData().Comfort;
}
[SyncMethod]
public static void DesignateComfort(this Pawn pawn)
{
DesignatorsData.rjwComfort.AddDistinct(pawn);
pawn.GetRJWPawnData().Comfort = true;
}
[SyncMethod]
public static void UnDesignateComfort(this Pawn pawn)
{
DesignatorsData.rjwComfort.Remove(pawn);
pawn.GetRJWPawnData().Comfort = false;
}
}
}
| Korth95/rjw | 1.5/Source/Designators/Comfort.cs | C# | mit | 2,597 |
using Verse;
using RimWorld;
using Multiplayer.API;
namespace rjw
{
public static class PawnDesignations_Hero
{
public static bool UpdateCanDesignateHero(this Pawn pawn)
{
if ((RJWSettings.RPG_hero_control)
&& xxx.is_human(pawn)
&& pawn.IsColonist
&& !xxx.is_slave(pawn)
&& !pawn.IsPrisoner)
{
if (!pawn.IsDesignatedHero())
{
foreach (Pawn item in DesignatorsData.rjwHero)
{
if (item.IsHeroOwner())
{
if (RJWSettings.RPG_hero_control_Ironman && !SaveStorage.DataStore.GetPawnData(item).Ironman)
SetHeroIronman(item);
if (item.Dead && !SaveStorage.DataStore.GetPawnData(item).Ironman)
{
UnDesignateHero(item);
//Log.Warning("CanDesignateHero:: " + MP.PlayerName + " hero is dead remove hero tag from " + item.Name);
}
else
{
//Log.Warning("CanDesignateHero:: " + MP.PlayerName + " already has hero - " + item.Name);
return pawn.GetRJWPawnData().CanDesignateHero = false;
}
}
else
continue;
}
return pawn.GetRJWPawnData().CanDesignateHero = true;
}
}
return pawn.GetRJWPawnData().CanDesignateHero = false;
}
public static bool CanDesignateHero(this Pawn pawn)
{
return pawn.GetRJWPawnData().CanDesignateHero;
}
public static void ToggleHero(this Pawn pawn)
{
pawn.UpdateCanDesignateHero();
if (pawn.CanDesignateHero() && Find.Selector.NumSelected <= 1)
{
if (!pawn.IsDesignatedHero())
DesignateHero(pawn);
}
}
public static bool IsDesignatedHero(this Pawn pawn)
{
return pawn.GetRJWPawnData().Hero;
}
public static void DesignateHero(this Pawn pawn)
{
SyncHero(pawn, MP.PlayerName);
}
[SyncMethod]
public static void UnDesignateHero(this Pawn pawn)
{
DesignatorsData.rjwHero.Remove(pawn);
pawn.GetRJWPawnData().Hero = false;
}
public static bool IsHeroOwner(this Pawn pawn)
{
if (!MP.enabled)
return pawn.GetRJWPawnData().HeroOwner == "Player" || pawn.GetRJWPawnData().HeroOwner == null || pawn.GetRJWPawnData().HeroOwner == "";
else
return pawn.GetRJWPawnData().HeroOwner == MP.PlayerName;
}
[SyncMethod]
static void SyncHero(Pawn pawn, string theName)
{
if (!MP.enabled)
theName = "Player";
pawn.GetRJWPawnData().Hero = true;
pawn.GetRJWPawnData().HeroOwner = theName;
pawn.GetRJWPawnData().Ironman = RJWSettings.RPG_hero_control_Ironman;
DesignatorsData.rjwHero.AddDistinct(pawn);
string text = pawn.Name + " is now hero of " + theName;
Messages.Message(text, pawn, MessageTypeDefOf.NeutralEvent);
//Log.Message(MP.PlayerName + " set " + pawn.Name + " to hero:" + pawn.GetPawnData().Hero);
pawn.UpdatePermissions();
}
[SyncMethod]
public static void SetHeroIronman(this Pawn pawn)
{
pawn.GetRJWPawnData().Ironman = true;
}
}
}
| Korth95/rjw | 1.5/Source/Designators/Hero.cs | C# | mit | 2,861 |
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;
}
}
}
| Korth95/rjw | 1.5/Source/Designators/Milking.cs | C# | mit | 1,258 |
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;
}
}
}
| Korth95/rjw | 1.5/Source/Designators/Service.cs | C# | mit | 2,249 |
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;
}
}
}
| Korth95/rjw | 1.5/Source/Designators/Utility.cs | C# | mit | 3,125 |
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) { }
}
}
}
| Korth95/rjw | 1.5/Source/Designators/_RJWdesignationsWidget.cs | C# | mit | 12,842 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using HarmonyLib;
using Verse;
using RimWorld;
using UnityEngine;
// Non-pregnancy Biotech-related patches
namespace rjw
{
[HarmonyPatch]
class LifeStageWorker_HumanlikeX_Notify_LifeStageStarted
{
static IEnumerable<MethodBase> TargetMethods()
{
const string lifeStageStarted = nameof(LifeStageWorker.Notify_LifeStageStarted);
yield return AccessTools.Method(typeof(LifeStageWorker_HumanlikeChild), lifeStageStarted);
yield return AccessTools.Method(typeof(LifeStageWorker_HumanlikeAdult), lifeStageStarted);
}
// Fixes errors caused by trying to spawn a biotech-only effector when a child starts a new lifestage
// and by trying to send a biotech-only letter when a child turns three
[HarmonyTranspiler]
static IEnumerable<CodeInstruction> FixLifeStageStartError(IEnumerable<CodeInstruction> instructions, MethodBase original)
{
PropertyInfo thingSpawned = AccessTools.DeclaredProperty(typeof(Thing), nameof(Thing.Spawned));
MethodInfo shouldSendNotificationsAbout = AccessTools.Method(typeof(PawnUtility), nameof(PawnUtility.ShouldSendNotificationAbout));
bool foundAny = false;
foreach (var instruction in instructions)
{
yield return instruction;
// if (pawn.Spawned) SpawnBiotechOnlyEffector()
// => if (pawn.Spawned && ModsConfig.IsBiotechActive) SpawnBiotechOnlyEffector()
if (instruction.Calls(thingSpawned.GetMethod) || instruction.Calls(shouldSendNotificationsAbout))
{
yield return CodeInstruction.Call(typeof(ModsConfig), "get_BiotechActive");
yield return new CodeInstruction(OpCodes.And);
foundAny = true;
}
}
if (!foundAny)
{
ModLog.Error("Failed to patch " + original.Name);
}
}
}
[HarmonyPatch(typeof(WidgetsWork), "get_WorkBoxBGTex_AgeDisabled")]
class WidgetsWork_WorkBoxBGTex_AgeDisabled
{
[HarmonyPrefix]
static bool DontLoadMissingTexture(ref Texture2D __result)
{
if (!ModsConfig.BiotechActive)
{
__result = WidgetsWork.WorkBoxBGTex_Awful;
return false;
}
return true;
}
}
// If biotech is disabled, TeachOpportunity will NRE due to a null ConceptDef argument
// Silence the error that interrupts AgeTick results by adding a null check.
[HarmonyPatch(typeof(LessonAutoActivator), nameof(LessonAutoActivator.TeachOpportunity), new [] {typeof(ConceptDef), typeof(Thing), typeof(OpportunityType)})]
static class Patch_LessonAutoActivator_TeachOpportunity
{
public static bool Prefix(ConceptDef conc)
{
// call the underlying method if concept is non-null
return conc != null;
}
}
// If biotech is disabled, make the Baby() method return false in the targeted method.
[HarmonyPatch]
static class Patch_DevelopmentalStageExtensions_Baby_Callers
{
static IEnumerable<MethodBase> TargetMethods()
{
// Make babies follow adult rules for food eligibility instead of requiring milk/baby food
yield return AccessTools.Method(typeof(FoodUtility), nameof(FoodUtility.WillEat), new [] {typeof(Pawn), typeof(ThingDef), typeof(Pawn), typeof(bool), typeof(bool)});
// Make babies able to be fed in bed as a patient in lieu of nursing
yield return AccessTools.Method(typeof(WorkGiver_FeedPatient), nameof(WorkGiver_FeedPatient.HasJobOnThing), new [] {typeof(Pawn), typeof(Thing), typeof(bool)});
}
[HarmonyTranspiler]
public static IEnumerable<CodeInstruction> BabyMethodShouldReturnFalse(IEnumerable<CodeInstruction> instructions, MethodBase original)
{
bool foundAny = false;
MethodInfo developmentalStageIsBabyMethod = AccessTools.Method(typeof(DevelopmentalStageExtensions), nameof(DevelopmentalStageExtensions.Baby));
List<CodeInstruction> codeInstructions = instructions.ToList();
foreach (CodeInstruction instruction in codeInstructions)
{
yield return instruction;
if (instruction.Calls(developmentalStageIsBabyMethod))
{
foundAny = true;
if (!ModsConfig.BiotechActive)
{
// After calling the Baby() method, AND the result with 0, to make it as if DevelopmentalStageExtensions::Baby() returned false.
yield return new CodeInstruction(OpCodes.Ldc_I4_0);
yield return new CodeInstruction(OpCodes.And);
}
}
}
if (!foundAny)
{
ModLog.Error("Failed to patch " + original.Name);
}
}
}
// Check for fertile penis instead of gender when compiling list of pawns that could fertilize ovum
[HarmonyPatch]
static class Patch_HumanOvum_CanFertilizeReport
{
static IEnumerable<MethodBase> TargetMethods()
{
yield return AccessTools.Method(typeof(HumanOvum), "CanFertilizeReport", new[] { typeof(Pawn) });
}
static bool hasPenis(Pawn p)
{
// need to use current hediffSet, else has_penis_fertile reads data from save (an issue if a pawn lost their penis since then)
List<Hediff> parts = p?.health?.hediffSet?.hediffs;
return Genital_Helper.has_penis_fertile(p, parts);
}
[HarmonyTranspiler]
public static IEnumerable<CodeInstruction> CheckForPenisInsteadOfGender(IEnumerable<CodeInstruction> instructions, MethodBase original)
{
MethodInfo checkForPenis = AccessTools.Method(typeof(Patch_HumanOvum_CanFertilizeReport), nameof(Patch_HumanOvum_CanFertilizeReport.hasPenis));
bool foundGenderCheck = false;
foreach (CodeInstruction ci in instructions)
{
string cis = ci.ToString();
if (cis.Contains("Verse.Gender Verse.Pawn::gender"))
{
// check for fertile penis instead of male gender
foundGenderCheck = true;
yield return new CodeInstruction(OpCodes.Call, checkForPenis);
}
else
{
yield return ci;
}
}
if (!foundGenderCheck)
{
ModLog.Warning("Failed to patch " + original.Name);
}
}
}
// If babies are malnourished, mark them as needing urgent medical rest, despite being permanently downed.
[HarmonyPatch(typeof(HealthAIUtility), nameof(HealthAIUtility.ShouldSeekMedicalRestUrgent), new [] {typeof(Pawn)})]
static class Patch_HealthAIUtility_ShouldSeekMedicalRestUrgent
{
public static bool Prefix(Pawn pawn, ref bool __result)
{
if (!ModsConfig.BiotechActive && pawn.DevelopmentalStage.Baby())
{
__result = true;
return false;
}
return true;
}
}
}
| Korth95/rjw | 1.5/Source/Harmony/BiotechPatches.cs | C# | mit | 7,185 |
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);
}
}
}
}
} | Korth95/rjw | 1.5/Source/Harmony/Building_Bed_Patch.cs | C# | mit | 10,116 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using HarmonyLib;
namespace rjw
{
public static class CodeExtensions
{
/// <summary>
/// <para>Breaks apart a list of instructions at some specific point, identified by a
/// predicate function. The first instruction that the predicate matches will be
/// included in the `before` list, while all remaining instructions will be
/// in the `after` list.</para>
/// <para>If no instructions matched the predicate, all instructions will be in
/// the `before` list and the `after` list will be empty.</para>
/// <para>This is useful for breaking apart the instructions into more manageable
/// chunks to better identify the target of your patch.</para>
/// </summary>
/// <param name="instructions">This list of instructions.</param>
/// <param name="predicate">The predicate to identify the break point.</param>
/// <returns>A tuple, the first being the instructions up to and including the
/// instruction that matched the predicate and the second being everything
/// afterward.</returns>
public static (List<CodeInstruction> before, List<CodeInstruction> after) SplitAfter(
this List<CodeInstruction> instructions,
Predicate<CodeInstruction> predicate)
{
if (instructions.FindIndex(predicate) is var idx and not -1)
{
var before = instructions.Take(idx + 1).ToList();
var after = instructions.Skip(before.Count).ToList();
return (before, after);
}
return (instructions, new());
}
/// <summary>
/// <para>Checks the next instructions in this list of instructions to make sure
/// they all match some expectation, one predicate per instruction. If the
/// predicates all match, it produces two new lists, one with the matched
/// instructions and the other with those matched instructions removed.</para>
/// <para>If any predicate fails to match, the `cut` list will be empty and
/// the `remainder` list will be the same instance as `instructions`.</para>
/// <para>Use this to validate that the code actually is the code you expect
/// and isolate it from other instructions so you can tweak it safely.</para>
/// </summary>
/// <param name="instructions">This list of instructions.</param>
/// <param name="predicates">One or more predicates to test each instruction.</param>
/// <returns>A tuple, the first being the list of cut instructions and the second
/// being the remaining instructions after the cut.</returns>
public static (List<CodeInstruction> cut, List<CodeInstruction> remainder) CutMatchingSequence(
this List<CodeInstruction> instructions,
params Predicate<CodeInstruction>[] predicates)
{
if (predicates.Length == 0)
return (new(), instructions);
if (instructions.Count < predicates.Length)
return (new(), instructions);
if (instructions.Zip(predicates, (il, pred) => pred(il)).Contains(false))
return (new(), instructions);
var cut = instructions.Take(predicates.Length).ToList();
var remainder = instructions.Skip(predicates.Length).ToList();
return (cut, remainder);
}
/// <summary>
/// <para>Determines if this instruction is some form of `stloc` that matches the
/// given index in the locals table.</para>
/// <para>Why is this not a part of Harmony's API?</para>
/// </summary>
/// <param name="il">This instruction.</param>
/// <param name="index">The locals table index to check for.</param>
/// <returns>Whether this is a `stloc` targeting the given index.</returns>
public static bool IsStlocOf(this CodeInstruction il, int index) => index switch
{
0 when il.opcode == OpCodes.Stloc_0 => true,
1 when il.opcode == OpCodes.Stloc_1 => true,
2 when il.opcode == OpCodes.Stloc_2 => true,
3 when il.opcode == OpCodes.Stloc_3 => true,
// Most common thing we'll see...
_ when il.IsStloc() && il.operand is LocalBuilder lb => lb.LocalIndex == index,
// ...but these are also technically possible with `stloc_s` and `stloc`.
_ when il.IsStloc() && il.operand is byte bIndex => bIndex == Convert.ToByte(index),
_ when il.IsStloc() && il.operand is ushort uIndex => uIndex == Convert.ToUInt16(index),
_ => false
};
/// <summary>
/// Copies the labels from this instruction to its replacement. If the replacement
/// instruction also has labels, it ensures that duplicate labels are discarded.
/// </summary>
/// <param name="il">This instruction.</param>
/// <param name="newIl">The instruction that will replace it.</param>
/// <returns>The replacement instruction.</returns>
public static CodeInstruction Replace(this CodeInstruction il, CodeInstruction newIl)
{
var copyLabels = newIl.labels.ToList();
newIl.labels.Clear();
newIl.labels.AddRange(copyLabels.Concat(il.labels).Distinct());
return newIl;
}
}
} | Korth95/rjw | 1.5/Source/Harmony/CodeExtensions.cs | C# | mit | 4,861 |
using HarmonyLib;
using RimWorld;
using System;
using Verse;
namespace rjw
{
///<summary>
///unset designators on GuestRelease
///until pawn leaves map, pawn is still guest/slave/prisoner, so they can actually be changed back
///</summary>
[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());
}
}
}
///<summary>
///unset designators on Pawn_ExitMap
///now pawn actually leaves map and get their factions reset
///</summary>
[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());
}
}
}
} | Korth95/rjw | 1.5/Source/Harmony/DesignatorsUnset.cs | C# | mit | 1,618 |
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.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.");
}
}
{// 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
//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");
}
}
}
| Korth95/rjw | 1.5/Source/Harmony/First.cs | C# | mit | 13,734 |
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), 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);
}
}
}
}
}
| Korth95/rjw | 1.5/Source/Harmony/Patch_GenSpawn.cs | C# | mit | 1,109 |
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,
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.AllowedDevelopmentalStages == DevelopmentalStage.Newborn)
{
if(__result.style != null)
{
__result.style.beardDef = BeardDefOf.NoBeard;
__result.style.SetupTattoos_NoIdeology();
}
}
}
}
}
| Korth95/rjw | 1.5/Source/Harmony/Patch_PawnGenerator.cs | C# | mit | 1,796 |
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)
{
pawn.story.Childhood = null;
pawn.story.Adulthood = null;
// set child to tribal
try
{
if (!ModsConfig.BiotechActive)
pawn.story.Childhood = DefDatabase<BackstoryDef>.AllDefsListForReading.FirstOrDefault(x => x.defName.Contains("rjw_childT"));
else
pawn.story.Childhood = DefDatabase<BackstoryDef>.GetNamed("Newborn79");
}
catch (Exception e)
{
ModLog.Warning(e.ToString());
}
}
static void grow(Pawn pawn)
{
if (!ModsConfig.BiotechActive)
{
// 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;
}
}
} | Korth95/rjw | 1.5/Source/Harmony/Patch_PawnUtility.cs | C# | mit | 4,208 |
using HarmonyLib;
using RimWorld;
using rjw.RMB;
using System.Collections.Generic;
using UnityEngine;
using Verse;
namespace rjw
{
/// <summary>
/// Patches FloatMenuMakerMap to add manual RJW interactions to the context menu
/// </summary>
[HarmonyPatch(typeof(FloatMenuMakerMap), nameof(FloatMenuMakerMap.ChoicesAtFor))]
static class Patch_RMBMenu
{
public static void Postfix(List<FloatMenuOption> __result, Vector3 clickPos, Pawn pawn)
{
RMB_Menu.AddSexFloatMenuOptions(pawn, __result, clickPos);
}
}
} | Korth95/rjw | 1.5/Source/Harmony/Patch_RMBMenu.cs | C# | mit | 526 |
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 LifestageAndXenotypeOptions = AccessTools.Method(typeof(CharacterCardUtility), "LifestageAndXenotypeOptions");
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 as MethodInfo == LifestageAndXenotypeOptions)
{
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.4
if (ModsConfig.BiotechActive)
{
rectNew = new Rect(creationRect.width - 24f, 108f, 24f, 24f);
}
//1.3
else 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;
}
}
}
| Korth95/rjw | 1.5/Source/Harmony/SexualityCard.cs | C# | mit | 3,361 |
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;
using LudeonTK;
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, SaveStorage.ModId);//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);
}
}
//Archotech genitals FertilityToggle
var GenitalBPR = Genital_Helper.get_genitalsBPR(pawn);
IEnumerable<ISexPartHediff> parts = Genital_Helper.get_PartsHediffList(pawn, GenitalBPR).Cast<ISexPartHediff>();
if (parts.Any())
{
foreach (var p in parts)
{
if (p.Def.partTags.Contains("FertilityToggle"))
{
if (pawn.health.hediffSet.HasHediff(HediffDef.Named("ImpregnationBlocker")))
{
if (Widgets.ButtonText(button2, "Enable reproduction"))
{
Change_Fertility(pawn);
}
}
else if (!pawn.health.hediffSet.HasHediff(HediffDef.Named("FertilityEnhancer")))
{
if (Widgets.ButtonText(button2, "Enchance fertility"))
{
Change_Fertility(pawn);
}
}
else
{
if (Widgets.ButtonText(button2, "Disable reproduction"))
{
Change_Fertility(pawn);
}
}
break;
}
}
}
// 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, warnOnFail: true))));
//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_Fertility(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.Cast<ISexPartHediff>())
{
if (p.Def.partTags.Contains("Resizable"))
resizable = true;
}
if (resizable && hed is ISexPartHediff)
{
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 || (p.def as HediffDef_SexPart).partTags.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();
}
}
}
} | Korth95/rjw | 1.5/Source/Harmony/SexualityCardInternal.cs | C# | mit | 23,039 |
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;
}
}
} | Korth95/rjw | 1.5/Source/Harmony/d.cs | C# | mit | 1,332 |
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;
}
}
} | Korth95/rjw | 1.5/Source/Harmony/patch_ABF.cs | C# | mit | 2,262 |
using System.Collections.Generic;
using Verse;
using HarmonyLib;
namespace rjw
{
//adds new gizmo for sex
[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;
}
}
}
}
| Korth95/rjw | 1.5/Source/Harmony/patch_AddSexGizmo.cs | C# | mit | 569 |
using System.Collections.Generic;
using System.Linq;
using HarmonyLib;
using RimWorld;
using Verse;
using UnityEngine;
using Multiplayer.API;
namespace rjw
{
/// <summary>
/// Harmony patch to toggle the RJW designation box showing
/// </summary>
[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());
}
}
///<summary>
///Compact button group containing rjw designations on pawn
///</summary>
[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;
} ///<summary>
///Submit gizmo
///</summary>
[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);
}
}
} | Korth95/rjw | 1.5/Source/Harmony/patch_AnimalTab.cs | C# | mit | 3,157 |
using RimWorld;
using Verse;
using HarmonyLib;
using System.Reflection;
using System.Collections.Generic;
/// <summary>
/// Modifies Dialog_NamePawn so it properly displays same-gender parents in their children’s rename window
/// </summary>
namespace rjw
{
[HarmonyPatch(typeof(Dialog_NamePawn))]
[HarmonyPatch(MethodType.Constructor)]
[HarmonyPatch(new System.Type[] {
typeof(Pawn),
typeof(NameFilter),
typeof(NameFilter),
typeof(Dictionary<NameFilter, List<string>>),
typeof(string),
typeof(string),
typeof(string),
typeof(string)})]
static class patch_Dialog_NamePawn
{
static AccessTools.FieldRef<Dialog_NamePawn, TaggedString> descriptionTextRef = AccessTools.FieldRefAccess<Dialog_NamePawn, TaggedString>("descriptionText");
static MethodInfo DescribePawn = AccessTools.Method(typeof(Dialog_NamePawn), nameof(DescribePawn));
[HarmonyPostfix]
static void Constructor(Dialog_NamePawn __instance)
{
string motherString = "Mother";
string fatherString = "Father";
Pawn pawn = __instance.pawn;
if (pawn != null && pawn.RaceProps.Humanlike)
{
Pawn mother = pawn.GetMother();
Pawn father = pawn.GetFather();
if (father == null && mother == null) return; // this code makes no sense if both failed, idk if this can happen
Pawn parent = RelationChecker.getParent(pawn);
Pawn secondParent = RelationChecker.getSecondParent(pawn);
if (parent != null && secondParent != null && (mother == null || father == null)) // same gender parents
{
if (father == null)
{
fatherString = "Mother"; // feel free to replace with any more fitting term
father = mother == parent ? secondParent : parent;
}
if (mother == null)
{
motherString = "Father";
mother = father == parent ? secondParent : parent;
}
descriptionTextRef(__instance) =
"{0}: {1}\n{2}: {3}".Formatted(
motherString.Translate().CapitalizeFirst(),
(TaggedString)DescribePawn.Invoke(__instance, [mother]),
fatherString.Translate().CapitalizeFirst(),
(TaggedString)DescribePawn.Invoke(__instance, [father]));
}
}
}
}
}
| Korth95/rjw | 1.5/Source/Harmony/patch_Dialog_NamePawn.cs | C# | mit | 2,142 |
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;
}
}
}
| Korth95/rjw | 1.5/Source/Harmony/patch_PartIsMissing.cs | C# | mit | 2,340 |
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;
}
}
}
| Korth95/rjw | 1.5/Source/Harmony/patch_StockGenerator_BuyExpensiveSimple.cs | C# | mit | 635 |
using HarmonyLib;
using RimWorld;
using rjw.RenderNodeWorkers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Verse;
namespace rjw
{
[HarmonyPatch(typeof(PawnRenderTree), "InitializeAncestors")]
public class patch_apparel
{
public static void Postfix(PawnRenderTree __instance)
{
if (__instance.pawn == null) return;
var comp = __instance.pawn.GetComp<CompRJW>();
if (comp == null) return;
if (!comp.drawNude) return;
if (!comp.keep_hat_on && RJWPreferenceSettings.sex_wear == RJWPreferenceSettings.Clothing.Nude)
{
PawnRenderNode value;
PawnRenderNode headNode = (__instance.nodesByTag.TryGetValue(PawnRenderNodeTagDefOf.Head, out value) ? value : null);
attachSubWorkerToNodeAndChildren(headNode);
}
PawnRenderNode value2;
PawnRenderNode bodyNode = (__instance.nodesByTag.TryGetValue(PawnRenderNodeTagDefOf.Body, out value2) ? value2 : null);
attachSubWorkerToNodeAndChildren(bodyNode);
}
public static void attachSubWorkerToNodeAndChildren(PawnRenderNode node)
{
if (node == null) return;
if (node.apparel != null)
{
Apparel x = node.apparel;
if (!(
x.def is bondage_gear_def
|| (!x.def.thingCategories.NullOrEmpty() && x.def.thingCategories.Any(x => x.defName.ToLower().ContainsAny("vibrator", "piercing", "strapon")))
))
{
if(node.Props.subworkerClasses==null) node.Props.subworkerClasses = new List<Type>();
if (!node.Props.subworkerClasses.Contains(typeof(PawnRenderNodeWorker_Apparel_DrawNude)))
node.Props.subworkerClasses.Add(typeof(PawnRenderNodeWorker_Apparel_DrawNude));
}
}
if(node.children != null)
foreach (var item in node.children)
{
attachSubWorkerToNodeAndChildren(item);
}
}
}
[HarmonyPatch(typeof(PawnRenderTree), nameof(PawnRenderTree.AdjustParms))]
public class Patch_skipFlags
{
private static RenderSkipFlagDef bodyTag = DefDatabase<RenderSkipFlagDef>.GetNamed("Body", false);
public static void Postfix(PawnRenderTree __instance, ref PawnDrawParms parms)
{
if (__instance.pawn == null) return;
var comp = __instance.pawn.GetComp<CompRJW>();
if (comp == null) return;
if (!comp.drawNude) return;
if (!comp.keep_hat_on && RJWPreferenceSettings.sex_wear == RJWPreferenceSettings.Clothing.Nude)
{
parms.skipFlags = 0UL;
}
else
{
parms.skipFlags &= ~bodyTag;
}
}
}
}
| Korth95/rjw | 1.5/Source/Harmony/patch_apparel.cs | C# | mit | 2,465 |
using System;
using System.Reflection;
using System.Runtime.Remoting.Messaging;
using HarmonyLib;
using RimWorld;
using RimWorld.Planet;
using Verse;
using Verse.AI;
namespace rjw
{
[HarmonyPatch(typeof(Pawn_ApparelTracker))]
[HarmonyPatch("Wear")]
internal static class PATCH_Pawn_ApparelTracker_Wear
{
// Prevents pawns from equipping a piece of apparel if it conflicts with some locked apparel that they're already wearing
[HarmonyPrefix]
private static bool prevent_wear_by_gear(Pawn_ApparelTracker __instance, ref Apparel newApparel)
{
var tra = __instance;
// //--Log.Message ("Pawn_ApparelTracker.Wear called for " + newApparel.Label + " on " + tra.xxx.get_pawnname(pawn));
foreach (var app in tra.WornApparel)
if (app.has_lock() && (!ApparelUtility.CanWearTogether(newApparel.def, app.def, tra.pawn.RaceProps.body)))
{
if (PawnUtility.ShouldSendNotificationAbout(tra.pawn))
Messages.Message(xxx.get_pawnname(tra.pawn) + " can't wear " + newApparel.def.label + " (blocked by " + app.def.label + ")", tra.pawn, MessageTypeDefOf.NegativeEvent);
return false;
}
return true;
}
// Add the appropriate hediff when gear is worn
[HarmonyPostfix]
private static void on_wear(Pawn_ApparelTracker __instance, Apparel newApparel)
{
var tra = __instance;
if ((newApparel.def is bondage_gear_def def) &&
(newApparel.Wearer == tra.pawn))
{ // Check that the apparel was actually worn
def.soul.on_wear(tra.pawn, newApparel);
}
}
}
// Remove the hediff when the gear is removed
[HarmonyPatch(typeof(Pawn_ApparelTracker))]
[HarmonyPatch("Notify_ApparelRemoved")]
internal static class PATCH_Pawn_ApparelTracker_Remove
{
[HarmonyPostfix]
private static void on_remove(Pawn_ApparelTracker __instance, Apparel apparel)
{
if (apparel.def is bondage_gear_def def)
{
def.soul.on_remove(apparel, __instance.pawn);
}
}
}
// Patch the TryDrop method so that locked apparel cannot be dropped by JobDriver_RemoveApparel or by stripping
// a corpse or downed pawn
internal static class PATCH_Pawn_ApparelTracker_TryDrop
{
// Can't call MakeByRefType in an attribute, which is why this method is necessary.
private static MethodInfo get_target()
{
return typeof(Pawn_ApparelTracker).GetMethod("TryDrop", new Type[] {
typeof(Apparel),
typeof(Apparel).MakeByRefType (),
typeof(IntVec3),
typeof(bool)
});
}
// Can't just put [HarmonyTargetMethod] on get_target, which is why this method is necessary. BTW I don't
// know why HarmonyTargetMethod wasn't working. I'm sure I had everything set up properly so it might be a
// bug in Harmony itself, but I can't be bothered to look into it in detail.
public static void apply(Harmony har)
{
var tar = get_target();
var pat = typeof(PATCH_Pawn_ApparelTracker_TryDrop).GetMethod("prevent_locked_apparel_drop");
har.Patch(tar, new HarmonyMethod(pat), null);
}
public static bool prevent_locked_apparel_drop(Pawn_ApparelTracker __instance, ref Apparel ap, ref bool __result)
{
if (!ap.has_lock())
return true;
else
{
__result = false;
return false;
}
}
}
// Prevent locked apparel from being removed from a pawn who's out on a caravan
// TODO: Allow the apparel to be removed if the key is in the caravan's inventory
//[HarmonyPatch (typeof (WITab_Caravan_Gear))]
//[HarmonyPatch ("TryRemoveFromCurrentWearer")]
//static class PATCH_WITab_Caravan_Gear_TryRemoveFromCurrentWearer {
// [HarmonyPrefix]
// static bool prevent_locked_apparel_removal (WITab_Caravan_Gear __instance, Thing t, ref bool __result)
// {
// var app = t as Apparel;
// if ((app == null) || (! app.has_lock ()))
// return true;
// else {
// __result = false;
// return false;
// }
// }
//}
// Check for the special case where a player uses the caravan gear tab to equip a piece of lockable apparel on a pawn that
// is wearing an identical piece of already locked apparel, and make sure that doesn't work or change anything. This is to
// fix a bug where, even though the new apparel would fail to be equipped on the pawn, it would somehow copy the holostamp
// info from the equipped apparel.
[HarmonyPatch(typeof(WITab_Caravan_Gear))]
[HarmonyPatch("TryEquipDraggedItem")]
internal static class PATCH_WITab_Caravan_Gear_TryEquipDraggedItem
{
private static Thing get_dragged_item(WITab_Caravan_Gear tab)
{
return (Thing)typeof(WITab_Caravan_Gear).GetField("draggedItem", xxx.ins_public_or_no).GetValue(tab);
}
private static void set_dragged_item(WITab_Caravan_Gear tab, Thing t)
{
typeof(WITab_Caravan_Gear).GetField("draggedItem", xxx.ins_public_or_no).SetValue(tab, t);
}
[HarmonyPrefix]
private static bool prevent_locked_apparel_conflict(WITab_Caravan_Gear __instance, ref Pawn p)
{
if (__instance == null) return true;
if (get_dragged_item(__instance) is Apparel dragged_app && p.apparel != null && dragged_app.has_lock())
{
foreach (var equipped_app in p.apparel.WornApparel)
{
if (equipped_app.has_lock() && (!ApparelUtility.CanWearTogether(dragged_app.def, equipped_app.def, p.RaceProps.body)))
{
set_dragged_item(__instance, null);
return false;
}
}
}
return true;
}
}
/* GONE IN b19
// Prevent locked apparel from being removed from a corpse
// TODO: Find out when this method is actually called (probably doesn't matter but still)
[HarmonyPatch(typeof(Dialog_FormCaravan))]
[HarmonyPatch("RemoveFromCorpseIfPossible")]
internal static class PATCH_Dialog_FormCaravan_RemoveFromCorpseIfPossible
{
[HarmonyPrefix]
private static bool prevent_locked_apparel_removal(Dialog_FormCaravan __instance, Thing thing)
{
var app = thing as Apparel;
return (app == null) || (!app.has_lock());
}
}
*/
// Patch a method in a pawn gear tab to give the pawn a special job driver if the player tells them to
// drop locked apparel they have equipped
// TODO: Search for the key and, if the pawn can access it, give them a new job that has them go to the key
// and use it to unlock the apparel
[HarmonyPatch(typeof(ITab_Pawn_Gear))]
[HarmonyPatch("InterfaceDrop")]
internal static class PATCH_ITab_Pawn_Gear_InterfaceDrop
{
private static Pawn SelPawnForGear(ITab_Pawn_Gear tab)
{
var pro = typeof(ITab_Pawn_Gear).GetProperty("SelPawnForGear", xxx.ins_public_or_no);
return (Pawn)pro.GetValue(tab, null);
}
[HarmonyPrefix]
private static bool drop_locked_apparel(ITab_Pawn_Gear __instance, Thing t)
{
var tab = __instance;
var apparel = t as Apparel;
if ((apparel == null) || (!apparel.has_lock()))
return true;
else
{
var p = SelPawnForGear(tab);
if ((p.apparel != null) && (p.apparel.WornApparel.Contains(apparel)))
{
p.jobs.TryTakeOrderedJob(JobMaker.MakeJob(xxx.struggle_in_BondageGear, apparel));
return false;
}
else
return true;
}
}
}
// Patch the method that prisoners use to find apparel in their cell so that they don't try to wear
// something that conflicts with locked apparel. The method used to prevent pawns from trying to
// optimize away locked apparel won't work here because prisoners don't check GetSpecialApparelScoreOffset.
[HarmonyPatch(typeof(JobGiver_PrisonerGetDressed))]
[HarmonyPatch("FindGarmentCoveringPart")]
internal static class PATCH_JobGiver_PrisonerGetDressed_FindGarmentCoveringPart
{
private static bool conflicts(Pawn_ApparelTracker tra, Apparel new_app)
{
foreach (var worn_app in tra.WornApparel)
if (worn_app.has_lock() && (!ApparelUtility.CanWearTogether(worn_app.def, new_app.def, tra.pawn.RaceProps.body)))
return true;
return false;
}
[HarmonyPrefix]
private static bool prevent_locked_apparel_conflict(JobGiver_PrisonerGetDressed __instance, Pawn pawn, BodyPartGroupDef bodyPartGroupDef, ref Apparel __result)
{
// If the prisoner is not wearing locked apparel then just run the regular method
if (!pawn.is_wearing_locked_apparel())
return true;
// Otherwise, duplicate the logic in the regular method except with an additional check
// to filter out apparel that conflicts with worn locked apparel.
else
{
var room = pawn.GetRoom();
if (room.IsPrisonCell)
foreach (var c in room.Cells)
foreach (var t in c.GetThingList(pawn.Map))
{
if ((t is Apparel app) &&
app.def.apparel.bodyPartGroups.Contains(bodyPartGroupDef) &&
pawn.CanReserve(app) &&
ApparelUtility.HasPartsToWear(pawn, app.def) &&
(!conflicts(pawn.apparel, app)))
{
__result = app;
return false;
}
}
__result = null;
return false;
}
}
}
// Patch the method that prisoners use to find apparel in their cell so that they don't try to wear
// something that conflicts with locked apparel. The method used to prevent pawns from trying to
// optimize away locked apparel won't work here because prisoners don't check GetSpecialApparelScoreOffset.
[HarmonyPatch(typeof(JobGiver_OptimizeApparel))]
[HarmonyPatch("ApparelScoreRaw")]
internal static class PATCH_JobGiver_OptimizeApparel_ApparelScoreRaw
{
[HarmonyPostfix]
static void bondage_score_offset(Pawn pawn, Apparel ap, ref float __result, JobGiver_OptimizeApparel __instance)
{
if (ap.HasThingCategory(ThingCategoryDef.Named("Bondage")))
{
if (ap.Wearer == pawn)
__result += 0f;
else if(ap.AllComps.Any(x=> x.props is CompProperties_HoloCryptoStamped))
__result -= 1e5f;
else
__result += 0f;
//Log.Message("bondage_score_offset " + __result);
}
}
}
} | Korth95/rjw | 1.5/Source/Harmony/patch_bondage_gear.cs | C# | mit | 9,662 |
using System;
using System.Reflection;
using HarmonyLib;
using RimWorld;
using rjw.Modules.Interactions.Enums;
using rjw.Modules.Interactions.Objects;
using Verse;
using Verse.AI;
using static HarmonyLib.Code;
namespace rjw
{
/// <summary>
/// Patch:
/// Core Loving, Mating
/// Rational Romance LovinCasual
/// CnP, remove pregnancy if rjw human preg enabled
/// </summary>
// Add a fail condition to JobDriver_Lovin that prevents pawns from lovin' if they aren't physically able/have genitals
[HarmonyPatch(typeof(JobDriver_Lovin), "MakeNewToils")]
internal static class PATCH_JobDriver_Lovin_MakeNewToils
{
[HarmonyPrefix]
private static bool lovin_patch_n_override(JobDriver_Lovin __instance)
{
Pawn pawn = __instance.pawn;
Pawn partner = null;
Building_Bed Bed = null;
var any_ins = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
partner = (Pawn)(__instance.GetType().GetProperty("Partner", any_ins).GetValue(__instance, null));
Bed = (Building_Bed)(__instance.GetType().GetProperty("Bed", any_ins).GetValue(__instance, null));
__instance.FailOn(() => (!(xxx.can_fuck(pawn) || xxx.can_be_fucked(pawn))));
__instance.FailOn(() => (!(xxx.can_fuck(partner) || xxx.can_be_fucked(partner))));
if (RJWSettings.override_lovin)
{
pawn.jobs.EndCurrentJob(JobCondition.Incompletable);
Job job = JobMaker.MakeJob(xxx.casual_sex, partner, Bed);
pawn.jobs.jobQueue.EnqueueFirst(job);
}
return true;
}
}
// Add a fail condition to JobDriver_Mate that prevents animals from lovin' if they aren't physically able/have genitals
[HarmonyPatch(typeof(JobDriver_Mate), "MakeNewToils")]
internal static class PATCH_JobDriver_Mate_MakeNewToils
{
[HarmonyPrefix]
private static bool matin_patch_n_override(JobDriver_Mate __instance)
{
//only reproductive male/futa starts mating job
Pawn pawn = __instance.pawn;
Pawn partner = null;
var any_ins = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
partner = (Pawn)(__instance.GetType().GetProperty("Female", any_ins).GetValue(__instance, null));
__instance.FailOn(() => (!(xxx.can_fuck(pawn) || xxx.can_be_fucked(pawn))));
__instance.FailOn(() => (!(xxx.can_fuck(partner) || xxx.can_be_fucked(partner))));
if (RJWSettings.override_matin)
{
//__instance.FailOn(() => (!RJWSettings.animal_on_animal_enabled));
//if (!RJWSettings.animal_on_animal_enabled)
// return true;
Job job;
if (pawn.kindDef == partner.kindDef || pawn.RaceProps.animalType == partner.RaceProps.animalType)
job = JobMaker.MakeJob(xxx.animalMate, partner);
else if (RJWSettings.animal_on_animal_enabled)
job = JobMaker.MakeJob(xxx.animalBreed, partner);
else
return true;
pawn.jobs.EndCurrentJob(JobCondition.Incompletable);
pawn.jobs.jobQueue.EnqueueFirst(job);
}
return true;
}
}
//Patch for futa animals to initiate mating (vanialla - only male)
[HarmonyPatch(typeof(JobGiver_Mate), "TryGiveJob")]
internal static class PATCH_JobGiver_Mate_TryGiveJob
{
[HarmonyPostfix]
public static void futa_animal_partner_search_patch(ref Job __result, Pawn pawn)
{
//ModLog.Message("patches_lovin::JobGiver_Mate fail, try rjw for " + xxx.get_pawnname(pawn));
var parts = pawn.GetGenitalsList();
if (!Genital_Helper.has_male_bits(pawn, parts) || !pawn.ageTracker.CurLifeStage.reproductive)
{
//ModLog.Message("patches_lovin::JobGiver_Mate " + xxx.get_pawnname(pawn) + ", has no penis " + (Genital_Helper.has_penis(pawn) || Genital_Helper.has_penis_infertile(pawn)));
//ModLog.Message("patches_lovin::JobGiver_Mate " + xxx.get_pawnname(pawn) + ", not reproductive " + !pawn.ageTracker.CurLifeStage.reproductive);
return;
}
Predicate<Thing> validator = delegate (Thing t)
{
Pawn pawn3 = t as Pawn;
var valid = !pawn3.Downed
&& pawn3 != pawn
&& pawn3.CanCasuallyInteractNow()
&& !pawn3.IsForbidden(pawn)
&& !pawn3.HostileTo(pawn)
&& PawnUtility.FertileMateTarget(pawn, pawn3)
&& (RJWSettings.WildMode || // go wild, mate everyone
(!RJWSettings.matin_crossbreed && pawn.def == pawn3.def) || // mate same species - vanilla behavior
(RJWSettings.matin_crossbreed && pawn.RaceProps.animalType != AnimalType.None && pawn.RaceProps.animalType == pawn3.RaceProps.animalType)); // mate same animalType
if (!valid && pawn3 != pawn)
{
//ModLog.Message("patches_lovin::JobGiver_Mate " + xxx.get_pawnname(pawn3) + ", not valid");
//ModLog.Message("patches_lovin::JobGiver_Mate Downed " + pawn3.Downed);
//ModLog.Message("patches_lovin::JobGiver_Mate CanCasuallyInteractNow " + pawn3.CanCasuallyInteractNow());
//ModLog.Message("patches_lovin::JobGiver_Mate IsForbidden " + pawn3.IsForbidden(pawn));
//ModLog.Message("patches_lovin::JobGiver_Mate FertileMateTarget " + PawnUtility.FertileMateTarget(pawn, pawn3));
}
return valid;
};
ThingRequest request = ThingRequest.ForGroup(ThingRequestGroup.Pawn); // mate everyone, filtered by validator
Pawn pawn2 = (Pawn)GenClosest.ClosestThingReachable(pawn.Position, pawn.Map, request, PathEndMode.Touch, TraverseParms.For(pawn), 30f, validator);
if (pawn2 == null)
{
//ModLog.Message("patches_lovin::JobGiver_Mate " + xxx.get_pawnname(pawn) + ", no valid partner found");
return;
}
//__result = JobMaker.MakeJob(xxx.animalBreed, pawn2);
__result = JobMaker.MakeJob(JobDefOf.Mate, pawn2);
//ModLog.Message("patches_lovin::JobGiver_Mate " + xxx.get_pawnname(pawn) + ", female " + xxx.get_pawnname(pawn2) + ", job " + __result);
}
}
//check if female can be impregnated for animal mating (also check rjw pregnancies)
[HarmonyPatch(typeof(PawnUtility), "FertileMateTarget")]
internal static class PATCH_PawnUtility_FertileMateTarget
{
[HarmonyPrefix]
public static bool Prefix(Pawn male, Pawn female, ref bool __state)
{
__state = female.IsPregnant();
//Log.Message("Prefix FertileMateTarget is vanilla/rjw pregnant: " + __state);
return true;
}
[HarmonyPostfix]
public static bool Postfix(bool __result, ref bool __state)
{
if (__result)
{
//Log.Message("Postfix FertileMateTarget is fertile and not vanilla pregnant: " + __result);
if (__state)
{
//Log.Message("Postfix FertileMateTarget is fertile and rjw pregnant: " + __state);
__result = false;
}
}
return __result;
}
}
//Suboptions when starting rjw sex through workgiver
//[HarmonyPatch(typeof(FloatMenuOption), "Chosen")]
//internal static class PATCH_test
//{
// [HarmonyPostfix]
// public static void Postfix(FloatMenuOption __instance)
// {
// try
// {
// if (Find.Selector.NumSelected == 1) //&& (Find.Selector.SingleSelectedThing as Pawn).IsDesignatedHero()
// {
// //TODO: check if rjw jobdriver,
// //Insert another menu or 2 that will modify initiator sex jobdriver to
// //use selected parts - oral/anal/vaginal/etc
// //use selectable sex action - give/receive?
// //use selectable sex action - fuck/fisting?
// Log.Message("---");
// ModLog.Message("FloatMenuOption::Chosen " + __instance);
// ModLog.Message("FloatMenuOption::Chosen " + __instance.Label);
// ModLog.Message("FloatMenuOption::Chosen " + __instance.action.Target);
// ModLog.Message("FloatMenuOption::Chosen initiator - " + Find.Selector.SingleSelectedThing);
// ModLog.Message("FloatMenuOption::Chosen target - " + __instance.revalidateClickTarget);
// ModLog.Message("FloatMenuOption::Chosen initiator - " + (Find.Selector.SingleSelectedThing as Pawn).CurJob);
// Log.Message("---");
// }
// }
// catch
// { }
// }
//}
//JobDriver_DoLovinCasual from RomanceDiversified should have handled whether pawns can do casual lovin,
//so I don't bothered to do a check here, unless some bugs occur due to this.
//this prob needs a patch like above, but who cares
// Call xxx.aftersex after pawns have finished lovin'
// You might be thinking, "wouldn't it be easier to add this code as a finish condition to JobDriver_Lovin in the patch above?" I tried that
// at first but it didn't work because the finish condition is always called regardless of how the job ends (i.e. if it's interrupted or not)
// and there's no way to find out from within the finish condition how the job ended. I want to make sure not apply the effects of sex if the
// job was interrupted somehow.
[HarmonyPatch(typeof(JobDriver), "Cleanup")]
internal static class PATCH_JobDriver_Loving_Cleanup
{
//RomanceDiversified lovin
//not very good solution, some other mod can have same named jobdrivers, but w/e
private readonly static Type JobDriverDoLovinCasual = AccessTools.TypeByName("JobDriver_DoLovinCasual");
//Nightmare Incarnation
//not very good solution, some other mod can have same named jobdrivers, but w/e
private readonly static Type JobDriverNIManaSqueeze = AccessTools.TypeByName("JobDriver_NIManaSqueeze");
//vanilla lovin
private readonly static Type JobDriverLovin = typeof(JobDriver_Lovin);
//vanilla mate
private readonly static Type JobDriverMate = typeof(JobDriver_Mate);
[HarmonyPrefix]
private static bool on_cleanup_driver(JobDriver __instance, JobCondition condition)
{
if (__instance == null)
return true;
if (condition == JobCondition.Succeeded)
{
Pawn pawn = __instance.pawn;
Pawn partner = null;
//ModLog.Message("patches_lovin::on_cleanup_driver" + xxx.get_pawnname(pawn));
var any_ins = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
//[RF] Rational Romance [1.0] loving
if (xxx.RomanceDiversifiedIsActive && __instance.GetType() == JobDriverDoLovinCasual)
{
// not sure RR can even cause pregnancies but w/e
partner = (Pawn)(__instance.GetType().GetProperty("Partner", any_ins).GetValue(__instance, null));
ModLog.Message("patches_lovin::on_cleanup_driver RomanceDiversified/RationalRomance:" + xxx.get_pawnname(pawn) + "+" + xxx.get_pawnname(partner));
}
//Nightmare Incarnation
else if (xxx.NightmareIncarnationIsActive && __instance.GetType() == JobDriverNIManaSqueeze)
{
partner = (Pawn)(__instance.GetType().GetProperty("Victim", any_ins).GetValue(__instance, null));
ModLog.Message("patches_lovin::on_cleanup_driver Nightmare Incarnation:" + xxx.get_pawnname(pawn) + "+" + xxx.get_pawnname(partner));
}
//Vanilla loving
else if (__instance.GetType() == JobDriverLovin)
{
partner = (Pawn)(__instance.GetType().GetProperty("Partner", any_ins).GetValue(__instance, null));
ModLog.Message("patches_lovin:: JobDriverLovin pregnancy:" + xxx.get_pawnname(pawn) + "+" + xxx.get_pawnname(partner));
}
//Vanilla mating
else if (__instance.GetType() == JobDriverMate)
{
partner = (Pawn)(__instance.GetType().GetProperty("Female", any_ins).GetValue(__instance, null));
ModLog.Message("patches_lovin:: JobDriverMate pregnancy:" + xxx.get_pawnname(pawn) + "+" + xxx.get_pawnname(partner));
}
else
return true;
// TODO: Doing TryUseCondom here is a bit weird... it should happen before.
//var usedCondom = CondomUtility.TryUseCondom(pawn) || CondomUtility.TryUseCondom(partner);
//vanilla will probably be fucked up for non humanlikes... but only humanlikes do loving, right? right?
//if rjw pregnancy enabled, remove vanilla for:
//human-human
//animal-animal
//bestiality
//always remove when someone is insect or mech
if (RJWPregnancySettings.humanlike_pregnancy_enabled && xxx.is_human(pawn) && xxx.is_human(partner)
|| RJWPregnancySettings.animal_pregnancy_enabled && xxx.is_animal(pawn) && xxx.is_animal(partner)
|| (RJWPregnancySettings.bestial_pregnancy_enabled && xxx.is_human(pawn) && xxx.is_animal(partner)
|| RJWPregnancySettings.bestial_pregnancy_enabled && xxx.is_animal(pawn) && xxx.is_human(partner))
|| xxx.is_insect(pawn) || xxx.is_insect(partner) || xxx.is_mechanoid(pawn) || xxx.is_mechanoid(partner)
)
{
ModLog.Message("patches_lovin::on_cleanup_driver vanilla pregnancy:" + xxx.get_pawnname(pawn) + "+" + xxx.get_pawnname(partner));
PregnancyHelper.cleanup_vanilla(pawn);
PregnancyHelper.cleanup_vanilla(partner);
}
SexProps nonRJWsexI = SexUtility.SelectSextype(pawn, partner, false, false);
var interaction = Modules.Interactions.Helpers.InteractionHelper.GetWithExtension(nonRJWsexI.dictionaryKey);
nonRJWsexI.isRevese = interaction.HasInteractionTag(InteractionTag.Reverse);
nonRJWsexI.isCoreLovin = true;
SexUtility.ProcessSex(nonRJWsexI); //TODO: fix me someday
SexUtility.SatisfyPersonal(nonRJWsexI);
SexUtility.SatisfyPersonal(nonRJWsexI.GetForPartner());
}
return true;
}
}
}
| Korth95/rjw | 1.5/Source/Harmony/patch_lovin.cs | C# | mit | 12,855 |
using HarmonyLib;
using RimWorld;
using Verse;
using Verse.AI;
namespace rjw
{
/// <summary>
/// disable meditation effects for nymphs (i.e meditation on throne)
/// </summary>
[HarmonyPatch(typeof(JobDriver_Meditate), "MeditationTick")]
internal static class PATCH_JobDriver_Meditate_MeditationTick
{
[HarmonyPrefix]
private static bool Disable_For_Nymph(JobDriver_Meditate __instance)
{
Pawn pawn = __instance.pawn;
if (xxx.is_nympho(pawn))
{
//ModLog.Message("JobGiver_Meditate::MeditationTick for nymph " + xxx.get_pawnname(pawn) + " __instance " + __instance);
CompProperties_MeditationFocus t0 = __instance.Focus.Thing?.def?.comps?.Find(x => x is CompProperties_MeditationFocus) as CompProperties_MeditationFocus;
if (t0 != null)
if (t0.focusTypes.Contains(xxx.SexMeditationFocus))
return true;
return false;
}
//ModLog.Message("JobGiver_Meditate::MeditationTick pass");
return true;
}
}
[HarmonyPatch(typeof(JobGiver_Meditate), "TryGiveJob")]
internal static class PATCH_JobGiver_Meditate_TryGiveJob
{
[HarmonyPostfix]
public static void Disable_For_Nymph(ref Job __result, Pawn pawn)
{
if (__result != null)
if (xxx.is_nympho(pawn))
{
//ModLog.Message("JobGiver_Meditate::TryGiveJob for nymph " + xxx.get_pawnname(pawn) + " job " + __result);
CompProperties_MeditationFocus t1 = __result.targetA.Thing?.def.comps.Find(x => x is CompProperties_MeditationFocus) as CompProperties_MeditationFocus;
CompProperties_MeditationFocus t2 = __result.targetB.Thing?.def.comps.Find(x => x is CompProperties_MeditationFocus) as CompProperties_MeditationFocus;
CompProperties_MeditationFocus t3 = __result.targetC.Thing?.def.comps.Find(x => x is CompProperties_MeditationFocus) as CompProperties_MeditationFocus;
//ModLog.Message("JobGiver_Meditate::TryGiveJob targetA " + t1);
//ModLog.Message("JobGiver_Meditate::TryGiveJob targetB " + t2);
//ModLog.Message("JobGiver_Meditate::TryGiveJob targetC " + t3);
if (t1 != null)
if (t1.focusTypes.Contains(xxx.SexMeditationFocus))
return;
if (t2 != null)
if (t2.focusTypes.Contains(xxx.SexMeditationFocus))
return;
if (t3 != null)
if (t3.focusTypes.Contains(xxx.SexMeditationFocus))
return;
//ModLog.Message("JobGiver_Meditate::Disable_For_Nymph no valid targets fail job");
__result = null;
//ModLog.Message("JobGiver_Meditate::Disable_For_Nymph " + xxx.get_pawnname(pawn) + " job " + __result);
}
}
}
}
| Korth95/rjw | 1.5/Source/Harmony/patch_meditate.cs | C# | mit | 2,541 |
namespace rjw
{
/*
[HarmonyPatch(typeof(Pawn_NeedsTracker))]
[HarmonyPatch("ShouldHaveNeed")]
static class patches_need
{
[HarmonyPostfix]
static void on_postfix(Pawn_NeedsTracker __instance, NeedDef nd, ref bool __result){
Pawn p=(Pawn)(typeof(Pawn_NeedsTracker).GetField("pawn", xxx.ins_public_or_no).GetValue(__instance));
__result = __result && (nd.defName != "Sex" || (p!=null && p.Map!=null));
}
}
*/
} | Korth95/rjw | 1.5/Source/Harmony/patch_need.cs | C# | mit | 430 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using HarmonyLib;
using Multiplayer.API;
using UnityEngine;
using Verse;
using RimWorld;
using rjw.Modules.Testing;
using Seeded = rjw.Modules.Rand.Seeded;
using LudeonTK;
namespace rjw
{
[HarmonyPatch(typeof(Hediff_Pregnant), "DoBirthSpawn")]
internal static class PATCH_Hediff_Pregnant_DoBirthSpawn
{
/// <summary>
/// This one overrides vanilla pregnancy hediff behavior.
/// 0 - try to find suitable father for debug pregnancy
/// 1st part if character pregnant and rjw pregnancies enabled - creates rjw pregnancy and instantly births it instead of vanilla
/// 2nd part if character pregnant with rjw pregnancy - birth it
/// 3rd part - debug - create rjw/vanila pregnancy and birth it
/// </summary>
/// <param name="mother"></param>
/// <param name="father"></param>
/// <returns></returns>
[HarmonyPrefix]
[SyncMethod]
private static bool on_begin_DoBirthSpawn(ref Pawn mother, ref Pawn father)
{
//--Log.Message("patches_pregnancy::PATCH_Hediff_Pregnant::DoBirthSpawn() called");
if (mother == null)
{
ModLog.Error("Hediff_Pregnant::DoBirthSpawn() - no mother defined -> exit");
return false;
}
//CompEggLayer compEggLayer = mother.TryGetComp<CompEggLayer>();
//if (compEggLayer != null)
//{
// ProcessVanillaEggPregnancy(mother, father);
// return false;
//}
//vanilla debug?
if (mother.gender == Gender.Male)
{
ModLog.Error("Hediff_Pregnant::DoBirthSpawn() - mother is male -> exit");
return false;
}
// get a reference to the hediff we are applying
//do birth for vanilla pregnancy Hediff
//if using rjw pregnancies - add RJW pregnancy Hediff and birth it instead
Hediff_Pregnant self = (Hediff_Pregnant)mother.health.hediffSet.GetFirstHediffOfDef(HediffDefOf.Pregnant);
if (self != null)
{
return ProcessVanillaPregnancy(self, mother, father);
}
// do birth for existing RJW pregnancies
if (ProcessRJWPregnancy(mother, father))
{
return false;
}
return ProcessDebugPregnancy(mother, father);
}
private static bool ProcessVanillaEggPregnancy(Pawn mother, Pawn father)
{
CompEggLayer compEggLayer = mother.TryGetComp<CompEggLayer>();
if (compEggLayer != null)
{
if (!compEggLayer.FullyFertilized)
{
if (father == null)
compEggLayer.Fertilize(mother);
else
compEggLayer.Fertilize(father);
compEggLayer.ProduceEgg();
}
}
CompHatcher compHatcher = mother.TryGetComp<CompHatcher>();
if (compHatcher != null)
{
compHatcher.Hatch();
}
ModLog.Message("patches_pregnancy::PATCH_Hediff_Pregnant::DoBirthSpawn():ProcessVanillaEggPregnancy birthing:" + xxx.get_pawnname(mother));
return true;
}
private static bool ProcessVanillaPregnancy(Hediff_Pregnant pregnancy, Pawn mother, Pawn father)
{
void CreateAndBirth<T>() where T : Hediff_BasePregnancy
{
T hediff = Hediff_BasePregnancy.Create<T>(mother, father);
hediff.GiveBirth();
if (pregnancy != null)
mother.health.RemoveHediff(pregnancy);
}
if (father == null)
{
father = Hediff_BasePregnancy.Trytogetfather(ref mother);
}
ModLog.Message("patches_pregnancy::PATCH_Hediff_Pregnant::DoBirthSpawn():Vanilla_pregnancy birthing:" + xxx.get_pawnname(mother));
if (RJWPregnancySettings.animal_pregnancy_enabled && ((father == null || xxx.is_animal(father)) && xxx.is_animal(mother)))
{
//RJW Bestial pregnancy animal-animal
ModLog.Message(" override as Bestial birthing(animal-animal): Father-" + xxx.get_pawnname(father) + " Mother-" + xxx.get_pawnname(mother));
CreateAndBirth<Hediff_BestialPregnancy>();
return false;
}
else if (RJWPregnancySettings.bestial_pregnancy_enabled && ((xxx.is_animal(father) && xxx.is_human(mother)) || (xxx.is_human(father) && xxx.is_animal(mother))))
{
//RJW Bestial pregnancy human-animal
ModLog.Message(" override as Bestial birthing(human-animal): Father-" + xxx.get_pawnname(father) + " Mother-" + xxx.get_pawnname(mother));
CreateAndBirth<Hediff_BestialPregnancy>();
return false;
}
else if (RJWPregnancySettings.humanlike_pregnancy_enabled && (xxx.is_human(father) && xxx.is_human(mother)))
{
//RJW Humanlike pregnancy
ModLog.Message(" override as Humanlike birthing: Father-" + xxx.get_pawnname(father) + " Mother-" + xxx.get_pawnname(mother));
CreateAndBirth<Hediff_HumanlikePregnancy>();
return false;
}
else
{
ModLog.Warning("Hediff_Pregnant::DoBirthSpawn() - checks failed, vanilla pregnancy birth");
ModLog.Warning("Hediff_Pregnant::DoBirthSpawn(): Father-" + xxx.get_pawnname(father) + " Mother-" + xxx.get_pawnname(mother));
//vanilla pregnancy code, no effects on rjw
return true;
}
}
private static bool ProcessRJWPregnancy(Pawn mother, Pawn father)
{
var p = PregnancyHelper.GetPregnancies(mother);
if (p.NullOrEmpty())
{
return false;
}
var birth = false;
foreach (var x in p)
{
if (x is Hediff_BasePregnancy)
{
var preg = x as Hediff_BasePregnancy;
ModLog.Message($"patches_pregnancy::{preg.GetType().Name}::DoBirthSpawn() birthing:" + xxx.get_pawnname(mother));
preg.GiveBirth();
birth = true;
}
}
return birth;
}
private static bool ProcessDebugPregnancy(Pawn mother, Pawn father)
{
void CreateAndBirth<T>() where T : Hediff_BasePregnancy
{
T hediff = Hediff_BasePregnancy.Create<T>(mother, father);
hediff.GiveBirth();
}
//CreateAndBirth<Hediff_HumanlikePregnancy>();
//CreateAndBirth<Hediff_BestialPregnancy>();
//CreateAndBirth<Hediff_MechanoidPregnancy>();
//return false;
//debug, add RJW pregnancy and birth it
ModLog.Message("patches_pregnancy::PATCH_Hediff_Pregnant::DoBirthSpawn():Debug_pregnancy birthing:" + xxx.get_pawnname(mother));
if (father == null)
{
father = Hediff_BasePregnancy.Trytogetfather(ref mother);
if (RJWPregnancySettings.bestial_pregnancy_enabled && ((xxx.is_animal(father) || xxx.is_animal(mother)))
|| (xxx.is_animal(mother) && RJWPregnancySettings.animal_pregnancy_enabled))
{
//RJW Bestial pregnancy
ModLog.Message(" override as Bestial birthing, mother: " + xxx.get_pawnname(mother));
CreateAndBirth<Hediff_BestialPregnancy>();
}
else if (RJWPregnancySettings.humanlike_pregnancy_enabled && ((father == null || xxx.is_human(father)) && xxx.is_human(mother)))
{
//RJW Humanlike pregnancy
ModLog.Message(" override as Humanlike birthing, mother: " + xxx.get_pawnname(mother));
CreateAndBirth<Hediff_HumanlikePregnancy>();
}
else
{
ModLog.Warning("Hediff_Pregnant::DoBirthSpawn() - debug vanilla pregnancy birth");
return true;
}
}
return false;
}
}
[HarmonyPatch(typeof(Hediff_Pregnant), "Tick")]
class PATCH_Hediff_Pregnant_Tick
{
[HarmonyPrefix]
static bool abort_on_missing_genitals(Hediff_Pregnant __instance)
{
if (__instance.pawn.IsHashIntervalTick(1000))
{
if (!Genital_Helper.has_vagina(__instance.pawn))
{
__instance.pawn.health.RemoveHediff(__instance);
}
}
return true;
}
}
// Enables pregnancy approach for same-gender couples as long as they have the right genitals,
// prevents the UI from bugging out if the first pawn is genderless, and ensures that the
// "Pawns are sterile" report is not misapplied in case of mpreg.
[HarmonyPatch(typeof(PregnancyUtility), nameof(PregnancyUtility.CanEverProduceChild))]
class PregnancyUtility_CanEverProduceChild
{
static Type thisType = typeof(PregnancyUtility_CanEverProduceChild);
static readonly MethodInfo SterileMethod =
AccessTools.Method(typeof(Pawn), nameof(Pawn.Sterile));
static readonly MethodInfo GetPregnancyHediffMethod =
AccessTools.Method(typeof(PregnancyUtility), nameof(PregnancyUtility.GetPregnancyHediff));
// TODO from Feb-2023: Uncomment the second version once `rjw-race-support` gets
// its shit together and patches their gender check.
static bool BypassGenderChecks => true;
// static bool BypassGenderChecks =>
// !ModsConfig.IsActive("erdelf.HumanoidAlienRaces") ||
// !ModsConfig.IsActive("ASMR.RJW.RaceSupport");
[HarmonyPrefix]
static bool CheckPlumbing(Pawn first, Pawn second, ref AcceptanceReport __result)
{
if (first.Dead || second.Dead)
{
return true;
}
var plumbingReport = GetPlumbingReport(first, second);
if (plumbingReport.Accepted)
{
return true;
}
__result = plumbingReport;
return false;
}
[HarmonyTranspiler]
static IEnumerable<CodeInstruction> SkipGenderCheckAndMakeSterilityCheckNotSexist(
IEnumerable<CodeInstruction> instructionEnumberable, ILGenerator generator)
{
var instructions = instructionEnumberable.ToList();
bool foundGenderCheck = false;
bool foundSupposedLocalFemaleAssignment = false;
bool foundFemaleSterilityCheck = false;
bool foundMaleSterilityCheck = false;
// Break this method up into blocks, either where a value is returned or where
// we set a local variable.
static bool findBlock(CodeInstruction il) => il.opcode == OpCodes.Ret || il.IsStloc();
(var curIns, var nextIns) = instructions.SplitAfter(findBlock);
while(curIns.Count > 0)
{
if (curIns.Any((il) => il.Is(OpCodes.Ldstr, "PawnsHaveSameGender")))
{
// Processing the same-gender check.
// We want to bypass this check, unless the Alien Races mod is active.
// RJW's compatibility mod can instead patch its `GenderReproductionCheck`
// method to alter its behavior.
if (!BypassGenderChecks)
{
foundGenderCheck = true;
goto yieldOriginal;
}
// Due to a quirk in how the optimizer handles branches, we must insert our
// bypass AFTER the conditional, otherwise the compiler just removes it.
// Isn't it great when documentation doesn't mention stuff like this?
(var beforeBr, var afterBr) = curIns.SplitAfter((il) => il.Branches(out _));
// Verify that we found the branch.
if (afterBr.Count is 0) goto yieldOriginal;
foreach (var il in beforeBr) yield return il;
if (beforeBr.LastOrDefault() is { } br && br.Branches(out var bypassLabel))
{
foundGenderCheck = true;
// Adds `&& false` after the conditional.
yield return new(OpCodes.Ldc_I4_0);
yield return new(OpCodes.Brfalse_S, bypassLabel);
}
foreach (var il in afterBr) yield return il;
goto setupNextLoop;
}
else if (curIns.Any((il) => il.IsStlocOf(1)))
{
// Processing the initialization of `pawn2` into local #1:
// Pawn pawn2 = (first.gender == Gender.Female) ? first : second;
// This needs to be changed to just select the other pawn, the one that is
// not the assumed father. It is possible that Alien Races has already
// patched this, so we'll need to take that into consideration.
// Locate the branch instruction.
(var beforeBr, var afterBr) = curIns.SplitAfter((il) => il.Branches(out _));
// Verify that we found the branch.
if (afterBr.Count is 0) goto yieldOriginal;
if (beforeBr.LastOrDefault() is not { } br) goto yieldOriginal;
if (!br.Branches(out var label)) goto yieldOriginal;
foundSupposedLocalFemaleAssignment = true;
// Rewrite to:
// Pawn pawn2 = (first != pawn) ? first : second;
// Make sure the labels are preserved.
yield return curIns[0].Replace(new CodeInstruction(OpCodes.Ldarg_0));
yield return new(OpCodes.Ldloc_0);
yield return new(OpCodes.Bne_Un_S, label);
// The remaining instructions handle the selection of the pawn, so we
// can spit those out without changes.
foreach (var il in afterBr) yield return il;
goto setupNextLoop;
}
else if (curIns.Any((il) => il.IsStlocOf(6)))
{
// Processing the initialization of `flag5` into local #6:
// bool flag5 = pawn2.Sterile(false) && PregnancyUtility.GetPregnancyHediff(pawn2) == null;
// This needs to be changed to call `PregnancyHelper.GetPregnancy`.
// Look for the call `pawn2.Sterile(false)`.
(var callToSterile, var remainder) = curIns.CutMatchingSequence(
(il) => il.opcode == OpCodes.Ldloc_1,
(il) => il.Calls(SterileMethod),
(il) => il.opcode == OpCodes.Brfalse_S
);
// Verify we found this sequence and abort if not.
if (callToSterile.Count == 0) goto yieldOriginal;
// Look for the call `PregnancyUtility.GetPregnancyHediff(pawn2)`.
(var callToPregnancy, remainder) = remainder.CutMatchingSequence(
(il) => il.opcode == OpCodes.Ldloc_1,
(il) => il.Calls(GetPregnancyHediffMethod)
);
// Verify we found this sequence and abort if not.
if (callToPregnancy.Count == 0) goto yieldOriginal;
foundFemaleSterilityCheck = true;
// Rewrite this to call `PregnancyHelper.GetPregnancy` instead.
// We're keeping the call to `Sterile`.
foreach (var il in callToSterile) yield return il;
// Setup and call.
yield return new(OpCodes.Ldloc_1);
yield return CodeInstruction.Call(typeof(PregnancyHelper), nameof(PregnancyHelper.GetPregnancy));
// The remaining instructions just check for `null`, so should be good.
foreach (var il in remainder) yield return il;
goto setupNextLoop;
}
else if (curIns.Any((il) => il.IsStlocOf(7)))
{
// Processing the initialization of `flag6` into local #7:
// bool flag6 = pawn.Sterile(false);
// We need to add a call to `PregnancyHelper.GetPregnancy` just like for
// the female, since this pawn may actually be a futa or something.
// Look for the call `pawn.Sterile(false)`.
(var callToSterile, var remainder) = curIns.CutMatchingSequence(
(il) => il.opcode == OpCodes.Ldloc_0,
(il) => il.Calls(SterileMethod)
);
// Verify we found this sequence and abort if not.
if (callToSterile.Count == 0) goto yieldOriginal;
// There should only be 1 instruction left, which sets the variable.
if (remainder.Count != 1) goto yieldOriginal;
foundMaleSterilityCheck = true;
// We need to setup a label pointing to the instruction that will set
// `false` if the call to `pawn.Sterile(false)` returns false.
var labelToFalse = generator.DefineLabel();
var IL_SetToFalse = new CodeInstruction(OpCodes.Ldc_I4_0);
IL_SetToFalse.labels.Add(labelToFalse);
// We also need a label on the instruction that sets the variable.
var labelToSet = generator.DefineLabel();
remainder[0].labels.Add(labelToSet);
foreach (var il in callToSterile) yield return il;
// If the return value was false, skip to `IL_SetToFalse`.
yield return new(OpCodes.Brfalse_S, labelToFalse);
// Now, write `PregnancyHelper.GetPregnancy(pawn) == null`.
yield return new(OpCodes.Ldloc_0);
yield return CodeInstruction.Call(typeof(PregnancyHelper), nameof(PregnancyHelper.GetPregnancy));
yield return new(OpCodes.Ldnull);
yield return new(OpCodes.Ceq);
// If it was `true`, skip over the next instruction so that is set to the variable.
yield return new(OpCodes.Br_S, labelToSet);
// Otherwise, we'll set `false`.
yield return IL_SetToFalse;
// The remaining instruction just sets the variable to whatever was last pushed
// to the stack.
foreach (var il in remainder) yield return il;
goto setupNextLoop;
}
yieldOriginal:
foreach (var il in curIns)
yield return il;
setupNextLoop:
(curIns, nextIns) = nextIns.SplitAfter(findBlock);
}
if (!foundGenderCheck)
ModLog.Error("Failed to patch PregnancyUtility.CanEverProduceChild: Could not find gender check");
if (!foundSupposedLocalFemaleAssignment)
ModLog.Error("Error when patching PregnancyUtility.CanEverProduceChild: Could not find assignment to local variable `pawn2`");
if (!foundFemaleSterilityCheck)
ModLog.Error("Error when patching PregnancyUtility.CanEverProduceChild: Could not find sterility check on local variable `pawn2`");
if (!foundMaleSterilityCheck)
ModLog.Error("Error when patching PregnancyUtility.CanEverProduceChild: Could not find sterility check on local variable `pawn`");
}
static AcceptanceReport GetPlumbingReport(Pawn first, Pawn second)
{
bool firstHasPenis = Genital_Helper.has_penis_fertile(first);
bool firstHasVagina = Genital_Helper.has_vagina(first);
if (!firstHasPenis && !firstHasVagina)
{
return "PawnLacksFunctionalGenitals".Translate(first.Named("PAWN")).Resolve();
}
bool secondHasPenis = Genital_Helper.has_penis_fertile(second);
bool secondHasVagina = Genital_Helper.has_vagina(second);
if (!secondHasPenis && !secondHasVagina)
{
return "PawnLacksFunctionalGenitals".Translate(second.Named("PAWN")).Resolve();
}
if ((firstHasPenis && secondHasVagina) || (firstHasVagina && secondHasPenis))
{
return true;
}
if (firstHasPenis && !secondHasVagina)
{
return "PawnLacksVagina".Translate(second.Named("PAWN")).Resolve();
}
if (firstHasVagina && !secondHasPenis)
{
return "PawnLacksFunctionalPenis".Translate(second.Named("PAWN")).Resolve();
}
return true;
}
/// <summary>
/// <para>Tests various pairings to make sure that that the patch is operating
/// correctly. The results of this test may be affected by other mods,
/// so keep that in mind.</para>
/// <para>This doesn't go into too much depth, mostly just checking colonists
/// and a few animals. It does not currently test integration with Alien
/// Races or anything. RJW's Alien Races compatibility mod should provide
/// its own auto-test for that.</para>
/// </summary>
[DebugOutput("RJW Auto-Tests", onlyWhenPlaying = true)]
public static void TestCanEverProduceChild()
{
var logger = Modules.Shared.Logs.LogManager.GetLogger("TestCanEverProduceChild");
var sb = new StringBuilder();
var passedColor = GenColor.FromHex("66CC00");
var failedColor = GenColor.FromHex("FF3300");
var maleColonistRequest = new PawnGenerationRequest(
kind: PawnKindDefOf.Colonist,
fixedGender: Gender.Male,
excludeBiologicalAgeRange: new(0f, 18f)
).RequestDefaults();
var femaleColonistRequest = new PawnGenerationRequest(
kind: PawnKindDefOf.Colonist,
fixedGender: Gender.Female,
allowPregnant: false,
excludeBiologicalAgeRange: new(0f, 18f)
).RequestDefaults();
var maleThrumboRequest = new PawnGenerationRequest(
kind: PawnKindDefOf.Thrumbo,
fixedGender: Gender.Male,
excludeBiologicalAgeRange: new(0f, 8f)
).RequestDefaults();
var femaleThrumboRequest = new PawnGenerationRequest(
kind: PawnKindDefOf.Thrumbo,
fixedGender: Gender.Female,
allowPregnant: false,
excludeBiologicalAgeRange: new(0f, 8f)
).RequestDefaults();
// Checks regarding basic sex-parts.
Trial("Male Colonist + Female Colonist", () =>
{
var male = TestHelper.GenerateSeededPawn(maleColonistRequest);
var female = TestHelper.GenerateSeededPawn(femaleColonistRequest);
TryToReport(male, female, true);
});
Trial("Male Colonist + Male Colonist", () =>
{
var male1 = TestHelper.GenerateSeededPawn(maleColonistRequest);
var male2 = TestHelper.GenerateSeededPawn(maleColonistRequest);
TryToReport(male1, male2, false);
});
Trial("Female Colonist + Female Colonist", () =>
{
var female1 = TestHelper.GenerateSeededPawn(femaleColonistRequest);
var female2 = TestHelper.GenerateSeededPawn(femaleColonistRequest);
TryToReport(female1, female2, false);
});
Trial("Futa Colonist + Female Colonist", () =>
{
var male = TestHelper.GenerateSeededPawn(maleColonistRequest);
var female = TestHelper.GenerateSeededPawn(femaleColonistRequest);
if (TestHelper.MakeIntoFuta(male))
TryToReport(male, female, true);
else
{
var text = "Failed to Create Futa".Colorize(failedColor);
sb.AppendLineTagged($" {text}");
}
});
Trial("Male Colonist + Futa Colonist", () =>
{
var male = TestHelper.GenerateSeededPawn(maleColonistRequest);
var female = TestHelper.GenerateSeededPawn(femaleColonistRequest);
if (TestHelper.MakeIntoFuta(female))
TryToReport(male, female, true);
else
{
var text = "Failed to Create Futa".Colorize(failedColor);
sb.AppendLineTagged($" {text}");
}
});
Trial("Futa Colonist + Futa Colonist", () =>
{
var male = TestHelper.GenerateSeededPawn(maleColonistRequest);
var female = TestHelper.GenerateSeededPawn(femaleColonistRequest);
if (TestHelper.MakeIntoFuta(male) && TestHelper.MakeIntoFuta(female))
TryToReport(male, female, true);
else
{
var text = "Failed to Create Futa".Colorize(failedColor);
sb.AppendLineTagged($" {text}");
}
});
// Tests regarding pregnancy.
Trial("Male Colonist + Pregnant Female Colonist (Vanilla)", () =>
{
if (!ModsConfig.BiotechActive)
{
sb.AppendLine(" Biotech Not Active");
return;
}
var male = TestHelper.GenerateSeededPawn(maleColonistRequest);
var female = TestHelper.GenerateSeededPawn(femaleColonistRequest);
if (VanillaHumanPregnancy(female, male) is { } hediff)
{
female.health.AddHediff(hediff);
TryToReport(male, female, true);
}
else
{
var text = "Failed to Impregnate".Colorize(failedColor);
sb.AppendLineTagged($" {text}");
}
});
Trial("Male Colonist + Pregnant Female Colonist (RJW)", () =>
{
var male = TestHelper.GenerateSeededPawn(maleColonistRequest);
var female = TestHelper.GenerateSeededPawn(femaleColonistRequest);
PregnancyHelper.AddPregnancyHediff(female, male);
TryToReport(male, female, true);
});
Trial("Pregnant Male Colonist + Female Colonist (Vanilla)", () =>
{
if (!ModsConfig.BiotechActive)
{
sb.AppendLine(" Biotech Not Active");
return;
}
var male = TestHelper.GenerateSeededPawn(maleColonistRequest);
var female = TestHelper.GenerateSeededPawn(femaleColonistRequest);
if (VanillaHumanPregnancy(male, female) is { } hediff)
{
male.health.AddHediff(hediff);
TryToReport(male, female, true);
}
else
{
var text = "Failed to Impregnate".Colorize(failedColor);
sb.AppendLineTagged($" {text}");
}
});
Trial("Pregnant Male Colonist + Female Colonist (RJW)", () =>
{
var male = TestHelper.GenerateSeededPawn(maleColonistRequest);
var female = TestHelper.GenerateSeededPawn(femaleColonistRequest);
PregnancyHelper.AddPregnancyHediff(male, female);
TryToReport(male, female, true);
});
// Tests regarding artificial genitalia and sterilization.
Trial("Sterilized Male Colonist + Female Colonist", () =>
{
if (!ModsConfig.BiotechActive)
{
sb.AppendLine(" Biotech Not Active");
return;
}
var male = TestHelper.GenerateSeededPawn(maleColonistRequest);
var female = TestHelper.GenerateSeededPawn(femaleColonistRequest);
male.health.AddHediff(HediffDefOf.Sterilized);
TryToReport(male, female, false);
});
Trial("Artificially Male Colonist + Female Colonist", () =>
{
var male = TestHelper.GenerateSeededPawn(maleColonistRequest);
var female = TestHelper.GenerateSeededPawn(femaleColonistRequest);
if (TestHelper.GiveArtificialGenitals(male))
TryToReport(male, female, false);
else
{
var text = "Failed to Render Artifical".Colorize(failedColor);
sb.AppendLineTagged($" {text}");
}
});
Trial("Male Colonist + Sterilized Female Colonist", () =>
{
if (!ModsConfig.BiotechActive)
{
sb.AppendLine(" Biotech Not Active");
return;
}
var male = TestHelper.GenerateSeededPawn(maleColonistRequest);
var female = TestHelper.GenerateSeededPawn(femaleColonistRequest);
female.health.AddHediff(HediffDefOf.Sterilized);
TryToReport(male, female, false);
});
Trial("Male Colonist + Artificially Female Colonist", () =>
{
// The hydraulic vagina is still somehow fertile, btw.
var male = TestHelper.GenerateSeededPawn(maleColonistRequest);
var female = TestHelper.GenerateSeededPawn(femaleColonistRequest);
if (TestHelper.GiveArtificialGenitals(female))
TryToReport(male, female, true);
else
{
var text = "Failed to Render Artifical".Colorize(failedColor);
sb.AppendLineTagged($" {text}");
}
});
// Checks to verify the gender checks were disabled properly.
Trial("Male Colonist + Cuntboy Colonist", () =>
{
var male = TestHelper.GenerateSeededPawn(maleColonistRequest);
var female = TestHelper.GenerateSeededPawn(femaleColonistRequest);
female.gender = Gender.Male;
TryToReport(male, female, true);
});
Trial("Dickgirl Colonist + Female Colonist", () =>
{
var male = TestHelper.GenerateSeededPawn(maleColonistRequest);
var female = TestHelper.GenerateSeededPawn(femaleColonistRequest);
male.gender = Gender.Female;
TryToReport(male, female, true);
});
// Tests versus animals.
Trial("Male Thrumbo + Female Thrumbo", () =>
{
var male = TestHelper.GenerateSeededPawn(maleThrumboRequest);
var female = TestHelper.GenerateSeededPawn(femaleThrumboRequest);
TryToReport(male, female, true);
});
Trial("Male Thrumbo + Female Colonist", () =>
{
var male = TestHelper.GenerateSeededPawn(maleThrumboRequest);
var female = TestHelper.GenerateSeededPawn(femaleColonistRequest);
TryToReport(male, female, true);
});
Trial("Male Colonist + Female Thrumbo", () =>
{
var male = TestHelper.GenerateSeededPawn(maleColonistRequest);
var female = TestHelper.GenerateSeededPawn(femaleThrumboRequest);
TryToReport(male, female, true);
});
Find.WindowStack.Add(new Dialog_MessageBox(sb.ToString().Trim()));
void Trial(string title, Action action)
{
try
{
sb.AppendLine(title);
action();
}
catch (Exception ex)
{
var result = "Exception".Colorize(failedColor);
sb.AppendLineTagged($" {result} (see console logs)");
logger.Error("Auto-test exception.", ex);
}
finally
{
sb.AppendLine();
}
}
// Tries to give the `mother` a human pregnancy.
Hediff_Pregnant VanillaHumanPregnancy(Pawn mother, Pawn father)
{
using var _seeded = Seeded.With(mother);
var hediff = (Hediff_Pregnant)HediffMaker.MakeHediff(HediffDefOf.PregnantHuman, mother);
hediff.Severity = 0.1f;
var inheritedGeneSet = PregnancyUtility.GetInheritedGeneSet(father, mother, out var success);
if (success)
{
hediff.SetParents(null, father, inheritedGeneSet);
return hediff;
}
return null;
}
// Try the two pawns in both argument positions.
void TryToReport(Pawn pawn1, Pawn pawn2, bool expectAccepted)
{
var text = expectAccepted ? "Accepted" : "Rejected";
sb.AppendLine($" Expecting: {text}");
var result1 = PregnancyUtility.CanEverProduceChild(pawn1, pawn2);
sb.AppendLine(" Given Order");
sb.AppendLineTagged($" Status: {ReportToStatus(result1, expectAccepted)}");
sb.AppendLineTagged($" Reason: {ReportToReason(result1)}");
var result2 = PregnancyUtility.CanEverProduceChild(pawn2, pawn1);
sb.AppendLine(" Reversed Order");
sb.AppendLineTagged($" Status: {ReportToStatus(result2, expectAccepted)}");
sb.AppendLineTagged($" Reason: {ReportToReason(result2)}");
}
string ReportToStatus(AcceptanceReport report, bool expectAccepted) =>
(report.Accepted, expectAccepted) switch
{
(true, true) or (false, false) => "Passed".Colorize(passedColor),
_ => "Failed".Colorize(failedColor)
};
string ReportToReason(AcceptanceReport report) =>
report.Reason.NullOrEmpty() ? "(None)" : report.Reason;
}
}
[HarmonyPatch(typeof(PregnancyUtility), "RandomLastName")]
static class Patch_PregnancyUtility_RandomLastName
{
public static bool Prefix(ref Pawn geneticMother, ref Pawn birthingMother, ref Pawn father)
{
if (geneticMother != null)
if (geneticMother.Name == null || !xxx.is_human(geneticMother))
{
geneticMother = null;
}
if (father != null)
if (father.Name == null || !xxx.is_human(father))
{
father = null;
}
if (birthingMother != null)
if (birthingMother.Name == null || !xxx.is_human(birthingMother))
{
birthingMother = null;
}
return true;
}
}
// Fixes CompEggLayer and mating for humanlikes.
// Note that this involves skipping over a check for the Biotech DLC, but as of build 1.4.3534 this doesn't unlock
// any Biotech-only features or anything like that.
[HarmonyPatch(typeof(Pawn), nameof(Pawn.Sterile))]
class Pawn_Sterile
{
[HarmonyTranspiler]
static IEnumerable<CodeInstruction> NotOwningBiotechWillNotMakeYouSterileButModdingProbablyWill(
IEnumerable<CodeInstruction> instructions)
{
PropertyInfo biotechActive = AccessTools.DeclaredProperty(typeof(ModsConfig), nameof(ModsConfig.BiotechActive));
bool foundBiotechCheck = false;
foreach (var instruction in instructions)
{
// if (ModsConfig.BiotechActive) ...
// => if (true) ...
if (instruction.Calls(biotechActive.GetMethod))
{
yield return new CodeInstruction(OpCodes.Ldc_I4_1);
foundBiotechCheck = true;
continue;
}
yield return instruction;
}
if (!foundBiotechCheck)
{
ModLog.Error("Failed to patch Pawn.Sterile: Could not find `ModsConfig.BiotechActive`");
}
}
}
// Make the game use RJW's fertility capacity in vanilla pregnancy chance calculations
[HarmonyPatch]
class Various_GetStatValue
{
static IEnumerable<MethodBase> TargetMethods()
{
yield return AccessTools.Method(typeof(PregnancyUtility), nameof(PregnancyUtility.CanEverProduceChild));
yield return AccessTools.Method(typeof(PregnancyUtility), nameof(PregnancyUtility.PregnancyChanceForPawn));
yield return AccessTools.Method(typeof(Pawn), nameof(Pawn.Sterile));
}
[HarmonyTranspiler]
static IEnumerable<CodeInstruction> UseRjwFertilityInstead(IEnumerable<CodeInstruction> instructionEnumerable, MethodBase original)
{
bool foundFertilityStatDefLoad = false;
FieldInfo statDefOfFertility = AccessTools.DeclaredField(typeof(StatDefOf), nameof(StatDefOf.Fertility));
var instructions = instructionEnumerable.ToList();
for (int i = 0; i < instructions.Count; i++)
{
// pawn.GetStatValue(StatDefOf.Fertility)
// => pawn.health.capacities.GetLevel(xxx.reproduction)
if (instructions[i].LoadsField(statDefOfFertility) && i + 3 < instructions.Count)
{
foundFertilityStatDefLoad = true;
yield return CodeInstruction.LoadField(typeof(Pawn), nameof(Pawn.health)).WithLabels(instructions[i].ExtractLabels());
yield return CodeInstruction.LoadField(typeof(Pawn_HealthTracker), nameof(Pawn_HealthTracker.capacities));
yield return CodeInstruction.LoadField(typeof(xxx), nameof(xxx.reproduction));
yield return CodeInstruction.Call(typeof(PawnCapacitiesHandler), nameof(PawnCapacitiesHandler.GetLevel));
// Skip GetStatValue call
i += 3;
continue;
}
yield return instructions[i];
}
if (!foundFertilityStatDefLoad)
{
ModLog.Error($"Failed to patch {original.Name}: Could not find `pawn.GetStatValue(StatDefOf.Fertility)`");
}
}
}
// Mostly prevent pawns born from RJW pregnancies from getting named "Baby".
[HarmonyPatch(typeof(PawnBioAndNameGenerator), nameof(PawnBioAndNameGenerator.GiveAppropriateBioAndNameTo))]
class PawnBioAndNameGenerator_GiveAppropriateBioAndNameTo
{
static readonly MethodInfo getPawnDevelopmentalStage = AccessTools.Method(typeof(Pawn), "get_DevelopmentalStage");
[HarmonyTranspiler]
static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructionEnumerable, MethodBase original)
{
var instructions = instructionEnumerable.ToList();
bool found = false;
for (int i = 0; i < instructions.Count; i++)
{
// replace bool flag = pawn.DevelopmentalStage.Baby(); with bool flag = isBiotechBaby(Pawn pawn);
if (instructions[i].Calls(getPawnDevelopmentalStage))
{
yield return CodeInstruction.Call(typeof(PawnBioAndNameGenerator_GiveAppropriateBioAndNameTo), nameof(isBiotechBaby));
i++;
found = true;
}
else
{
yield return instructions[i];
}
}
if (!found)
{
ModLog.Error($"Failed to patch {original.Name}: could not find pawn.DevelopmentalStage");
}
}
public static bool isBiotechBaby(Pawn pawn)
{
return pawn.DevelopmentalStage.Baby() && RJWPregnancySettings.UseVanillaPregnancy;
}
}
// Adjust the pregnancy approach tooltip to reflect the fact that it no longer affects the chance of pregnancy directly.
[HarmonyPatch(typeof(PregnancyUtility), nameof(PregnancyUtility.GetDescription))]
class PregnancyUtility_GetDescription
{
[HarmonyTranspiler]
static IEnumerable<CodeInstruction> ModifyPregnancyApproachTooltip(IEnumerable<CodeInstruction> instructions)
{
foreach (var instruction in instructions)
{
if (instruction.LoadsConstant("PregnancyChance"))
{
yield return new CodeInstruction(OpCodes.Ldstr, "VaginalWeight");
}
else
{
yield return instruction;
}
}
}
}
[HarmonyPatch(typeof(PawnColumnWorker_Pregnant), "GetIconFor")]
public class PawnColumnWorker_Patch_Icon
{
public static void Postfix(Pawn pawn, ref Texture2D __result)
{
if (pawn.IsVisiblyPregnant()) __result = ContentFinder<Texture2D>.Get("UI/Icons/Animal/Pregnant", true);
}
}
[HarmonyPatch(typeof(PawnColumnWorker_Pregnant), "GetTooltipText")]
public class PawnColumnWorker_Patch_Tooltip
{
public static bool Prefix(Pawn pawn, ref string __result)
{
// Handles multi-pregnancy by getting the one nearest to birth.
var pregHediff = PregnancyHelper.GetPregnancy(pawn);
(var ticksCompleted, var ticksToBirth) = PregnancyHelper.GetProgressTicks(pregHediff);
__result = "PregnantIconDesc".Translate(
ticksCompleted.ToStringTicksToDays("F0"),
ticksToBirth.ToStringTicksToDays("F0")
);
return false;
}
}
[HarmonyPatch(typeof(TransferableUIUtility), "DoExtraIcons")]
public class TransferableUIUtility_Patch_Icon
{
//private static readonly Texture2D PregnantIcon = ContentFinder<Texture2D>.Get("UI/Icons/Animal/Pregnant", true);
public static void Postfix(Transferable trad, Rect rect, ref float curX, Texture2D ___PregnantIcon)
{
Pawn pawn = trad.AnyThing as Pawn;
if (pawn?.health?.hediffSet != null && pawn.IsVisiblyPregnant())
{
Rect rect3 = new Rect(curX - 24f, (rect.height - 24f) / 2f, 24f, 24f);
curX -= 24f;
if (Mouse.IsOver(rect3))
{
TooltipHandler.TipRegion(rect3, PawnColumnWorker_Pregnant.GetTooltipText(pawn));
}
GUI.DrawTexture(rect3, ___PregnantIcon);
}
}
}
//[HarmonyPatch(typeof(AutoSlaughterManager))]
//public class AutoSlaughterManager_AnimalsToSlaughter_rjw_preg
//{
// public static void Postfix(AutoSlaughterManager __instance)
// {
// List<Pawn> __result = new List<Pawn>();
// var any_ins = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
// __result = (List<Pawn>)(__instance.GetType().GetField("AnimalsToSlaughter", any_ins).GetValue(__instance));
// //(__instance.GetType().GetField("AnimalsToSlaughter", any_ins).SetValue(__instance, newresult));
// //List<Pawn> __result = new List<Pawn>((List < Pawn > )typeof(AutoSlaughterManager).GetField("AnimalsToSlaughter", BindingFlags.Instance | BindingFlags.NonPublic));
// if (!__result.NullOrEmpty())
// {
// var newresult = __result;
// foreach (var pawn in __result)
// {
// if (pawn?.health?.hediffSet != null && pawn.IsPregnant(true))
// {
// if (__instance.configs.Any(x => x.allowSlaughterPregnant != true && x.animal == pawn.def))
// {
// newresult.Remove(pawn);
// }
// }
// }
// __result = newresult;
// }
// //return __result;
// }
//}
}
| Korth95/rjw | 1.5/Source/Harmony/patch_pregnancy.cs | C# | mit | 36,270 |
using System.Linq;
using Verse;
using HarmonyLib;
using RimWorld;
using System.Collections;
using System.Collections.Generic;
namespace rjw
{
/// <summary>
/// Necessary to prevent duplicate stat entries on harvested part, since stats are populated by each recipe that
/// installs it.
/// </summary>
[HarmonyPatch(typeof(MedicalRecipesUtility), nameof(MedicalRecipesUtility.GetMedicalStatsFromRecipeDefs))]
public static class FixDuplicatePartStats
{
class StatDrawEntryEqualityComparer : IEqualityComparer<StatDrawEntry>
{
public bool Equals(StatDrawEntry x, StatDrawEntry y) => x.LabelCap == y.LabelCap && x.ValueString == y.ValueString;
public int GetHashCode(StatDrawEntry entry) => entry.LabelCap.GetHashCode() ^ entry.ValueString.GetHashCode();
}
static IEqualityComparer<StatDrawEntry> comparer = new StatDrawEntryEqualityComparer();
static IEnumerable<StatDrawEntry> Postfix(IEnumerable<StatDrawEntry> recipes) => recipes.Distinct(comparer);
}
/// <summary>
/// Patch all races into rjw parts recipes
/// </summary>
[StaticConstructorOnStartup]
public static class MakeAllRacesUseSexPartRecipes
{
static MakeAllRacesUseSexPartRecipes()
{
//summons carpet bombing
//inject races into rjw recipes
foreach (RecipeDef x in DefDatabase<RecipeDef>.AllDefsListForReading.Where(x => x.IsSurgery && (x.targetsBodyPart || !x.appliedOnFixedBodyParts.NullOrEmpty())))
{
if (x.appliedOnFixedBodyParts.Contains(xxx.genitalsDef)
|| x.appliedOnFixedBodyParts.Contains(xxx.breastsDef)
|| x.appliedOnFixedBodyParts.Contains(xxx.anusDef)
|| x.modContentPack?.PackageId == "rim.job.world"
|| x.modContentPack?.PackageId == "Safe.Job.World" //*sigh*
//|| x.modContentPack?.PackageId == "Abraxas.RJW.RaceSupport" // for udders?
)
foreach (ThingDef thingDef in DefDatabase<ThingDef>.AllDefs.Where(thingDef =>
thingDef.race != null && (
thingDef.race.Humanlike ||
thingDef.race.Animal
)))
{
//filter out something, probably?
//if (thingDef.race. == "Human")
// continue;
if (!x.recipeUsers.Contains(thingDef))
{
x.recipeUsers.Add(item: thingDef);
//Log.Message("recipe: " + x.defName + ", thing: " + thingDef.defName);
}
}
}
}
}
}
| Korth95/rjw | 1.5/Source/Harmony/patch_recipes.cs | C# | mit | 2,310 |
using HarmonyLib;
using RimWorld;
using System;
using Verse;
namespace rjw
{
///<summary>
///RJW Designators checks/update
///update designators only for selected pawn, once, instead of every tick(60 times per sec)
///</summary>
[HarmonyPatch(typeof(Selector), "Select")]
[StaticConstructorOnStartup]
static class PawnSelect
{
[HarmonyPrefix]
private static bool Update_Designators_Permissions(Selector __instance, ref object obj)
{
if (obj is Pawn)
{
//ModLog.Message("Selector patch");
Pawn pawn = (Pawn)obj;
//ModLog.Message("pawn: " + xxx.get_pawnname(pawn));
pawn.UpdatePermissions();
}
return true;
}
}
//[HarmonyPatch(typeof(Dialog_InfoCard), "Setup")]
////[HarmonyPatch(typeof(Dialog_InfoCard), "Dialog_InfoCard", new Type[] {typeof(Def)})]
//[StaticConstructorOnStartup]
//static class Button
//{
// [HarmonyPostfix]
// public static bool Postfix()
// {
// ModLog.Message("InfoCardButton");
// return true;
// }
//}
} | Korth95/rjw | 1.5/Source/Harmony/patch_selector.cs | C# | mit | 988 |
namespace rjw
{
/// <summary>
/// Patch:
/// recipes
/// </summary>
//TODO: inject rjw recipes
//[HarmonyPatch(typeof(HealthCardUtility), "GenerateSurgeryOption")]
//internal static class PATCH_HealthCardUtility_recipes
//{
// //private static FloatMenuOption GenerateSurgeryOption(Pawn pawn, Thing thingForMedBills, RecipeDef recipe, IEnumerable<ThingDef> missingIngredients, BodyPartRecord part = null)
// //public FloatMenuOption(string label, Action action, MenuOptionPriority priority = MenuOptionPriority.Default, Action mouseoverGuiAction = null, Thing revalidateClickTarget = null, float extraPartWidth = 0, Func<Rect, bool> extraPartOnGUI = null, WorldObject revalidateWorldClickTarget = null);
// //floatMenuOption = new FloatMenuOption(text, action, MenuOptionPriority.Default, null, null, 0f, null, null);
// [HarmonyPostfix]
// private static void Postfix(ref FloatMenuOption __result, ref Pawn pawn)
// {
// ModLog.Message("PATCH_HealthCardUtility_recipes");
// ModLog.Message("PATCH_HealthCardUtility_recipes list: " + __result);
// //foreach (FloatMenuOption recipe in recipeOptionsMaker)
// // {
// // ModLog.Message("PATCH_HealthCardUtility_recipes: " + recipe);
// // }
// return;
// }
//}
//erm.. idk ?
//[HarmonyPatch(typeof(HealthCardUtility), "GetTooltip")]
//internal static class PATCH_HealthCardUtility_GetTooltip
//{
// [HarmonyPostfix]
// private static void Postfix(Pawn pawn)
// {
// ModLog.Message("GetTooltip");
// //ModLog.Message("PATCH_HealthCardUtility_recipes list: " + floatMenuOption);
// //foreach (FloatMenuOption recipe in recipeOptionsMaker)
// // {
// // ModLog.Message("PATCH_HealthCardUtility_recipes: " + recipe);
// // }
// return;
// }
//}
//TODO: make toggle/floatmenu to parts switching
//[HarmonyPatch(typeof(HealthCardUtility), "EntryClicked")]
//internal static class PATCH_HealthCardUtility_EntryClicked
//{
// [HarmonyPostfix]
// private static void Postfix(Pawn pawn)
// {
// ModLog.Message("EntryClicked");
// //ModLog.Message("PATCH_HealthCardUtility_recipes list: " + floatMenuOption);
// //foreach (FloatMenuOption recipe in recipeOptionsMaker)
// // {
// // ModLog.Message("PATCH_HealthCardUtility_recipes: " + recipe);
// // }
// return;
// }
//}
}
| Korth95/rjw | 1.5/Source/Harmony/patch_surgery.cs | C# | mit | 2,301 |
using System.Linq;
using Verse;
using System.Collections.Generic;
using HarmonyLib;
using RimWorld;
namespace rjw
{
/// <summary>
/// Patch ui for hero mode
/// - disable pawn control for non owned hero
/// - disable equipment management for non owned hero
/// hardcore mode:
/// - disable equipment management for non hero
/// - disable pawn rmb menu for non hero
/// - remove drafting widget for non hero
/// </summary>
//disable forced works(rmb workgivers)
[HarmonyPatch(typeof(FloatMenuMakerMap), "CanTakeOrder")]
[StaticConstructorOnStartup]
static class disable_FloatMenuMakerMap
{
[HarmonyPostfix]
static void NonHero_disable_controls(ref bool __result, Pawn pawn)
{
if (RJWSettings.RPG_hero_control)
{
if ((pawn.IsDesignatedHero() && !pawn.IsHeroOwner()))
{
__result = false; //not hero owner, disable menu
return;
}
if (!pawn.IsDesignatedHero() && RJWSettings.RPG_hero_control_HC)
{
if (pawn.Drafted && pawn.CanChangeDesignationPrisoner() && pawn.CanChangeDesignationColonist())
{
//allow control over drafted pawns, this is limited by below disable_Gizmos patch
}
else
{
__result = false; //not hero, disable menu
}
}
}
}
}
//TODO: disable equipment management
/*
//disable equipment management
[HarmonyPatch(typeof(ITab_Pawn_Gear), "CanControl")]
static class disable_equipment_management
{
[HarmonyPostfix]
static bool this_is_postfix(ref bool __result, Pawn selPawnForGear)
{
Pawn pawn = selPawnForGear;
if (RJWSettings.RPG_hero_control)
{
if ((pawn.IsDesignatedHero() && !pawn.IsHeroOwner())) //not hero owner, disable drafting
{
__result = false; //not hero owner, disable menu
}
else if (!pawn.IsDesignatedHero() && RJWSettings.RPG_hero_control_HC) //not hero, disable drafting
{
if (false)
{
//add some filter for bots and stuff? if there is such stuff
//so it can be drafted and controlled for fighting
}
else
{
__result = false; //not hero, disable menu
}
}
}
return true;
}
}
*/
//TODO: allow shared control over non colonists(droids, etc)?
//disable command gizmos
[HarmonyPatch(typeof(Pawn), "GetGizmos")]
[StaticConstructorOnStartup]
static class disable_Gizmos
{
[HarmonyPostfix]
[HarmonyPriority(100)]
static IEnumerable<Gizmo> NonHero_disable_gizmos(IEnumerable<Gizmo> __result, Pawn __instance)
{
Pawn pawn = __instance;
string disablementReason = string.Empty;
if (RJWSettings.RPG_hero_control)
{
if ((pawn.IsDesignatedHero() && !pawn.IsHeroOwner())) //not hero owner, disable drafting
{
disablementReason = "ForHeroRefuse1Desc";
}
else if (!pawn.IsDesignatedHero() && RJWSettings.RPG_hero_control_HC) //not hero, disable drafting
{
//no permission to change designation for NON prisoner hero/ other player
if (pawn.CanChangeDesignationPrisoner() && pawn.CanChangeDesignationColonist()
&& (pawn.kindDef.race.defName.Contains("AIRobot")
|| (pawn.kindDef.race.defName.Contains("Droid") && !pawn.kindDef.race.defName.Contains("AndDroid"))
|| pawn.kindDef.race.defName.Contains("RPP_Bot")
))
//if (false)
{
//add some filter for bots and stuff? if there is such stuff
//so it can be drafted and controlled for fighting
}
else
{
disablementReason = "ForHeroRefuseHCDesc";
}
}
}
foreach (var gizmo in __result)
{
if ( disablementReason.NullOrEmpty() || (!(gizmo is Command)) ) //we do not filter out non-command Gizmos, such as shield bar or psychic entropy
{
yield return gizmo;
}
//ModLog.Message("Gizmo for " + xxx.get_pawnname(__instance) + " type: " + gizmo.GetType()+ ": " + gizmo);
if (!disablementReason.NullOrEmpty())
{
if (gizmo is Verse.Command_VerbTarget) { //weapon icons
gizmo.Disable(disablementReason.Translate());
yield return gizmo;
}
}
//all other command gizmos are dropped
}
}
}
}
| Korth95/rjw | 1.5/Source/Harmony/patch_ui_hero.cs | C# | mit | 4,092 |
using System.Collections.Generic;
using System.Linq;
using HarmonyLib;
using RimWorld;
using Verse;
using UnityEngine;
using Multiplayer.API;
namespace rjw
{
/// <summary>
/// Harmony patch to toggle the RJW designation box showing
/// </summary>
[HarmonyPatch(typeof(PlaySettings), "DoPlaySettingsGlobalControls")]
[StaticConstructorOnStartup]
public static class RJW_corner_toggle
{
static readonly Texture2D icon = ContentFinder<Texture2D>.Get("UI/Commands/ComfortPrisoner_off");
[HarmonyPostfix]
public static void add_RJW_toggle(WidgetRow row, bool worldView)
{
if (worldView) return;
if (!RJWSettings.show_RJW_designation_box) return;
row.ToggleableIcon(ref RJWSettings.show_RJW_designation_box, icon, "RJW_designation_box_desc".Translate());
}
}
///<summary>
///Compact button group containing rjw designations on pawn
///</summary>
[HarmonyPatch(typeof(Pawn), "GetGizmos")]
[StaticConstructorOnStartup]
static class Rjw_buttons
{
[HarmonyPostfix]
[HarmonyPriority(99)]
static IEnumerable<Gizmo> add_designation_box(IEnumerable<Gizmo> __result, Pawn __instance)
{
foreach (var gizmo in __result)
{
yield return gizmo;
}
if (!RJWSettings.show_RJW_designation_box) yield break;
if (!(__instance.Faction == Faction.OfPlayer || __instance.IsPrisonerOfColony)) yield break;
//ModLog.Message("Harmony patch submit_button is called");
var pawn = __instance;
yield return new RJWdesignations(pawn);
}
}
///<summary>
///Submit gizmo
///</summary>
[HarmonyPatch(typeof(Pawn), "GetGizmos")]
[StaticConstructorOnStartup]
static class submit_button
{
[HarmonyPostfix]
[HarmonyPriority(101)]
static IEnumerable<Gizmo> add_button(IEnumerable<Gizmo> __result, Pawn __instance)
{
foreach (var gizmo in __result)
{
yield return gizmo;
}
//ModLog.Message("Harmony patch submit_button is called");
var pawn = __instance;
var enabled = RJWSettings.submit_button_enabled;
if (enabled && pawn.IsColonistPlayerControlled && pawn.Drafted)
if (pawn.CanChangeDesignationColonist())
if (!(pawn.kindDef.race.defName.Contains("Droid") && !AndroidsCompatibility.IsAndroid(pawn)))
{
yield return new Command_Action
{
defaultLabel = "CommandSubmit".Translate(),
icon = submit_icon,
defaultDesc = "CommandSubmitDesc".Translate(),
action = delegate
{
LayDownAndAccept(pawn);
},
hotKey = KeyBindingDefOf.Misc3
};
}
}
static Texture2D submit_icon = ContentFinder<Texture2D>.Get("UI/Commands/Submit", true);
static HediffDef submit_hediff = HediffDef.Named("Hediff_Submitting");
[SyncMethod]
static void LayDownAndAccept(Pawn pawn)
{
//Log.Message("Submit button is pressed for " + pawn);
pawn.health.AddHediff(submit_hediff);
}
}
} | Korth95/rjw | 1.5/Source/Harmony/patch_ui_rjw_buttons.cs | C# | mit | 2,846 |
using System;
using RimWorld;
using Verse;
using HarmonyLib;
namespace rjw
{
[HarmonyPatch(typeof(CompAbilityEffect_WordOfLove), "ValidateTarget")]
internal static class PATCH_CompAbilityEffect_WordOfLove_ValidateTarget
{
[HarmonyPrefix]
static bool GenderChecks(ref LocalTargetInfo target, LocalTargetInfo ___selectedTarget, ref bool __result)
{
Pawn pawn = ___selectedTarget.Pawn;
Pawn pawn2 = target.Pawn;
if (pawn != pawn2 && pawn != null && pawn2 != null)
{
__result = !xxx.is_asexual(pawn) && (xxx.is_bisexual(pawn) || xxx.is_pansexual(pawn) || (xxx.is_heterosexual(pawn) && pawn.gender != pawn2.gender) || (xxx.is_homosexual(pawn) && pawn.gender == pawn2.gender));
if (__result == false)
{ Messages.Message("AbilityCantApplyWrongAttractionGender".Translate(pawn, pawn2), pawn, MessageTypeDefOf.RejectInput, false); }
return false;
}
return true;
}
}
}
| Korth95/rjw | 1.5/Source/Harmony/patch_wordoflove.cs | C# | mit | 906 |
using HarmonyLib;
using RimWorld;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using Verse;
using Verse.AI.Group;
namespace rjw
{
class StatsReportUtilityPatch
{
[HarmonyPatch(typeof(StatsReportUtility))]
[StaticConstructorOnStartup]
public static class Patch_StatsReportUtility
{
private static StatDrawEntry DescriptionEntry(Hediff thing)
{
return new StatDrawEntry(StatCategoryDefOf.BasicsImportant, "Description".Translate(), "", thing.DescriptionFlavor, 99999, null, Dialog_InfoCard.DefsToHyperlinks(thing.def.descriptionHyperlinks), false);
}
}
}
class HediffPatch
{
[HarmonyPatch(typeof(Hediff))]
[StaticConstructorOnStartup]
public static class Patch_Hediff
{
public virtual string DescriptionFlavor
{
get
{
return this.def.description;
}
}
}
}
} | Korth95/rjw | 1.5/Source/Harmony/test.cs | C# | mit | 892 |
using System.Collections.Generic;
using RimWorld;
using Verse;
namespace rjw
{
public class HediffCompProperties_SexPart : HediffCompProperties
{
public HediffCompProperties_SexPart()
{
compClass = typeof(HediffComp_SexPart);
}
}
public class HediffCompProperties_Ovipositor : HediffCompProperties
{
// Currently unused in favour of searching parentDefs of every egg def, should refactor
public List<HediffDef_InsectEgg> eggs;
public IntRange eggIntervalTicks = new(GenDate.TicksPerDay, GenDate.TicksPerDay);
public FloatRange eggCount = FloatRange.One;
public HediffCompProperties_Ovipositor()
{
compClass = typeof(HediffComp_Ovipositor);
}
public override IEnumerable<string> ConfigErrors(HediffDef parentDef)
{
foreach (string err in base.ConfigErrors(parentDef))
{
yield return err;
}
// if (eggs.NullOrEmpty())
// {
// yield return "One or more <eggs> is required";
// }
}
}
public class HediffCompProperties_GrowsWithOwner : HediffCompProperties
{
public bool evenIfTransplanted;
public HediffCompProperties_GrowsWithOwner()
{
compClass = typeof(HediffComp_GrowsWithOwner);
}
}
} | Korth95/rjw | 1.5/Source/Hediffs/Comps/HediffCompProperties.cs | C# | mit | 1,174 |
using System.Collections.Generic;
using Verse;
using RimWorld;
namespace rjw
{
public class HediffComp_GrowsWithOwner : HediffComp
{
public float lastOwnerSize = -1;
public HediffCompProperties_GrowsWithOwner Props => (HediffCompProperties_GrowsWithOwner)props;
public override void CompPostTick(ref float severityAdjustment)
{
//change pawn parts sizes for kids(?)
//update size if pawn bodysize changed from last check
if (Pawn.BodySize != lastOwnerSize)
{
var partComp = parent.TryGetComp<HediffComp_SexPart>();
if (partComp != null && (!partComp.isTransplant || Props.evenIfTransplanted)) //no changes for transplants
{
//get ~relative size variable from calculation()
var relativeSize = partComp.baseSize;
relativeSize /= partComp.originalOwnerSize; //remove old lifestage bodysize mod
relativeSize *= Pawn.BodySize; //add new lifestage bodysize mod
partComp.baseSize = relativeSize; //save new size
partComp.originalOwnerSize = Pawn.BodySize; //update owner size
lastOwnerSize = Pawn.BodySize;
partComp.UpdateSeverity(); // update/reset part size
partComp.UpdatePartFluidFactor(); // update/reset part fluid volume
}
}
}
public override void CompExposeData()
{
base.CompExposeData();
Scribe_Values.Look(ref lastOwnerSize, "lastOwnerSize");
}
}
} | Korth95/rjw | 1.5/Source/Hediffs/Comps/HediffComp_GrowsWithOwner.cs | C# | mit | 1,386 |
using System.Collections.Generic;
using System.Linq;
using Multiplayer.API;
using RimWorld;
using Verse;
namespace rjw;
public class HediffComp_Ovipositor : HediffComp
{
public IntRange eggInterval;
private int nextEggTick;
private static HediffDef_InsectEgg UnknownEgg = DefDatabase<HediffDef_InsectEgg>.GetNamed("RJW_UnknownEgg");
public HediffCompProperties_Ovipositor Props => props as HediffCompProperties_Ovipositor;
public override void CompPostMake()
{
eggInterval = Props.eggIntervalTicks;
}
/// <summary>
/// egg production ticks
/// </summary>
public override void CompPostTick(ref float severityAdjustment)
{
base.CompPostTick(ref severityAdjustment);
var thisTick = Find.TickManager.TicksGame;
if (thisTick >= nextEggTick)
{
var def = parent.def as HediffDef_SexPart;
var pawn = parent.pawn;
var isPlayerFaction = pawn.Faction?.IsPlayer ?? false; // Colonists/animals/mechs/mutants
var onHomeMap = pawn.Map?.IsPlayerHome ?? false;
if (!onHomeMap && !isPlayerFaction && !pawn.IsPrisonerOfColony && !pawn.IsSlaveOfColony)
{
return;
}
if (pawn.health.capacities.GetLevel(PawnCapacityDefOf.Moving) <= 0.5)
{
return;
}
float maxEggsSize = pawn.BodySize / 10f;
if (xxx.has_quirk(pawn, "Incubator"))
{
maxEggsSize *= 2;
}
if (Genital_Helper.has_ovipositorF(pawn))
{
maxEggsSize *= 4;
}
float eggedSize = GetCombinedEggSize(pawn);
if (RJWSettings.DevMode) ModLog.Message($"{xxx.get_pawnname(pawn)} filled with {eggedSize} out of max capacity of {maxEggsSize} eggs.");
if (eggedSize < maxEggsSize)
{
HediffDef_InsectEgg egg;
if (RJWSettings.DevMode) ModLog.Message($" Trying to find a {pawn.kindDef} egg");
if (!TryGetEgg(pawn.kindDef.defName, out egg))
{
if (RJWSettings.DevMode) ModLog.Message($" No {pawn.kindDef} egg found, defaulting to UnknownEgg");
egg = UnknownEgg;
}
if (RJWSettings.DevMode) ModLog.Message($"I choose you, {egg}!");
var parentPart = parent.Part;
if (parentPart != null)
{
AddEggs(egg, parentPart, Props.eggCount);
}
}
// Reset for next egg.
nextEggTick = RandomNextEggTick(thisTick);
}
}
private static float GetCombinedEggSize(Pawn pawn)
{
float eggedSize = 0;
List<Hediff_InsectEgg> ownEggs = new();
pawn.health.hediffSet.GetHediffs(ref ownEggs);
foreach (var ownEgg in ownEggs)
{
eggedSize += ownEgg.eggssize;
}
return eggedSize;
}
[SyncMethod]
private int RandomNextEggTick(int fromTick)
{
return fromTick + eggInterval.RandomInRange;
}
[SyncMethod]
private static bool TryGetEgg(string defname, out HediffDef_InsectEgg result)
{
var possibleEggs = PossibleEggs(defname);
return possibleEggs.TryRandomElement(out result);
}
public static IEnumerable<HediffDef_InsectEgg> PossibleEggs(string defName)
{
if (defName == null)
{
return Enumerable.Empty<HediffDef_InsectEgg>();
}
return DefDatabase<HediffDef_InsectEgg>.AllDefs.Where(eggDef => eggDef.CanHaveParent(defName));
}
[SyncMethod]
public void AddEggs(HediffDef_InsectEgg eggDef, BodyPartRecord bodyPart, FloatRange range)
{
float eggScore = range.RandomInRange + 0.5f;
if (RJWSettings.DevMode)
{
ModLog.Message($"Added egg count: {eggScore}, int: {(int)eggScore}");
ModLog.Message($"Min egg count: {range.min}, int: {(int)range.min}");
ModLog.Message($"Max egg count: {range.max}, int: {(int)range.max}");
}
int eggsToAdd = (int) eggScore;
for (int i = 0; i < eggsToAdd; i++)
{
var addedEgg = parent.pawn.health.AddHediff(eggDef, bodyPart) as Hediff_InsectEgg;
addedEgg?.InitImplanter(parent.pawn);
}
}
public override void CompExposeData()
{
base.CompExposeData();
Scribe_Values.Look(ref nextEggTick, "nextEggTick");
Scribe_Values.Look(ref eggInterval, "eggInterval", defaultValue: Props.eggIntervalTicks);
}
} | Korth95/rjw | 1.5/Source/Hediffs/Comps/HediffComp_Ovipositor.cs | C# | mit | 3,889 |
using Verse;
using RimWorld;
using Multiplayer.API;
using System.Collections.Generic;
using HugsLib.Utils;
using System.Linq;
using ShowParts = rjw.RJWSettings.ShowParts;
namespace rjw
{
/// <summary>
/// Comp for rjw hediff parts
/// </summary>
public class HediffComp_SexPart : HediffComp
{
public string SizeLabel => parent.CurStage?.label ?? "";
public string originalOwnerRace = ""; //base race when part created
public string previousOwner = ""; //base race when part created
private float? forcedSize;
public float baseSize; // Absolute base size when part created, someday alter by operation
public float originalOwnerSize = 0; // Body size of this part's first owner. Not used in calculations.
public float bodySizeOverride = -1; // For modders, used to overwrite the (displayed) size instead of pawn.body.size
private SexFluidDef fluidOverride; //cummies/milk - insectjelly/honey etc
public float partFluidFactor; //amount of Milk/Ejaculation/Wetness
public string possibleEggsTipString; //for ovi eggs, maybe
public bool isTransplant = false; //transplanted from someone else
// Whether this part could ever have been seen by the player based on mod settings and apparel.
public bool discovered;
private bool initialised;
public new HediffDef_SexPart Def => (HediffDef_SexPart)base.Def;
public HediffCompProperties_SexPart Props => (HediffCompProperties_SexPart)props;
public float FluidAmount => partFluidFactor * Def.fluidMultiplier;
public SexFluidDef Fluid
{
get => fluidOverride ?? Def.fluid;
set
{
if (value == Def.fluid)
{
fluidOverride = null;
}
else
{
fluidOverride = value;
}
}
}
private List<string> DefaultPositionNames
{
get
{
List<string> result = Def.defaultBodyPartList ?? new();
string singleDefaultPart = Def.defaultBodyPart;
if (!singleDefaultPart.NullOrEmpty() && !result.Contains(singleDefaultPart))
{
result.Add(singleDefaultPart);
}
return result;
}
}
public float Size
{
get
{
if (forcedSize.HasValue)
{
return forcedSize.Value;
}
return baseSize * BodySizeFactor;
}
}
// Scales with square of body size so that severity is not constant. May be worth using relBodySize * Growth instead.
private float BodySizeFactor => Pawn.BodySize * Pawn.BodySize
/ (Pawn.RaceProps.baseBodySize * Pawn.RaceProps.baseBodySize);
public bool HasForcedSize => forcedSize.HasValue;
/// <summary>
/// save data
/// </summary>
public override void CompExposeData()
{
base.CompExposeData();
Scribe_Values.Look(ref baseSize, nameof(baseSize));
Scribe_Values.Look(ref originalOwnerSize, nameof(originalOwnerSize));
Scribe_Values.Look(ref originalOwnerRace, nameof(originalOwnerRace));
Scribe_Values.Look(ref previousOwner, nameof(previousOwner));
Scribe_Defs.Look(ref fluidOverride, nameof(fluidOverride));
Scribe_Values.Look(ref partFluidFactor, nameof(partFluidFactor));
Scribe_Values.Look(ref possibleEggsTipString, "possibleEggs");
Scribe_Values.Look(ref isTransplant, nameof(isTransplant));
Scribe_Values.Look(ref forcedSize, nameof(forcedSize));
Scribe_Values.Look(ref discovered, nameof(discovered));
Scribe_Values.Look(ref initialised, nameof(initialised), defaultValue: true);
}
public override void CompPostPostAdd(DamageInfo? dinfo)
{
base.CompPostPostAdd(dinfo);
try//error at world gen
{
Pawn.GetRJWPawnData().genitals = new List<Hediff>();
Pawn.GetRJWPawnData().breasts = new List<Hediff>();
Pawn.GetRJWPawnData().anus = new List<Hediff>();
}
catch
{
}
if (!initialised)
{
Init(reroll: false);
}
}
public override void CompPostMake()
{
base.CompPostMake();
// A null pawn is only possible in vanilla in verb-related debug outputs, but better safe than sorry.
if (Pawn != null)
{
Init();
}
}
public override void CompPostPostRemoved()
{
base.CompPostPostRemoved();
try
{
Pawn.GetRJWPawnData().genitals = new List<Hediff>();
Pawn.GetRJWPawnData().breasts = new List<Hediff>();
Pawn.GetRJWPawnData().anus = new List<Hediff>();
}
catch
{
}
}
public override bool CompDisallowVisible()
{
if (base.CompDisallowVisible())
{
return true;
}
if (RJWSettings.ShowRjwParts == ShowParts.Hide)
{
return true;
}
if (discovered)
{
return false;
}
// Show if required by settings, or at game start if in dev mode
if (RJWSettings.ShowRjwParts != ShowParts.Known || (Current.ProgramState != ProgramState.Playing && Prefs.DevMode))
{
discovered = true;
return false;
}
// Show for hero and apparel-less pawns
if (Pawn.IsDesignatedHero() && Pawn.IsHeroOwner() || Pawn.apparel == null)
{
discovered = true;
}
else
{
var partGroups = parent.Part.groups;
if (!partGroups.Any(group => Pawn.apparel.BodyPartGroupIsCovered(group)))
{
discovered = true;
}
}
return !discovered;
}
/// <summary>
/// show part info in healthtab
/// </summary>
public override string CompTipStringExtra
{
get
{
if (!initialised)
{
ModLog.Warning(" " + xxx.get_pawnname(Pawn) + " part " + parent.def.defName + " is broken, resetting");
Init();
UpdateSeverity();
updatepartposition();
}
// In theory the tip should be a condensed form and the longer form should be elsewhere, but where?
return GetTipString(RJWSettings.ShowRjwParts == RJWSettings.ShowParts.Extended).Join("\n");
}
}
IEnumerable<string> GetTipString(bool extended)
{
//ModLog.Message(" CompTipStringExtra " + xxx.get_pawnname(Pawn) + " " + parent.def.defName);
// TODO: Part type should be a property in the extension.
//StringBuilder defstringBuilder = new StringBuilder();
if (parent.Part != null)
if (Def.genitalFamily == GenitalFamily.Breasts)
{
return GetBreastTip(extended);
}
else if (Def.genitalFamily == GenitalFamily.Penis)
{
return GetPenisTip(extended);
}
else if (Def.genitalFamily == GenitalFamily.Anus || Def.genitalFamily == GenitalFamily.Vagina)
{
return GetOrificeTip(extended);
}
else if (Def.genitalFamily == GenitalFamily.FemaleOvipositor || Def.genitalFamily == GenitalFamily.MaleOvipositor)
{
return GetEggTip();
}
return Enumerable.Empty<string>();
}
IEnumerable<string> GetEggTip()
{
if (!possibleEggsTipString.NullOrEmpty())
{
yield return "RJW_PartInfo_eggs".Translate(possibleEggsTipString);
}
}
IEnumerable<string> GetPenisTip(bool extended)
{
if (PartSizeCalculator.TryGetLength(parent, out float length))
{
yield return "RJW_PartInfo_length".Translate(length.ToString("F1"));
}
if (!extended)
{
yield break;
}
if (PartSizeCalculator.TryGetGirth(parent, out float girth))
{
yield return "RJW_PartInfo_girth".Translate(girth.ToString("F1"));
}
if (PartSizeCalculator.TryGetPenisWeight(parent, out float weight))
{
yield return "RJW_PartInfo_weight".Translate(weight.ToString("F1"));
}
foreach (var line in GetFluidTip())
{
yield return line;
}
if (Def.partTags.Any())
{
yield return "RJW_PartInfo_properties".Translate(Def.partTags.ToCommaList());
}
}
IEnumerable<string> GetOrificeTip(bool extended)
{
if (!extended)
{
yield break;
}
//defstringBuilder.Append(this.Def.description);
//defstringBuilder.AppendLine("Cum: " + FluidType);
//defstringBuilder.AppendLine("Ejaculation: " + (FluidAmmount * FluidModifier).ToString("F2") + "ml");
// TODO: Should be scaled bigger than penis size either in xml or here.
if (PartSizeCalculator.TryGetLength(parent, out float length))
{
yield return "RJW_PartInfo_maxLength".Translate(length.ToString("F1"));
}
if (PartSizeCalculator.TryGetGirth(parent, out float girth))
{
yield return "RJW_PartInfo_maxGirth".Translate(girth.ToString("F1"));
}
foreach (var line in GetFluidTip())
{
yield return line;
}
if (Def.partTags.Any())
{
yield return "Properties: " + Def.partTags.ToCommaList();
}
}
IEnumerable<string> GetBreastTip(bool extended)
{
if (parent.Part.def == xxx.breastsDef)
{
foreach (var line in GetBraCupTip())
{
yield return line;
}
if (!extended)
{
yield break;
}
if (PartSizeCalculator.TryGetCupSize(parent, out float size))
{
var cupSize = (int)size;
if (cupSize > 0)
{
var bandSize = PartSizeCalculator.GetBandSize(parent);
yield return "RJW_PartInfo_braSize".Translate(
bandSize,
cupSize);
if (PartSizeCalculator.TryGetOverbustSize(parent, out float overbust))
{
var underbust = PartSizeCalculator.GetUnderbustSize(parent);
yield return "RJW_PartInfo_underbust".Translate(underbust.ToString("F1"));
yield return "RJW_PartInfo_overbust".Translate(overbust.ToString("F1"));
}
if (PartSizeCalculator.TryGetBreastWeight(parent, out float weight))
{
yield return "RJW_PartInfo_weight".Translate(weight.ToString("F1"));
}
}
else
{
yield return "RJW_PartInfo_braSizeNone".Translate();
}
}
}
foreach (var line in GetFluidTip())
{
yield return line;
}
if (Def.partTags.Any())
{
yield return "Properties: " + Def.partTags.ToCommaList();
}
}
IEnumerable<string> GetBraCupTip()
{
if (PartSizeCalculator.TryGetCupSize(parent, out float size))
{
var cupSize = (int)size;
if (cupSize > 0)
{
yield return "RJW_PartInfo_braCup".Translate(
BraSizeConfigDef.GetCupSizeLabel(cupSize));
}
}
}
IEnumerable<string> GetFluidTip()
{
if (partFluidFactor != 0 && Fluid != null)
{
yield return "RJW_PartInfo_fluidTypeFluidAmount".Translate(
Fluid.LabelCap,
partFluidFactor.ToString("F1"));
}
}
//TODO: someday part(SizeOwner) change operations
public void UpdateSeverity(float newSeverity = -1f)
{
if (newSeverity != -1f)
{
baseSize = newSeverity * Pawn.BodySize / BodySizeFactor;
}
parent.Severity = Size / Pawn.BodySize;
}
public void UpdatePartFluidFactor()
{
if (Def.fluidMultiplier > 0)
{
partFluidFactor = Def.GetRandomFluidAmount(Pawn.RaceProps.baseBodySize, baseSize);
}
}
public void ForceSize(float size)
{
forcedSize = size;
UpdateSeverity();
}
public void UnforceSize()
{
forcedSize = null;
UpdateSeverity();
}
[SyncMethod]
public void updatepartposition()
{
if (parent.def is not HediffDef_SexPart def)
{
return;
}
//Log.Message("0 " + (parent.Part == null));
//Log.Message("1 " +parent.Part);
//Log.Message("2 " +parent.Part.def);
//Log.Message("3 " +parent.Part.def.defName);
//Log.Message("4 " +partBase);
//Log.Message("5 " +partBase.DefaultBodyPart);
//ModLog.Message("pawn " + xxx.get_pawnname(Pawn) + ", part: " + parent.def.defName);
if (parent.Part == null)
{
var bp = Pawn.RaceProps.body.AllParts.Find(x => DefaultPositionNames.Any(x.def.defName.Contains));
if (bp != null)
{
ModLog.Warning(" " + xxx.get_pawnname(Pawn) + " part is null/wholebody? is in wrong BodyPart position, resetting to default: " + def.defaultBodyPart);
parent.Part = bp;
Pawn.GetRJWPawnData().genitals = new List<Hediff>();
Pawn.GetRJWPawnData().breasts = new List<Hediff>();
Pawn.GetRJWPawnData().anus = new List<Hediff>();
}
else
{
ModLog.Message(" " + xxx.get_pawnname(Pawn) + " default bodypart not found: " + def.defaultBodyPart + " -skip.");
}
}
else if (def.defaultBodyPart != "" && !parent.Part.def.defName.Contains(def.defaultBodyPart))
{
//Log.Message("f");
//Log.Message(partBase.DefaultBodyPartList.ToLineList());
if (def.defaultBodyPartList.Any() && def.defaultBodyPartList.Any(parent.Part.def.defName.Contains))
{
return;
}
var bp = Pawn.RaceProps.body.AllParts.Find(x => x.def.defName.Contains(def.defaultBodyPart));
if (bp != null)
{
ModLog.Warning(" " + xxx.get_pawnname(Pawn) + " part " + parent.def.defName + " is in wrong BodyPart position, resetting to default: " + def.defaultBodyPart);
parent.Part = bp;
Pawn.GetRJWPawnData().genitals = new List<Hediff>();
Pawn.GetRJWPawnData().breasts = new List<Hediff>();
Pawn.GetRJWPawnData().anus = new List<Hediff>();
}
else
{
ModLog.Message(" " + xxx.get_pawnname(Pawn) + " default bodypart not found: " + def.defaultBodyPart + " -skip.");
}
//if (pawn.IsColonist)
//{
// Log.Message(xxx.get_pawnname(pawn) + " has broken hediffs, removing " + this.ToString());
// Log.Message(Part.ToString());
// Log.Message(bp.def.defName);
// Log.Message(partBase.DefaultBodyPart.ToString());
//}
}
}
/// <summary>
/// fill comp data
/// </summary>
[SyncMethod]
public void Init(Pawn pawn = null, bool reroll = true)
{
pawn ??= Pawn;
if (originalOwnerSize == 0)
{
originalOwnerSize = pawn.BodySize;
}
if (reroll || baseSize == 0)
{
//var s = (parent is Hediff_NaturalSexPart) ? originalOwnerSize : Pawn.RaceProps.baseBodySize;
baseSize = CalculateSize(pawn, originalOwnerSize);
UpdatePartFluidFactor();
}
if (Def.genitalTags.Contains(GenitalTag.CanFertilizeEgg) || Def.HasComp(typeof(HediffComp_Ovipositor)))
{
var possibleEggNames = HediffComp_Ovipositor.PossibleEggs(pawn.kindDef?.defName)
.SelectMany(eggDef => eggDef.childrenDefs)
.Select(defName => DefDatabase<PawnKindDef>.GetNamedSilentFail(defName)?.label)
.Where(label => label != null);
if (possibleEggNames.Any())
{
possibleEggsTipString = possibleEggNames.ToCommaList();
}
else
{
possibleEggsTipString = pawn?.kindDef?.label ?? "";
}
}
if (originalOwnerRace.NullOrEmpty())
{
originalOwnerRace = pawn?.kindDef.race.LabelCap ?? "RJW_PartInfo_unknownSpecies".Translate();
}
previousOwner = pawn?.LabelNoCount ?? "RJW_PartInfo_unknownOwner".Translate();
UpdateSeverity();
initialised = true;
}
[SyncMethod]
public float CalculateSize(Pawn pawn, float bodySize)
{
float relativeSize;
if (Def.genitalFamily == GenitalFamily.Breasts && pawn?.gender == Gender.Male && !Rand.Chance(TrapChance(pawn)))
{
relativeSize = .01f;
}
else
{
relativeSize = Def.GetRandomSize();
}
return relativeSize * bodySize;
}
private static float TrapChance(Pawn pawn)
{
if (RJWSettings.MaleTrap && !xxx.is_animal(pawn))
{
if (xxx.is_nympho(pawn))
{
return RJWSettings.futa_nymph_chance;
}
if (pawn.Faction != null && (int)pawn.Faction.def.techLevel < 5)
{
return RJWSettings.futa_natives_chance;
}
return RJWSettings.futa_spacers_chance;
}
return 0f;
}
}
}
| Korth95/rjw | 1.5/Source/Hediffs/Comps/HediffComp_SexPart.cs | C# | mit | 15,198 |
using Verse;
using RimWorld;
namespace rjw
{
/// <summary>
/// FeelingBroken raise/lower severity
/// </summary>
public class HediffCompProperties_FeelingBrokenSeverityReduce : HediffCompProperties
{
public HediffCompProperties_FeelingBrokenSeverityReduce()
{
this.compClass = typeof(HediffComp_FeelingBrokenSeverityReduce);
}
public SimpleCurve severityPerDayReduce;
}
class HediffComp_FeelingBrokenSeverityReduce : HediffComp_SeverityModifierBase
{
private HediffCompProperties_FeelingBrokenSeverityReduce Props
{
get
{
return (HediffCompProperties_FeelingBrokenSeverityReduce)this.props;
}
}
public override void CompPostTick(ref float severityAdjustment)
{
base.CompPostTick(ref severityAdjustment);
if (base.Pawn.IsHashIntervalTick(SeverityUpdateInterval))
{
float num = this.SeverityChangePerDay();
num *= 0.00333333341f;
if (xxx.has_traits(Pawn))
{
if (xxx.RoMIsActive)
if (Pawn.story.traits.HasTrait(xxx.Succubus))
num *= 4.0f;
if (Pawn.story.traits.HasTrait(VanillaTraitDefOf.Tough))
{
num *= 2.0f;
}
if (Pawn.story.traits.HasTrait(VanillaTraitDefOf.Tough))
{
num *= 2.0f;
}
if (Pawn.story.traits.HasTrait(TraitDefOf.Wimp))
{
num *= 0.5f;
}
if (Pawn.story.traits.HasTrait(VanillaTraitDefOf.Nerves))
{
int td = Pawn.story.traits.DegreeOfTrait(VanillaTraitDefOf.Nerves);
switch (td)
{
case -2:
num *= 2.0f;
break;
case -1:
num *= 1.5f;
break;
case 1:
num *= 0.5f;
break;
case 2:
num *= 0.25f;
break;
}
}
}
severityAdjustment += num;
}
}
public override float SeverityChangePerDay()
{
return this.Props.severityPerDayReduce.Evaluate(this.parent.ageTicks / GenDate.TicksPerDay);
}
}
public class HediffCompProperties_FeelingBrokenSeverityIncrease : HediffCompProperties
{
public HediffCompProperties_FeelingBrokenSeverityIncrease()
{
this.compClass = typeof(HediffComp_FeelingBrokenSeverityIncrease);
}
public SimpleCurve severityPerDayIncrease;
}
class HediffComp_FeelingBrokenSeverityIncrease : AdvancedHediffComp
{
private HediffCompProperties_FeelingBrokenSeverityIncrease Props
{
get
{
return (HediffCompProperties_FeelingBrokenSeverityIncrease)this.props;
}
}
public override void CompPostMerged(Hediff other)
{
float num = Props.severityPerDayIncrease.Evaluate(this.parent.ageTicks / GenDate.TicksPerDay);
if (xxx.has_traits(Pawn))
{
if (xxx.RoMIsActive)
if (Pawn.story.traits.HasTrait(xxx.Succubus))
num *= 0.25f;
if (Pawn.story.traits.HasTrait(VanillaTraitDefOf.Tough))
{
num *= 0.5f;
}
if (Pawn.story.traits.HasTrait(TraitDefOf.Wimp))
{
num *= 2.0f;
}
if (Pawn.story.traits.HasTrait(VanillaTraitDefOf.Nerves))
{
int td = Pawn.story.traits.DegreeOfTrait(VanillaTraitDefOf.Nerves);
switch (td)
{
case -2:
num *= 0.25f;
break;
case -1:
num *= 0.5f;
break;
case 1:
num *= 1.5f;
break;
case 2:
num *= 2.0f;
break;
}
}
}
other.Severity *= num;
}
}
public class AdvancedHediffWithComps : HediffWithComps
{
public override bool TryMergeWith(Hediff other)
{
for (int i = 0; i < this.comps.Count; i++)
{
if(this.comps[i] is AdvancedHediffComp) ((AdvancedHediffComp)this.comps[i]).CompBeforeMerged(other);
}
return base.TryMergeWith(other);
}
}
public class AdvancedHediffComp : HediffComp
{
public virtual void CompBeforeMerged(Hediff other)
{
}
}
}
| Korth95/rjw | 1.5/Source/Hediffs/HediffComp_FeelingBroken.cs | C# | mit | 3,721 |
using System.Linq;
using Verse;
using RimWorld;
using System.Text;
using Multiplayer.API;
using UnityEngine;
using System.Collections.Generic;
using rjw.Modules.Genitals.Enums;
using RimWorld.QuestGen;
namespace rjw
{
//TODO figure out how this thing works and move eggs to comps
[StaticConstructorOnStartup]
public class HediffDef_SexPart : HediffDef
{
public const float BaseFluidAmount = 20f;
private static readonly FloatRange FluidAmountVariation = new(.75f, 1.25f);
public SexFluidDef fluid; //cummies/milk - insectjelly/honey etc
public float fluidMultiplier = 1; //amount of Milk/Ejaculation/Wetness
public bool produceFluidOnOrgasm;
public string defaultBodyPart = ""; //Bodypart to move this part to, after fucking up with pc or other mod
public List<string> defaultBodyPartList; //Bodypart list to move this part to, after fucking up with pc or other mod
public float sizeMultiplier = 1f;
public PartSizeConfigDef sizeProfile;
public List<string> partTags = new();
public GenitalFamily genitalFamily;
public List<GenitalTag> genitalTags = new();
public override IEnumerable<string> ConfigErrors()
{
foreach (string err in base.ConfigErrors())
{
yield return err;
}
if (sizeProfile == null && genitalFamily != GenitalFamily.Undefined)
{
yield return $"Missing required <{nameof(sizeProfile)}> field. Pick a default from "
+ "<RJW Defs folder>/ConfigDefs/PartSizeConfigs.xml.";
}
}
[SyncMethod]
public float GetRandomFluidAmount(float raceSize, float partSize)
{
return fluidMultiplier * partSize * BaseFluidAmount * FluidAmountVariation.RandomInRange * raceSize * raceSize;
}
[SyncMethod]
public float GetRandomSize()
{
float sample = Rand.Gaussian(0.5f, 0.125f);
return Mathf.Clamp(sample, 0.01f, 1f) * sizeMultiplier;
}
public string GetStandardSizeLabel(float size)
{
return stages.FindLast(stage => stage.minSeverity < size)?.label;
}
}
} | Korth95/rjw | 1.5/Source/Hediffs/HediffDef_SexPart.cs | C# | mit | 1,981 |