Decompiled source of H3VR Plus v1.0.0

H3VRPlus.dll

Decompiled a day ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using FistVR;
using HarmonyLib;
using Kickback.Core;
using Kickback.Core.Reload;
using Kickback.Reload;
using Microsoft.CodeAnalysis;
using Sodalite;
using Sodalite.Api;
using UnityEngine;
using UnityEngine.Rendering;
using Valve.VR;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyCompany("H3VRPlus")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+916addb9a26894abc40df83c6412d11f6fc0dc31")]
[assembly: AssemblyProduct("H3VRPlus")]
[assembly: AssemblyTitle("H3VRPlus")]
[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.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[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 Kickback
{
	internal static class AmmoDump
	{
		private static bool _running;

		public static void Start(MonoBehaviour host, Action<string> status)
		{
			if (!_running)
			{
				host.StartCoroutine(Run(status));
			}
		}

		private static IEnumerator Run(Action<string> status)
		{
			_running = true;
			string path = Path.Combine(Plugin.DataDir, "ammo_" + DateTime.Now.ToString("yyyy-MM-dd_HHmmss", CultureInfo.InvariantCulture) + ".csv");
			StreamWriter w = new StreamWriter(path, append: false, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
			w.WriteLine("round_type,round_class,class_name,object_id,round_mass,proj_mass,muzzle_vel,front_area,num_proj,spread,ke_joules,vel_mult_4in,vel_mult_10in,vel_mult_16in,vel_mult_20in,vel_mult_24in,note");
			int total = 0;
			int done = 0;
			foreach (KeyValuePair<FireArmRoundType, Dictionary<FireArmRoundClass, DisplayDataClass>> item in AM.STypeDic)
			{
				total += item.Value.Count;
			}
			status($"Dumping ammo 0/{total}");
			foreach (KeyValuePair<FireArmRoundType, Dictionary<FireArmRoundClass, DisplayDataClass>> typeEntry in AM.STypeDic)
			{
				AM.SRoundDisplayDataDic.TryGetValue(typeEntry.Key, out var display);
				foreach (KeyValuePair<FireArmRoundClass, DisplayDataClass> classEntry in typeEntry.Value)
				{
					done++;
					DisplayDataClass data = classEntry.Value;
					FVRObject obj = data?.ObjectID;
					GameObject val = null;
					string note = "";
					if ((Object)(object)obj == (Object)null)
					{
						note = "no ObjectID";
					}
					else
					{
						AnvilCallback<GameObject> load = ((AnvilAsset)obj).GetGameObjectAsync();
						yield return load;
						val = load.Result;
						if ((Object)(object)val == (Object)null)
						{
							note = "prefab failed to load";
						}
					}
					FVRFireArmRound val2 = (((Object)(object)val != (Object)null) ? val.GetComponent<FVRFireArmRound>() : null);
					BallisticProjectile val3 = (((Object)(object)val2 != (Object)null && (Object)(object)val2.BallisticProjectilePrefab != (Object)null) ? val2.BallisticProjectilePrefab.GetComponent<BallisticProjectile>() : null);
					if ((Object)(object)val != (Object)null && (Object)(object)val2 == (Object)null)
					{
						note = "no FVRFireArmRound";
					}
					else if ((Object)(object)val2 != (Object)null && (Object)(object)val3 == (Object)null)
					{
						note = "no BallisticProjectile";
					}
					try
					{
						CultureInfo invariantCulture = CultureInfo.InvariantCulture;
						StringBuilder stringBuilder = new StringBuilder();
						stringBuilder.Append(typeEntry.Key).Append(',').Append(classEntry.Key)
							.Append(',')
							.Append(Csv((data != null) ? data.Name : ""))
							.Append(',')
							.Append(Csv(((Object)(object)obj != (Object)null) ? obj.ItemID : ""))
							.Append(',')
							.Append(((Object)(object)obj != (Object)null) ? obj.Mass.ToString(invariantCulture) : "")
							.Append(',');
						if ((Object)(object)val3 != (Object)null)
						{
							stringBuilder.Append(val3.Mass.ToString(invariantCulture)).Append(',').Append(val3.MuzzleVelocityBase.ToString(invariantCulture))
								.Append(',')
								.Append(val3.FrontArea.ToString(invariantCulture))
								.Append(',');
						}
						else
						{
							stringBuilder.Append(",,,");
						}
						stringBuilder.Append(((Object)(object)val2 != (Object)null) ? val2.NumProjectiles.ToString(invariantCulture) : "").Append(',').Append(((Object)(object)val2 != (Object)null) ? val2.ProjectileSpread.ToString(invariantCulture) : "")
							.Append(',');
						stringBuilder.Append(((Object)(object)val3 != (Object)null) ? (0.5f * val3.Mass * val3.MuzzleVelocityBase * val3.MuzzleVelocityBase * (float)((!((Object)(object)val2 != (Object)null)) ? 1 : Mathf.Max(1, val2.NumProjectiles))).ToString("0.#", invariantCulture) : "").Append(',');
						float[] array = new float[5] { 4f, 10f, 16f, 20f, 24f };
						foreach (float num in array)
						{
							stringBuilder.Append(((Object)(object)display != (Object)null && display.VelMultByBarrelLengthCurve != null) ? display.VelMultByBarrelLengthCurve.Evaluate(num).ToString("0.###", invariantCulture) : "").Append(',');
						}
						stringBuilder.Append(Csv(note));
						w.WriteLine(stringBuilder.ToString());
					}
					catch (Exception arg)
					{
						Plugin.Log.LogError((object)$"Ammo dump row {typeEntry.Key}/{classEntry.Key} failed: {arg}");
					}
					if (done % 10 == 0)
					{
						status($"Dumping ammo {done}/{total}");
					}
				}
				display = null;
			}
			w.Close();
			Plugin.Log.LogInfo((object)$"Ammo dump: {done} rows -> {path}");
			status($"Ammo dumped ({done})");
			_running = false;
		}

		private static string Csv(string v)
		{
			if (!string.IsNullOrEmpty(v))
			{
				if (v.IndexOfAny(new char[3] { ',', '"', '\n' }) < 0)
				{
					return v;
				}
				return "\"" + v.Replace("\"", "\"\"") + "\"";
			}
			return "";
		}
	}
	internal static class Calibers
	{
		private struct Entry
		{
			public double Bullet;

			public double Charge;

			public double Bore;

			public double MaxPressure;

			public double CaseVolume;

			public double GameMass;

			public double GameVelocity;

			public Entry(double bulletGr, double chargeGr, double boreMm, double map, double caseCc, double gameGrams, double gameVelocity)
			{
				Bullet = bulletGr * 6.479891E-05;
				Charge = chargeGr * 6.479891E-05;
				Bore = boreMm * 0.001;
				MaxPressure = map;
				CaseVolume = caseCc * 1E-06;
				GameMass = gameGrams * 0.001;
				GameVelocity = gameVelocity;
			}
		}

		private const double Grain = 6.479891E-05;

		private const double Psi = 6894.757;

		private static readonly Dictionary<FireArmRoundType, Entry> Table = new Dictionary<FireArmRoundType, Entry>
		{
			{
				(FireArmRoundType)0,
				new Entry(40.0, 1.6, 5.7, 165474168.0, 0.12, 2.6, 345.0)
			},
			{
				(FireArmRoundType)28,
				new Entry(50.0, 1.4, 6.4, 172368925.0, 0.14, 3.0, 248.0)
			},
			{
				(FireArmRoundType)34,
				new Entry(71.0, 2.2, 7.9, 141342518.5, 0.3, 4.0, 310.0)
			},
			{
				(FireArmRoundType)24,
				new Entry(95.0, 3.0, 9.0, 148237275.5, 0.45, 6.0, 381.0)
			},
			{
				(FireArmRoundType)27,
				new Entry(95.0, 3.4, 9.2, 155132032.5, 0.5, 6.0, 365.0)
			},
			{
				(FireArmRoundType)18,
				new Entry(124.0, 5.5, 9.02, 241316495.0, 0.86, 7.5, 350.0)
			},
			{
				(FireArmRoundType)130,
				new Entry(125.0, 9.0, 9.02, 275790280.0, 1.0, 8.1, 450.0)
			},
			{
				(FireArmRoundType)6,
				new Entry(180.0, 5.5, 10.2, 241316495.0, 1.1, 12.0, 320.0)
			},
			{
				(FireArmRoundType)61,
				new Entry(180.0, 8.5, 10.2, 258553387.5, 1.4, 12.0, 430.0)
			},
			{
				(FireArmRoundType)8,
				new Entry(230.0, 5.0, 11.48, 144789897.0, 1.62, 21.0, 255.0)
			},
			{
				(FireArmRoundType)31,
				new Entry(31.0, 6.5, 5.7, 344737850.0, 0.8, 2.0, 680.0)
			},
			{
				(FireArmRoundType)30,
				new Entry(31.0, 5.5, 4.65, 399895906.0, 0.7, 2.0, 680.0)
			},
			{
				(FireArmRoundType)14,
				new Entry(85.0, 7.0, 7.85, 234421738.0, 0.9, 5.8, 525.0)
			},
			{
				(FireArmRoundType)36,
				new Entry(158.0, 4.5, 9.07, 117210869.0, 1.95, 9.5, 310.0)
			},
			{
				(FireArmRoundType)5,
				new Entry(158.0, 14.0, 9.07, 241316495.0, 2.2, 8.5, 440.0)
			},
			{
				(FireArmRoundType)7,
				new Entry(240.0, 23.0, 10.9, 248211252.0, 2.53, 22.0, 430.0)
			},
			{
				(FireArmRoundType)9,
				new Entry(250.0, 8.5, 11.5, 96526598.0, 2.6, 21.0, 262.0)
			},
			{
				(FireArmRoundType)59,
				new Entry(300.0, 28.0, 11.5, 448159205.0, 2.8, 26.0, 430.0)
			},
			{
				(FireArmRoundType)51,
				new Entry(350.0, 40.0, 12.7, 413685420.0, 4.3, 26.0, 511.0)
			},
			{
				(FireArmRoundType)49,
				new Entry(300.0, 30.0, 12.7, 248211252.0, 2.9, 20.0, 470.0)
			},
			{
				(FireArmRoundType)13,
				new Entry(55.0, 26.0, 5.7, 379211635.0, 1.85, 3.56, 905.0)
			},
			{
				(FireArmRoundType)60,
				new Entry(125.0, 19.0, 7.82, 379211635.0, 1.3, 8.0, 675.0)
			},
			{
				(FireArmRoundType)12,
				new Entry(53.0, 22.0, 5.6, 351632607.0, 1.75, 3.43, 880.0)
			},
			{
				(FireArmRoundType)15,
				new Entry(123.0, 25.0, 7.92, 355000000.0, 2.31, 7.9, 730.0)
			},
			{
				(FireArmRoundType)16,
				new Entry(147.0, 46.0, 7.82, 415000000.0, 3.63, 8.0, 940.0)
			},
			{
				(FireArmRoundType)4,
				new Entry(150.0, 46.0, 7.82, 427474934.0, 3.63, 11.0, 860.0)
			},
			{
				(FireArmRoundType)3,
				new Entry(150.0, 52.0, 7.82, 413685420.0, 4.4, 12.0, 850.0)
			},
			{
				(FireArmRoundType)17,
				new Entry(148.0, 50.0, 7.92, 358527364.0, 4.1, 11.7, 797.0)
			},
			{
				(FireArmRoundType)48,
				new Entry(174.0, 38.0, 7.92, 358527364.0, 3.8, 12.0, 850.0)
			},
			{
				(FireArmRoundType)11,
				new Entry(660.0, 240.0, 12.98, 379211635.0, 23.0, 45.0, 928.0)
			},
			{
				(FireArmRoundType)21,
				new Entry(560.0, 27.0, 18.5, 79289705.5, 2.0, 34.0, 410.0)
			},
			{
				(FireArmRoundType)22,
				new Entry(440.0, 20.0, 15.6, 82737084.0, 1.6, 23.8, 410.0)
			}
		};

		private const double ShotgunWad = 0.0025;

		public unsafe static Loading ToLoading(RoundInfo r)
		{
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Invalid comparison between Unknown and I4
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Invalid comparison between Unknown and I4
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Invalid comparison between Unknown and I4
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Expected O, but got Unknown
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Invalid comparison between Unknown and I4
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Invalid comparison between Unknown and I4
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Invalid comparison between Unknown and I4
			int num = ((r.NumProjectiles <= 0) ? 1 : r.NumProjectiles);
			double muzzleVelocity = r.MuzzleVelocity * ((r.ChamberVelMult > 0f) ? r.ChamberVelMult : 1f) * ((r.VelMult > 0f) ? r.VelMult : 1f);
			double num2 = r.ProjectileMass * (float)num;
			bool flag = (int)r.Type == 21 || (int)r.Type == 22 || (int)r.Type == 133 || (int)r.Type == 140 || (int)r.Type == 137 || (int)r.Type == 91;
			if (flag)
			{
				num2 += 0.0025;
			}
			Loading val = new Loading
			{
				Name = ((object)(*(FireArmRoundType*)(&r.Type))/*cast due to .constrained prefix*/).ToString() + "/" + ((object)(*(FireArmRoundClass*)(&r.Class))/*cast due to .constrained prefix*/).ToString(),
				MuzzleVelocity = muzzleVelocity
			};
			if (Table.TryGetValue(r.Type, out var value))
			{
				num2 = ((!(num2 <= 0.0)) ? (num2 * ((flag ? (value.Bullet + 0.0025) : value.Bullet) / (value.GameMass + (flag ? 0.0025 : 0.0)))) : value.Bullet);
				double num3 = ((r.MuzzleVelocity > 0f) ? ((double)r.MuzzleVelocity) : value.GameVelocity);
				double val2 = num2 * num3 * num3 / (value.Bullet * value.GameVelocity * value.GameVelocity);
				val.ChargeMass = value.Charge * Math.Max(0.5, Math.Min(2.0, val2));
				val.BoreDiameter = value.Bore;
				val.MaxPressure = value.MaxPressure * (((object)(*(FireArmRoundClass*)(&r.Class))/*cast due to .constrained prefix*/).ToString().StartsWith("PlusP") ? 1.1 : 1.0);
				val.CaseVolume = value.CaseVolume;
			}
			else
			{
				val.BoreDiameter = (((double)r.ProjectileDiameter > 0.002 && (double)r.ProjectileDiameter < 0.03) ? ((double)r.ProjectileDiameter) : 0.009);
			}
			val.BulletMass = ((num2 > 0.0) ? num2 : 0.008);
			if (val.MuzzleVelocity <= 0.0)
			{
				val.MuzzleVelocity = 350.0;
			}
			return val;
		}
	}
	internal class Driver
	{
		private enum Support
		{
			None,
			Cup,
			Grab
		}

		private static readonly Dictionary<int, Driver> Drivers = new Dictionary<int, Driver>();

		private static readonly List<int> Dead = new List<int>();

		private readonly FVRFireArm _gun;

		private readonly GunModel _model;

		private readonly RecoilSim _sim;

		private readonly Vector3 _holderRestPos;

		private float _idleTime;

		private int _holdKey = -1;

		private string _holdName = "";

		private HoldSpec _baseHold;

		private bool _shouldered;

		private bool _mechanismPending;

		private Vector3 _lastHandVel;

		private Vector3 _lastHandAngVel;

		private Vector3 _handAcc;

		private Vector3 _handAngAcc;

		private bool _hasHandVel;

		private const float HeftFilterHz = 15f;

		private const float MaxHandAcc = 80f;

		private const float MaxHandAngAcc = 400f;

		private static bool HeftOn
		{
			get
			{
				if (Settings.Enabled)
				{
					return Settings.HeftScale > 0f;
				}
				return false;
			}
		}

		private bool Settled
		{
			get
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_0029: 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_0047: Unknown result type (might be due to invalid IL or missing references)
				Vec3 val = _sim.Offset;
				if (((Vec3)(ref val)).Length < 0.0002)
				{
					val = _sim.Rotation;
					if (((Vec3)(ref val)).Length < 0.0002)
					{
						val = _sim.AngularVelocity;
						return ((Vec3)(ref val)).Length < 0.002;
					}
				}
				return false;
			}
		}

		public static bool IsHandgun(FVRFireArm gun)
		{
			if (!(gun is Handgun) && !(gun is Revolver) && !(gun is SingleActionRevolver))
			{
				return gun is Derringer;
			}
			return true;
		}

		public static bool Handles(FVRFireArm gun)
		{
			if (!IsHandgun(gun) && !(gun is ClosedBoltWeapon) && !(gun is OpenBoltReceiver) && !(gun is BoltActionRifle) && !(gun is TubeFedShotgun) && !(gun is LeverActionFirearm) && !(gun is BreakActionWeapon) && !(gun is RevolvingShotgun))
			{
				return gun is RollingBlock;
			}
			return true;
		}

		public static Driver For(FVRFireArm gun)
		{
			Drivers.TryGetValue(((Object)gun).GetInstanceID(), out var value);
			return value;
		}

		private Driver(FVRFireArm gun, Vector3 holderRestPos, Loading firstLoad, RecoilCurve firstCurve)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Expected O, but got Unknown
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			_gun = gun;
			_holderRestPos = holderRestPos;
			_model = GunModel.Build(gun);
			if (Settings.MechanismEnabled && firstCurve != null)
			{
				_model.Spec.Mechanism = GunModel.BuildMechanism(gun, _model.Spec, firstLoad, firstCurve);
			}
			else
			{
				_mechanismPending = Settings.MechanismEnabled;
			}
			_sim = new RecoilSim(_model.Spec, Settings.CurrentHold(), ((Object)gun).GetInstanceID() ^ Environment.TickCount);
			Mechanism mechanism = _model.Spec.Mechanism;
			Plugin.Log.LogInfo((object)($"Kickback driving {_model.Spec.Name}: mass {_model.Spec.Mass:0.00} kg ({_model.MassSource}), " + $"grip {_model.GripSource}, bore {_model.Spec.BoreOrigin}, CoM {_model.Spec.CenterOfMass}, roll lean {_model.Spec.KickRollBias:0.00}, " + ((mechanism == null) ? "no mechanism" : $"{mechanism.Kind} {mechanism.Mass:0.000} kg over {mechanism.Travel * 1000.0:0} mm, spring {mechanism.SpringPreload:0} N + {mechanism.SpringRate:0} N/m")));
		}

		public static bool TryTakeShot(FVRFireArm gun)
		{
			if (!Settings.Enabled || !Handles(gun) || (Object)(object)gun.RecoilingPoseHolder == (Object)null || (Object)(object)((FVRInteractiveObject)gun).m_hand == (Object)null)
			{
				return false;
			}
			RoundInfo r = Rounds.ThisFrame(gun);
			if (!r.Known)
			{
				return false;
			}
			Loading val = Calibers.ToLoading(r);
			double num = Math.Max(0.02, (double)r.BarrelLength - 0.01);
			RecoilCurve val2 = Ballistics.Solve(val, num, val.MuzzleVelocity);
			Driver driver = For(gun) ?? Create(gun, val, val2);
			if (driver._mechanismPending)
			{
				driver._model.Spec.Mechanism = GunModel.BuildMechanism(gun, driver._model.Spec, val, val2);
				driver._mechanismPending = false;
			}
			driver.UpdateHold();
			PostureScore.Result result = (Settings.PostureEnabled ? PostureScore.Measure(gun, driver._shouldered) : new PostureScore.Result
			{
				Quality = 1f,
				ArmLine = 1f,
				Cant = 1f,
				Gaze = 1f
			});
			double num2 = default(double);
			driver._sim.SetHold(Posture.Apply(driver._baseHold, driver._model.Spec, (double)result.Quality, ref num2));
			Settings.ReportPosture(result.Quality);
			driver._sim.ShotVariation = Settings.WobbleScale;
			driver._sim.BurstWalk = Settings.WalkScale;
			driver._sim.PostureShake = (double)Settings.ShakeScale * num2;
			driver._sim.Fire(Scaled(val2, Settings.KickScale * gun.GetReductionFactor()));
			driver._idleTime = 0f;
			GunModel model = driver._model;
			string holdName = driver._holdName;
			PostureScore.Result result2 = result;
			ShotLog.Note(gun, model, val, val2, holdName + " " + result2.ToString());
			Readout.Shot(gun, driver._model, val, val2, result.Quality, driver._holdName);
			return true;
		}

		private static Driver Create(FVRFireArm gun, Loading load, RecoilCurve curve)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: 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_0024: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = RecoilState.HolderRestPosition(gun);
			gun.RecoilingPoseHolder.localPosition = val;
			gun.RecoilingPoseHolder.localRotation = Quaternion.identity;
			Driver driver = new Driver(gun, val, load, curve);
			Drivers[((Object)gun).GetInstanceID()] = driver;
			return driver;
		}

		public static Driver Ensure(FVRFireArm gun)
		{
			if (!HeftOn || !Handles(gun) || (Object)(object)gun.RecoilingPoseHolder == (Object)null || (Object)(object)((FVRInteractiveObject)gun).m_hand == (Object)null || !((FVRInteractiveObject)gun).IsHeld)
			{
				return null;
			}
			Driver driver = Create(gun, null, null);
			driver.UpdateHold();
			driver._sim.SetHold(driver._baseHold);
			return driver;
		}

		private bool UpdateHold()
		{
			//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: 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_0152: 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_0162: Unknown result type (might be due to invalid IL or missing references)
			Support support = Support.None;
			Transform val = null;
			FVRAlternateGrip altGrip = ((FVRPhysicalObject)_gun).AltGrip;
			if ((Object)(object)altGrip != (Object)null && (Object)(object)((FVRInteractiveObject)altGrip).m_hand != (Object)null)
			{
				support = Support.Grab;
				val = ((FVRInteractiveObject)altGrip).m_hand.PalmTransform;
			}
			else if (_gun.IsTwoHandStabilized() && (Object)(object)((FVRInteractiveObject)_gun).m_hand.OtherHand != (Object)null)
			{
				support = Support.Cup;
				val = ((FVRInteractiveObject)_gun).m_hand.OtherHand.PalmTransform;
			}
			bool flag = _gun.IsShoulderStabilized() && (Object)(object)_gun.StockPos != (Object)null;
			bool flag2 = (Object)(object)((FVRPhysicalObject)_gun).Bipod != (Object)null && ((FVRPhysicalObject)_gun).Bipod.IsBipodActive;
			int num = (int)support * 100 + (flag ? 10 : 0) + (flag2 ? 1 : 0);
			if (num == _holdKey)
			{
				return false;
			}
			_holdKey = num;
			List<Contact> list = new List<Contact>();
			List<string> list2 = new List<string> { "hand" };
			if (support != Support.None && (Object)(object)val != (Object)null)
			{
				Contact val2 = ((support == Support.Grab) ? References.SupportGrab : References.SupportCup).At(PointOf(val.position));
				val2.LinearStiffness *= (double)Settings.WristScale;
				val2.AngularStiffness *= (double)Settings.WristScale;
				val2.ReturnDamping = Settings.ReturnDamping(val2.ReturnDamping);
				list.Add(val2);
				list2.Add((support == Support.Grab) ? "support" : "cup");
			}
			if (flag)
			{
				list.Add(References.Shoulder.At(PointOf(_gun.StockPos.position)));
				list2.Add("shoulder");
			}
			if (flag2)
			{
				Contact val3 = References.Bipod.At(PointOf(((Component)((FVRPhysicalObject)_gun).Bipod).transform.position));
				val3.Preload = 0.5 * _model.Spec.Mass * 9.81;
				list.Add(val3);
				list2.Add("bipod");
			}
			_baseHold = Settings.CurrentHold().With(list.ToArray());
			_baseHold.TorsoTwist = (((FVRInteractiveObject)_gun).m_hand.IsThisTheRightHand ? 1 : (-1));
			_shouldered = flag;
			_holdName = string.Join("+", list2.ToArray());
			return true;
		}

		private Vec3 PointOf(Vector3 world)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: 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_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			return Frames.ToCore(((Component)_gun).transform.InverseTransformPoint(world) - _model.GripLocal);
		}

		private static RecoilCurve Scaled(RecoilCurve c, float scale)
		{
			if (!(Math.Abs(scale - 1f) < 0.0001f))
			{
				return c.Scaled((double)scale);
			}
			return c;
		}

		public void BeforeFollow(float dt)
		{
			if (HeftOn && (Object)(object)((FVRInteractiveObject)_gun).m_hand != (Object)null && UpdateHold())
			{
				_sim.SetHold(_baseHold);
			}
			FeedHand(dt);
			_sim.Advance((double)dt);
			ApplyHolder();
			List<Impact> impacts = _sim.DrainImpacts();
			Feel.Play(_gun, impacts, _shouldered);
			Readout.Track(_gun, _sim, impacts);
		}

		private void FeedHand(float dt)
		{
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: 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_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: 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_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: 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_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)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: 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_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_0177: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: 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_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01de: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			FVRViveHand hand = ((FVRInteractiveObject)_gun).m_hand;
			bool flag = (Object)(object)((FVRPhysicalObject)_gun).Bipod != (Object)null && ((FVRPhysicalObject)_gun).Bipod.IsBipodActive;
			if (!HeftOn || (Object)(object)hand == (Object)null || (Object)(object)hand.WholeRig == (Object)null || flag)
			{
				_sim.SetHandMotion(Vec3.Zero, Vec3.Zero);
				_hasHandVel = false;
				return;
			}
			Vector3 velLinearLocal = hand.Input.VelLinearLocal;
			Vector3 velAngularLocal = hand.Input.VelAngularLocal;
			if (_hasHandVel)
			{
				float num = 1f - Mathf.Exp((0f - dt) * 2f * (float)Math.PI * 15f);
				_handAcc += ((velLinearLocal - _lastHandVel) / dt - _handAcc) * num;
				_handAngAcc += ((velAngularLocal - _lastHandAngVel) / dt - _handAngAcc) * num;
			}
			else
			{
				_handAcc = (_handAngAcc = Vector3.zero);
			}
			_lastHandVel = velLinearLocal;
			_lastHandAngVel = velAngularLocal;
			_hasHandVel = true;
			Vector3 val = Vector3.ClampMagnitude(hand.WholeRig.TransformDirection(_handAcc), 80f);
			Vector3 val2 = Vector3.ClampMagnitude(hand.WholeRig.TransformDirection(_handAngAcc), 400f);
			Quaternion val3 = Quaternion.Inverse(((Component)_gun).transform.rotation * Quaternion.Inverse(Frames.RotationToUnity(_sim.Rotation)));
			float heftScale = Settings.HeftScale;
			_sim.SetHandMotion(Frames.ToCore(val3 * val) * (double)heftScale, Frames.ToCore(val3 * val2) * (double)heftScale);
		}

		public void ApplyBipod()
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			FVRFireArmBipod bipod = ((FVRPhysicalObject)_gun).Bipod;
			if (!((Object)(object)bipod == (Object)null) && bipod.IsBipodActive)
			{
				bipod.RecoilFactor += 0f - Frames.ToUnity(_sim.Offset).z;
			}
		}

		public void AfterFollow()
		{
			//IL_0021: 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_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: 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)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: 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_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: 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_0080: 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)
			Rigidbody rootRigidbody = ((FVRPhysicalObject)_gun).RootRigidbody;
			if (!((Object)(object)rootRigidbody == (Object)null))
			{
				Quaternion val = ((Component)_gun).transform.rotation * Quaternion.Inverse(Frames.RotationToUnity(_sim.Rotation));
				rootRigidbody.angularVelocity += val * Frames.ToUnity(_sim.AngularVelocity);
				rootRigidbody.velocity += val * Frames.ToUnity(_sim.Velocity);
			}
		}

		public void ApplyHolder()
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: 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_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: 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)
			//IL_004e: 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_0059: 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_0066: 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_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: 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_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: 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_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_00b6: 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_00ba: 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_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: 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)
			Transform recoilingPoseHolder = _gun.RecoilingPoseHolder;
			Transform transform = ((Component)_gun).transform;
			Transform parent = recoilingPoseHolder.parent;
			RecoilState.VanillaHolderPose(_gun, _holderRestPos, out var localPos, out var localRot);
			Vector3 val = transform.InverseTransformPoint(parent.TransformPoint(localPos));
			Quaternion val2 = Quaternion.Inverse(transform.rotation) * parent.rotation * localRot;
			Vector3 gripLocal = _model.GripLocal;
			Vector3 val3 = Frames.ToUnity(_sim.Offset);
			Quaternion val4 = Quaternion.Inverse(Frames.RotationToUnity(_sim.Rotation));
			val = gripLocal + val4 * (val - gripLocal - val3);
			val2 = val4 * val2;
			recoilingPoseHolder.position = transform.TransformPoint(val);
			recoilingPoseHolder.rotation = transform.rotation * val2;
		}

		public static void Prune(float dt)
		{
			Dead.Clear();
			foreach (KeyValuePair<int, Driver> driver in Drivers)
			{
				Driver value = driver.Value;
				if ((Object)(object)value._gun == (Object)null || !((FVRInteractiveObject)value._gun).IsHeld)
				{
					Dead.Add(driver.Key);
					continue;
				}
				value._idleTime = (value.Settled ? (value._idleTime + dt) : 0f);
				if (value._idleTime > 2f && !HeftOn)
				{
					Dead.Add(driver.Key);
				}
			}
			foreach (int item in Dead)
			{
				Drivers.Remove(item);
			}
		}

		public static void ResetAll()
		{
			Drivers.Clear();
		}
	}
	[HarmonyPatch(typeof(FVRPhysicalObject), "FU")]
	internal static class FollowPatch
	{
		private static void Prefix(FVRPhysicalObject __instance)
		{
			FVRFireArm val = (FVRFireArm)(object)((__instance is FVRFireArm) ? __instance : null);
			if (val == null)
			{
				return;
			}
			Driver driver = Driver.For(val) ?? (((FVRInteractiveObject)val).IsHeld ? Driver.Ensure(val) : null);
			if (driver == null)
			{
				return;
			}
			try
			{
				driver.BeforeFollow(Time.fixedDeltaTime);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Kickback step failed: " + ex));
				Driver.ResetAll();
			}
		}

		private static void Postfix(FVRPhysicalObject __instance)
		{
			FVRFireArm val = (FVRFireArm)(object)((__instance is FVRFireArm) ? __instance : null);
			if (val != null && ((FVRInteractiveObject)val).IsHeld)
			{
				Driver.For(val)?.AfterFollow();
			}
		}
	}
	[HarmonyPatch(typeof(FVRFireArm), "FVRFixedUpdate")]
	internal static class FireArmFixedUpdatePatch
	{
		private static void Postfix(FVRFireArm __instance)
		{
			Driver driver = Driver.For(__instance);
			if (driver != null)
			{
				driver.ApplyHolder();
				driver.ApplyBipod();
			}
		}
	}
	internal static class Feel
	{
		private const float SupportShare = 0.7f;

		private static readonly MethodInfo EnableShake = typeof(ScreenShake).GetMethod("EnableShake", BindingFlags.Instance | BindingFlags.NonPublic);

		public static void Play(FVRFireArm gun, List<Impact> impacts, bool shouldered)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Invalid comparison between Unknown and I4
			//IL_0076: 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_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Invalid comparison between Unknown and I4
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			if (impacts.Count == 0)
			{
				return;
			}
			bool flag = Settings.HapticsScale > 0f && (int)GM.Options.ControlOptions.HapticsState != 1;
			FVRViveHand hand = ((FVRInteractiveObject)gun).m_hand;
			FVRViveHand hand2 = (((Object)(object)((FVRPhysicalObject)gun).AltGrip != (Object)null) ? ((FVRInteractiveObject)((FVRPhysicalObject)gun).AltGrip).m_hand : ((gun.IsTwoHandStabilized() && (Object)(object)hand != (Object)null) ? hand.OtherHand : null));
			foreach (Impact impact in impacts)
			{
				if (flag)
				{
					Pulse(impact, out var amp, out var freq, out var dur);
					amp *= Settings.HapticsScale;
					Vibrate(hand, dur, freq, amp);
					Vibrate(hand2, dur, freq, amp * 0.7f);
				}
				if ((int)impact.Kind == 0 && shouldered && Settings.HeadKickScale > 0f)
				{
					HeadKick(Mathf.Min(1.5f, 0.08f * (float)impact.Impulse) * Settings.HeadKickScale);
				}
			}
		}

		private static void HeadKick(float magnitude)
		{
			//IL_0036: 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)
			ScreenShake instance = ScreenShake.instance;
			if (!((Object)(object)instance == (Object)null) && !((Object)(object)instance.vrShake == (Object)null) && (object)EnableShake != null)
			{
				instance.vrShake.Shake(new ShakeProfile(magnitude, 0.15f, 2f), VignetteProfile.None);
				EnableShake.Invoke(instance, new object[1] { 0.15f });
			}
		}

		private static void Pulse(Impact i, out float amp, out float freq, out float dur)
		{
			//IL_0000: 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_000e: 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_0037: 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_0014: Invalid comparison between Unknown and I4
			float num = (float)i.Impulse;
			ImpactKind kind = i.Kind;
			if ((int)kind != 0)
			{
				if ((int)kind == 1)
				{
					amp = Mathf.Clamp01(0.15f + 0.3f * num);
					freq = 260f;
					dur = 0.015f;
				}
				else
				{
					amp = Mathf.Clamp01(0.1f + 0.25f * num);
					freq = 320f;
					dur = 0.012f;
				}
			}
			else
			{
				amp = Mathf.Clamp01(0.2f + 0.065f * num);
				freq = 120f + 120f * Mathf.Clamp01((float)(i.PeakPressure / 400000000.0));
				dur = Mathf.Min(0.06f, 0.025f + 0.002f * num);
			}
		}

		internal static void Vibrate(FVRViveHand hand, float duration, float frequency, float amplitude)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)hand == (Object)null) && !((SteamVR_Action)(object)hand.Vibration == (SteamVR_Action)null) && !(amplitude < 0.01f))
			{
				hand.Vibration.Execute(0f, duration, frequency, Mathf.Clamp01(amplitude), hand.HandSource);
			}
		}
	}
	internal static class Frames
	{
		public static Vec3 ToCore(Vector3 u)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			return new Vec3((double)u.z, (double)u.y, (double)(0f - u.x));
		}

		public static Vector3 ToUnity(Vec3 s)
		{
			//IL_0000: 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_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			return new Vector3((float)(0.0 - s.Z), (float)s.Y, (float)s.X);
		}

		public static Quaternion RotationToUnity(Vec3 rotationVector)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: 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_001e: 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_0025: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = ToUnity(rotationVector);
			float magnitude = ((Vector3)(ref val)).magnitude;
			if (!(magnitude < 1E-07f))
			{
				return Quaternion.AngleAxis(magnitude * 57.29578f, val / magnitude);
			}
			return Quaternion.identity;
		}
	}
	internal class GunModel
	{
		public GunSpec Spec;

		public Vector3 GripLocal;

		public string MassSource;

		public string GripSource;

		private const float PistolBoxDensity = 1100f;

		private const float RevolverBoxDensity = 420f;

		private const float LongGunBoxDensity = 250f;

		private const float MinBoreAbovePalm = 0.03f;

		private const float MaxBoreAbovePalmHandgun = 0.1f;

		private const float MaxBoreAbovePalmLongGun = 0.14f;

		private const float FallbackBoreAbovePalm = 0.055f;

		private const double DefaultRollBias = 0.25;

		private const double SideMagRollBias = 0.35;

		private const double BlowbackEnergyLimit = 1000.0;

		private static readonly Vector3 MaxPartSize = new Vector3(0.4f, 0.6f, 1.6f);

		public static GunModel Build(FVRFireArm gun)
		{
			//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_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_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: 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_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: 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_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: 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_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: 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_01a5: 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_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: 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)
			//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0225: Unknown result type (might be due to invalid IL or missing references)
			//IL_022c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0233: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0204: Unknown result type (might be due to invalid IL or missing references)
			//IL_020b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0254: Unknown result type (might be due to invalid IL or missing references)
			//IL_0256: Unknown result type (might be due to invalid IL or missing references)
			//IL_026a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0278: Unknown result type (might be due to invalid IL or missing references)
			//IL_0286: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_02eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0301: Unknown result type (might be due to invalid IL or missing references)
			//IL_0306: Unknown result type (might be due to invalid IL or missing references)
			//IL_030b: Unknown result type (might be due to invalid IL or missing references)
			//IL_030c: Unknown result type (might be due to invalid IL or missing references)
			//IL_030e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0310: Unknown result type (might be due to invalid IL or missing references)
			//IL_0315: Unknown result type (might be due to invalid IL or missing references)
			//IL_031a: Unknown result type (might be due to invalid IL or missing references)
			//IL_031f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0323: Unknown result type (might be due to invalid IL or missing references)
			//IL_032a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0331: Unknown result type (might be due to invalid IL or missing references)
			//IL_0346: Unknown result type (might be due to invalid IL or missing references)
			//IL_034b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0350: Unknown result type (might be due to invalid IL or missing references)
			//IL_0362: Expected O, but got Unknown
			Transform transform = ((Component)gun).transform;
			string source;
			Bounds val = LocalBounds(gun, out source);
			Vector3 size = ((Bounds)(ref val)).size;
			Vector3 val2 = (Vector3)(((Object)(object)gun.MuzzlePos != (Object)null) ? transform.InverseTransformPoint(gun.MuzzlePos.position) : new Vector3(0f, ((Bounds)(ref val)).max.y, ((Bounds)(ref val)).max.z));
			Vector3 val3 = (((Object)(object)((FVRPhysicalObject)gun).RootRigidbody != (Object)null) ? ((FVRPhysicalObject)gun).RootRigidbody.centerOfMass : ((Bounds)(ref val)).center);
			if (!((Bounds)(ref val)).Contains(val3))
			{
				val3 = ((Bounds)(ref val)).center;
			}
			bool flag = Driver.IsHandgun(gun);
			bool flag2 = gun is Revolver || gun is SingleActionRevolver;
			Transform val4 = (((Object)(object)((FVRInteractiveObject)gun).m_hand != (Object)null) ? ((FVRInteractiveObject)gun).m_hand.PalmTransform : null);
			Vector3 val6 = default(Vector3);
			string gripSource;
			if ((Object)(object)val4 != (Object)null)
			{
				Vector3 val5 = transform.InverseTransformPoint(val4.position);
				float num = val2.y - val5.y;
				float num2 = Mathf.Clamp(num, 0.03f, flag ? 0.1f : 0.14f);
				((Vector3)(ref val6))..ctor(val2.x, val2.y - num2, val5.z);
				gripSource = (Mathf.Approximately(num, num2) ? $"palm, bore {num * 100f:0.0} cm above" : $"palm clamped ({num * 100f:0.0} -> {num2 * 100f:0.0} cm)");
			}
			else
			{
				Vector3 val7 = (((Object)(object)((FVRInteractiveObject)gun).PoseOverride != (Object)null) ? transform.InverseTransformPoint(((FVRInteractiveObject)gun).PoseOverride.position) : ((Bounds)(ref val)).center);
				((Vector3)(ref val6))..ctor(val2.x, val2.y - 0.055f, val7.z);
				gripSource = "no palm, default height";
			}
			float num3 = ((!flag) ? 250f : (flag2 ? 420f : 1100f));
			float num4 = (flag ? Mathf.Clamp(num3 * size.x * size.y * size.z, 0.35f, 2.5f) : Mathf.Clamp(num3 * size.x * size.y * size.z, 1.5f, 9f));
			GunModel gunModel = new GunModel();
			gunModel.GripLocal = val6;
			gunModel.MassSource = $"box {size.z:0.000}x{size.y:0.000}x{size.x:0.000} m x {num3} kg/m³ from {source}";
			gunModel.GripSource = gripSource;
			gunModel.Spec = new GunSpec
			{
				Name = (((Object)(object)((FVRPhysicalObject)gun).ObjectWrapper != (Object)null) ? ((FVRPhysicalObject)gun).ObjectWrapper.ItemID : ((Object)gun).name),
				Mass = num4,
				Length = size.z,
				CenterOfMass = Frames.ToCore(val3 - val6),
				BoreOrigin = Frames.ToCore(val2 - val6),
				Inertia = GunSpec.BoxInertia((double)num4, (double)size.z, (double)size.y, Math.Max(size.x, 0.025)),
				KickRollBias = RollBias(gun, transform)
			};
			return gunModel;
		}

		private static double RollBias(FVRFireArm gun, Transform root)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			double num = 0.25;
			if ((Object)(object)gun.MagazineMountPos != (Object)null)
			{
				num += 0.35 * (double)root.InverseTransformDirection(gun.MagazineMountPos.up).x;
			}
			return Math.Max(-1.0, Math.Min(1.0, num));
		}

		public static Mechanism BuildMechanism(FVRFireArm gun, GunSpec spec, Loading load, RecoilCurve curve)
		{
			//IL_0196: Unknown result type (might be due to invalid IL or missing references)
			//IL_019c: Unknown result type (might be due to invalid IL or missing references)
			Transform val = null;
			Transform val2 = null;
			double num = 0.5 * load.BulletMass * load.MuzzleVelocity * load.MuzzleVelocity;
			Handgun val3 = (Handgun)(object)((gun is Handgun) ? gun : null);
			string text;
			double num2;
			double num3;
			double num4;
			if (val3 != null)
			{
				text = "slide";
				num2 = 0.28;
				num3 = 0.85;
				num4 = 0.03;
				if ((Object)(object)val3.Slide != (Object)null)
				{
					val = val3.Slide.Point_Slide_Forward;
					val2 = val3.Slide.Point_Slide_Rear;
				}
			}
			else
			{
				if (!(gun is OpenBoltReceiver) && !(gun is ClosedBoltWeapon))
				{
					return null;
				}
				bool flag = num < 1000.0;
				text = ((gun is OpenBoltReceiver) ? "open bolt, " : "closed bolt, ") + (flag ? "blowback" : "gas");
				num2 = (flag ? 0.15 : 0.1);
				num3 = (flag ? 0.9 : 0.3);
				num4 = 0.09;
				OpenBoltReceiver val4 = (OpenBoltReceiver)(object)((gun is OpenBoltReceiver) ? gun : null);
				if (val4 != null && (Object)(object)val4.Bolt != (Object)null)
				{
					val = val4.Bolt.Point_Bolt_Forward;
					val2 = val4.Bolt.Point_Bolt_Rear;
				}
				ClosedBoltWeapon val5 = (ClosedBoltWeapon)(object)((gun is ClosedBoltWeapon) ? gun : null);
				if (val5 != null && (Object)(object)val5.Bolt != (Object)null)
				{
					val = val5.Bolt.Point_Bolt_Forward;
					val2 = val5.Bolt.Point_Bolt_Rear;
				}
			}
			double num5 = (((Object)(object)val != (Object)null && (Object)(object)val2 != (Object)null) ? ((double)Vector3.Distance(val.position, val2.position)) : num4);
			if (num5 < 0.015 || num5 > 0.25)
			{
				num5 = num4;
			}
			return Mechanism.Sized(text, num2 * spec.Mass, num5, num3, spec.BoreOrigin.Y, curve.TotalImpulse, spec.Mass);
		}

		private static Bounds LocalBounds(FVRFireArm gun, out string source)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0242: Unknown result type (might be due to invalid IL or missing references)
			//IL_021e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0232: Unknown result type (might be due to invalid IL or missing references)
			//IL_0237: Unknown result type (might be due to invalid IL or missing references)
			//IL_023c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: 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_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: 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_0182: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
			Transform root = ((Component)gun).transform;
			bool any = false;
			Bounds b = default(Bounds);
			source = "meshes";
			MeshFilter[] componentsInChildren = ((Component)gun).GetComponentsInChildren<MeshFilter>();
			foreach (MeshFilter val in componentsInChildren)
			{
				MeshRenderer component = ((Component)val).GetComponent<MeshRenderer>();
				if (!((Object)(object)val.sharedMesh == (Object)null) && !((Object)(object)component == (Object)null) && ((Renderer)component).enabled && ((Component)val).gameObject.activeInHierarchy)
				{
					Add(val.sharedMesh.bounds, ((Component)val).transform);
				}
			}
			if (!any)
			{
				source = "colliders";
				Collider[] componentsInChildren2 = ((Component)gun).GetComponentsInChildren<Collider>();
				foreach (Collider val2 in componentsInChildren2)
				{
					if (val2.isTrigger || !val2.enabled || !((Component)val2).gameObject.activeInHierarchy)
					{
						continue;
					}
					BoxCollider val3 = (BoxCollider)(object)((val2 is BoxCollider) ? val2 : null);
					if (val3 != null)
					{
						Add(new Bounds(val3.center, val3.size), ((Component)val2).transform);
						continue;
					}
					SphereCollider val4 = (SphereCollider)(object)((val2 is SphereCollider) ? val2 : null);
					if (val4 != null)
					{
						Add(new Bounds(val4.center, Vector3.one * val4.radius * 2f), ((Component)val2).transform);
						continue;
					}
					CapsuleCollider val5 = (CapsuleCollider)(object)((val2 is CapsuleCollider) ? val2 : null);
					if (val5 != null)
					{
						Vector3 val6 = Vector3.one * val5.radius * 2f;
						((Vector3)(ref val6))[val5.direction] = Mathf.Max(val5.height, val5.radius * 2f);
						Add(new Bounds(val5.center, val6), ((Component)val2).transform);
						continue;
					}
					MeshCollider val7 = (MeshCollider)(object)((val2 is MeshCollider) ? val2 : null);
					if (val7 != null && (Object)(object)val7.sharedMesh != (Object)null)
					{
						Add(val7.sharedMesh.bounds, ((Component)val2).transform);
					}
				}
			}
			if (!any)
			{
				source = "default";
				b = new Bounds(Vector3.zero, new Vector3(0.03f, 0.13f, 0.2f));
			}
			return b;
			void Add(Bounds local, Transform t)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_000c: 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_0016: Unknown result type (might be due to invalid IL or missing references)
				//IL_001e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0028: Unknown result type (might be due to invalid IL or missing references)
				//IL_002d: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0038: 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_0045: Unknown result type (might be due to invalid IL or missing references)
				//IL_004c: 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_00be: 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_00c4: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d9: 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_010c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0111: Unknown result type (might be due to invalid IL or missing references)
				//IL_0072: Unknown result type (might be due to invalid IL or missing references)
				//IL_0077: Unknown result type (might be due to invalid IL or missing references)
				//IL_007c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0081: Unknown result type (might be due to invalid IL or missing references)
				//IL_0088: Unknown result type (might be due to invalid IL or missing references)
				//IL_008a: Unknown result type (might be due to invalid IL or missing references)
				//IL_008f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0094: Unknown result type (might be due to invalid IL or missing references)
				//IL_0098: 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_00a2: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
				//IL_013c: 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)
				//IL_011e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0123: Unknown result type (might be due to invalid IL or missing references)
				//IL_0128: Unknown result type (might be due to invalid IL or missing references)
				Matrix4x4 val8 = root.worldToLocalMatrix * t.localToWorldMatrix;
				Vector3[] array = (Vector3[])(object)new Vector3[8];
				Vector3 val9 = Vector3.one * float.MaxValue;
				Vector3 val10 = Vector3.one * float.MinValue;
				for (int j = 0; j < 8; j++)
				{
					Vector3 val11 = ((Bounds)(ref local)).center + Vector3.Scale(((Bounds)(ref local)).extents, new Vector3((float)(((j & 1) != 0) ? 1 : (-1)), (float)(((j & 2) != 0) ? 1 : (-1)), (float)(((j & 4) != 0) ? 1 : (-1))));
					array[j] = ((Matrix4x4)(ref val8)).MultiplyPoint3x4(val11);
					val9 = Vector3.Min(val9, array[j]);
					val10 = Vector3.Max(val10, array[j]);
				}
				Vector3 val12 = val10 - val9;
				if (!(val12.x > MaxPartSize.x) && !(val12.y > MaxPartSize.y) && !(val12.z > MaxPartSize.z))
				{
					Vector3[] array2 = array;
					foreach (Vector3 val13 in array2)
					{
						if (!any)
						{
							b = new Bounds(val13, Vector3.zero);
							any = true;
						}
						else
						{
							((Bounds)(ref b)).Encapsulate(val13);
						}
					}
				}
			}
		}
	}
	[BepInPlugin("captience.h3vrplus", "H3VR+", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInProcess("h3vr.exe")]
	public class Plugin : BaseUnityPlugin
	{
		public const string Guid = "captience.h3vrplus";

		public const string Name = "H3VR+";

		private const string OldGuid = "captience.kickback";

		private const string OldDataFolder = "Kickback";

		private const string DataFolder = "H3VRPlus";

		public const string Version = "1.0.0";

		private static readonly string[] RecoilTouchingMods = new string[6] { "OomphFactor", "UniversalRecoilControl", "ThirdLaw", "HandStabilizer", "XRotateOomph", "ZLinearOomph" };

		internal static ManualLogSource Log;

		internal static string DataDir;

		internal static bool DevTools;

		internal static bool TraceEnabled;

		private WristMenuButton _traceButton;

		private WristMenuButton _ammoButton;

		private const float AutoAmmoDelay = 20f;

		private bool _autoAmmoDone;

		private void Awake()
		{
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Expected O, but got Unknown
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Expected O, but got Unknown
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Expected O, but got Unknown
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			DataDir = Path.Combine(Paths.BepInExRootPath, "H3VRPlus");
			MigrateFromKickback();
			DevTools = ((BaseUnityPlugin)this).Config.Bind<bool>("Developer", "DevTools", false, "Mod development tools: per-shot trace logging to BepInEx/H3VRPlus (large files), the ammo data dump and the reload rail overlay. Not needed to play; leave off unless you were asked for a trace.").Value;
			TraceEnabled = DevTools;
			if (DevTools)
			{
				Directory.CreateDirectory(DataDir);
			}
			TraceRecorder.Create(((Component)this).gameObject);
			Readout.Create();
			RailOverlay.Create();
			new Harmony("captience.h3vrplus").PatchAll(typeof(Plugin).Assembly);
			WristMenuSectionProxy val = WristMenuAPI.CreateSection("H3VR+ Recoil");
			Settings.Init(((BaseUnityPlugin)this).Config, val);
			if (DevTools)
			{
				_traceButton = new WristMenuButton(TraceLabel(), (ButtonClickEvent)delegate
				{
					TraceEnabled = !TraceEnabled;
					_traceButton.Text = TraceLabel();
				});
				val.Buttons.Add(_traceButton);
				_ammoButton = new WristMenuButton("Dump ammo data", (ButtonClickEvent)delegate
				{
					AmmoDump.Start((MonoBehaviour)(object)this, SetAmmoText);
				});
				val.Buttons.Add(_ammoButton);
			}
			ReloadSettings.Init(((BaseUnityPlugin)this).Config, WristMenuAPI.CreateSection("H3VR+ Reload"));
			Log.LogInfo((object)("H3VR+ 1.0.0 loaded." + (DevTools ? (" Dev tools on, data folder: " + DataDir) : "")));
		}

		private void Start()
		{
			string[] array = (from p in Chainloader.PluginInfos.Values
				where RecoilTouchingMods.Any((string m) => p.Metadata.Name.IndexOf(m, StringComparison.OrdinalIgnoreCase) >= 0 || p.Metadata.GUID.IndexOf(m, StringComparison.OrdinalIgnoreCase) >= 0)
				select $"{p.Metadata.Name} {p.Metadata.Version}").ToArray();
			TraceRecorder.Instance.SetActiveRecoilMods(array);
			if (array.Length != 0)
			{
				Log.LogWarning((object)("Other recoil mods are loaded and will fight with H3VR+ recoil: " + string.Join(", ", array) + ". Disable them, or turn Kickback off in the wrist menu."));
			}
		}

		private void Update()
		{
			Driver.Prune(Time.deltaTime);
			Readout.Refresh();
			if (DevTools && !_autoAmmoDone && !(TraceRecorder.Instance.FirstShotTime < 0f) && !(Time.time - TraceRecorder.Instance.FirstShotTime < 20f))
			{
				_autoAmmoDone = true;
				if (Directory.GetFiles(DataDir, "ammo_*.csv").Length == 0)
				{
					Log.LogInfo((object)"No ammo dump yet; starting one automatically.");
					AmmoDump.Start((MonoBehaviour)(object)this, SetAmmoText);
				}
			}
		}

		private void MigrateFromKickback()
		{
			try
			{
				string text = Path.Combine(Paths.ConfigPath, "captience.kickback.cfg");
				if (File.Exists(text) && !File.Exists(((BaseUnityPlugin)this).Config.ConfigFilePath))
				{
					File.Copy(text, ((BaseUnityPlugin)this).Config.ConfigFilePath);
					((BaseUnityPlugin)this).Config.Reload();
					File.Move(text, text + ".migrated");
					((BaseUnityPlugin)this).Logger.LogInfo((object)"Settings carried over from Kickback.");
				}
				string text2 = Path.Combine(Paths.BepInExRootPath, "Kickback");
				if (Directory.Exists(text2) && !Directory.Exists(DataDir))
				{
					Directory.Move(text2, DataDir);
					((BaseUnityPlugin)this).Logger.LogInfo((object)"Data folder moved from BepInEx/Kickback to BepInEx/H3VRPlus.");
				}
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Carrying Kickback's settings over failed: " + ex.Message));
			}
		}

		private static string TraceLabel()
		{
			if (!TraceEnabled)
			{
				return "Trace logging: OFF";
			}
			return "Trace logging: ON";
		}

		private void SetAmmoText(string text)
		{
			if (_ammoButton != null)
			{
				_ammoButton.Text = text;
			}
		}
	}
	internal static class PostureScore
	{
		public struct Result
		{
			public float Quality;

			public float ArmLine;

			public float Cant;

			public float Gaze;

			public override string ToString()
			{
				return $"q{Quality:0.00} (arm {ArmLine:0.00}, cant {Cant:0.00}, gaze {Gaze:0.00})";
			}
		}

		private const float ShoulderSide = 0.15f;

		private const float ShoulderForward = 0.1f;

		private const float ShoulderUp = 0.1f;

		public static Result Measure(FVRFireArm gun, bool shouldered)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: 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_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: 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_0171: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: 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_0187: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: 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_019d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01db: Unknown result type (might be due to invalid IL or missing references)
			Result result = new Result
			{
				ArmLine = 1f,
				Cant = 1f,
				Gaze = 1f
			};
			FVRPlayerBody currentPlayerBody = GM.CurrentPlayerBody;
			FVRViveHand hand = ((FVRInteractiveObject)gun).m_hand;
			Vector3 forward = ((Component)gun).transform.forward;
			Vector3 val = Vector3.ProjectOnPlane(((Component)gun).transform.up, forward);
			Vector3 val2 = Vector3.ProjectOnPlane(Vector3.up, forward);
			if (((Vector3)(ref val)).sqrMagnitude > 0.0001f && ((Vector3)(ref val2)).sqrMagnitude > 0.0001f)
			{
				float num = Vector3.Angle(val, val2);
				result.Cant = Mathf.Lerp(0.3f, 1f, Mathf.InverseLerp(80f, 20f, num));
			}
			if ((Object)(object)currentPlayerBody != (Object)null && (Object)(object)currentPlayerBody.Head != (Object)null)
			{
				float num2 = Vector3.Angle(currentPlayerBody.Head.forward, forward);
				result.Gaze = Mathf.Lerp(0.5f, 1f, Mathf.InverseLerp(75f, 25f, num2));
			}
			if (!shouldered && (Object)(object)currentPlayerBody != (Object)null && (Object)(object)currentPlayerBody.Torso != (Object)null && (Object)(object)hand != (Object)null && (Object)(object)hand.PalmTransform != (Object)null)
			{
				Transform torso = currentPlayerBody.Torso;
				Vector3 val3 = torso.position + torso.right * (hand.IsThisTheRightHand ? 0.15f : (-0.15f)) + torso.forward * 0.1f + torso.up * 0.1f;
				Vector3 val4 = hand.PalmTransform.position - val3;
				if (((Vector3)(ref val4)).magnitude < 0.12f)
				{
					result.ArmLine = 0.6f;
				}
				else
				{
					float num3 = Vector3.Angle(val4, forward);
					result.ArmLine = Mathf.Lerp(0f, 1f, Mathf.InverseLerp(85f, 25f, num3));
				}
			}
			result.Quality = Mathf.Clamp01(result.ArmLine * result.Cant * result.Gaze);
			return result;
		}
	}
	internal class Readout : MonoBehaviour
	{
		private const int PathPoints = 90;

		private const float MetresPerDegree = 0.006f;

		private static Readout _instance;

		private TextMesh _text;

		private LineRenderer _path;

		private LineRenderer _axes;

		private FVRFireArm _gun;

		private readonly Queue<Vector2> _points = new Queue<Vector2>();

		private string _header = "";

		private double _peakPitch;

		public static void Create()
		{
			//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_0010: Expected O, but got Unknown
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("Kickback Readout");
			Object.DontDestroyOnLoad((Object)val);
			_instance = val.AddComponent<Readout>();
			_instance.Build();
			val.SetActive(false);
		}

		private void Build()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Expected O, but got Unknown
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_014a: Unknown result type (might be due to invalid IL or missing references)
			//IL_014f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: 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_019b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c1: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("Text");
			val.transform.SetParent(((Component)this).transform, false);
			val.transform.localPosition = new Vector3(-0.09f, 0.11f, 0f);
			_text = val.AddComponent<TextMesh>();
			Font builtinResource = Resources.GetBuiltinResource<Font>("Arial.ttf");
			_text.font = builtinResource;
			((Renderer)val.GetComponent<MeshRenderer>()).material = builtinResource.material;
			_text.fontSize = 48;
			_text.characterSize = 0.0035f;
			_text.anchor = (TextAnchor)0;
			_text.color = new Color(1f, 0.9f, 0.6f);
			Material mat = new Material(Shader.Find("Sprites/Default") ?? Shader.Find("Unlit/Color"));
			_axes = Line("Axes", mat, new Color(1f, 1f, 1f, 0.35f), 0.0008f);
			_axes.positionCount = 5;
			_axes.SetPositions((Vector3[])(object)new Vector3[5]
			{
				new Vector3(-0.06f, 0f, 0f),
				new Vector3(0.06f, 0f, 0f),
				new Vector3(0f, 0f, 0f),
				new Vector3(0f, -0.02f, 0f),
				new Vector3(0f, 0.1f, 0f)
			});
			_path = Line("Path", mat, new Color(1f, 0.35f, 0.25f), 0.0015f);
		}

		private LineRenderer Line(string name, Material mat, Color color, float width)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject(name);
			val.transform.SetParent(((Component)this).transform, false);
			LineRenderer obj = val.AddComponent<LineRenderer>();
			obj.useWorldSpace = false;
			((Renderer)obj).material = mat;
			Color startColor = (obj.endColor = color);
			obj.startColor = startColor;
			obj.widthMultiplier = width;
			obj.positionCount = 0;
			return obj;
		}

		public static void Shot(FVRFireArm gun, GunModel model, Loading load, RecoilCurve curve, float posture, string hold)
		{
			if (!((Object)(object)_instance == (Object)null) && Settings.ReadoutEnabled)
			{
				Readout instance = _instance;
				if ((Object)(object)instance._gun != (Object)(object)gun)
				{
					instance._points.Clear();
				}
				instance._gun = gun;
				instance._peakPitch = 0.0;
				double totalImpulse = curve.TotalImpulse;
				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.AppendLine(model.Spec.Name + "  " + load.Name);
				stringBuilder.AppendLine($"{totalImpulse:0.0} N·s   free recoil {totalImpulse * totalImpulse / (2.0 * model.Spec.Mass):0.0} J   {curve.PeakPressure / 1000000.0:0} MPa");
				stringBuilder.AppendLine($"gun {model.Spec.Mass:0.0} kg   {hold}   posture {posture * 100f:0}%");
				instance._header = stringBuilder.ToString();
			}
		}

		public static void Track(FVRFireArm gun, RecoilSim sim, List<Impact> impacts)
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)_instance == (Object)null) && Settings.ReadoutEnabled && !((Object)(object)gun != (Object)(object)_instance._gun))
			{
				Readout instance = _instance;
				instance._peakPitch = Math.Max(instance._peakPitch, sim.PitchDeg);
				instance._points.Enqueue(new Vector2((float)sim.YawDeg, (float)sim.PitchDeg));
				while (instance._points.Count > 90)
				{
					instance._points.Dequeue();
				}
			}
		}

		public static void Refresh()
		{
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: 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_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: 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_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ae: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_instance == (Object)null)
			{
				return;
			}
			Readout instance = _instance;
			bool flag = Settings.ReadoutEnabled && (Object)(object)instance._gun != (Object)null && ((FVRInteractiveObject)instance._gun).IsHeld && (Object)(object)((FVRInteractiveObject)instance._gun).m_hand != (Object)null && (Object)(object)((FVRInteractiveObject)instance._gun).m_hand.OtherHand != (Object)null;
			if (((Component)instance).gameObject.activeSelf != flag)
			{
				((Component)instance).gameObject.SetActive(flag);
			}
			if (!flag)
			{
				return;
			}
			Transform transform = ((Component)((FVRInteractiveObject)instance._gun).m_hand.OtherHand).transform;
			Transform val = (((Object)(object)GM.CurrentPlayerBody != (Object)null) ? GM.CurrentPlayerBody.Head : null);
			((Component)instance).transform.position = transform.position + Vector3.up * 0.12f;
			if ((Object)(object)val != (Object)null)
			{
				((Component)instance).transform.rotation = Quaternion.LookRotation(((Component)instance).transform.position - val.position, Vector3.up);
			}
			instance._text.text = instance._header + $"peak flip {instance._peakPitch:0.0}°";
			Vector3[] array = (Vector3[])(object)new Vector3[instance._points.Count];
			int num = 0;
			foreach (Vector2 point in instance._points)
			{
				array[num++] = new Vector3(Mathf.Clamp(point.x * 0.006f, -0.12f, 0.12f), Mathf.Clamp(point.y * 0.006f, -0.04f, 0.3f), 0f);
			}
			instance._path.positionCount = array.Length;
			instance._path.SetPositions(array);
		}
	}
	internal static class Rounds
	{
		private static readonly Dictionary<int, RoundInfo> Last = new Dictionary<int, RoundInfo>();

		public static void Note(FVRFireArm gun, RoundInfo info)
		{
			Last[((Object)gun).GetInstanceID()] = info;
		}

		public static RoundInfo ThisFrame(FVRFireArm gun)
		{
			if (!Last.TryGetValue(((Object)gun).GetInstanceID(), out var value) || value.Frame != Time.frameCount)
			{
				return default(RoundInfo);
			}
			return value;
		}
	}
	internal static class Settings
	{
		private static readonly float[] Steps = new float[7] { 0.25f, 0.5f, 0.75f, 1f, 1.25f, 1.5f, 2f };

		private static readonly float[] WobbleSteps = new float[8] { 0f, 0.5f, 1f, 1.5f, 2f, 3f, 4f, 5f };

		private static ConfigEntry<bool> _enabled;

		private static ConfigEntry<bool> _mechanism;

		private static ConfigEntry<bool> _posture;

		private static ConfigEntry<bool> _readout;

		private static WristMenuButton _postureButton;

		private static float _lastPosture = -1f;

		private static ConfigEntry<float> _kick;

		private static ConfigEntry<float> _wrist;

		private static ConfigEntry<float> _grip;

		private static ConfigEntry<float> _wobble;

		private static ConfigEntry<float> _walk;

		private static ConfigEntry<float> _shake;

		private static ConfigEntry<float> _haptics;

		private static ConfigEntry<float> _headKick;

		private static ConfigEntry<float> _bounce;

		private static ConfigEntry<float> _heft;

		private static readonly float[] WalkSteps = new float[5] { 0f, 0.5f, 1f, 1.5f, 2f };

		private static readonly List<KeyValuePair<WristMenuButton, Func<string>>> Labels = new List<KeyValuePair<WristMenuButton, Func<string>>>();

		public static bool Enabled => _enabled.Value;

		public static bool MechanismEnabled => _mechanism.Value;

		public static bool PostureEnabled => _posture.Value;

		public static bool ReadoutEnabled => _readout.Value;

		public static float HapticsScale => _haptics.Value;

		public static float HeadKickScale => _headKick.Value;

		public static float KickScale => _kick.Value;

		public static float WristScale => _wrist.Value;

		public static float WobbleScale => _wobble.Value;

		public static float WalkScale => _walk.Value;

		public static float ShakeScale => _shake.Value;

		public static float HeftScale => _heft.Value;

		public static void Init(ConfigFile cfg, WristMenuSectionProxy section)
		{
			_enabled = cfg.Bind<bool>("Kickback", "Enabled", true, "Kickback physics recoil instead of vanilla");
			_mechanism = cfg.Bind<bool>("Kickback", "Mechanism", true, "Simulate the slide / bolt / carrier hitting the frame");
			_posture = cfg.Bind<bool>("Kickback", "Posture", true, "Awkward holds (bent arm, canted, off-gaze) kick, drift and shake harder");
			_kick = cfg.Bind<float>("Kickback", "Kick", 1f, "Recoil force multiplier (1 = real)");
			_haptics = cfg.Bind<float>("Kickback", "Haptics", 1f, "Per-impact controller haptics strength (0 = off, uses the game's buzz)");
			_headKick = cfg.Bind<float>("Kickback", "HeadKick", 0f, "Screen warp on shouldered shots (0 = off; motion-sickness risk)");
			_readout = cfg.Bind<bool>("Kickback", "Readout", false, "Floating last-shot readout above the off hand");
			_wrist = cfg.Bind<float>("Kickback", "Wrist", 1f, "Wrist/arm stiffness multiplier (higher = flips less, settles faster)");
			_grip = cfg.Bind<float>("Kickback", "Grip", 1f, "Grip strength multiplier (higher = slips less in the hand)");
			_heft = cfg.Bind<float>("Kickback", "Heft", 1f, "Guns have weight when you swing them: heavy ones lag and overshoot, pistols stay snappy (0 = off)");
			_shake = cfg.Bind<float>("Kickback", "Shake", 1f, "Posture shake: absorbed recoil comes back as a short shake that builds in bursts (0 = off)");
			_walk = cfg.Bind<float>("Kickback", "Walk", 1f, "Burst walk: hands and shoulder give way under sustained fire (0 = off)");
			_wobble = cfg.Bind<float>("Kickback", "Wobble", 1f, "Shot-to-shot variation: strength spread, off-centre push, sideways jolt of every impact (0 = every shot identical)");
			_bounce = cfg.Bind<float>("Kickback", "Bounce", 1f, "How far a hand-held gun dips below the aim on the way back (0 = glides back, no dip)");
			Button(section, () => (!_enabled.Value) ? "Kickback: OFF (vanilla)" : "Kickback: ON", delegate
			{
				_enabled.Value = !_enabled.Value;
			});
			Button(section, () => (!_mechanism.Value) ? "Bolt/slide: OFF" : "Bolt/slide: ON", delegate
			{
				_mechanism.Value = !_mechanism.Value;
			});
			_postureButton = Button(section, PostureLabel, delegate
			{
				_posture.Value = !_posture.Value;
			});
			Button(section, () => $"Kick: {_kick.Value * 100f:0}%", delegate
			{
				_kick.Value = Next(_kick.Value);
			});
			Button(section, () => $"Wrist: {_wrist.Value * 100f:0}%", delegate
			{
				_wrist.Value = Next(_wrist.Value);
			});
			Button(section, () => $"Grip: {_grip.Value * 100f:0}%", delegate
			{
				_grip.Value = Next(_grip.Value);
			});
			Button(section, () => $"Wobble: {_wobble.Value * 100f:0}%", delegate
			{
				_wobble.Value = NextWobble(_wobble.Value);
			});
			Button(section, () => (!(_bounce.Value > 0f)) ? "Bounce: OFF" : $"Bounce: {_bounce.Value * 100f:0}%", delegate
			{
				_bounce.Value = NextWalk(_bounce.Value);
			});
			Button(section, () => $"Shake: {_shake.Value * 100f:0}%", delegate
			{
				_shake.Value = NextWalk(_shake.Value);
			});
			Button(section, () => (!(_heft.Value > 0f)) ? "Heft: OFF" : $"Heft: {_heft.Value * 100f:0}%", delegate
			{
				_heft.Value = NextWalk(_heft.Value);
			});
			Button(section, () => $"Haptics: {_haptics.Value * 100f:0}%", delegate
			{
				_haptics.Value = NextWalk(_haptics.Value);
			});
			Button(section, () => (!(_headKick.Value > 0f)) ? "Head kick: OFF" : $"Head kick: {_headKick.Value * 100f:0}%", delegate
			{
				_headKick.Value = NextWalk(_headKick.Value);
			});
			Button(section, () => (!_readout.Value) ? "Readout: OFF" : "Readout: ON", delegate
			{
				_readout.Value = !_readout.Value;
			});
			Button(section, () => $"Walk: {_walk.Value * 100f:0}%", delegate
			{
				_walk.Value = NextWalk(_walk.Value);
			});
			Button(section, () => "Reset tuning to 100%", delegate
			{
				ConfigEntry<float> kick = _kick;
				ConfigEntry<float> wrist = _wrist;
				ConfigEntry<float> grip = _grip;
				ConfigEntry<float> wobble = _wobble;
				ConfigEntry<float> walk = _walk;
				ConfigEntry<float> shake = _shake;
				ConfigEntry<float> haptics = _haptics;
				ConfigEntry<float> bounce = _bounce;
				float num = (_heft.Value = 1f);
				float num3 = (bounce.Value = num);
				float num5 = (haptics.Value = num3);
				float num7 = (shake.Value = num5);
				float num9 = (walk.Value = num7);
				float num11 = (wobble.Value = num9);
				float num13 = (grip.Value = num11);
				float value = (wrist.Value = num13);
				kick.Value = value;
			});
		}

		private static float NextWalk(float v)
		{
			float[] walkSteps = WalkSteps;
			foreach (float num in walkSteps)
			{
				if (num > v + 0.001f)
				{
					return num;
				}
			}
			return WalkSteps[0];
		}

		private static float NextWobble(float v)
		{
			float[] wobbleSteps = WobbleSteps;
			foreach (float num in wobbleSteps)
			{
				if (num > v + 0.001f)
				{
					return num;
				}
			}
			return WobbleSteps[0];
		}

		private static float Next(float v)
		{
			for (int i = 0; i < Steps.Length; i++)
			{
				if (Steps[i] > v + 0.001f)
				{
					return Steps[i];
				}
			}
			return Steps[0];
		}

		private static string PostureLabel()
		{
			if (_posture.Value)
			{
				if (!(_lastPosture < 0f))
				{
					return $"Posture: ON (last shot {_lastPosture * 100f:0}%)";
				}
				return "Posture: ON";
			}
			return "Posture: OFF";
		}

		public static void ReportPosture(float quality)
		{
			if (!(Mathf.Abs(quality - _lastPosture) < 0.01f))
			{
				_lastPosture = quality;
				if (_postureButton != null)
				{
					_postureButton.Text = PostureLabel();
				}
			}
		}

		private static WristMenuButton Button(WristMenuSectionProxy section, Func<string> label, Action click)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected O, but got Unknown
			WristMenuButton val = null;
			val = new WristMenuButton(label(), (ButtonClickEvent)delegate
			{
				click();
				Driver.ResetAll();
				foreach (KeyValuePair<WristMenuButton, Func<string>> label2 in Labels)
				{
					label2.Key.Text = label2.Value();
				}
			});
			Labels.Add(new KeyValuePair<WristMenuButton, Func<string>>(val, label));
			section.Buttons.Add(val);
			return val;
		}

		public static double ReturnDamping(double reference)
		{
			if (!(_bounce.Value <= 0f))
			{
				return Math.Pow(reference, _bounce.Value);
			}
			return 1.0;
		}

		public static HoldSpec CurrentHold()
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: 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_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: 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_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: 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_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: 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_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Expected O, but got Unknown
			HoldSpec oneHandFirm = References.OneHandFirm;
			double num = _wrist.Value;
			double num2 = _grip.Value;
			return new HoldSpec
			{
				Name = oneHandFirm.Name,
				LinearStiffness = oneHandFirm.LinearStiffness * num,
				LinearDamping = oneHandFirm.LinearDamping,
				AngularStiffness = oneHandFirm.AngularStiffness * num,
				AngularDamping = oneHandFirm.AngularDamping,
				ReturnDamping = ReturnDamping(oneHandFirm.ReturnDamping),
				ImpactKick = oneHandFirm.ImpactKick,
				SlipTorque = oneHandFirm.SlipTorque * num2,
				SlipRate = oneHandFirm.SlipRate,
				SlipMax = oneHandFirm.SlipMax,
				SlipBleedTime = oneHandFirm.SlipBleedTime
			};
		}
	}
	internal struct RoundInfo
	{
		public bool Known;

		public FireArmRoundType Type;

		public FireArmRoundClass Class;

		public float ProjectileMass;

		public float MuzzleVelocity;

		public int NumProjectiles;

		public float ChamberVelMult;

		public float VelMult;

		public int Frame;

		public float BarrelLength;

		public float ProjectileDiameter;
	}
	[HarmonyPatch(typeof(FVRFireArm), "Fire")]
	internal static class FirePatch
	{
		private static void Prefix(FVRFireArm __instance, FVRFireArmChamber chamber, Transform muzzle, float velMult, ref bool doBuzz)
		{
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			if (doBuzz && Settings.Enabled && Settings.HapticsScale > 0f && Driver.Handles(__instance))
			{
				doBuzz = false;
			}
			try
			{
				RoundInfo info = new RoundInfo
				{
					Frame = Time.frameCount,
					VelMult = velMult
				};
				FVRFireArmRound val = (((Object)(object)chamber != (Object)null) ? chamber.GetRound() : null);
				if ((Object)(object)val != (Object)null)
				{
					info.Known = true;
					info.Type = val.RoundType;
					info.Class = val.RoundClass;
					info.NumProjectiles = val.NumProjectiles;
					BallisticProjectile val2 = (((Object)(object)val.BallisticProjectilePrefab != (Object)null) ? val.BallisticProjectilePrefab.GetComponent<BallisticProjectile>() : null);
					if ((Object)(object)val2 != (Object)null)
					{
						info.ProjectileMass = val2.Mass;
						info.MuzzleVelocity = val2.MuzzleVelocityBase;
						if (val2.FrontArea > 0f)
						{
							info.ProjectileDiameter = 2f * Mathf.Sqrt(val2.FrontArea / (float)Math.PI);
						}
					}
					if ((Object)(object)muzzle != (Object)null)
					{
						info.BarrelLength = Vector3.Distance(((Component)chamber).transform.position, muzzle.position);
						info.ChamberVelMult = AM.GetChamberVelMult(val.RoundType, info.BarrelLength);
					}
				}
				Rounds.Note(__instance, info);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Fire capture failed: " + ex));
			}
		}
	}
	internal struct ShotState
	{
		public RecoilState Before;

		public bool Kickback;
	}
	[HarmonyPatch(typeof(FVRFireArm), "Recoil")]
	internal static class RecoilPatch
	{
		private static bool Prefix(FVRFireArm __instance, out ShotState __state)
		{
			__state = new ShotState
			{
				Before = (Plugin.TraceEnabled ? RecoilState.Read(__instance) : default(RecoilState))
			};
			try
			{
				__state.Kickback = Driver.TryTakeShot(__instance);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Kickback shot failed, using vanilla: " + ex));
				__state.Kickback = false;
			}
			return !__state.Kickback;
		}

		private static void Postfix(FVRFireArm __instance, bool twoHandStabilized, bool foregripStabilized, bool shoulderStabilized, FVRFireArmRecoilProfile overrideprofile, float VerticalRecoilMult, ShotState __state)
		{
			if (!Plugin.TraceEnabled)
			{
				return;
			}
			try
			{
				RecoilState after = RecoilState.Read(__instance);
				TraceRecorder.Instance.NoteShot(__instance, twoHandStabilized, foregripStabilized, shoulderStabilized, overrideprofile, VerticalRecoilMult, __state.Before, after, __state.Kickback);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Recoil capture failed: " + ex));
			}
		}
	}
	internal struct RecoilState
	{
		public float X;

		public float Y;

		public float Z;

		public float LinearZ;

		public float MassDrift;

		public Vector2 LinearXY;

		private static readonly FieldRef<FVRFireArm, float> RX = AccessTools.FieldRefAccess<FVRFireArm, float>("m_recoilX");

		private static readonly FieldRef<FVRFireArm, float> RY = AccessTools.FieldRefAccess<FVRFireArm, float>("m_recoilY");

		private static readonly FieldRef<FVRFireArm, float> RZ = AccessTools.FieldRefAccess<FVRFireArm, float>("m_recoilZ");

		private static readonly FieldRef<FVRFireArm, float> RLZ = AccessTools.FieldRefAccess<FVRFireArm, float>("m_recoilLinearZ");

		private static readonly FieldRef<FVRFireArm, Vector2> RLXY = AccessTools.FieldRefAccess<FVRFireArm, Vector2>("m_recoilLinearXY");

		private static readonly FieldRef<FVRFireArm, float> RMD = AccessTools.Fiel

Kickback.Core.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyCompany("Kickback.Core")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+916addb9a26894abc40df83c6412d11f6fc0dc31")]
[assembly: AssemblyProduct("Kickback.Core")]
[assembly: AssemblyTitle("Kickback.Core")]
[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 Kickback.Core
{
	public class Loading
	{
		public string Name;

		public double BulletMass;

		public double MuzzleVelocity;

		public double ChargeMass;

		public double BoreDiameter;

		public double MaxPressure;

		public double GasFactor = 1.5;

		public double CaseVolume;

		public double EffectiveCaseVolume(double charge)
		{
			if (!(CaseVolume > 0.0))
			{
				return charge / 900.0 / 0.9;
			}
			return CaseVolume;
		}

		public static double EstimateCharge(double bulletMass, double velocity)
		{
			return 0.5 * bulletMass * velocity * velocity / 1200000.0;
		}
	}
	public class RecoilCurve
	{
		public double PeakPressure;

		public double TimeToPeak;

		public double ExitTime;

		public double ExitPressure;

		public double GasTau;

		private const double GasCutoff = 12.0;

		private double _boreScale;

		private double _gasF0;

		public double BoreImpulse { get; private set; }

		public double GasImpulse { get; private set; }

		public double TotalImpulse => BoreImpulse + GasImpulse;

		public double Duration => ExitTime + 12.0 * GasTau;

		public RecoilCurve Scaled(double scale)
		{
			RecoilCurve obj = (RecoilCurve)MemberwiseClone();
			obj.BoreImpulse *= scale;
			obj.GasImpulse *= scale;
			obj._boreScale *= scale;
			obj._gasF0 *= scale;
			return obj;
		}

		public double Force(double t)
		{
			if (t < 0.0 || t > Duration)
			{
				return 0.0;
			}
			if (t < ExitTime)
			{
				double num = t / TimeToPeak;
				return _boreScale * num * Math.Exp(1.0 - num);
			}
			return _gasF0 * Math.Exp((0.0 - (t - ExitTime)) / GasTau);
		}

		internal static RecoilCurve Create(double peakPressure, double tp, double exitU, double boreForceScale, double boreImpulse, double gasImpulse, double exitPressure, double gasTau)
		{
			return new RecoilCurve
			{
				PeakPressure = peakPressure,
				TimeToPeak = tp,
				ExitTime = exitU * tp,
				ExitPressure = exitPressure,
				GasTau = gasTau,
				BoreImpulse = boreImpulse,
				GasImpulse = gasImpulse,
				_boreScale = boreForceScale,
				_gasF0 = gasImpulse / (gasTau * (1.0 - Math.Exp(-12.0)))
			};
		}
	}
	public static class Ballistics
	{
		private const double PressureTargetFraction = 0.9;

		private const double DefaultExitU = 4.5;

		private const double JetThrustCoefficient = 1.25;

		private const double GasGamma = 1.25;

		private const double BurnoutU = 2.0;

		private static double G(double u)
		{
			return Math.E * (1.0 - (1.0 + u) * Math.Exp(0.0 - u));
		}

		private static double H(double u)
		{
			return Math.E * (u - 2.0 + (2.0 + u) * Math.Exp(0.0 - u));
		}

		public static RecoilCurve Solve(Loading l, double travel, double muzzleVelocity = 0.0)
		{
			if (travel <= 0.0)
			{
				throw new ArgumentException("barrel travel must be positive", "travel");
			}
			double num = ((muzzleVelocity > 0.0) ? muzzleVelocity : l.MuzzleVelocity);
			double num2 = ((l.ChargeMass > 0.0) ? l.ChargeMass : Loading.EstimateCharge(l.BulletMass, num));
			double num3 = Math.PI / 4.0 * l.BoreDiameter * l.BoreDiameter;
			double num4 = l.BulletMass + num2 / 3.0;
			double num5 = 4.5;
			if (l.MaxPressure > 0.0)
			{
				num5 = SolveExitU(0.9 * l.MaxPressure, num, travel, num4, num3);
			}
			double num6 = travel / num * G(num5) / H(num5);
			double num7 = num / (num6 * G(num5)) * num4 / num3;
			double boreImpulse = (l.BulletMass + num2 / 2.0) * num;
			double boreForceScale = num7 * num3 * (l.BulletMass + num2 / 2.0) / num4;
			double num8 = num2 * num * Math.Max(0.0, l.GasFactor - 0.5);
			double num9 = Math.Min(2.0, num5);
			double num10 = travel * H(num9) / H(num5);
			double num11 = num7 * num9 * Math.Exp(1.0 - num9);
			double num12 = l.EffectiveCaseVolume(num2);
			double x = (num12 + num3 * travel) / (num12 + num3 * num10);
			double num13 = num11 * Math.Pow(x, -1.25);
			double gasTau = ((num8 > 0.0) ? (num8 / (1.25 * num13 * num3)) : 0.0001);
			return RecoilCurve.Create(num7, num6, num5, boreForceScale, boreImpulse, num8, num13, gasTau);
		}

		private static double SolveExitU(double targetPeak, double v, double travel, double mEff, double area)
		{
			double num = 1.2;
			double num2 = 14.0;
			for (int i = 0; i < 60; i++)
			{
				double num3 = 0.5 * (num + num2);
				double num4 = travel / v * G(num3) / H(num3);
				if (v / (num4 * G(num3)) * mEff / area < targetPeak)
				{
					num = num3;
				}
				else
				{
					num2 = num3;
				}
			}
			return 0.5 * (num + num2);
		}
	}
	public static class Posture
	{
		public const double WristAtWorst = 0.15;

		public const double ArmAtWorst = 0.5;

		public const double GripAtWorst = 0.35;

		public const double SupportAtWorst = 0.4;

		public const double YieldAtWorst = 0.35;

		public const double ShakeAtWorst = 2.5;

		public const double DriftReferenceMass = 3.0;

		public const double DriftReferenceReach = 0.12;

		private static double Lerp(double atWorst, double quality)
		{
			return atWorst + (1.0 - atWorst) * quality;
		}

		public static HoldSpec Apply(HoldSpec hold, GunSpec gun, double quality, out double shakeScale)
		{
			double quality2 = Math.Max(0.0, Math.Min(1.0, quality));
			HoldSpec holdSpec = hold.With();
			holdSpec.AngularStiffness = hold.AngularStiffness * Lerp(0.15, quality2);
			holdSpec.LinearStiffness = hold.LinearStiffness * Lerp(0.5, quality2);
			holdSpec.SlipTorque = hold.SlipTorque * Lerp(0.35, quality2);
			double num = Lerp(0.35, quality2) * GunDrift(hold, gun);
			List<Contact> list = new List<Contact>();
			foreach (Contact contact2 in hold.Contacts)
			{
				Contact contact = contact2.At(contact2.Point);
				if (contact2.PushOnly == PushOnly.None)
				{
					double num2 = Lerp(0.4, quality2);
					contact.LinearStiffness = contact2.LinearStiffness * num2;
					contact.AngularStiffness = contact2.AngularStiffness * num2;
				}
				contact.YieldForce = contact2.YieldForce * num;
				list.Add(contact);
			}
			holdSpec.Contacts = list;
			shakeScale = Lerp(2.5, quality2);
			return holdSpec;
		}

		public static double GunDrift(HoldSpec hold, GunSpec gun)
		{
			double num = gun.CenterOfMass.Length;
			foreach (Contact contact in hold.Contacts)
			{
				if (contact.PushOnly == PushOnly.None)
				{
					num = Math.Min(num, (gun.CenterOfMass - contact.Point).Length);
				}
			}
			double num2 = Math.Pow(3.0 / Math.Max(0.3, gun.Mass), 0.3);
			double num3 = 1.0 / (1.0 + 0.5 * Math.Max(0.0, num - 0.12) / 0.12);
			return Math.Max(0.5, Math.Min(1.3, num2 * num3));
		}
	}
	public class RecoilSim
	{
		public enum ImpactKind
		{
			Shot,
			RearStop,
			Battery
		}

		public struct Impact
		{
			public double Time;

			public ImpactKind Kind;

			public double Impulse;

			public double PeakPressure;
		}

		private struct Shot
		{
			public double Start;

			public RecoilCurve Curve;

			public double Strength;

			public Vec3 LineOffset;

			public Vec3 Direction;

			public double RollLever;
		}

		public const double FineStep = 2E-06;

		public const double MechanismStep = 2E-05;

		public const double CoarseStep = 0.0002;

		public readonly GunSpec Gun;

		private string[] _creepNames = new string[0];

		private Vec3 _com;

		private Vec3 _vel;

		private Quat _rot = Quat.Identity;

		private Vec3 _omega;

		private Vec3 _slip;

		private bool _mechFree;

		private double _mechS;

		private double _mechU;

		private readonly List<Impact> _impacts = new List<Impact>();

		private readonly Vec3 _invInertiaBody;

		private readonly Vec3 _inertiaBody;

		private Vec3 _linDamping;

		private Vec3 _angDamping;

		private Vec3[] _contactLinDamping = new Vec3[0];

		private Vec3[] _contactAngDamping = new Vec3[0];

		private Vec3[] _bearing = new Vec3[0];

		private Vec3[] _creep = new Vec3[0];

		public double BurstWalk;

		public double PostureShake;

		public const double ShakeGain = 10.0;

		public const double ShakeDecay = 0.08;

		public const double WristLimit = Math.PI / 3.0;

		public const double WristLimitStiffness = 300.0;

		public const double WristLimitDamping = 15.0;

		public const double ShakeLevelMax = 6.0;

		public const double ShakeHz = 9.0;

		private static readonly Vec3 ShakeAxes = new Vec3(0.6, 1.0, 0.8);

		private double _shakeLevel;

		private Vec3 _shakeNoise;

		private readonly List<Shot> _shots = new List<Shot>();

		public double ShotVariation;

		private readonly Random _rng;

		private const double StrengthSigma = 0.03;

		private const double LineOffsetSigmaY = 0.0015;

		private const double TiltSigma = 0.005;

		public const double KickVelocityCap = 1.0;

		public const double ShoulderedKickShare = 0.3;

		public const double KickLightMass = 0.8;

		public const double KickFullMass = 2.0;

		public const double KickLightShare = 0.3;

		public const double OneHandRollFromMass = 1.4;

		public const double OneHandRollFullMass = 2.0;

		public const double OneHandRockHz = 8.0;

		public const double OneHandRockDamping = 0.3;

		public const double RockGain = 2.8;

		private double _rock;

		private double _rockRate;

		private const double LineOffsetSigmaZ = 0.002;

		private const double RollLeverSigma = 0.002;

		private Vec3 _handAcc;

		private Vec3 _handAngAcc;

		public HoldSpec Hold { get; private set; }

		public double Time { get; private set; }

		public int MechanismHits { get; private set; }

		public double ShakeLevel => _shakeLevel;

		public double RockDeg => _rock * 180.0 / Math.PI;

		private Quat RockQuat => Quat.FromRotationVector(new Vec3(_rock, 0.0, 0.0));

		public Vec3 Offset => GripWorld();

		public Vec3 Rotation => (_rot * RockQuat).ToRotationVector();

		public Vec3 Slip => _slip;

		public Vec3 AngularVelocity => _omega;

		public Vec3 Velocity => _vel;

		public double PitchDeg => Rotation.Z * 180.0 / Math.PI;

		public double YawDeg => Rotation.Y * 180.0 / Math.PI;

		public double RollDeg => Rotation.X * 180.0 / Math.PI;

		public double KineticEnergy => 0.5 * Gun.Mass * Vec3.Dot(_vel, _vel) + 0.5 * Vec3.Dot(_omega, InertiaWorld(_omega));

		public Vec3 Momentum => _vel * FrameMass + (_mechFree ? (SlideVelocity(MechPoint(), RearAxis()) * Gun.Mechanism.Mass) : Vec3.Zero);

		public double MechanismPosition
		{
			get
			{
				if (!_mechFree)
				{
					return 0.0;
				}
				return _mechS;
			}
		}

		private double FrameMass
		{
			get
			{
				if (!_mechFree)
				{
					return Gun.Mass;
				}
				return Gun.Mass - Gun.Mechanism.Mass;
			}
		}

		public List<Impact> DrainImpacts()
		{
			List<Impact> result = new List<Impact>(_impacts);
			_impacts.Clear();
			return result;
		}

		public Vec3 ContactCreep(int i)
		{
			return _creep[i];
		}

		public static double OneHandRollShare(double mass)
		{
			return Math.Max(0.0, Math.Min(1.0, (mass - 1.4) / 0.6000000000000001));
		}

		public static double KickWeightShare(double mass)
		{
			return 0.3 + 0.7 * Math.Max(0.0, Math.Min(1.0, (mass - 0.8) / 1.2));
		}

		public RecoilSim(GunSpec gun, HoldSpec hold, int seed = 12345)
		{
			Gun = gun;
			_rng = new Random(seed);
			_com = gun.CenterOfMass;
			_inertiaBody = gun.Inertia;
			_invInertiaBody = new Vec3(1.0 / gun.Inertia.X, 1.0 / gun.Inertia.Y, 1.0 / gun.Inertia.Z);
			SetHold(hold);
		}

		public void SetHold(HoldSpec hold)
		{
			Hold = hold;
			Vec3 m = new Vec3(Gun.Mass, Gun.Mass, Gun.Mass);
			_linDamping = DampingCoefficients(hold.LinearStiffness, m, hold.LinearDamping);
			_angDamping = DampingCoefficients(hold.AngularStiffness, InertiaAbout(Vec3.Zero), hold.AngularDamping);
			int count = hold.Contacts.Count;
			_contactLinDamping = new Vec3[count];
			_contactAngDamping = new Vec3[count];
			Vec3[] creep = _creep;
			string[] array = ((Hold != null && _creep.Length != 0) ? _creepNames : new string[0]);
			_bearing = new Vec3[count];
			_creep = new Vec3[count];
			_creepNames = new string[count];
			for (int i = 0; i < count; i++)
			{
				_creepNames[i] = hold.Contacts[i].Name;
				int num = Array.IndexOf(array, _creepNames[i]);
				if (num >= 0 && num < creep.Length)
				{
					_creep[i] = creep[num];
				}
			}
			for (int j = 0; j < count; j++)
			{
				Contact contact = hold.Contacts[j];
				_contactLinDamping[j] = DampingCoefficients(contact.LinearStiffness, m, contact.LinearDamping);
				_contactAngDamping[j] = DampingCoefficients(contact.AngularStiffness, InertiaAbout(contact.Point), contact.AngularDamping);
			}
		}

		private static Vec3 Returning(Vec3 damping, Vec3 tilt, Vec3 omega, double returning)
		{
			if (returning == 1.0 || !(tilt.Z > 0.0) || !(omega.Z < 0.0))
			{
				return damping;
			}
			return new Vec3(damping.X, damping.Y, damping.Z * returning);
		}

		private Vec3 InertiaAbout(Vec3 point)
		{
			Vec3 vec = Gun.CenterOfMass - point;
			return new Vec3(Gun.Inertia.X + Gun.Mass * (vec.Y * vec.Y + vec.Z * vec.Z), Gun.Inertia.Y + Gun.Mass * (vec.X * vec.X + vec.Z * vec.Z), Gun.Inertia.Z + Gun.Mass * (vec.X * vec.X + vec.Y * vec.Y));
		}

		private static Vec3 DampingCoefficients(Vec3 k, Vec3 m, double zeta)
		{
			return new Vec3(2.0 * zeta * Math.Sqrt(k.X * m.X), 2.0 * zeta * Math.Sqrt(k.Y * m.Y), 2.0 * zeta * Math.Sqrt(k.Z * m.Z));
		}

		public void Fire(RecoilCurve curve)
		{
			if (Gun.Mechanism != null && !_mechFree)
			{
				_mechFree = true;
				_mechS = 0.0;
				_mechU = Vec3.Dot(PointVelocity(MechPoint()), RearAxis());
			}
			_impacts.Add(new Impact
			{
				Time = Time,
				Kind = ImpactKind.Shot,
				Impulse = curve.TotalImpulse,
				PeakPressure = curve.PeakPressure
			});
			double shotVariation = ShotVariation;
			Shot item = new Shot
			{
				Start = Time,
				Curve = curve,
				Strength = 1.0,
				Direction = new Vec3(-1.0, 0.0, 0.0)
			};
			if (shotVariation > 0.0)
			{
				item.Strength = 1.0 + Clamp(Gauss() * 0.03 * shotVariation, -0.08, 0.08);
				item.LineOffset = new Vec3(0.0, Gauss() * 0.0015 * shotVariation, 0.0);
				Vec3 vec = new Vec3(-1.0, Gauss() * 0.005 * shotVariation, Gauss() * 0.005 * shotVariation);
				item.Direction = vec / vec.Length;
				item.LineOffset.Z = Gauss() * 0.002 * shotVariation;
				item.RollLever = Gauss() * 0.002 * shotVariation;
				for (int i = 0; i < _bearing.Length; i++)
				{
					Vec3 bearingSpread = Hold.Contacts[i].BearingSpread;
					_bearing[i] = new Vec3(0.0, Gauss() * bearingSpread.Y * shotVariation, Gauss() * bearingSpread.Z * shotVariation);
				}
			}
			_shots.Add(item);
			Kick(curve.TotalImpulse * (_mechFree ? (1.0 - Gun.Mechanism.DriveFraction) : 1.0));
		}

		private double Gauss()
		{
			double d = 1.0 - _rng.NextDouble();
			double num = _rng.NextDouble();
			return Math.Sqrt(-2.0 * Math.Log(d)) * Math.Cos(Math.PI * 2.0 * num);
		}

		private static double Clamp(double x, double lo, double hi)
		{
			if (!(x < lo))
			{
				if (!(x > hi))
				{
					return x;
				}
				return hi;
			}
			return lo;
		}

		public Vec3 PointWorld(Vec3 gunPoint)
		{
			return GripWorld() + _rot.Rotate(RockQuat.Rotate(gunPoint));
		}

		public void SetHandMotion(Vec3 acceleration, Vec3 angularAcceleration)
		{
			_handAcc = acceleration;
			_handAngAcc = angularAcceleration;
		}

		public void Advance(double seconds)
		{
			double num = Time + seconds;
			while (Time < num - 1E-12)
			{
				double num2 = (ForceActive() ? 2E-06 : (_mechFree ? 2E-05 : 0.0002));
				if (Time + num2 > num)
				{
					num2 = num - Time;
				}
				Step(num2);
			}
		}

		private bool ForceActive()
		{
			for (int i = 0; i < _shots.Count; i++)
			{
				if (Time - _shots[i].Start < _shots[i].Curve.Duration)
				{
					return true;
				}
			}
			return false;
		}

		private void Step(double dt)
		{
			Vec3 zero = Vec3.Zero;
			Vec3 zero2 = Vec3.Zero;
			Mechanism mechanism = Gun.Mechanism;
			double num = (_mechFree ? (1.0 - mechanism.DriveFraction) : 1.0);
			double num2 = 0.0;
			for (int num3 = _shots.Count - 1; num3 >= 0; num3--)
			{
				Shot shot = _shots[num3];
				double num4 = Time - shot.Start;
				if (num4 > shot.Curve.Duration)
				{
					_shots.RemoveAt(num3);
				}
				else
				{
					double num5 = shot.Curve.Force(num4) * shot.Strength;
					if (num5 != 0.0)
					{
						if (_mechFree)
						{
							num2 += num5 * mechanism.DriveFraction;
						}
						num5 *= num;
						Vec3 vec = _rot.Rotate(shot.Direction * num5);
						Vec3 a = _rot.Rotate(Gun.BoreOrigin + shot.LineOffset - Gun.CenterOfMass);
						zero += vec;
						zero2 += Vec3.Cross(a, vec) + _rot.Rotate(new Vec3(num5 * shot.RollLever, 0.0, 0.0));
					}
				}
			}
			if (_handAcc.X != 0.0 || _handAcc.Y != 0.0 || _handAcc.Z != 0.0 || _handAngAcc.X != 0.0 || _handAngAcc.Y != 0.0 || _handAngAcc.Z != 0.0)
			{
				Vec3 vec2 = _com - GripWorld();
				Vec3 b = -(_handAcc + Vec3.Cross(_handAngAcc, vec2)) * Gun.Mass;
				zero2 += Vec3.Cross(vec2, b) - InertiaWorld(_handAngAcc);
			}
			Vec3 vec3 = GripWorld();
			Vec3 vec4 = vec3 - _com;
			Vec3 b2 = _vel + Vec3.Cross(_omega, vec4);
			Vec3 vec5 = -Vec3.Scale(Hold.LinearStiffness, vec3) - Vec3.Scale(_linDamping, b2);
			zero += vec5;
			Vec3 b3 = RearAxis();
			double num6 = Math.Abs(Vec3.Dot(vec5, b3));
			zero2 += Vec3.Cross(vec4, vec5);
			double num7 = 0.0;
			for (int i = 0; i < Hold.Contacts.Count; i++)
			{
				if (Hold.Contacts[i].PushOnly == PushOnly.Forward)
				{
					num7 = Math.Max(num7, 0.0 - _creep[i].X);
				}
			}
			Vec3 vec6 = new Vec3(0.0, 0.0, (0.0 - Hold.TorsoTwist) * num7);
			for (int j = 0; j < Hold.Contacts.Count; j++)
			{
				Contact contact = Hold.Contacts[j];
				Vec3 vec7 = _rot.Rotate(contact.Point - Gun.CenterOfMass);
				Vec3 vec8 = _com + vec7;
				Vec3 velocity = _vel + Vec3.Cross(_omega, vec7);
				Vec3 vec9 = contact.Point + _creep[j] + ((contact.PushOnly == PushOnly.None && contact.Point.X > 0.0) ? vec6 : Vec3.Zero);
				Vec3 vec10 = Contact.Force(vec8 - vec9, velocity, contact.LinearStiffness, _contactLinDamping[j], contact.PushOnly, contact.Preload);
				zero += vec10;
				num6 += Math.Abs(Vec3.Dot(vec10, b3));
				if (BurstWalk > 0.0)
				{
					Creep(j, contact, vec10, dt);
				}
				zero2 += Vec3.Cross(_rot.Rotate(contact.Point + _bearing[j] - Gun.CenterOfMass), vec10);
				if (contact.AngularStiffness.X != 0.0 || contact.AngularStiffness.Y != 0.0 || contact.AngularStiffness.Z != 0.0)
				{
					Vec3 vec11 = _rot.ToRotationVector();
					zero2 += -Vec3.Scale(contact.AngularStiffness, vec11) - Vec3.Scale(Returning(_contactAngDamping[j], vec11, _omega, contact.ReturnDamping), _omega);
				}
			}
			Vec3 vec12 = (_rot * Quat.FromRotationVector(_slip).Conjugate).ToRotationVector();
			Vec3 vec13 = -Vec3.Scale(Hold.AngularStiffness, vec12);
			zero2 += vec13 - Vec3.Scale(Returning(_angDamping, vec12, _omega, Hold.ReturnDamping), _omega);
			double length = vec12.Length;
			if (length > Math.PI / 3.0)
			{
				Vec3 vec14 = vec12 / length;
				double num8 = Vec3.Dot(_omega, vec14);
				zero2 += vec14 * (-300.0 * (length - Math.PI / 3.0) - ((num8 > 0.0) ? (15.0 * num8) : 0.0));
			}
			UpdateSlip(vec12, vec13, dt);
			if (PostureShake > 0.0)
			{
				zero2 += Shake((ForceActive() || _mechFree) ? num6 : 0.0, dt);
			}
			if (_mechFree)
			{
				double num9 = mechanism.SpringPreload + mechanism.SpringRate * _mechS;
				Vec3 vec15 = RearAxis();
				Vec3 a2 = _rot.Rotate(MechPoint() - Gun.CenterOfMass);
				zero += vec15 * num9;
				zero2 += Vec3.Cross(a2, vec15 * num9);
				_mechU += (num2 - num9) / mechanism.Mass * dt;
			}
			_vel += zero * (dt / FrameMass);
			_com += _vel * dt;
			Vec3 vec16 = Vec3.Cross(_omega, InertiaWorld(_omega));
			_omega += InvInertiaWorld(zero2 - vec16) * dt;
			_rot = _rot.Integrate(_omega, dt);
			if (_mechFree)
			{
				StepMechanism(dt);
			}
			if (_rock != 0.0 || _rockRate != 0.0)
			{
				double num10 = Math.PI * 16.0;
				_rockRate += ((0.0 - num10) * num10 * _rock - 0.6 * num10 * _rockRate) * dt;
				_rock += _rockRate * dt;
				if (Math.Abs(_rock) < 1E-06 && Math.Abs(_rockRate) < 1E-05)
				{
					_rock = (_rockRate = 0.0);
				}
			}
			Time += dt;
		}

		private void StepMechanism(double dt)
		{
			Mechanism mechanism = Gun.Mechanism;
			Vec3 vec = RearAxis();
			Vec3 vec2 = MechPoint();
			double num = _mechU - Vec3.Dot(PointVelocity(vec2), vec);
			_mechS += num * dt;
			if (_mechS >= mechanism.Travel && num > 0.0)
			{
				_mechS = mechanism.Travel;
				double num2 = (1.0 + mechanism.RearRestitution) * EffectiveMass(vec2, vec) * num;
				Hit(vec2, vec, num2);
				_impacts.Add(new Impact
				{
					Time = Time,
					Kind = ImpactKind.RearStop,
					Impulse = num2
				});
			}
			else if (_mechS <= 0.0 && num < 0.0 && ForceActive())
			{
				_mechS = 0.0;
				Exchange(vec2, vec, EffectiveMass(vec2, vec) * num);
			}
			else if (_mechS <= 0.0 && num < 0.0)
			{
				_mechS = 0.0;
				double num3 = (1.0 + mechanism.FrontRestitution) * EffectiveMass(vec2, vec) * num;
				Hit(vec2, vec, num3);
				_impacts.Add(new Impact
				{
					Time = Time,
					Kind = ImpactKind.Battery,
					Impulse = 0.0 - num3
				});
				Vec3 vec3 = SlideVelocity(vec2, vec);
				_vel = (_vel * FrameMass + vec3 * mechanism.Mass) / Gun.Mass;
				_mechFree = false;
			}
		}

		private void Hit(Vec3 point, Vec3 axis, double j)
		{
			Exchange(point, axis, j);
			MechanismHits++;
			Kick(Math.Abs(j));
		}

		private void Kick(double impulse)
		{
			if (ShotVariation <= 0.0)
			{
				return;
			}
			double num = Math.Min(1.0, impulse / Gun.Mass) * ShotVariation * KickWeightShare(Gun.Mass);
			foreach (Contact contact in Hold.Contacts)
			{
				if (contact.PushOnly == PushOnly.Forward)
				{
					num *= 0.3;
					break;
				}
			}
			Vec3 impactKick = Hold.ImpactKick;
			double num2 = impactKick.X * num * (Gauss() + Gun.KickRollBias);
			double num3 = ((Hold.Contacts.Count == 0) ? OneHandRollShare(Gun.Mass) : 0.0);
			_rockRate += num2 * num3 * 2.8;
			_omega += _rot.Rotate(new Vec3(num2 * (1.0 - num3), Gauss() * impactKick.Y * num, Gauss() * impactKick.Z * num));
		}

		private void Exchange(Vec3 point, Vec3 axis, double j)
		{
			_mechU -= j / Gun.Mechanism.Mass;
			Vec3 vec = axis * j;
			_vel += vec / FrameMass;
			_omega += InvInertiaWorld(Vec3.Cross(_rot.Rotate(point - Gun.CenterOfMass), vec));
		}

		private double EffectiveMass(Vec3 point, Vec3 axis)
		{
			Vec3 vec = _rot.Rotate(point - Gun.CenterOfMass);
			Vec3 v = Vec3.Cross(vec, axis);
			double num = 1.0 / FrameMass + Vec3.Dot(Vec3.Cross(InvInertiaWorld(v), vec), axis);
			return 1.0 / (1.0 / Gun.Mechanism.Mass + num);
		}

		private Vec3 SlideVelocity(Vec3 point, Vec3 axis)
		{
			Vec3 vec = PointVelocity(point);
			return vec - axis * Vec3.Dot(vec, axis) + axis * _mechU;
		}

		private Vec3 RearAxis()
		{
			return _rot.Rotate(new Vec3(-1.0, 0.0, 0.0));
		}

		private Vec3 MechPoint()
		{
			return new Vec3(Gun.BoreOrigin.X, Gun.Mechanism.LineHeight, 0.0);
		}

		private Vec3 PointVelocity(Vec3 gunPoint)
		{
			return _vel + Vec3.Cross(_omega, _rot.Rotate(gunPoint - Gun.CenterOfMass));
		}

		private Vec3 Shake(double absorbedForce, double dt)
		{
			_shakeLevel = Math.Min(6.0, _shakeLevel * Math.Exp((0.0 - dt) / 0.08) + absorbedForce * dt / Gun.Mass);
			double num = 1.0 / (18.0 * Math.PI);
			double num2 = Math.Exp((0.0 - dt) / num);
			double num3 = Math.Sqrt(1.0 - num2 * num2);
			_shakeNoise = new Vec3(_shakeNoise.X * num2 + num3 * Gauss(), _shakeNoise.Y * num2 + num3 * Gauss(), _shakeNoise.Z * num2 + num3 * Gauss());
			Vec3 b = Vec3.Scale(ShakeAxes, _shakeNoise) * (10.0 * PostureShake * _shakeLevel);
			return _rot.Rotate(Vec3.Scale(_inertiaBody, b));
		}

		private void Creep(int i, Contact c, Vec3 fc, double dt)
		{
			double rate = c.CreepRate * BurstWalk;
			double decay = ((c.CreepBleedTime > 0.0) ? Math.Exp((0.0 - dt) / c.CreepBleedTime) : 1.0);
			_creep[i] = new Vec3(CreepAxis(_creep[i].X, 0.0 - fc.X, c.YieldForce.X, c.LinearStiffness.X, rate, c.CreepMax, decay, dt), CreepAxis(_creep[i].Y, 0.0 - fc.Y, c.YieldForce.Y, c.LinearStiffness.Y, rate, c.CreepMax, decay, dt), CreepAxis(_creep[i].Z, 0.0 - fc.Z, c.YieldForce.Z, c.LinearStiffness.Z, rate, c.CreepMax, decay, dt));
		}

		private static double CreepAxis(double creep, double load, double yield, double k, double rate, double max, double decay, double dt)
		{
			if (yield > 0.0 && k > 0.0)
			{
				double num = Math.Abs(load) - yield;
				if (num > 0.0)
				{
					creep += (double)Math.Sign(load) * rate * (num / k) * dt;
				}
			}
			creep *= decay;
			return Math.Max(0.0 - max, Math.Min(max, creep));
		}

		private void UpdateSlip(Vec3 err, Vec3 springTorque, double dt)
		{
			_slip = new Vec3(SlipAxis(_slip.X, err.X, springTorque.X, Hold.SlipTorque.X, Hold.AngularStiffness.X, dt), SlipAxis(_slip.Y, err.Y, springTorque.Y, Hold.SlipTorque.Y, Hold.AngularStiffness.Y, dt), SlipAxis(_slip.Z, err.Z, springTorque.Z, Hold.SlipTorque.Z, Hold.AngularStiffness.Z, dt));
		}

		private double SlipAxis(double slip, double err, double torque, double limit, double k, double dt)
		{
			if (limit > 0.0 && k > 0.0)
			{
				double num = Math.Abs(torque) - limit;
				if (num > 0.0)
				{
					slip += (double)Math.Sign(err) * Hold.SlipRate * (num / k) * dt;
				}
			}
			if (Hold.SlipBleedTime > 0.0)
			{
				slip *= Math.Exp((0.0 - dt) / Hold.SlipBleedTime);
			}
			return Math.Max(0.0 - Hold.SlipMax, Math.Min(Hold.SlipMax, slip));
		}

		private Vec3 GripWorld()
		{
			return _com - _rot.Rotate(Gun.CenterOfMass);
		}

		private Vec3 InertiaWorld(Vec3 v)
		{
			Vec3 b = _rot.Conjugate.Rotate(v);
			return _rot.Rotate(Vec3.Scale(_inertiaBody, b));
		}

		private Vec3 InvInertiaWorld(Vec3 v)
		{
			Vec3 b = _rot.Conjugate.Rotate(v);
			return _rot.Rotate(Vec3.Scale(_invInertiaBody, b));
		}
	}
	public static class References
	{
		private const double Grain = 6.479891E-05;

		private const double Psi = 6894.757;

		public static readonly Loading Nine = new Loading
		{
			Name = "9x19 124gr FMJ",
			BulletMass = 0.00803506484,
			MuzzleVelocity = 360.0,
			ChargeMass = 0.000356394005,
			BoreDiameter = 0.00902,
			MaxPressure = 241316495.0,
			CaseVolume = 8.6E-07
		};

		public static readonly Loading FortyFive = new Loading
		{
			Name = ".45 ACP 230gr FMJ",
			BulletMass = 0.014903749299999998,
			MuzzleVelocity = 255.0,
			ChargeMass = 0.00032399454999999995,
			BoreDiameter = 0.01148,
			MaxPressure = 144789897.0,
			CaseVolume = 1.62E-06
		};

		public static readonly Loading FortyFourMag = new Loading
		{
			Name = ".44 Magnum 240gr",
			BulletMass = 0.015551738399999999,
			MuzzleVelocity = 440.0,
			ChargeMass = 0.0014903749299999998,
			BoreDiameter = 0.0109,
			MaxPressure = 248211252.0,
			CaseVolume = 2.53E-06
		};

		public static readonly Loading FiveFiveSix = new Loading
		{
			Name = "5.56x45 M193 55gr",
			BulletMass = 0.0035639400499999996,
			MuzzleVelocity = 990.0,
			ChargeMass = 0.0016847716599999998,
			BoreDiameter = 0.0057,
			MaxPressure = 379211635.0,
			CaseVolume = 1.85E-06
		};

		public static readonly Loading SevenSixTwoSoviet = new Loading
		{
			Name = "7.62x39 123gr FMJ",
			BulletMass = 0.00797026593,
			MuzzleVelocity = 715.0,
			ChargeMass = 0.00161997275,
			BoreDiameter = 0.00792,
			MaxPressure = 355000000.0,
			CaseVolume = 2.31E-06
		};

		public static readonly Loading SevenSixTwoNato = new Loading
		{
			Name = "7.62x51 M80 147gr",
			BulletMass = 0.00952543977,
			MuzzleVelocity = 840.0,
			ChargeMass = 0.0029807498599999996,
			BoreDiameter = 0.00782,
			MaxPressure = 415000000.0,
			CaseVolume = 3.63E-06
		};

		public static readonly Loading TwelveBuck = new Loading
		{
			Name = "12ga 2-3/4in 00 buck",
			BulletMass = 0.034,
			MuzzleVelocity = 400.0,
			ChargeMass = 0.0017495705699999999,
			BoreDiameter = 0.0185,
			MaxPressure = 79289705.5,
			CaseVolume = 2E-06
		};

		public static readonly GunSpec Glock17 = new GunSpec
		{
			Name = "Glock 17",
			Mass = 0.905,
			Length = 0.186,
			BarrelLength = 0.114,
			BulletTravel = 0.098,
			CenterOfMass = new Vec3(0.03, 0.025, 0.0),
			BoreOrigin = new Vec3(0.0, 0.065, 0.0),
			Inertia = GunSpec.BoxInertia(0.905, 0.186, 0.139, 0.032)
		};

		public static readonly GunSpec M1911 = new GunSpec
		{
			Name = "M1911",
			Mass = 1.13,
			Length = 0.216,
			BarrelLength = 0.127,
			BulletTravel = 0.109,
			CenterOfMass = new Vec3(0.04, 0.02, 0.0),
			BoreOrigin = new Vec3(0.0, 0.06, 0.0),
			Inertia = GunSpec.BoxInertia(1.13, 0.216, 0.14, 0.033)
		};

		public static readonly GunSpec Sw629 = new GunSpec
		{
			Name = "S&W 629 6.5in",
			Mass = 1.3,
			Length = 0.31,
			BarrelLength = 0.165,
			BulletTravel = 0.2,
			CenterOfMass = new Vec3(0.06, 0.035, 0.0),
			BoreOrigin = new Vec3(0.0, 0.075, 0.0),
			Inertia = GunSpec.BoxInertia(1.3, 0.31, 0.15, 0.04)
		};

		public static readonly GunSpec M4A1 = new GunSpec
		{
			Name = "M4A1",
			Mass = 3.4,
			Length = 0.84,
			BarrelLength = 0.368,
			BulletTravel = 0.345,
			CenterOfMass = new Vec3(0.12, 0.03, 0.0),
			BoreOrigin = new Vec3(0.0, 0.075, 0.0),
			Inertia = GunSpec.BoxInertia(3.4, 0.84, 0.25, 0.07)
		};

		public static readonly GunSpec Akm = new GunSpec
		{
			Name = "AKM",
			Mass = 3.8,
			Length = 0.88,
			BarrelLength = 0.415,
			BulletTravel = 0.39,
			CenterOfMass = new Vec3(0.15, 0.02, 0.0),
			BoreOrigin = new Vec3(0.0, 0.07, 0.0),
			Inertia = GunSpec.BoxInertia(3.8, 0.88, 0.25, 0.07)
		};

		public static readonly GunSpec M40A1 = new GunSpec
		{
			Name = "M40A1 + scope",
			Mass = 6.6,
			Length = 1.12,
			BarrelLength = 0.61,
			BulletTravel = 0.57,
			CenterOfMass = new Vec3(0.2, 0.0, 0.0),
			BoreOrigin = new Vec3(0.0, 0.05, 0.0),
			Inertia = GunSpec.BoxInertia(6.6, 1.12, 0.2, 0.07)
		};

		public static readonly GunSpec Remington870 = new GunSpec
		{
			Name = "Remington 870 18in",
			Mass = 3.3,
			Length = 0.98,
			BarrelLength = 0.457,
			BulletTravel = 0.46,
			CenterOfMass = new Vec3(0.2, 0.0, 0.0),
			BoreOrigin = new Vec3(0.0, 0.04, 0.0),
			Inertia = GunSpec.BoxInertia(3.3, 0.98, 0.18, 0.07)
		};

		public static readonly HoldSpec OneHandFirm = new HoldSpec
		{
			Name = "one hand, firm",
			LinearStiffness = new Vec3(2500.0, 2000.0, 2000.0),
			LinearDamping = 0.6,
			AngularStiffness = new Vec3(9.0, 14.0, 10.0),
			AngularDamping = 0.7,
			ReturnDamping = 0.7,
			ImpactKick = new Vec3(2.6, 0.5, 0.0),
			SlipTorque = new Vec3(2.5, 3.5, 4.0)
		};

		public static readonly Contact SupportGrab = new Contact
		{
			Name = "support hand",
			LinearStiffness = new Vec3(1200.0, 800.0, 800.0),
			LinearDamping = 0.7,
			AngularStiffness = new Vec3(4.0, 6.0, 5.0),
			AngularDamping = 0.7,
			ReturnDamping = 0.7,
			BearingSpread = new Vec3(0.0, 0.004, 0.005),
			YieldForce = new Vec3(40.0, 6.0, 6.0)
		};

		public static readonly Contact SupportCup = new Contact
		{
			Name = "support hand (cup)",
			LinearStiffness = new Vec3(1500.0, 2000.0, 2000.0),
			LinearDamping = 0.7,
			AngularStiffness = new Vec3(8.0, 12.0, 9.0),
			AngularDamping = 0.7,
			ReturnDamping = 0.7,
			BearingSpread = new Vec3(0.0, 0.002, 0.002),
			YieldForce = new Vec3(60.0, 15.0, 15.0)
		};

		public static readonly Contact Shoulder = new Contact
		{
			Name = "shoulder",
			LinearStiffness = new Vec3(4000.0, 900.0, 900.0),
			LinearDamping = 0.9,
			PushOnly = PushOnly.Forward,
			Preload = 40.0,
			BearingSpread = new Vec3(0.0, 0.008, 0.01),
			YieldForce = new Vec3(100.0, 9.0, 9.0)
		};

		public static readonly Contact Bipod = new Contact
		{
			Name = "bipod",
			LinearStiffness = new Vec3(5000.0, 30000.0, 8000.0),
			LinearDamping = 0.4,
			PushOnly = PushOnly.Up,
			Preload = 30.0,
			BearingSpread = new Vec3(0.0, 0.0, 0.006)
		};

		public static readonly Vec3 M4Stock = new Vec3(-0.3, 0.06, 0.0);

		public static readonly Vec3 M4Support = new Vec3(0.3, 0.04, 0.0);

		public static readonly Vec3 AkmStock = new Vec3(-0.33, 0.0, 0.0);

		public static readonly Vec3 AkmSupport = new Vec3(0.28, 0.03, 0.0);

		public static readonly Vec3 M40Stock = new Vec3(-0.33, 0.0, 0.0);

		public static readonly Vec3 M40Support = new Vec3(0.3, 0.0, 0.0);

		public static readonly Vec3 M40Bipod = new Vec3(0.45, 0.0, 0.0);

		public static readonly Vec3 Shotgun870Stock = new Vec3(-0.35, -0.02, 0.0);

		public static readonly Vec3 Shotgun870Support = new Vec3(0.35, 0.0, 0.0);

		public static readonly HoldSpec Free = new HoldSpec
		{
			Name = "free",
			LinearStiffness = Vec3.Zero,
			AngularStiffness = Vec3.Zero,
			SlipTorque = Vec3.Zero,
			SlipBleedTime = 0.0
		};
	}
	public class GunSpec
	{
		public string Name;

		public double Mass;

		public Vec3 CenterOfMass;

		public Vec3 Inertia;

		public Vec3 BoreOrigin;

		public double Length;

		public double BarrelLength;

		public double BulletTravel;

		public Mechanism Mechanism;

		public double KickRollBias;

		public static Vec3 BoxInertia(double mass, double length, double height, double width)
		{
			double num = length * length;
			double num2 = height * height;
			double num3 = width * width;
			return new Vec3(mass * (num2 + num3) / 12.0, mass * (num + num3) / 12.0, mass * (num + num2) / 12.0);
		}
	}
	public class Mechanism
	{
		public string Kind;

		public double Mass;

		public double Travel;

		public double DriveFraction;

		public double LineHeight;

		public double SpringPreload;

		public double SpringRate;

		public double RearRestitution = 0.3;

		public double FrontRestitution = 0.05;

		public const double ShortRecoilDrive = 0.85;

		public const double BlowbackDrive = 0.9;

		public const double GasDrive = 0.3;

		public static Mechanism Sized(string kind, double mass, double travel, double driveFraction, double lineHeight, double standardImpulse, double gunMass)
		{
			double num = gunMass - mass;
			double num2 = standardImpulse * (driveFraction / mass - (1.0 - driveFraction) / num);
			double num3 = mass * num / gunMass;
			double num4 = 0.5 * num3 * num2 * num2;
			double num5 = 0.6 * num4 / (1.5 * travel);
			return new Mechanism
			{
				Kind = kind,
				Mass = mass,
				Travel = travel,
				DriveFraction = driveFraction,
				LineHeight = lineHeight,
				SpringPreload = num5,
				SpringRate = num5 / travel
			};
		}
	}
	public class HoldSpec
	{
		public string Name;

		public Vec3 LinearStiffness;

		public double LinearDamping;

		public Vec3 AngularStiffness;

		public double AngularDamping;

		public double ReturnDamping = 1.0;

		public Vec3 ImpactKick;

		public Vec3 SlipTorque;

		public double SlipRate = 20.0;

		public double SlipMax = 0.1;

		public double SlipBleedTime = 8.0;

		public List<Contact> Contacts = new List<Contact>();

		public double TorsoTwist;

		public HoldSpec With(params Contact[] contacts)
		{
			HoldSpec obj = (HoldSpec)MemberwiseClone();
			obj.Contacts = new List<Contact>(contacts);
			return obj;
		}
	}
	public enum PushOnly
	{
		None,
		Forward,
		Up
	}
	public class Contact
	{
		public string Name;

		public Vec3 Point;

		public Vec3 LinearStiffness;

		public double LinearDamping;

		public Vec3 AngularStiffness;

		public double AngularDamping;

		public double ReturnDamping = 1.0;

		public PushOnly PushOnly;

		public double Preload;

		public Vec3 BearingSpread;

		public Vec3 YieldForce;

		public double CreepRate = 15.0;

		public double CreepMax = 0.03;

		public double CreepBleedTime = 1.2;

		public Contact At(Vec3 point)
		{
			Contact obj = (Contact)MemberwiseClone();
			obj.Point = point;
			return obj;
		}

		public static Vec3 Force(Vec3 displacement, Vec3 velocity, Vec3 k, Vec3 c, PushOnly pushOnly, double preload = 0.0)
		{
			Vec3 result = -Vec3.Scale(k, displacement) - Vec3.Scale(c, velocity);
			if (pushOnly == PushOnly.Forward)
			{
				result.X = Math.Max(result.X, 0.0 - preload);
			}
			if (pushOnly == PushOnly.Up)
			{
				result.Y = Math.Max(result.Y, 0.0 - preload);
			}
			return result;
		}
	}
	public struct Vec3
	{
		public double X;

		public double Y;

		public double Z;

		public static readonly Vec3 Zero = new Vec3(0.0, 0.0, 0.0);

		public static readonly Vec3 UnitX = new Vec3(1.0, 0.0, 0.0);

		public static readonly Vec3 UnitY = new Vec3(0.0, 1.0, 0.0);

		public static readonly Vec3 UnitZ = new Vec3(0.0, 0.0, 1.0);

		public double Length => Math.Sqrt(X * X + Y * Y + Z * Z);

		public Vec3(double x, double y, double z)
		{
			X = x;
			Y = y;
			Z = z;
		}

		public static Vec3 operator +(Vec3 a, Vec3 b)
		{
			return new Vec3(a.X + b.X, a.Y + b.Y, a.Z + b.Z);
		}

		public static Vec3 operator -(Vec3 a, Vec3 b)
		{
			return new Vec3(a.X - b.X, a.Y - b.Y, a.Z - b.Z);
		}

		public static Vec3 operator -(Vec3 a)
		{
			return new Vec3(0.0 - a.X, 0.0 - a.Y, 0.0 - a.Z);
		}

		public static Vec3 operator *(Vec3 a, double s)
		{
			return new Vec3(a.X * s, a.Y * s, a.Z * s);
		}

		public static Vec3 operator *(double s, Vec3 a)
		{
			return a * s;
		}

		public static Vec3 operator /(Vec3 a, double s)
		{
			return new Vec3(a.X / s, a.Y / s, a.Z / s);
		}

		public static double Dot(Vec3 a, Vec3 b)
		{
			return a.X * b.X + a.Y * b.Y + a.Z * b.Z;
		}

		public static Vec3 Cross(Vec3 a, Vec3 b)
		{
			return new Vec3(a.Y * b.Z - a.Z * b.Y, a.Z * b.X - a.X * b.Z, a.X * b.Y - a.Y * b.X);
		}

		public static Vec3 Scale(Vec3 a, Vec3 b)
		{
			return new Vec3(a.X * b.X, a.Y * b.Y, a.Z * b.Z);
		}

		public override string ToString()
		{
			return $"({X:0.####}, {Y:0.####}, {Z:0.####})";
		}
	}
	public struct Quat
	{
		public double W;

		public double X;

		public double Y;

		public double Z;

		public static readonly Quat Identity = new Quat(1.0, 0.0, 0.0, 0.0);

		public Quat Conjugate => new Quat(W, 0.0 - X, 0.0 - Y, 0.0 - Z);

		public Quat Normalized
		{
			get
			{
				double num = Math.Sqrt(W * W + X * X + Y * Y + Z * Z);
				return new Quat(W / num, X / num, Y / num, Z / num);
			}
		}

		public Quat(double w, double x, double y, double z)
		{
			W = w;
			X = x;
			Y = y;
			Z = z;
		}

		public static Quat operator *(Quat a, Quat b)
		{
			return new Quat(a.W * b.W - a.X * b.X - a.Y * b.Y - a.Z * b.Z, a.W * b.X + a.X * b.W + a.Y * b.Z - a.Z * b.Y, a.W * b.Y - a.X * b.Z + a.Y * b.W + a.Z * b.X, a.W * b.Z + a.X * b.Y - a.Y * b.X + a.Z * b.W);
		}

		public Vec3 Rotate(Vec3 v)
		{
			Vec3 a = new Vec3(X, Y, Z);
			Vec3 vec = 2.0 * Vec3.Cross(a, v);
			return v + W * vec + Vec3.Cross(a, vec);
		}

		public static Quat FromRotationVector(Vec3 r)
		{
			double length = r.Length;
			if (length < 1E-12)
			{
				return new Quat(1.0, r.X * 0.5, r.Y * 0.5, r.Z * 0.5).Normalized;
			}
			double num = Math.Sin(length * 0.5) / length;
			return new Quat(Math.Cos(length * 0.5), r.X * num, r.Y * num, r.Z * num);
		}

		public Vec3 ToRotationVector()
		{
			Quat quat = ((W < 0.0) ? new Quat(0.0 - W, 0.0 - X, 0.0 - Y, 0.0 - Z) : this);
			double num = Math.Sqrt(quat.X * quat.X + quat.Y * quat.Y + quat.Z * quat.Z);
			if (num < 1E-12)
			{
				return new Vec3(2.0 * quat.X, 2.0 * quat.Y, 2.0 * quat.Z);
			}
			double num2 = 2.0 * Math.Atan2(num, quat.W);
			return new Vec3(quat.X, quat.Y, quat.Z) * (num2 / num);
		}

		public Quat Integrate(Vec3 omegaWorld, double dt)
		{
			return (FromRotationVector(omegaWorld * dt) * this).Normalized;
		}
	}
}
namespace Kickback.Core.Reload
{
	public class RailFunnel
	{
		public double Mouth = 0.05;

		public double Range = 0.12;

		public double MaxAngle = 0.9599310885968813;

		public double LateralAtMouth = 0.03;

		public double LateralSpread = 0.5;

		public const double ReleaseRangeFactor = 1.25;

		public const double ReleaseLateralFactor = 1.5;

		public const double ReleaseExtraAngle = Math.PI / 12.0;

		public const double ShellRangeShare = 0.7;

		public const double ShellLateralAtMouth = 0.04;

		public const double ShellLateralSpread = 1.2;

		public bool Spherical;

		public const double InsertedLateralRelease = 0.1;

		public const double InsertedExtraAngle = Math.PI / 6.0;

		public const double EaseTime = 0.06;

		public const double MaxDepthSpeed = 1.2;

		public const double MinSlideSpeed = 0.6;

		public const double MinSlideTime = 0.04;

		public const double MaxSlideTime = 0.15;

		public static RailFunnel Preset(int strength)
		{
			return strength switch
			{
				0 => new RailFunnel
				{
					Range = 0.07,
					MaxAngle = Math.PI * 2.0 / 9.0
				}, 
				2 => new RailFunnel
				{
					Range = 0.18,
					MaxAngle = Math.PI * 7.0 / 18.0
				}, 
				_ => new RailFunnel(), 
			};
		}

		public static RailFunnel ShellPreset(int strength, double shellLength)
		{
			RailFunnel railFunnel = Preset(strength);
			railFunnel.Spherical = true;
			railFunnel.Mouth = ((shellLength < 0.02) ? 0.02 : ((shellLength > 0.12) ? 0.12 : shellLength));
			railFunnel.Range *= 0.7;
			railFunnel.LateralAtMouth = 0.04;
			railFunnel.LateralSpread = 1.2;
			return railFunnel;
		}

		public double Depth(Vec3 pos)
		{
			return 0.0 - pos.Y;
		}

		public static double Lateral(Vec3 pos)
		{
			return Math.Sqrt(pos.X * pos.X + pos.Z * pos.Z);
		}

		public static double Angle(Quat rot)
		{
			return rot.ToRotationVector().Length;
		}

		public double LateralLimit(double depth)
		{
			return LateralAtMouth + LateralSpread * Math.Max(0.0, depth - Mouth);
		}

		public double Weight(double depth)
		{
			return Smooth((Mouth + Range - depth) / Range);
		}

		private static double Smooth(double t)
		{
			t = ((t < 0.0) ? 0.0 : ((t > 1.0) ? 1.0 : t));
			return t * t * (3.0 - 2.0 * t);
		}

		public double OffRail(Vec3 pos)
		{
			double num = Depth(pos);
			if (num <= Mouth)
			{
				return Lateral(pos);
			}
			double num2 = num - Mouth;
			return Math.Sqrt(num2 * num2 + pos.X * pos.X + pos.Z * pos.Z);
		}

		public double Weight(Vec3 pos)
		{
			if (!Spherical)
			{
				return Weight(Depth(pos));
			}
			return Smooth((Range - OffRail(pos)) / Range);
		}

		public bool CanEnter(Vec3 pos, Quat rot)
		{
			if (Spherical)
			{
				if (Lateral(pos) <= LateralAtMouth)
				{
					return Angle(rot) <= MaxAngle;
				}
				return false;
			}
			return true;
		}

		public bool Captures(Vec3 pos, Quat rot)
		{
			double num = Depth(pos);
			if (Spherical)
			{
				if (num > -0.01 && OffRail(pos) <= Range && Angle(rot) <= MaxAngle)
				{
					if (!(num > Mouth - 0.005))
					{
						return Lateral(pos) > LateralAtMouth;
					}
					return true;
				}
				return false;
			}
			if (num > Mouth - 0.005 && num <= Mouth + Range && Lateral(pos) <= LateralLimit(num))
			{
				return Angle(rot) <= MaxAngle;
			}
			return false;
		}

		public bool Releases(Vec3 pos, Quat rot)
		{
			double num = Depth(pos);
			if (Spherical && (!(num < Mouth) || !(Lateral(pos) <= LateralAtMouth)))
			{
				if (!(OffRail(pos) > Range * 1.25))
				{
					return Angle(rot) > MaxAngle + Math.PI / 12.0;
				}
				return true;
			}
			if (num < Mouth)
			{
				if (!(Lateral(pos) > 0.1))
				{
					return Angle(rot) > MaxAngle + Math.PI / 6.0;
				}
				return true;
			}
			if (!(num > Mouth + Range * 1.25) && !(Lateral(pos) > LateralLimit(Math.Max(num, Mouth)) * 1.5))
			{
				return Angle(rot) > MaxAngle + Math.PI / 12.0;
			}
			return true;
		}

		public bool Commits(Vec3 pos)
		{
			return Depth(pos) <= Mouth;
		}

		public void Guide(Vec3 pos, Quat rot, out Vec3 guidedPos, out Quat guidedRot)
		{
			double num = Weight(pos);
			guidedPos = new Vec3(pos.X * (1.0 - num), pos.Y, pos.Z * (1.0 - num));
			guidedRot = Quat.FromRotationVector(rot.ToRotationVector() * (1.0 - num));
		}

		public static void Blend(Vec3 pos, Quat rot, double weight, double depth, out Vec3 guidedPos, out Quat guidedRot)
		{
			double num = ((weight < 0.0) ? 0.0 : ((weight > 1.0) ? 1.0 : weight));
			guidedPos = new Vec3(pos.X * (1.0 - num), 0.0 - depth, pos.Z * (1.0 - num));
			guidedRot = Quat.FromRotationVector(rot.ToRotationVector() * (1.0 - num));
		}

		public static double EaseWeight(double current, double target, double dt)
		{
			return current + (target - current) * (1.0 - Math.Exp((0.0 - dt) / 0.06));
		}

		public static double EaseDepth(double current, double target, double dt)
		{
			double num = 1.2 * dt;
			return current + Math.Max(0.0 - num, Math.Min(num, target - current));
		}

		public static double SlideTime(double remaining, double inwardSpeed)
		{
			double num = Math.Max(0.0, remaining) / Math.Max(0.6, inwardSpeed);
			if (!(num < 0.04))
			{
				if (!(num > 0.15))
				{
					return num;
				}
				return 0.15;
			}
			return 0.04;
		}

		public static double SlideDepth(double start, double progress)
		{
			double num = ((progress < 0.0) ? 0.0 : ((progress > 1.0) ? 1.0 : progress));
			return start * (1.0 - num * num);
		}

		public static double MouthFrom(double tipHeight, double? openingHeight)
		{
			double num = (openingHeight.HasValue ? (tipHeight - openingHeight.Value) : Math.Min(tipHeight, 0.06));
			if (!(num < 0.015))
			{
				if (!(num > 0.12))
				{
					return num;
				}
				return 0.12;
			}
			return 0.015;
		}
	}
}