Decompiled source of Realistic Ragdolls v1.0.0

Mods/RealisticRagdolls.dll

Decompiled a day ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using BoneLib.BoneMenu;
using HarmonyLib;
using Il2CppSLZ.Marrow.AI;
using Il2CppSLZ.Marrow.Combat;
using Il2CppSLZ.Marrow.PuppetMasta;
using MelonLoader;
using MelonLoader.Preferences;
using Microsoft.CodeAnalysis;
using RagdollMod;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: MelonInfo(typeof(Mod), "Realistic Ragdolls", "1.0.0", "you", null)]
[assembly: MelonGame("Stress Level Zero", "BONELAB")]
[assembly: MelonAdditionalDependencies(new string[] { "BoneLib" })]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("RealisticRagdolls")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("RealisticRagdolls")]
[assembly: AssemblyTitle("RealisticRagdolls")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace RagdollMod
{
	public class Mod : MelonMod
	{
		public override void OnInitializeMelon()
		{
			Cfg.Init();
			MenuBuilder.Build();
			MelonLogger.Msg("Realistic Ragdolls loaded.");
		}

		public override void OnSceneWasLoaded(int buildIndex, string sceneName)
		{
			Brains.Clear();
		}
	}
	internal static class Cfg
	{
		private static MelonPreferences_Category c;

		public static MelonPreferences_Entry<bool> Enabled;

		public static MelonPreferences_Entry<bool> HeadPrecision;

		public static MelonPreferences_Entry<bool> BrainZone;

		public static MelonPreferences_Entry<bool> BrainstemZone;

		public static MelonPreferences_Entry<bool> NeckSpineZone;

		public static MelonPreferences_Entry<float> GrazeCap;

		public static MelonPreferences_Entry<float> LethalDamage;

		public static MelonPreferences_Entry<bool> KneeLock;

		public static MelonPreferences_Entry<bool> ArmCurl;

		public static MelonPreferences_Entry<bool> LimpEnabled;

		public static MelonPreferences_Entry<float> KneeLockChance;

		public static MelonPreferences_Entry<float> ArmCurlChance;

		public static MelonPreferences_Entry<float> LimpTime;

		public static MelonPreferences_Entry<float> LimpFade;

		public static MelonPreferences_Entry<bool> HitReaction;

		public static MelonPreferences_Entry<bool> RealMass;

		public static MelonPreferences_Entry<bool> Stability;

		public static MelonPreferences_Entry<bool> FleshMaterial;

		public static MelonPreferences_Entry<float> Impulse;

		public static MelonPreferences_Entry<float> BodyMass;

		public static MelonPreferences_Entry<float> Damping;

		public static MelonPreferences_Entry<bool> FlipFacing;

		public static MelonPreferences_Entry<bool> DebugLog;

		private static MelonPreferences_Entry<T> E<T>(string id, T def, string desc)
		{
			return c.CreateEntry<T>(id, def, desc, (string)null, false, false, (ValueValidator)null, (string)null);
		}

		public static void Init()
		{
			c = MelonPreferences.CreateCategory("RealisticRagdolls");
			Enabled = E("Enabled", def: true, "Master switch");
			HeadPrecision = E("HeadPrecision", def: true, "Only vital head hits kill instantly");
			BrainZone = E("BrainZone", def: true, "Brain hits are lethal");
			BrainstemZone = E("BrainstemZone", def: true, "Brainstem / base of skull hits are lethal");
			NeckSpineZone = E("NeckSpineZone", def: true, "Rear upper neck (spinal cord) is lethal");
			GrazeCap = E("GrazeCap", 15f, "Max damage from non-vital head hits");
			LethalDamage = E("LethalDamage", 9999f, "Damage applied on a vital hit");
			KneeLock = E("KneeLock", def: true, "Allow knee-lock falls");
			KneeLockChance = E("KneeLockChance", 50f, "% chance of knee lock (else legs just drop)");
			ArmCurl = E("ArmCurl", def: true, "Allow arm curl to chest");
			ArmCurlChance = E("ArmCurlChance", 50f, "% chance of arm curl");
			LimpEnabled = E("LimpEnabled", def: true, "Go limp after delay (off = hold posture up to 60s)");
			LimpTime = E("LimpTime", 4f, "Seconds until fully limp");
			LimpFade = E("LimpFade", 0.6f, "Seconds over which muscle tone fades out");
			HitReaction = E("HitReaction", def: true, "Apply bullet momentum to the head");
			Impulse = E("Impulse", 2.5f, "Bullet momentum in N*s (9mm is roughly 3)");
			RealMass = E("RealMass", def: true, "Use human body-segment mass distribution");
			BodyMass = E("BodyMass", 80f, "Total body mass in kg");
			Stability = E("Stability", def: true, "Solver iterations, CCD, depenetration cap");
			FleshMaterial = E("FleshMaterial", def: true, "Non-bouncy flesh friction material");
			Damping = E("Damping", 3f, "Passive joint damping (muscle viscosity)");
			FlipFacing = E("FlipFacing", def: false, "Debug: flip front/back if brainstem zone is on the wrong side");
			DebugLog = E("DebugLog", def: false, "Log hit regions");
		}
	}
	internal static class MenuBuilder
	{
		private static void B(Page p, string n, MelonPreferences_Entry<bool> e)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			p.CreateBool(n, Color.white, e.Value, (Action<bool>)delegate(bool v)
			{
				e.Value = v;
				MelonPreferences.Save();
			});
		}

		private static void F(Page p, string n, MelonPreferences_Entry<float> e, float inc, float min, float max)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			p.CreateFloat(n, Color.white, e.Value, inc, min, max, (Action<float>)delegate(float v)
			{
				e.Value = v;
				MelonPreferences.Save();
			});
		}

		public static void Build()
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_0215: Unknown result type (might be due to invalid IL or missing references)
			//IL_0246: Unknown result type (might be due to invalid IL or missing references)
			Page obj = Page.Root.CreatePage("Realistic Ragdolls", new Color(0.9f, 0.2f, 0.2f), 0, true);
			B(obj, "Mod Enabled", Cfg.Enabled);
			Page p = obj.CreatePage("Head Damage", Color.yellow, 0, true);
			B(p, "Vital-only Headshots", Cfg.HeadPrecision);
			B(p, "Brain Kills", Cfg.BrainZone);
			B(p, "Brainstem Kills", Cfg.BrainstemZone);
			B(p, "Rear Neck/Spine Kills", Cfg.NeckSpineZone);
			F(p, "Graze Damage Cap", Cfg.GrazeCap, 5f, 0f, 200f);
			Page p2 = obj.CreatePage("Death Motion", Color.cyan, 0, true);
			B(p2, "Knee Lock Enabled", Cfg.KneeLock);
			F(p2, "Knee Lock Chance %", Cfg.KneeLockChance, 5f, 0f, 100f);
			B(p2, "Arm Curl Enabled", Cfg.ArmCurl);
			F(p2, "Arm Curl Chance %", Cfg.ArmCurlChance, 5f, 0f, 100f);
			B(p2, "Go Limp Enabled", Cfg.LimpEnabled);
			F(p2, "Limp After (s)", Cfg.LimpTime, 0.5f, 0.5f, 20f);
			F(p2, "Limp Fade (s)", Cfg.LimpFade, 0.1f, 0f, 3f);
			Page p3 = obj.CreatePage("Physics", Color.green, 0, true);
			B(p3, "Bullet Momentum", Cfg.HitReaction);
			F(p3, "Bullet Impulse (N*s)", Cfg.Impulse, 0.5f, 0f, 20f);
			B(p3, "Real Body Mass Split", Cfg.RealMass);
			F(p3, "Body Mass (kg)", Cfg.BodyMass, 5f, 30f, 200f);
			F(p3, "Joint Damping", Cfg.Damping, 0.5f, 0f, 30f);
			B(p3, "Stable Solver + CCD", Cfg.Stability);
			B(p3, "Flesh Material", Cfg.FleshMaterial);
			Page obj2 = obj.CreatePage("Debug", Color.gray, 0, true);
			B(obj2, "Log Hit Regions", Cfg.DebugLog);
			B(obj2, "Flip Facing", Cfg.FlipFacing);
			obj2.CreateFunction("Dump Last NPC Bones", Color.white, (Action)delegate
			{
				Brains.DumpLast();
			});
		}
	}
	internal enum Role
	{
		Other,
		Hip,
		Knee
	}
	internal sealed class BoneMap
	{
		public enum Region
		{
			None,
			Brain,
			Brainstem,
			Spine,
			Graze
		}

		public Transform Root;

		public Rigidbody Head;

		public Rigidbody Neck;

		public Rigidbody Hips;

		public Rigidbody Spine;

		public Rigidbody Chest;

		public Rigidbody[] UpperArm = (Rigidbody[])(object)new Rigidbody[2];

		public Rigidbody[] Forearm = (Rigidbody[])(object)new Rigidbody[2];

		public Rigidbody[] Hand = (Rigidbody[])(object)new Rigidbody[2];

		public Rigidbody[] Thigh = (Rigidbody[])(object)new Rigidbody[2];

		public Rigidbody[] Calf = (Rigidbody[])(object)new Rigidbody[2];

		public Rigidbody[] Foot = (Rigidbody[])(object)new Rigidbody[2];

		public List<Rigidbody> All = new List<Rigidbody>();

		public List<(ConfigurableJoint j, Role role)> Joints = new List<(ConfigurableJoint, Role)>();

		private static readonly string[] kHead = new string[1] { "head" };

		private static readonly string[] kHeadX = new string[3] { "headset", "headphone", "headband" };

		private static readonly string[] kNeck = new string[1] { "neck" };

		private static readonly string[] kHips = new string[2] { "hips", "pelvis" };

		private static readonly string[] kChest = new string[5] { "chest", "spine2", "spine_02", "spine_03", "upperchest" };

		private static readonly string[] kSpine = new string[5] { "spine1", "spine_01", "lumbar", "abdomen", "spine" };

		private static readonly string[] kUpperArm = new string[5] { "upperarm", "upper_arm", "uparm", "arm", "shoulder" };

		private static readonly string[] kUpperArmX = new string[4] { "fore", "lower", "hand", "low" };

		private static readonly string[] kForearm = new string[4] { "forearm", "lowerarm", "lower_arm", "elbow" };

		private static readonly string[] kHand = new string[2] { "hand", "wrist" };

		private static readonly string[] kThigh = new string[5] { "thigh", "upleg", "upperleg", "upper_leg", "hip" };

		private static readonly string[] kThighX = new string[1] { "hips" };

		private static readonly string[] kCalf = new string[6] { "calf", "shin", "lowerleg", "lower_leg", "knee", "leg" };

		private static readonly string[] kCalfX = new string[3] { "upper", "up", "thigh" };

		private static readonly string[] kFoot = new string[2] { "foot", "ankle" };

		private const float HeadH = 0.23f;

		private const float HeadD = 0.2f;

		private const float HeadW = 0.16f;

		private static int SideOf(string n)
		{
			if (n.Contains("left"))
			{
				return 0;
			}
			if (n.Contains("right"))
			{
				return 1;
			}
			if (Regex.IsMatch(n, "(^|[._\\- ])l\\d*($|[._\\- ])"))
			{
				return 0;
			}
			if (Regex.IsMatch(n, "(^|[._\\- ])r\\d*($|[._\\- ])"))
			{
				return 1;
			}
			return -1;
		}

		private static Rigidbody Pick(List<Rigidbody> rbs, string[] keys, string[] excl, int side, Rigidbody not = null)
		{
			foreach (string value in keys)
			{
				foreach (Rigidbody rb in rbs)
				{
					if ((Object)(object)rb == (Object)null || ((Object)(object)not != (Object)null && (Object)(object)rb == (Object)(object)not))
					{
						continue;
					}
					string text = ((Object)rb).name.ToLowerInvariant();
					if (!text.Contains(value))
					{
						continue;
					}
					bool flag = false;
					if (excl != null)
					{
						foreach (string value2 in excl)
						{
							if (text.Contains(value2))
							{
								flag = true;
								break;
							}
						}
					}
					if (!flag && (side < 0 || SideOf(text) == side))
					{
						return rb;
					}
				}
			}
			return null;
		}

		public static BoneMap Build(Transform root)
		{
			BoneMap boneMap = new BoneMap
			{
				Root = root
			};
			foreach (Rigidbody componentsInChild in ((Component)root).GetComponentsInChildren<Rigidbody>(true))
			{
				boneMap.All.Add(componentsInChild);
			}
			if (boneMap.All.Count == 0 && (Object)(object)root.root != (Object)(object)root)
			{
				boneMap.Root = root.root;
				foreach (Rigidbody componentsInChild2 in ((Component)boneMap.Root).GetComponentsInChildren<Rigidbody>(true))
				{
					boneMap.All.Add(componentsInChild2);
				}
			}
			boneMap.Head = Pick(boneMap.All, kHead, kHeadX, -1);
			boneMap.Neck = Pick(boneMap.All, kNeck, null, -1);
			boneMap.Hips = Pick(boneMap.All, kHips, null, -1);
			boneMap.Chest = Pick(boneMap.All, kChest, null, -1);
			boneMap.Spine = Pick(boneMap.All, kSpine, null, -1, boneMap.Chest);
			for (int i = 0; i < 2; i++)
			{
				boneMap.UpperArm[i] = Pick(boneMap.All, kUpperArm, kUpperArmX, i);
				boneMap.Forearm[i] = Pick(boneMap.All, kForearm, null, i);
				boneMap.Hand[i] = Pick(boneMap.All, kHand, new string[1] { "fore" }, i);
				boneMap.Thigh[i] = Pick(boneMap.All, kThigh, kThighX, i);
				boneMap.Calf[i] = Pick(boneMap.All, kCalf, kCalfX, i);
				boneMap.Foot[i] = Pick(boneMap.All, kFoot, null, i);
			}
			foreach (Rigidbody item2 in boneMap.All)
			{
				ConfigurableJoint component = ((Component)item2).GetComponent<ConfigurableJoint>();
				if ((Object)(object)component == (Object)null)
				{
					continue;
				}
				Role item = Role.Other;
				for (int j = 0; j < 2; j++)
				{
					if ((Object)(object)boneMap.Thigh[j] != (Object)null && (Object)(object)item2 == (Object)(object)boneMap.Thigh[j])
					{
						item = Role.Hip;
					}
					if ((Object)(object)boneMap.Calf[j] != (Object)null && (Object)(object)item2 == (Object)(object)boneMap.Calf[j])
					{
						item = Role.Knee;
					}
				}
				boneMap.Joints.Add((component, item));
			}
			return boneMap;
		}

		public bool Frame(out Vector3 up, out Vector3 right, out Vector3 fwd)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_0149: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_015f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = (fwd = Vector3.zero);
			val = (up = (right = val));
			Rigidbody val2 = Neck ?? Chest ?? Hips;
			if ((Object)(object)Head == (Object)null || (Object)(object)val2 == (Object)null)
			{
				return false;
			}
			val = Head.position - val2.position;
			up = ((Vector3)(ref val)).normalized;
			Vector3 val3;
			if ((Object)(object)UpperArm[0] != (Object)null && (Object)(object)UpperArm[1] != (Object)null)
			{
				val3 = UpperArm[1].position - UpperArm[0].position;
			}
			else
			{
				if (!((Object)(object)Thigh[0] != (Object)null) || !((Object)(object)Thigh[1] != (Object)null))
				{
					return false;
				}
				val3 = Thigh[1].position - Thigh[0].position;
			}
			val = Vector3.ProjectOnPlane(val3, up);
			right = ((Vector3)(ref val)).normalized;
			if (((Vector3)(ref right)).sqrMagnitude < 0.5f)
			{
				return false;
			}
			fwd = Vector3.Cross(right, up);
			if (Cfg.FlipFacing.Value)
			{
				fwd = -fwd;
				right = -right;
			}
			return true;
		}

		private Bounds BoundsOf(Rigidbody rb)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			bool flag = true;
			Bounds bounds = default(Bounds);
			((Bounds)(ref bounds))..ctor(rb.position, Vector3.zero);
			foreach (Collider componentsInChild in ((Component)rb).GetComponentsInChildren<Collider>())
			{
				if (!((Object)(object)componentsInChild.attachedRigidbody != (Object)(object)rb) && !componentsInChild.isTrigger)
				{
					if (flag)
					{
						bounds = componentsInChild.bounds;
						flag = false;
					}
					else
					{
						((Bounds)(ref bounds)).Encapsulate(componentsInChild.bounds);
					}
				}
			}
			return bounds;
		}

		public Region Classify(Collider col, Vector3 point)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			Rigidbody attachedRigidbody = col.attachedRigidbody;
			if ((Object)(object)attachedRigidbody == (Object)null || !Frame(out var up, out var right, out var fwd))
			{
				return Region.None;
			}
			Bounds val;
			if ((Object)(object)Head != (Object)null && (Object)(object)attachedRigidbody == (Object)(object)Head)
			{
				val = BoundsOf(Head);
				Vector3 val2 = point - ((Bounds)(ref val)).center;
				float num = Vector3.Dot(val2, up) / 0.23f;
				float num2 = Vector3.Dot(val2, fwd) / 0.2f;
				float num3 = Vector3.Dot(val2, right) / 0.16f;
				if (num < -0.05f && num2 < 0f && Mathf.Abs(num3) < 0.35f)
				{
					return Region.Brainstem;
				}
				if (!(Sq(num3 / 0.55f) + Sq((num - 0.15f) / 0.3f) + Sq(num2 / 0.56f) <= 1f))
				{
					return Region.Graze;
				}
				return Region.Brain;
			}
			if ((Object)(object)Neck != (Object)null && (Object)(object)attachedRigidbody == (Object)(object)Neck)
			{
				val = BoundsOf(Neck);
				if (Vector3.Dot(point - ((Bounds)(ref val)).center, fwd) < 0f)
				{
					return Region.Spine;
				}
				return Region.None;
			}
			return Region.None;
		}

		private static float Sq(float x)
		{
			return x * x;
		}

		public string Describe()
		{
			StringBuilder sb = new StringBuilder();
			L("Head", Head);
			L("Neck", Neck);
			L("Hips", Hips);
			L("Spine", Spine);
			L("Chest", Chest);
			for (int i = 0; i < 2; i++)
			{
				string text = ((i == 0) ? "L" : "R");
				L("UpperArm." + text, UpperArm[i]);
				L("Forearm." + text, Forearm[i]);
				L("Hand." + text, Hand[i]);
				L("Thigh." + text, Thigh[i]);
				L("Calf." + text, Calf[i]);
				L("Foot." + text, Foot[i]);
			}
			sb.AppendLine("  All rigidbodies:");
			foreach (Rigidbody item in All)
			{
				sb.AppendLine("    " + ((Object)item).name);
			}
			return sb.ToString();
			void L(string n, Rigidbody rb)
			{
				StringBuilder stringBuilder = sb;
				StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(6, 2, stringBuilder);
				handler.AppendLiteral("  ");
				handler.AppendFormatted<string>(n, -12);
				handler.AppendLiteral(" -> ");
				handler.AppendFormatted(((Object)(object)rb != (Object)null) ? ((Object)rb).name : "NOT FOUND");
				stringBuilder.AppendLine(ref handler);
			}
		}
	}
	internal static class Brains
	{
		private static readonly Dictionary<int, BoneMap> cache = new Dictionary<int, BoneMap>();

		private static BoneMap last;

		public static void Clear()
		{
			cache.Clear();
			last = null;
		}

		public static BoneMap Get(AIBrain b)
		{
			int instanceID = ((Object)((Component)b).gameObject).GetInstanceID();
			if (cache.TryGetValue(instanceID, out var value) && (Object)(object)value.Head != (Object)null)
			{
				last = value;
				return value;
			}
			value = BoneMap.Build(((Component)b).transform);
			cache[instanceID] = value;
			last = value;
			return value;
		}

		public static void DumpLast()
		{
			if (last == null)
			{
				MelonLogger.Msg("[Ragdolls] No NPC seen yet. Shoot one first.");
			}
			else
			{
				MelonLogger.Msg("[Ragdolls] Bone mapping:\n" + last.Describe());
			}
		}
	}
	internal sealed class Shot
	{
		public bool Lethal;

		public AIBrain Brain;

		public Vector3 Point;

		public Vector3 Dir;
	}
	[HarmonyPatch(typeof(MuscleCollisionBroadcaster), "ReceiveAttack")]
	internal static class AttackPatch
	{
		private static void Prefix(MuscleCollisionBroadcaster __instance, Attack attack, out Shot __state)
		{
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0158: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0185: Unknown result type (might be due to invalid IL or missing references)
			//IL_018a: Unknown result type (might be due to invalid IL or missing references)
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_017d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			__state = null;
			try
			{
				if (!Cfg.Enabled.Value || !Cfg.HeadPrecision.Value || attack == null || (Object)(object)attack.collider == (Object)null || attack.damage <= 0f)
				{
					return;
				}
				AIBrain val = ((Component)__instance).GetComponentInParent<AIBrain>();
				if ((Object)(object)val == (Object)null)
				{
					val = ((Component)((Component)__instance).transform.root).GetComponentInChildren<AIBrain>(true);
				}
				if ((Object)(object)val == (Object)null || val.isDead)
				{
					return;
				}
				BoneMap boneMap = Brains.Get(val);
				if ((Object)(object)boneMap.Head == (Object)null)
				{
					return;
				}
				Vector3 val2 = attack.collider.ClosestPoint(attack.origin);
				BoneMap.Region region = boneMap.Classify(attack.collider, val2);
				if (region == BoneMap.Region.None)
				{
					return;
				}
				if (Cfg.DebugLog.Value)
				{
					MelonLogger.Msg($"[Ragdolls] hit region: {region}, dmg {attack.damage}");
				}
				if ((region == BoneMap.Region.Brain && Cfg.BrainZone.Value) || (region == BoneMap.Region.Brainstem && Cfg.BrainstemZone.Value) || (region == BoneMap.Region.Spine && Cfg.NeckSpineZone.Value))
				{
					attack.damage = Cfg.LethalDamage.Value;
					Vector3 val3 = attack.direction;
					Vector3 normalized;
					if (!(((Vector3)(ref val3)).sqrMagnitude > 0.01f))
					{
						val3 = val2 - attack.origin;
						normalized = ((Vector3)(ref val3)).normalized;
					}
					else
					{
						val3 = attack.direction;
						normalized = ((Vector3)(ref val3)).normalized;
					}
					Vector3 dir = normalized;
					__state = new Shot
					{
						Lethal = true,
						Brain = val,
						Point = val2,
						Dir = dir
					};
				}
				else if (region == BoneMap.Region.Graze || region == BoneMap.Region.Brain || region == BoneMap.Region.Brainstem)
				{
					attack.damage = Mathf.Min(attack.damage, Cfg.GrazeCap.Value);
				}
			}
			catch (Exception ex)
			{
				MelonLogger.Error("[Ragdolls] Prefix: " + ex);
			}
		}

		private static void Postfix(Shot __state)
		{
			if (__state == null || !__state.Lethal)
			{
				return;
			}
			try
			{
				MelonCoroutines.Start(Death.Run(Brains.Get(__state.Brain), __state));
			}
			catch (Exception ex)
			{
				MelonLogger.Error("[Ragdolls] Postfix: " + ex);
			}
		}
	}
	internal static class Death
	{
		private static float Smooth(float x)
		{
			x = Mathf.Clamp01(x);
			return x * x * (3f - 2f * x);
		}

		public static IEnumerator Run(BoneMap m, Shot shot)
		{
			yield return (object)new WaitForFixedUpdate();
			if (m == null || (Object)(object)m.Head == (Object)null)
			{
				yield break;
			}
			if (Cfg.RealMass.Value)
			{
				ApplyMass(m);
			}
			if (Cfg.Stability.Value)
			{
				ApplyStability(m);
			}
			if (Cfg.FleshMaterial.Value)
			{
				ApplyMaterial(m);
			}
			if (Cfg.HitReaction.Value)
			{
				m.Head.AddForceAtPosition(shot.Dir * Cfg.Impulse.Value, shot.Point, (ForceMode)1);
			}
			bool lockKnees = Cfg.KneeLock.Value && Random.value * 100f < Cfg.KneeLockChance.Value;
			bool curl = Cfg.ArmCurl.Value && Random.value * 100f < Cfg.ArmCurlChance.Value;
			float limp = (Cfg.LimpEnabled.Value ? Mathf.Max(0.1f, Cfg.LimpTime.Value) : 60f);
			float fade = Mathf.Clamp(Cfg.LimpFade.Value, 0f, limp);
			float phase = Random.value * 6.2832f;
			if (Cfg.DebugLog.Value)
			{
				MelonLogger.Msg($"[Ragdolls] death: kneeLock={lockKnees} armCurl={curl} limp={limp}s");
			}
			float t = 0f;
			while (!((Object)(object)m.Head == (Object)null))
			{
				float num = 1f;
				if (t >= limp)
				{
					num = 0f;
				}
				else if (fade > 0f && t > limp - fade)
				{
					num = 1f - Smooth((t - (limp - fade)) / fade);
				}
				ApplyJointTone(m, t, lockKnees, num);
				if (curl && num > 0f)
				{
					ApplyArmCurl(m, t, num, phase);
				}
				if (!(t >= limp))
				{
					t += Time.fixedDeltaTime;
					yield return (object)new WaitForFixedUpdate();
					continue;
				}
				break;
			}
		}

		private static void ApplyJointTone(BoneMap m, float t, bool lockKnees, float tone)
		{
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			float num = Cfg.BodyMass.Value / 80f;
			float num2 = Cfg.Damping.Value * num;
			float num3 = (lockKnees ? 1f : Mathf.Exp((0f - t) / 0.12f)) * tone;
			foreach (var (val, role) in m.Joints)
			{
				if (!((Object)(object)val == (Object)null))
				{
					float num4 = 0f;
					float num5 = num2;
					switch (role)
					{
					case Role.Knee:
						num4 = 6000f * num * num3;
						num5 += 250f * num * num3;
						break;
					case Role.Hip:
						num4 = 2500f * num * num3;
						num5 += 120f * num * num3;
						break;
					}
					val.rotationDriveMode = (RotationDriveMode)1;
					JointDrive slerpDrive = default(JointDrive);
					((JointDrive)(ref slerpDrive)).positionSpring = num4;
					((JointDrive)(ref slerpDrive)).positionDamper = num5;
					((JointDrive)(ref slerpDrive)).maximumForce = 1000000f;
					val.slerpDrive = slerpDrive;
					if (num4 > 0f)
					{
						val.targetRotation = Quaternion.identity;
					}
				}
			}
		}

		private static void ApplyArmCurl(BoneMap m, float t, float tone, float phase)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			if (!m.Frame(out var up, out var right, out var fwd))
			{
				return;
			}
			Rigidbody val = m.Chest ?? m.Spine ?? m.Hips;
			if (!((Object)(object)val == (Object)null))
			{
				Vector3 position = val.position;
				float num = Mathf.Clamp01(t / 0.35f) * tone;
				float num2 = Mathf.Sin(t * 6.2832f * 9f + phase) * 0.008f * num;
				for (int i = 0; i < 2; i++)
				{
					float num3 = ((i == 0) ? (-1f) : 1f);
					Vector3 target = position + fwd * 0.14f + up * (0.05f + num2) + right * (num3 * 0.05f);
					Vector3 target2 = position + fwd * 0.09f - up * 0.1f + right * (num3 * 0.17f);
					Pull(m.Hand[i], target, num, 140f, 16f);
					Pull(m.Forearm[i], target2, num, 60f, 10f);
				}
			}
		}

		private static void Pull(Rigidbody rb, Vector3 target, float w, float kp, float kd)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)rb == (Object)null) && !(w <= 0f))
			{
				Vector3 val = (target - rb.position) * kp - rb.velocity * kd;
				val = Vector3.ClampMagnitude(val, 45f);
				rb.AddForce(val * w, (ForceMode)5);
			}
		}

		private static void ApplyMass(BoneMap m)
		{
			float M = Cfg.BodyMass.Value;
			S(m.Head, 0.081f);
			S(m.Hips, 0.142f);
			S(m.Spine, 0.139f);
			S(m.Chest, 0.216f + (((Object)(object)m.Spine == (Object)null) ? 0.139f : 0f));
			for (int i = 0; i < 2; i++)
			{
				S(m.UpperArm[i], 0.028f);
				S(m.Forearm[i], 0.016f);
				S(m.Hand[i], 0.006f);
				S(m.Thigh[i], 0.1f);
				S(m.Calf[i], 0.0465f);
				S(m.Foot[i], 0.0145f);
			}
			void S(Rigidbody rb, float f)
			{
				if ((Object)(object)rb != (Object)null)
				{
					rb.mass = Mathf.Max(0.2f, M * f);
				}
			}
		}

		private static void ApplyStability(BoneMap m)
		{
			foreach (Rigidbody item in m.All)
			{
				if (!((Object)(object)item == (Object)null))
				{
					item.solverIterations = 24;
					item.solverVelocityIterations = 8;
					item.maxDepenetrationVelocity = 3f;
					item.maxAngularVelocity = 25f;
					item.collisionDetectionMode = (CollisionDetectionMode)2;
					item.drag = 0.02f;
					item.angularDrag = 0.15f;
					item.WakeUp();
				}
			}
		}

		private static void ApplyMaterial(BoneMap m)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			PhysicMaterial sharedMaterial = new PhysicMaterial("RagdollFlesh")
			{
				dynamicFriction = 0.65f,
				staticFriction = 0.75f,
				bounciness = 0f,
				frictionCombine = (PhysicMaterialCombine)0,
				bounceCombine = (PhysicMaterialCombine)2
			};
			foreach (Rigidbody item in m.All)
			{
				if ((Object)(object)item == (Object)null)
				{
					continue;
				}
				foreach (Collider componentsInChild in ((Component)item).GetComponentsInChildren<Collider>())
				{
					if ((Object)(object)componentsInChild.attachedRigidbody == (Object)(object)item && !componentsInChild.isTrigger)
					{
						componentsInChild.sharedMaterial = sharedMaterial;
					}
				}
			}
		}
	}
}