Decompiled source of Sosiggun Scale Multipliers v1.0.0

SosigGunScale.dll

Decompiled 12 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using FistVR;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyCompany("SosigGunScale")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("SosigGunScale")]
[assembly: AssemblyTitle("SosigGunScale")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace SosigGunScale;

internal struct GunMeasurements
{
	public bool HasMesh;

	public float RearExtent;

	public float FrontExtent;

	public float Height;

	public float Width;

	public float Length => RearExtent + FrontExtent;
}
public static class GunScaler
{
	private static readonly Dictionary<int, float> s_shiftByWeapon = new Dictionary<int, float>();

	private static readonly HashSet<string> s_loggedItemIds = new HashSet<string>();

	internal static void RegisterShift(int weaponId, float shift)
	{
		if (shift > 0f)
		{
			s_shiftByWeapon[weaponId] = shift;
		}
		else
		{
			s_shiftByWeapon.Remove(weaponId);
		}
	}

	internal static void UnregisterShift(int weaponId)
	{
		s_shiftByWeapon.Remove(weaponId);
	}

	internal static float GetShift(SosigWeapon w)
	{
		if ((Object)(object)w != (Object)null && s_shiftByWeapon.TryGetValue(((Object)w).GetInstanceID(), out var value))
		{
			return value;
		}
		return 0f;
	}

	public static Vector3 HoldPoint(SosigWeapon w, bool isInventorySlot)
	{
		//IL_0008: 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_0053: Unknown result type (might be due to invalid IL or missing references)
		//IL_001d: 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_0042: 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_004d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		Transform recoilHolder = w.RecoilHolder;
		Vector3 val = recoilHolder.position;
		if (isInventorySlot && !Plugin.ShiftInInventorySlots.Value)
		{
			return val;
		}
		if (s_shiftByWeapon.Count > 0 && s_shiftByWeapon.TryGetValue(((Object)w).GetInstanceID(), out var value))
		{
			val -= recoilHolder.forward * value;
		}
		return val;
	}

	internal static string GetItemId(FVRPhysicalObject o)
	{
		if ((Object)(object)o.ObjectWrapper != (Object)null && !string.IsNullOrEmpty(o.ObjectWrapper.ItemID))
		{
			return o.ObjectWrapper.ItemID;
		}
		return ((Object)((Component)o).gameObject).name.Replace("(Clone)", "").Trim();
	}

	internal static void TryScale(SosigWeaponPlayerInterface swpi, bool recoilWasMissing)
	{
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_012c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0133: 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_0161: Unknown result type (might be due to invalid IL or missing references)
		//IL_019f: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a4: 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_01ae: Invalid comparison between Unknown and I4
		if (!Plugin.IsActive || (Object)(object)((Component)swpi).GetComponent<ScaledGunMarker>() != (Object)null)
		{
			return;
		}
		SosigWeapon val = (((Object)(object)swpi.W != (Object)null) ? swpi.W : ((Component)swpi).GetComponent<SosigWeapon>());
		if ((Object)(object)val == (Object)null || !Plugin.ShouldScaleType(val.Type))
		{
			return;
		}
		string itemId = GetItemId((FVRPhysicalObject)(object)swpi);
		if (Plugin.IsExcluded(itemId))
		{
			return;
		}
		Transform transform = ((Component)swpi).transform;
		Transform rh = (((Object)(object)val.RecoilHolder != (Object)null) ? val.RecoilHolder : ((Component)val).transform);
		GunMeasurements m = Measure(swpi, val, rh);
		string reason;
		WeaponClass weaponClass = WeaponClassifier.Classify(swpi, val, itemId, m, out reason);
		float num = WeaponClassifier.MultiplierFor(weaponClass);
		bool flag = s_loggedItemIds.Add(itemId);
		bool flag2 = Mathf.Abs(num - 1f) < 0.001f;
		if (flag && Plugin.LogClassification.Value)
		{
			Plugin.Log.LogInfo((object)(flag2 ? $"[Class] {itemId}: {weaponClass} ({reason}), left at vanilla size" : $"[Class] {itemId}: {weaponClass} ({reason}) -> x{num:0.###}"));
		}
		if (flag2)
		{
			return;
		}
		transform.localScale *= num;
		if (val.MuzzleOffsetSets != null)
		{
			for (int i = 0; i < val.MuzzleOffsetSets.Count; i++)
			{
				val.MuzzleOffsetSets[i] = val.MuzzleOffsetSets[i] * num;
			}
		}
		if (Plugin.ScaleParticleEffects.Value)
		{
			ParticleSystem[] componentsInChildren = ((Component)swpi).GetComponentsInChildren<ParticleSystem>(true);
			for (int j = 0; j < componentsInChildren.Length; j++)
			{
				MainModule main = componentsInChildren[j].main;
				if ((int)((MainModule)(ref main)).scalingMode == 1)
				{
					((MainModule)(ref main)).scalingMode = (ParticleSystemScalingMode)0;
				}
			}
		}
		float num2 = 0f;
		if (num > 1f && m.HasMesh)
		{
			num2 = (num - 1f) * m.RearExtent * Plugin.StockCompensation.Value;
			num2 = Mathf.Clamp(num2, 0f, Plugin.MaxStockShift.Value);
		}
		ScaledGunMarker scaledGunMarker = ((Component)swpi).gameObject.AddComponent<ScaledGunMarker>();
		scaledGunMarker.ItemID = itemId;
		scaledGunMarker.AppliedScale = num;
		scaledGunMarker.VanillaLength = m.Length;
		scaledGunMarker.Bind(val, num2);
		if (flag && Plugin.LogMeasurements.Value)
		{
			LogMeasurement(itemId, swpi, val, rh, m, num, num2, recoilWasMissing);
		}
	}

	private static GunMeasurements Measure(SosigWeaponPlayerInterface swpi, SosigWeapon w, Transform rh)
	{
		//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_0010: Unknown result type (might be due to invalid IL or missing references)
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_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_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_0168: 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_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_0183: 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_0189: Unknown result type (might be due to invalid IL or missing references)
		//IL_0191: Unknown result type (might be due to invalid IL or missing references)
		//IL_0192: Unknown result type (might be due to invalid IL or missing references)
		//IL_019a: 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_0154: Unknown result type (might be due to invalid IL or missing references)
		GunMeasurements result = default(GunMeasurements);
		Vector3 position = rh.position;
		Vector3 right = rh.right;
		Vector3 up = rh.up;
		Vector3 forward = rh.forward;
		float num = float.MaxValue;
		float num2 = float.MinValue;
		float num3 = float.MaxValue;
		float num4 = float.MinValue;
		float num5 = float.MaxValue;
		float num6 = float.MinValue;
		Transform ancestor = (((Object)(object)w.Laser != (Object)null) ? w.Laser.transform : null);
		Transform ancestor2 = (((Object)(object)swpi.HoloSight != (Object)null) ? swpi.HoloSight.transform : null);
		Vector3[] array = (Vector3[])(object)new Vector3[8];
		Renderer[] componentsInChildren = ((Component)swpi).GetComponentsInChildren<Renderer>(false);
		foreach (Renderer val in componentsInChildren)
		{
			if (!val.enabled || (!(val is MeshRenderer) && !(val is SkinnedMeshRenderer)) || IsUnder(((Component)val).transform, ancestor) || IsUnder(((Component)val).transform, ancestor2))
			{
				continue;
			}
			if (val is MeshRenderer)
			{
				MeshFilter component = ((Component)val).GetComponent<MeshFilter>();
				if ((Object)(object)component == (Object)null || (Object)(object)component.sharedMesh == (Object)null)
				{
					continue;
				}
				FillCorners(component.sharedMesh.bounds, array);
				for (int j = 0; j < 8; j++)
				{
					array[j] = ((Component)val).transform.TransformPoint(array[j]);
				}
			}
			else
			{
				FillCorners(val.bounds, array);
			}
			for (int k = 0; k < 8; k++)
			{
				Vector3 val2 = array[k] - position;
				float num7 = Vector3.Dot(val2, right);
				float num8 = Vector3.Dot(val2, up);
				float num9 = Vector3.Dot(val2, forward);
				if (num7 < num)
				{
					num = num7;
				}
				if (num7 > num2)
				{
					num2 = num7;
				}
				if (num8 < num3)
				{
					num3 = num8;
				}
				if (num8 > num4)
				{
					num4 = num8;
				}
				if (num9 < num5)
				{
					num5 = num9;
				}
				if (num9 > num6)
				{
					num6 = num9;
				}
			}
			result.HasMesh = true;
		}
		if (result.HasMesh)
		{
			result.RearExtent = Mathf.Max(0f, 0f - num5);
			result.FrontExtent = Mathf.Max(0f, num6);
			result.Height = num4 - num3;
			result.Width = num2 - num;
		}
		return result;
	}

	private static void FillCorners(Bounds b, Vector3[] c)
	{
		//IL_0002: 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_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_0018: 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_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_0030: 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_003c: 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)
		//IL_004e: 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_005a: 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_0065: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: 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_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_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_0096: 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_00a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a8: 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_00b4: 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_00c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d2: 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_00dd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f0: 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)
		Vector3 min = ((Bounds)(ref b)).min;
		Vector3 max = ((Bounds)(ref b)).max;
		c[0] = new Vector3(min.x, min.y, min.z);
		c[1] = new Vector3(max.x, min.y, min.z);
		c[2] = new Vector3(min.x, max.y, min.z);
		c[3] = new Vector3(max.x, max.y, min.z);
		c[4] = new Vector3(min.x, min.y, max.z);
		c[5] = new Vector3(max.x, min.y, max.z);
		c[6] = new Vector3(min.x, max.y, max.z);
		c[7] = new Vector3(max.x, max.y, max.z);
	}

	private static bool IsUnder(Transform t, Transform ancestor)
	{
		if ((Object)(object)ancestor == (Object)null)
		{
			return false;
		}
		Transform val = t;
		while ((Object)(object)val != (Object)null)
		{
			if ((Object)(object)val == (Object)(object)ancestor)
			{
				return true;
			}
			val = val.parent;
		}
		return false;
	}

	private static string Local(Transform rh, Transform t)
	{
		//IL_0010: 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_001b: 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_0026: 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_0037: 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_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)t == (Object)null)
		{
			return "none";
		}
		Vector3 val = t.position - rh.position;
		return $"({Vector3.Dot(val, rh.right):0.000},{Vector3.Dot(val, rh.up):0.000},{Vector3.Dot(val, rh.forward):0.000})";
	}

	private static void LogMeasurement(string itemId, SosigWeaponPlayerInterface swpi, SosigWeapon w, Transform rh, GunMeasurements m, float s, float shift, bool recoilWasMissing)
	{
		//IL_00a1: 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_00e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_0202: Unknown result type (might be due to invalid IL or missing references)
		//IL_0209: Unknown result type (might be due to invalid IL or missing references)
		//IL_020e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0275: Unknown result type (might be due to invalid IL or missing references)
		//IL_027a: Unknown result type (might be due to invalid IL or missing references)
		//IL_027e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0285: Unknown result type (might be due to invalid IL or missing references)
		//IL_028c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0291: Unknown result type (might be due to invalid IL or missing references)
		Transform transform = ((Component)swpi).transform;
		bool flag = false;
		Renderer[] componentsInChildren = ((Component)swpi).GetComponentsInChildren<Renderer>(true);
		foreach (Renderer val in componentsInChildren)
		{
			if (IsUnder(((Component)val).transform, rh) && (Object)(object)((Component)val).transform != (Object)(object)rh)
			{
				flag = true;
				break;
			}
		}
		Transform t = null;
		if ((Object)(object)swpi.Foregrip != (Object)null)
		{
			t = (((Object)(object)((FVRInteractiveObject)swpi.Foregrip).PoseOverride != (Object)null) ? ((FVRInteractiveObject)swpi.Foregrip).PoseOverride : ((Component)swpi.Foregrip).transform);
		}
		Plugin.Log.LogInfo((object)string.Format("[Measure] {0}: {1}/{2}, {3}, {4} rounds/load, size {5}", itemId, w.Type, w.AmmoType, w.isFullAuto ? "full-auto" : "semi-auto", w.ShotsPerLoad, ((FVRPhysicalObject)swpi).Size));
		Plugin.Log.LogInfo((object)$"[Measure] {itemId} vanilla: length {m.Length:0.000} m (rear {m.RearExtent:0.000}, front {m.FrontExtent:0.000}), height {m.Height:0.000}, width {m.Width:0.000}");
		Plugin.Log.LogInfo((object)$"[Measure] {itemId} scaled-frame points (divide by {s:0.00} for vanilla): muzzle {Local(rh, w.Muzzle)}, grip {Local(rh, ((FVRInteractiveObject)swpi).PoseOverride)}, foregrip {Local(rh, t)}, stock {Local(rh, swpi.StockPos)}");
		ManualLogSource log = Plugin.Log;
		object[] obj = new object[7]
		{
			itemId,
			(Object)(object)rh == (Object)(object)transform,
			(Object)(object)rh.parent == (Object)(object)transform,
			flag,
			null,
			null,
			null
		};
		Vector3 val2 = transform.localScale / s;
		obj[4] = ((Vector3)(ref val2)).ToString("F2");
		obj[5] = s;
		obj[6] = shift;
		log.LogInfo((object)string.Format("[Measure] {0} structure: holdPointIsRoot={1}, holdPointParentIsRoot={2}, meshesUnderHoldPoint={3}, rootScale {4} -> x{5:0.00}, stock shift {6:0.000} m", obj));
		string text = "none (all shots from the muzzle)";
		if (w.MuzzleOffsetSets != null && w.MuzzleOffsetSets.Count > 0)
		{
			float num = 0f;
			foreach (Vector3 muzzleOffsetSet in w.MuzzleOffsetSets)
			{
				float num2 = num;
				Vector2 val3 = new Vector2(muzzleOffsetSet.x, muzzleOffsetSet.y);
				num = Mathf.Max(num2, ((Vector2)(ref val3)).magnitude / s);
			}
			text = $"{w.MuzzleOffsetSets.Count} offsets, used={w.HasMuzzleOffsetSet}, widest {num:0.000} m from muzzle (vanilla)";
		}
		string text2 = "none";
		if ((Object)(object)w.Projectile != (Object)null)
		{
			text2 = ((Object)w.Projectile).name + (((Object)(object)w.Projectile.GetComponent<BallisticProjectile>() != (Object)null) ? "" : " (NOT a BallisticProjectile)");
		}
		Plugin.Log.LogInfo((object)string.Format("[Measure] {0} firing: {1} projectile(s)/shot, spread {2:0.0} deg, barrel offsets: {3}, projectile {4} ({5:0.00} kJ), recoil profile {6}", itemId, w.ProjectilesPerShot, w.ProjectileSpread, text, text2, WeaponClassifier.ProjectileEnergyKJ(w), (!recoilWasMissing) ? "ok" : (Plugin.FixMissingRecoilProfile.Value ? "MISSING (neutral one added)" : "MISSING")));
	}
}
[HarmonyPatch(typeof(FVRPhysicalObject), "Awake")]
internal static class FVRPhysicalObject_Awake_Patch
{
	[HarmonyPrefix]
	private static void Prefix(FVRPhysicalObject __instance)
	{
		SosigWeaponPlayerInterface val = (SosigWeaponPlayerInterface)(object)((__instance is SosigWeaponPlayerInterface) ? __instance : null);
		if ((Object)(object)val == (Object)null)
		{
			return;
		}
		try
		{
			bool recoilWasMissing = RecoilProfileFix.Apply(val);
			GunScaler.TryScale(val, recoilWasMissing);
		}
		catch (Exception ex)
		{
			Plugin.Log.LogError((object)("Failed to scale " + ((Object)__instance).name + ": " + ex));
		}
	}
}
internal static class HoldPointTranspiler
{
	internal static List<CodeInstruction> Apply(IEnumerable<CodeInstruction> instructions, bool isInventorySlot, string where, out bool patched)
	{
		List<CodeInstruction> list = new List<CodeInstruction>(instructions);
		FieldInfo field = typeof(SosigWeapon).GetField("RecoilHolder", BindingFlags.Instance | BindingFlags.Public);
		MethodInfo getMethod = typeof(Transform).GetProperty("position").GetGetMethod();
		MethodInfo method = typeof(GunScaler).GetMethod("HoldPoint", BindingFlags.Static | BindingFlags.Public);
		int num = 0;
		for (int i = 0; i < list.Count - 1; i++)
		{
			CodeInstruction val = list[i];
			CodeInstruction val2 = list[i + 1];
			if (val.opcode == OpCodes.Ldfld && object.Equals(val.operand, field) && (val2.opcode == OpCodes.Callvirt || val2.opcode == OpCodes.Call) && object.Equals(val2.operand, getMethod))
			{
				val.opcode = (isInventorySlot ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
				val.operand = null;
				val2.opcode = OpCodes.Call;
				val2.operand = method;
				num++;
			}
		}
		patched = num > 0;
		if (num != 1)
		{
			Plugin.Log.LogWarning((object)string.Format("{0}: expected 1 RecoilHolder.position read, found {1}. {2}", where, num, (num == 0) ? "Stock shift disabled there." : "Patched all of them."));
		}
		return list;
	}
}
[HarmonyPatch(typeof(SosigHand), "Hold")]
internal static class SosigHand_Hold_Patch
{
	[HarmonyTranspiler]
	private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
	{
		return HoldPointTranspiler.Apply(instructions, isInventorySlot: false, "SosigHand.Hold", out Plugin.HandHoldPatched);
	}
}
[HarmonyPatch(typeof(Slot), "PhysHold")]
internal static class SosigInventorySlot_PhysHold_Patch
{
	[HarmonyTranspiler]
	private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
	{
		return HoldPointTranspiler.Apply(instructions, isInventorySlot: true, "SosigInventory.Slot.PhysHold", out Plugin.SlotHoldPatched);
	}
}
[HarmonyPatch(typeof(SosigHand), "ForceUpdateHold")]
internal static class SosigHand_ForceUpdateHold_Patch
{
	[HarmonyPostfix]
	private static void Postfix(SosigHand __instance)
	{
		//IL_006f: 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_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)
		if (!__instance.IsHoldingObject || (Object)(object)__instance.HeldObject == (Object)null || (Object)(object)__instance.Target == (Object)null)
		{
			return;
		}
		float shift = GunScaler.GetShift(__instance.HeldObject);
		if (!(shift <= 0f) && !((Object)(object)__instance.HeldObject.O == (Object)null))
		{
			Rigidbody rootRigidbody = __instance.HeldObject.O.RootRigidbody;
			if (!((Object)(object)rootRigidbody == (Object)null))
			{
				rootRigidbody.position = __instance.Target.position + __instance.Target.forward * shift;
			}
		}
	}
}
[HarmonyPatch(typeof(SosigHand), "PickUp")]
internal static class SosigHand_PickUp_Patch
{
	[HarmonyPostfix]
	private static void Postfix(SosigHand __instance, SosigWeapon o)
	{
		try
		{
			if (!((Object)(object)o == (Object)null) && !((Object)(object)__instance.S == (Object)null))
			{
				HolderCollision.OnHeldBy(o, __instance.S);
				HolderDebug.LogFirstHold(__instance, o);
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogError((object)("SosigHand.PickUp postfix: " + ex));
		}
	}
}
[HarmonyPatch(typeof(Slot), "PlaceObjectIn")]
internal static class SosigInventorySlot_PlaceObjectIn_Patch
{
	[HarmonyPostfix]
	private static void Postfix(SosigWeapon o)
	{
		try
		{
			if ((Object)(object)o != (Object)null && (Object)(object)o.SosigWithInventory != (Object)null)
			{
				HolderCollision.OnHeldBy(o, o.SosigWithInventory);
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogError((object)("SosigInventory.Slot.PlaceObjectIn postfix: " + ex));
		}
	}
}
internal static class HolderCollision
{
	internal static void OnHeldBy(SosigWeapon w, Sosig s)
	{
		if (!Plugin.IgnoreCollisionsWithHolder.Value)
		{
			return;
		}
		ScaledGunMarker scaledGunMarker = (((Object)(object)w.O != (Object)null) ? ((Component)w.O).GetComponent<ScaledGunMarker>() : null);
		if ((Object)(object)scaledGunMarker == (Object)null)
		{
			scaledGunMarker = ((Component)w).GetComponent<ScaledGunMarker>();
		}
		if (!((Object)(object)scaledGunMarker == (Object)null) && scaledGunMarker.IgnoredWith.Add(((Object)s).GetInstanceID()))
		{
			Apply(w, s);
			if ((Object)(object)Plugin.Instance != (Object)null)
			{
				((MonoBehaviour)Plugin.Instance).StartCoroutine(ApplyLater(w, s, 1.5f));
			}
		}
	}

	private static IEnumerator ApplyLater(SosigWeapon w, Sosig s, float delay)
	{
		yield return (object)new WaitForSeconds(delay);
		if ((Object)(object)w != (Object)null && (Object)(object)s != (Object)null)
		{
			Apply(w, s);
		}
	}

	private static void Apply(SosigWeapon w, Sosig s)
	{
		if ((Object)(object)w.O == (Object)null || s.Links == null)
		{
			return;
		}
		Collider[] componentsInChildren = ((Component)w.O).GetComponentsInChildren<Collider>(false);
		List<Collider> list = new List<Collider>();
		for (int i = 0; i < s.Links.Count; i++)
		{
			SosigLink val = s.Links[i];
			if (!((Object)(object)val == (Object)null))
			{
				list.AddRange(((Component)val).GetComponentsInChildren<Collider>(false));
			}
		}
		foreach (Collider val2 in componentsInChildren)
		{
			if ((Object)(object)val2 == (Object)null || !val2.enabled)
			{
				continue;
			}
			for (int k = 0; k < list.Count; k++)
			{
				Collider val3 = list[k];
				if (!((Object)(object)val3 == (Object)null) && val3.enabled && !((Object)(object)val3 == (Object)(object)val2))
				{
					Physics.IgnoreCollision(val2, val3, true);
				}
			}
		}
	}
}
internal static class HolderDebug
{
	private static readonly HashSet<string> s_logged = new HashSet<string>();

	internal static void LogFirstHold(SosigHand hand, SosigWeapon w)
	{
		//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
		//IL_0191: 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_01ac: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
		//IL_01bc: Unknown result type (might be due to invalid IL or missing references)
		//IL_01cb: 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_01de: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e2: 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_00b8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
		if (!Plugin.LogMeasurements.Value || (Object)(object)w.O == (Object)null)
		{
			return;
		}
		ScaledGunMarker component = ((Component)w.O).GetComponent<ScaledGunMarker>();
		if ((Object)(object)component == (Object)null || !s_logged.Add(component.ItemID ?? "?"))
		{
			return;
		}
		Sosig s = hand.S;
		float num = float.MaxValue;
		float num2 = float.MinValue;
		if (s.Links != null)
		{
			foreach (SosigLink link in s.Links)
			{
				if ((Object)(object)link == (Object)null)
				{
					continue;
				}
				Collider[] componentsInChildren = ((Component)link).GetComponentsInChildren<Collider>(false);
				for (int i = 0; i < componentsInChildren.Length; i++)
				{
					Bounds bounds = componentsInChildren[i].bounds;
					if (((Bounds)(ref bounds)).min.y < num)
					{
						num = ((Bounds)(ref bounds)).min.y;
					}
					if (((Bounds)(ref bounds)).max.y > num2)
					{
						num2 = ((Bounds)(ref bounds)).max.y;
					}
				}
			}
		}
		float num3 = ((num2 > num) ? (num2 - num) : 0f);
		string text = "n/a";
		if ((Object)(object)hand.Point_Aimed != (Object)null && s.Links != null && s.Links.Count > 1 && (Object)(object)s.Links[0] != (Object)null && (Object)(object)s.Links[1] != (Object)null)
		{
			Transform transform = ((Component)s.Links[1]).transform;
			Vector3 val = hand.Point_Aimed.position - ((Component)s.Links[0]).transform.position;
			text = $"({Vector3.Dot(val, transform.right):0.000},{Vector3.Dot(val, transform.up):0.000},{Vector3.Dot(val, transform.forward):0.000})";
		}
		Plugin.Log.LogInfo((object)string.Format("[Holder] {0} first held by '{1}': sosig height {2:0.000} m, vanilla gun length {3:0.000} m ({4:0.00}x sosig height, now {5:0.00}x), aim point from head {6}", component.ItemID, ((Object)s).name.Replace("(Clone)", "").Trim(), num3, component.VanillaLength, (num3 > 0f) ? (component.VanillaLength / num3) : 0f, (num3 > 0f) ? (component.VanillaLength * component.AppliedScale / num3) : 0f, text));
	}
}
[BepInPlugin("h3vr.sosiggunscale", "Sosig Gun Scale", "1.0.0")]
[BepInProcess("h3vr.exe")]
public class Plugin : BaseUnityPlugin
{
	public const string Guid = "h3vr.sosiggunscale";

	public const string PluginName = "Sosig Gun Scale";

	public const string Version = "1.0.0";

	internal static Plugin Instance;

	internal static ManualLogSource Log;

	internal static bool HandHoldPatched;

	internal static bool SlotHoldPatched;

	internal static ConfigEntry<bool> Enabled;

	internal static ConfigEntry<bool> ScaleGuns;

	internal static ConfigEntry<bool> ScaleMeleeWeapons;

	internal static ConfigEntry<bool> ScaleGrenades;

	internal static ConfigEntry<bool> ScaleShields;

	internal static ConfigEntry<string> ExcludedItemIDs;

	internal static ConfigEntry<bool> ScaleParticleEffects;

	internal static ConfigEntry<float> HandgunMultiplier;

	internal static ConfigEntry<float> LongGunMultiplier;

	internal static ConfigEntry<float> OrdnanceMultiplier;

	internal static ConfigEntry<float> RotweinerMultiplier;

	internal static ConfigEntry<float> OtherWeaponMultiplier;

	internal static ConfigEntry<float> HandgunMaxLength;

	internal static ConfigEntry<string> OrdnanceAmmoTypes;

	internal static ConfigEntry<int> OrdnanceMinRounds;

	internal static ConfigEntry<float> AntiMaterielMinEnergyKJ;

	internal static ConfigEntry<string> HandgunItemIDs;

	internal static ConfigEntry<string> LongGunItemIDs;

	internal static ConfigEntry<string> OrdnanceItemIDs;

	internal static ConfigEntry<string> RotweinerItemIDs;

	internal static ConfigEntry<float> StockCompensation;

	internal static ConfigEntry<float> MaxStockShift;

	internal static ConfigEntry<bool> ShiftInInventorySlots;

	internal static ConfigEntry<bool> IgnoreCollisionsWithHolder;

	internal static ConfigEntry<bool> FixMissingRecoilProfile;

	internal static ConfigEntry<bool> LogClassification;

	internal static ConfigEntry<bool> LogMeasurements;

	private static readonly HashSet<string> s_excluded = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

	private static bool s_patchFailed;

	internal static bool IsActive
	{
		get
		{
			if (Enabled != null && Enabled.Value)
			{
				return !s_patchFailed;
			}
			return false;
		}
	}

	private void Awake()
	{
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		Instance = this;
		Log = ((BaseUnityPlugin)this).Logger;
		BindConfig();
		try
		{
			new Harmony("h3vr.sosiggunscale").PatchAll(typeof(Plugin).Assembly);
		}
		catch (Exception ex)
		{
			Log.LogError((object)("Harmony patching failed; the mod will do nothing this session.\n" + ex));
			s_patchFailed = true;
			return;
		}
		Log.LogInfo((object)string.Format("{0} {1} loaded. Scale: handguns x{2:0.00}, long guns x{3:0.00}, ordnance x{4:0.00}, Rotwiener x{5:0.00}. Stock compensation {6:0.00}, hand stock shift {7}, inventory stock shift {8}.", "Sosig Gun Scale", "1.0.0", HandgunMultiplier.Value, LongGunMultiplier.Value, OrdnanceMultiplier.Value, RotweinerMultiplier.Value, StockCompensation.Value, HandHoldPatched ? "active" : "UNAVAILABLE (game code changed?)", (!ShiftInInventorySlots.Value) ? "off" : (SlotHoldPatched ? "active" : "UNAVAILABLE")));
		if (LogMeasurements.Value)
		{
			LogLayerCollision();
		}
	}

	private void BindConfig()
	{
		//IL_0143: Unknown result type (might be due to invalid IL or missing references)
		//IL_014d: Expected O, but got Unknown
		//IL_0173: Unknown result type (might be due to invalid IL or missing references)
		//IL_017d: Expected O, but got Unknown
		//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ad: Expected O, but got Unknown
		//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
		//IL_01dd: Expected O, but got Unknown
		//IL_0203: Unknown result type (might be due to invalid IL or missing references)
		//IL_020d: Expected O, but got Unknown
		//IL_0241: Unknown result type (might be due to invalid IL or missing references)
		//IL_024b: Expected O, but got Unknown
		//IL_0400: Unknown result type (might be due to invalid IL or missing references)
		//IL_040a: Expected O, but got Unknown
		//IL_043e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0448: Expected O, but got Unknown
		Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Master switch. Changes apply to guns spawned after the change.");
		ScaleGuns = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "ScaleGuns", true, "Scale sosig firearms.");
		ScaleMeleeWeapons = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "ScaleMeleeWeapons", false, "Scale sosig melee weapons (knives, bats, swords...).");
		ScaleGrenades = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "ScaleGrenades", false, "Scale sosig grenades.");
		ScaleShields = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "ScaleShields", false, "Scale sosig shields.");
		ExcludedItemIDs = ((BaseUnityPlugin)this).Config.Bind<string>("General", "ExcludedItemIDs", "", "Comma-separated ItemIDs that should never be scaled (the debug log prints each gun's ItemID).");
		ExcludedItemIDs.SettingChanged += delegate
		{
			ParseExclusions();
		};
		ParseExclusions();
		ScaleParticleEffects = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "ScaleParticleEffects", true, "Make the gun's own particle effects (muzzle flash, smoke) scale with it. Unity doesn't do this by default.");
		AcceptableValueRange<float> val = new AcceptableValueRange<float>(0.25f, 4f);
		HandgunMultiplier = ((BaseUnityPlugin)this).Config.Bind<float>("Scale", "HandgunMultiplier", 1.3f, new ConfigDescription("Size multiplier for sosig pistols, revolvers and machine pistols. 1 = vanilla. All multipliers apply to weapons spawned after the change.", (AcceptableValueBase)(object)val, new object[0]));
		LongGunMultiplier = ((BaseUnityPlugin)this).Config.Bind<float>("Scale", "LongGunMultiplier", 1.375f, new ConfigDescription("Size multiplier for sosig rifles, carbines, SMGs and shotguns.", (AcceptableValueBase)(object)val, new object[0]));
		OrdnanceMultiplier = ((BaseUnityPlugin)this).Config.Bind<float>("Scale", "OrdnanceMultiplier", 1.55f, new ConfigDescription("Size multiplier for sosig launchers, machine guns, miniguns and anti-materiel rifles.", (AcceptableValueBase)(object)val, new object[0]));
		RotweinerMultiplier = ((BaseUnityPlugin)this).Config.Bind<float>("Scale", "RotweinerMultiplier", 1f, new ConfigDescription("Size multiplier for the Rotwiener creatures' launchers (prick, barfer, flamer, spore...). 1 = leave them alone.", (AcceptableValueBase)(object)val, new object[0]));
		OtherWeaponMultiplier = ((BaseUnityPlugin)this).Config.Bind<float>("Scale", "OtherWeaponMultiplier", 1.35f, new ConfigDescription("Size multiplier for melee weapons, grenades and shields, if their Scale... switch in General is on.", (AcceptableValueBase)(object)val, new object[0]));
		HandgunMaxLength = ((BaseUnityPlugin)this).Config.Bind<float>("Classification", "HandgunMaxLength", 0.22f, new ConfigDescription("A gun firing pistol ammo counts as a handgun if its vanilla length (meters, printed in the log) is at most this. Longer pistol-caliber guns (Uzi, MP5, Vector...) count as long guns.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 2f), new object[0]));
		OrdnanceAmmoTypes = ((BaseUnityPlugin)this).Config.Bind<string>("Classification", "OrdnanceAmmoTypes", "Rocket, Machinegun, Grenade", "Sosig ammo types that always count as ordnance. Valid: " + string.Join(", ", Enum.GetNames(typeof(SosiggunAmmoType))) + ". Remove Grenade to treat grenade launchers as long guns.");
		OrdnanceAmmoTypes.SettingChanged += delegate
		{
			WeaponClassifier.ParseOrdnanceAmmoTypes(OrdnanceAmmoTypes.Value);
		};
		OrdnanceMinRounds = ((BaseUnityPlugin)this).Config.Bind<int>("Classification", "OrdnanceMinRounds", 90, "A full-auto rifle-caliber gun holding at least this many rounds per load counts as a machine gun (ordnance).");
		AntiMaterielMinEnergyKJ = ((BaseUnityPlugin)this).Config.Bind<float>("Classification", "AntiMaterielMinEnergyKJ", 9f, "A sniper rifle whose projectile has at least this much muzzle energy (kJ, printed in the log) counts as an anti-materiel rifle (ordnance). For reference, .308 is about 3.5 kJ and .50 BMG about 18 kJ.");
		HandgunItemIDs = ((BaseUnityPlugin)this).Config.Bind<string>("Classification", "HandgunItemIDs", "", "Comma-separated ItemIDs always treated as handguns. These four lists override the automatic sorting.");
		LongGunItemIDs = ((BaseUnityPlugin)this).Config.Bind<string>("Classification", "LongGunItemIDs", "", "Comma-separated ItemIDs always treated as long guns.");
		OrdnanceItemIDs = ((BaseUnityPlugin)this).Config.Bind<string>("Classification", "OrdnanceItemIDs", "SosiggunFutureMeatleStorm, Sosiggun_M60, Sosiggun_MF_MG", "Comma-separated ItemIDs always treated as ordnance.");
		RotweinerItemIDs = ((BaseUnityPlugin)this).Config.Bind<string>("Classification", "RotweinerItemIDs", "", "Comma-separated ItemIDs always treated as Rotwiener creature weapons.");
		BindIdList(HandgunItemIDs, WeaponClassifier.HandgunIds);
		BindIdList(LongGunItemIDs, WeaponClassifier.LongGunIds);
		BindIdList(OrdnanceItemIDs, WeaponClassifier.OrdnanceIds);
		BindIdList(RotweinerItemIDs, WeaponClassifier.RotweinerIds);
		StockCompensation = ((BaseUnityPlugin)this).Config.Bind<float>("Holding", "StockCompensation", 1f, new ConfigDescription("How much of the extra stock length gets pushed forward so the stock doesn't sink into the sosig holding it. 1 = the back of the gun stays exactly where it is on a vanilla gun (the grip moves forward instead). 0 = the gun grows evenly around its grip (stock pokes further back).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), new object[0]));
		MaxStockShift = ((BaseUnityPlugin)this).Config.Bind<float>("Holding", "MaxStockShift", 0.5f, new ConfigDescription("Safety cap, in meters, on how far forward a gun can be pushed by StockCompensation.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 2f), new object[0]));
		ShiftInInventorySlots = ((BaseUnityPlugin)this).Config.Bind<bool>("Holding", "ShiftInInventorySlots", false, "Also apply the stock shift to guns a sosig is carrying in an inventory slot (not in its hands).");
		IgnoreCollisionsWithHolder = ((BaseUnityPlugin)this).Config.Bind<bool>("Holding", "IgnoreCollisionsWithHolder", true, "Stop a scaled gun from physically bumping into the sosig carrying it (in hands or inventory). This prevents a bigger gun from shoving its own sosig around.");
		FixMissingRecoilProfile = ((BaseUnityPlugin)this).Config.Bind<bool>("Compatibility", "FixMissingRecoilProfile", true, "Some sosig guns (e.g. the Meat Fortress ones) have no recoil profile, which makes the game throw errors when a player fires one two-handed, and can break other mods that rewrite sosig firing. This gives those guns a zero-recoil profile, which behaves the same as having none. Independent of scaling.");
		LogClassification = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "LogClassification", true, "Write one line per weapon type to the BepInEx log saying which class it was sorted into, why, and its multiplier, plus the list of Rotwiener creature weapons found. Handy while setting up the classes; turn off once you're happy to keep the console quiet.");
		LogMeasurements = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "LogMeasurements", false, "Write detailed per-weapon diagnostics to the BepInEx log: size, grab points, firing setup, holder info, recoil-profile fixes and the physics layer check. Only needed when troubleshooting.");
		WeaponClassifier.ParseOrdnanceAmmoTypes(OrdnanceAmmoTypes.Value);
	}

	private static void BindIdList(ConfigEntry<string> entry, ItemIdList list)
	{
		list.Parse(entry.Value);
		entry.SettingChanged += delegate
		{
			list.Parse(entry.Value);
		};
	}

	private static void ParseExclusions()
	{
		s_excluded.Clear();
		string[] array = (ExcludedItemIDs.Value ?? "").Split(new char[1] { ',' });
		for (int i = 0; i < array.Length; i++)
		{
			string text = array[i].Trim();
			if (text.Length > 0)
			{
				s_excluded.Add(text);
			}
		}
	}

	internal static bool IsExcluded(string itemId)
	{
		if (itemId != null)
		{
			return s_excluded.Contains(itemId);
		}
		return false;
	}

	internal static bool ShouldScaleType(SosigWeaponType type)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_001e: Expected I4, but got Unknown
		return (int)type switch
		{
			0 => ScaleGuns.Value, 
			1 => ScaleMeleeWeapons.Value, 
			2 => ScaleGrenades.Value, 
			5 => ScaleShields.Value, 
			_ => false, 
		};
	}

	private static void LogLayerCollision()
	{
		int num = LayerMask.NameToLayer("AgentMeleeWeapon");
		int num2 = LayerMask.NameToLayer("AgentBody");
		if (num < 0 || num2 < 0)
		{
			Log.LogInfo((object)"[Physics] Couldn't find the AgentMeleeWeapon / AgentBody layers.");
			return;
		}
		bool flag = !Physics.GetIgnoreLayerCollision(num, num2);
		Log.LogInfo((object)("[Physics] Guns held by sosigs " + (flag ? "DO" : "do NOT") + " physically collide with sosig bodies in vanilla."));
	}
}
internal static class RecoilProfileFix
{
	private static SosigWeaponRecoilProfile s_neutral;

	private static readonly HashSet<string> s_logged = new HashSet<string>();

	internal static bool Apply(SosigWeaponPlayerInterface swpi)
	{
		//IL_0084: Unknown result type (might be due to invalid IL or missing references)
		//IL_0089: 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_0098: Unknown result type (might be due to invalid IL or missing references)
		if (!Plugin.IsActive)
		{
			return false;
		}
		SosigWeapon val = (((Object)(object)swpi.W != (Object)null) ? swpi.W : ((Component)swpi).GetComponent<SosigWeapon>());
		if ((Object)(object)val == (Object)null || (Object)(object)val.RecoilP != (Object)null)
		{
			return false;
		}
		if (!Plugin.FixMissingRecoilProfile.Value)
		{
			return true;
		}
		if ((Object)(object)s_neutral == (Object)null)
		{
			s_neutral = ScriptableObject.CreateInstance<SosigWeaponRecoilProfile>();
			((Object)s_neutral).name = "SosigGunScale_NeutralRecoil";
			((Object)s_neutral).hideFlags = (HideFlags)32;
			s_neutral.RecoilPerShot = Vector4.zero;
			s_neutral.RecoilRecoveryMults = Vector3.one;
			s_neutral.PlayerAltGripMult = 1f;
		}
		val.RecoilP = s_neutral;
		string itemId = GunScaler.GetItemId((FVRPhysicalObject)(object)swpi);
		if (s_logged.Add(itemId) && Plugin.LogMeasurements.Value)
		{
			Plugin.Log.LogInfo((object)("[Compat] " + itemId + " has no recoil profile; gave it a neutral (zero-recoil) one."));
		}
		return true;
	}
}
public class ScaledGunMarker : MonoBehaviour
{
	public SosigWeapon Weapon;

	public string ItemID;

	public float AppliedScale = 1f;

	public float StockShift;

	public float VanillaLength;

	[NonSerialized]
	public HashSet<int> IgnoredWith = new HashSet<int>();

	private int m_weaponId;

	private void Awake()
	{
		if ((Object)(object)Weapon == (Object)null)
		{
			Weapon = ((Component)this).GetComponent<SosigWeapon>();
		}
		if ((Object)(object)Weapon != (Object)null)
		{
			m_weaponId = ((Object)Weapon).GetInstanceID();
			if (StockShift > 0f)
			{
				GunScaler.RegisterShift(m_weaponId, StockShift);
			}
		}
	}

	internal void Bind(SosigWeapon w, float stockShift)
	{
		Weapon = w;
		StockShift = stockShift;
		m_weaponId = ((Object)w).GetInstanceID();
		GunScaler.RegisterShift(m_weaponId, stockShift);
	}

	private void OnDestroy()
	{
		if (m_weaponId != 0)
		{
			GunScaler.UnregisterShift(m_weaponId);
		}
	}
}
internal enum WeaponClass
{
	Handgun,
	LongGun,
	Ordnance,
	Rotweiner,
	Other
}
internal sealed class ItemIdList
{
	private readonly HashSet<string> m_ids = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

	internal void Parse(string raw)
	{
		m_ids.Clear();
		string[] array = (raw ?? "").Split(new char[1] { ',' });
		for (int i = 0; i < array.Length; i++)
		{
			string text = array[i].Trim();
			if (text.Length > 0)
			{
				m_ids.Add(text);
			}
		}
	}

	internal bool Contains(string id)
	{
		if (id != null)
		{
			return m_ids.Contains(id);
		}
		return false;
	}
}
internal static class WeaponClassifier
{
	internal static readonly ItemIdList HandgunIds = new ItemIdList();

	internal static readonly ItemIdList LongGunIds = new ItemIdList();

	internal static readonly ItemIdList OrdnanceIds = new ItemIdList();

	internal static readonly ItemIdList RotweinerIds = new ItemIdList();

	private static readonly HashSet<SosiggunAmmoType> s_ordnanceAmmo = new HashSet<SosiggunAmmoType>();

	private static HashSet<string> s_rotweinerWeapons;

	private static HashSet<string> s_anyEnemyWeapons;

	private static int s_templateCountSeen = -1;

	internal static void ParseOrdnanceAmmoTypes(string raw)
	{
		//IL_0051: Unknown result type (might be due to invalid IL or missing references)
		s_ordnanceAmmo.Clear();
		string[] array = (raw ?? "").Split(new char[1] { ',' });
		for (int i = 0; i < array.Length; i++)
		{
			string text = array[i].Trim();
			if (text.Length == 0)
			{
				continue;
			}
			try
			{
				s_ordnanceAmmo.Add((SosiggunAmmoType)Enum.Parse(typeof(SosiggunAmmoType), text, ignoreCase: true));
			}
			catch (ArgumentException)
			{
				if (Plugin.Log != null)
				{
					Plugin.Log.LogWarning((object)("OrdnanceAmmoTypes: '" + text + "' isn't a sosig ammo type. Valid: " + string.Join(", ", Enum.GetNames(typeof(SosiggunAmmoType)))));
				}
			}
		}
	}

	internal static float MultiplierFor(WeaponClass c)
	{
		return c switch
		{
			WeaponClass.Handgun => Plugin.HandgunMultiplier.Value, 
			WeaponClass.LongGun => Plugin.LongGunMultiplier.Value, 
			WeaponClass.Ordnance => Plugin.OrdnanceMultiplier.Value, 
			WeaponClass.Rotweiner => Plugin.RotweinerMultiplier.Value, 
			_ => Plugin.OtherWeaponMultiplier.Value, 
		};
	}

	internal static WeaponClass Classify(SosigWeaponPlayerInterface swpi, SosigWeapon w, string itemId, GunMeasurements m, out string reason)
	{
		//IL_0001: 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_00ba: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c1: Invalid comparison between Unknown and I4
		//IL_010e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0114: Invalid comparison between Unknown and I4
		//IL_0121: Unknown result type (might be due to invalid IL or missing references)
		//IL_0174: Unknown result type (might be due to invalid IL or missing references)
		//IL_017a: Invalid comparison between Unknown and I4
		//IL_0138: Unknown result type (might be due to invalid IL or missing references)
		//IL_013e: Invalid comparison between Unknown and I4
		if ((int)w.Type != 0)
		{
			reason = ((object)Unsafe.As<SosigWeaponType, SosigWeaponType>(ref w.Type)/*cast due to .constrained prefix*/).ToString().ToLowerInvariant();
			return WeaponClass.Other;
		}
		if (RotweinerIds.Contains(itemId))
		{
			reason = "listed in RotweinerItemIDs";
			return WeaponClass.Rotweiner;
		}
		if (OrdnanceIds.Contains(itemId))
		{
			reason = "listed in OrdnanceItemIDs";
			return WeaponClass.Ordnance;
		}
		if (HandgunIds.Contains(itemId))
		{
			reason = "listed in HandgunItemIDs";
			return WeaponClass.Handgun;
		}
		if (LongGunIds.Contains(itemId))
		{
			reason = "listed in LongGunItemIDs";
			return WeaponClass.LongGun;
		}
		RefreshEnemyRosters();
		if (s_rotweinerWeapons != null && s_rotweinerWeapons.Contains(itemId))
		{
			reason = "carried by Rotwiener creatures";
			return WeaponClass.Rotweiner;
		}
		if ((s_anyEnemyWeapons == null || !s_anyEnemyWeapons.Contains(itemId)) && (int)w.AmmoType == 11 && !itemId.StartsWith("Sosiggun_MF_", StringComparison.OrdinalIgnoreCase))
		{
			reason = "Zosig ammo type, not on any enemy roster";
			return WeaponClass.Rotweiner;
		}
		if (s_ordnanceAmmo.Contains(w.AmmoType))
		{
			reason = "ammo type " + ((object)Unsafe.As<SosiggunAmmoType, SosiggunAmmoType>(ref w.AmmoType)/*cast due to .constrained prefix*/).ToString();
			return WeaponClass.Ordnance;
		}
		if ((int)((FVRPhysicalObject)swpi).Size >= 3)
		{
			reason = "massive object";
			return WeaponClass.Ordnance;
		}
		bool flag = IsPistolAmmo(w.AmmoType);
		if (w.isFullAuto && !flag && (int)w.AmmoType != 8 && w.ShotsPerLoad >= Plugin.OrdnanceMinRounds.Value)
		{
			reason = $"full-auto, {w.ShotsPerLoad} rounds per load";
			return WeaponClass.Ordnance;
		}
		float num = ProjectileEnergyKJ(w);
		if ((int)w.AmmoType == 6 && num >= Plugin.AntiMaterielMinEnergyKJ.Value)
		{
			reason = $"sniper round with {num:0.0} kJ";
			return WeaponClass.Ordnance;
		}
		if (flag && m.HasMesh && m.Length <= Plugin.HandgunMaxLength.Value)
		{
			reason = $"pistol ammo, {m.Length:0.000} m long";
			return WeaponClass.Handgun;
		}
		reason = "default";
		return WeaponClass.LongGun;
	}

	internal static bool IsPistolAmmo(SosiggunAmmoType t)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0002: Invalid comparison between Unknown and I4
		//IL_0004: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Invalid comparison between Unknown and I4
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_000a: Invalid comparison between Unknown and I4
		if ((int)t != 1 && (int)t != 2)
		{
			return (int)t == 3;
		}
		return true;
	}

	internal static float ProjectileEnergyKJ(SosigWeapon w)
	{
		if ((Object)(object)w.Projectile == (Object)null)
		{
			return 0f;
		}
		BallisticProjectile component = w.Projectile.GetComponent<BallisticProjectile>();
		if ((Object)(object)component == (Object)null)
		{
			return 0f;
		}
		return 0.5f * component.Mass * component.MuzzleVelocityBase * component.MuzzleVelocityBase / 1000f;
	}

	private static void RefreshEnemyRosters()
	{
		//IL_0076: Unknown result type (might be due to invalid IL or missing references)
		//IL_007d: Invalid comparison between Unknown and I4
		IM instance = ManagerSingleton<IM>.Instance;
		if ((Object)(object)instance == (Object)null || instance.odicSosigObjsByID == null)
		{
			return;
		}
		int count = instance.odicSosigObjsByID.Count;
		if (count == s_templateCountSeen)
		{
			return;
		}
		s_templateCountSeen = count;
		HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
		HashSet<string> hashSet2 = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
		foreach (KeyValuePair<SosigEnemyID, SosigEnemyTemplate> item in instance.odicSosigObjsByID)
		{
			SosigEnemyTemplate value = item.Value;
			if (!((Object)(object)value == (Object)null))
			{
				bool isRot = (int)value.SosigEnemyCategory == 20;
				AddWeapons(value.WeaponOptions, isRot, hashSet, hashSet2);
				AddWeapons(value.WeaponOptions_Secondary, isRot, hashSet, hashSet2);
				AddWeapons(value.WeaponOptions_Tertiary, isRot, hashSet, hashSet2);
			}
		}
		s_rotweinerWeapons = hashSet;
		s_anyEnemyWeapons = hashSet2;
		if (Plugin.LogClassification.Value)
		{
			List<string> list = new List<string>(hashSet);
			list.Sort(StringComparer.OrdinalIgnoreCase);
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendFormat("[Catalog] {0} enemy templates, {1} distinct weapons. Carried by Rotwiener creatures: ", count, hashSet2.Count);
			stringBuilder.Append((list.Count > 0) ? string.Join(", ", list.ToArray()) : "(none found)");
			Plugin.Log.LogInfo((object)stringBuilder.ToString());
		}
	}

	private static void AddWeapons(List<FVRObject> list, bool isRot, HashSet<string> rots, HashSet<string> any)
	{
		if (list == null)
		{
			return;
		}
		foreach (FVRObject item in list)
		{
			if (!((Object)(object)item == (Object)null) && !string.IsNullOrEmpty(item.ItemID))
			{
				any.Add(item.ItemID);
				if (isRot)
				{
					rots.Add(item.ItemID);
				}
			}
		}
	}
}