Decompiled source of HuntsmanLoot v1.1.4

plugins\HiarlyScripter-HuntsmanLoot\HuntsmanLoot.dll

Decompiled 3 hours ago
using System;
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.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Photon.Pun;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("HuntsmanLoot")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+b5ffa44b7b1c01b3b7d96647966210cba60710ec")]
[assembly: AssemblyProduct("HuntsmanLoot")]
[assembly: AssemblyTitle("HuntsmanLoot")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace HuntsmanLoot;

[BepInPlugin("com.hiarlyscripter.huntsmanloot", "Huntsman Loot", "1.1.4")]
public sealed class HuntsmanLootPlugin : BaseUnityPlugin
{
	internal static ConfigEntry<int> DropChance;

	internal static ConfigEntry<bool> BerserkerOnly;

	internal static ConfigEntry<bool> MasterClientOnly;

	internal static ConfigEntry<bool> RandomizeAmmo;

	internal static ConfigEntry<bool> EnableDebugLogging;

	internal static readonly FieldInfo _hasHealthField = AccessTools.Field(typeof(Enemy), "HasHealth");

	internal static readonly FieldInfo _healthField = AccessTools.Field(typeof(Enemy), "Health");

	internal static readonly FieldInfo _hpCurrentField = AccessTools.Field(typeof(EnemyHealth), "healthCurrent");

	internal static readonly FieldInfo _numberOfBulletsField = AccessTools.Field(typeof(ItemGun), "numberOfBullets");

	internal static readonly FieldInfo _batteryLifeIntField = AccessTools.Field(typeof(ItemBattery), "batteryLifeInt");

	internal static readonly FieldInfo _enemyParentField = AccessTools.Field(typeof(EnemyParent), "Enemy");

	internal static HuntsmanLootPlugin Instance { get; private set; }

	internal static ManualLogSource Log { get; private set; }

	internal static bool DebugLoggingEnabled
	{
		get
		{
			if (EnableDebugLogging != null)
			{
				return EnableDebugLogging.Value;
			}
			return false;
		}
	}

	private void Awake()
	{
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Expected O, but got Unknown
		//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
		Instance = this;
		Log = ((BaseUnityPlugin)this).Logger;
		DropChance = ((BaseUnityPlugin)this).Config.Bind<int>("Drop", "DropChance", 100, new ConfigDescription("Chance (%) de a arma cair quando o Huntsman morre. 100 = sempre, 1 = rarissimo.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 100), Array.Empty<object>()));
		BerserkerOnly = ((BaseUnityPlugin)this).Config.Bind<bool>("Drop", "BerserkerOnly", false, "true  = arma so cai de Huntsman no modo berserk (requer BerserkerEnemies).\nfalse = cai de qualquer Huntsman (padrao).");
		MasterClientOnly = ((BaseUnityPlugin)this).Config.Bind<bool>("Drop", "MasterClientOnly", true, "true  = apenas o HOST processa o drop (evita duplicatas em multiplayer).\nfalse = qualquer cliente pode gerar o drop.");
		RandomizeAmmo = ((BaseUnityPlugin)this).Config.Bind<bool>("Drop", "RandomizeAmmo", true, "true  = arma cai com municao aleatoria (entre 1 e o maximo).\nfalse = sempre cai com municao completa.");
		EnableDebugLogging = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "EnableDebugLogging", false, "true  = logs tecnicos detalhados para diagnostico.\nfalse = logs normais reduzidos.");
		LogReflectionStatus();
		new Harmony("com.hiarlyscripter.huntsmanloot").PatchAll(typeof(HuntsmanPatches));
		Log.LogInfo((object)"[HuntsmanLoot] v1.1.4 carregado. Patch Harmony aplicado.");
	}

	internal static void DebugLog(string message)
	{
		if (DebugLoggingEnabled)
		{
			ManualLogSource log = Log;
			if (log != null)
			{
				log.LogInfo((object)message);
			}
		}
	}

	internal static void DebugWarning(string message)
	{
		if (DebugLoggingEnabled)
		{
			ManualLogSource log = Log;
			if (log != null)
			{
				log.LogWarning((object)message);
			}
		}
	}

	private void LogReflectionStatus()
	{
		DebugLog("[HuntsmanLoot] Reflexao: " + $"HasHealth={_hasHealthField != null}, " + $"Health={_healthField != null}, " + $"healthCurrent={_hpCurrentField != null}, " + $"numberOfBullets={_numberOfBulletsField != null}, " + $"batteryLifeInt={_batteryLifeIntField != null}");
		if (_hasHealthField == null || _healthField == null || _hpCurrentField == null)
		{
			Log.LogError((object)"[HuntsmanLoot] ATENCAO: campos de saude nao encontrados — deteccao de morte pode falhar!");
		}
	}

	internal static void ApplyAmmoSync(GameObject spawned)
	{
		if ((Object)(object)spawned == (Object)null)
		{
			return;
		}
		ItemBattery componentInChildren = spawned.GetComponentInChildren<ItemBattery>();
		if ((Object)(object)componentInChildren == (Object)null)
		{
			Log.LogWarning((object)"[HuntsmanLoot] Ammo apply failed: expected=unknown actual=no-battery");
			return;
		}
		int num = Mathf.Max(1, GetAmmoCapacity(componentInChildren));
		int num2;
		if (RandomizeAmmo.Value)
		{
			num2 = RollWeightedAmmo(num);
			DebugLog($"[HuntsmanLoot] Ammo randomized: max={num} final={num2}");
		}
		else
		{
			num2 = num;
			DebugLog($"[HuntsmanLoot] Ammo kept full: max={num}");
		}
		num2 = Mathf.Clamp(num2, 1, num);
		HuntsmanLootAmmoState obj = spawned.GetComponent<HuntsmanLootAmmoState>() ?? spawned.AddComponent<HuntsmanLootAmmoState>();
		obj.finalAmmo = num2;
		obj.maxAmmo = num;
		obj.applied = false;
		obj.source = "spawn";
		Log.LogInfo((object)$"[HuntsmanLoot] Ammo final: {num2}/{num}");
	}

	internal static bool ApplyAmmoState(ItemBattery battery, HuntsmanLootAmmoState state, string source)
	{
		if ((Object)(object)battery == (Object)null || (Object)(object)state == (Object)null)
		{
			return false;
		}
		int num = Mathf.Max(1, state.maxAmmo);
		if (battery.batteryBars > 0)
		{
			num = battery.batteryBars;
		}
		int num2 = Mathf.Clamp(state.finalAmmo, 1, num);
		int batteryLife = Mathf.Clamp((int)Math.Round((float)num2 / (float)num * 100f), 0, 100);
		battery.SetBatteryLife(batteryLife);
		int num3 = ReadBatteryLifeInt(battery);
		state.finalAmmo = num2;
		state.maxAmmo = num;
		state.applied = num3 == num2;
		state.source = source;
		if (state.applied)
		{
			Log.LogInfo((object)($"[HuntsmanLoot] Ammo applied: expected={num2}/{num} " + $"actual={num3} battery={battery.batteryLife:0.##} source={source}"));
		}
		else
		{
			Log.LogWarning((object)($"[HuntsmanLoot] Ammo apply failed: expected={num2} " + $"actual={num3} battery={battery.batteryLife:0.##} source={source}"));
		}
		return state.applied;
	}

	private static int ReadBatteryLifeInt(ItemBattery battery)
	{
		if ((Object)(object)battery == (Object)null || _batteryLifeIntField == null)
		{
			return -1;
		}
		return (int)_batteryLifeIntField.GetValue(battery);
	}

	private static int GetAmmoCapacity(ItemBattery battery)
	{
		if ((Object)(object)battery != (Object)null && battery.batteryBars > 0)
		{
			return battery.batteryBars;
		}
		return 5;
	}

	private static int RollWeightedAmmo(int maxAmmo)
	{
		int roll = Random.Range(1, 101);
		return RollWeightedAmmoFromRoll(maxAmmo, roll);
	}

	internal static int RollWeightedAmmoFromRoll(int maxAmmo, int roll)
	{
		maxAmmo = Mathf.Max(1, maxAmmo);
		if (maxAmmo == 1)
		{
			return 1;
		}
		int[] ammoWeights = GetAmmoWeights(maxAmmo);
		roll = Mathf.Clamp(roll, 1, 100);
		int num = 0;
		for (int i = 0; i < ammoWeights.Length; i++)
		{
			num += ammoWeights[i];
			if (roll <= num)
			{
				return Mathf.Clamp(i + 1, 1, maxAmmo);
			}
		}
		return maxAmmo;
	}

	internal static int[] GetAmmoWeights(int maxAmmo)
	{
		maxAmmo = Mathf.Max(1, maxAmmo);
		return maxAmmo switch
		{
			1 => new int[1] { 100 }, 
			2 => new int[2] { 75, 25 }, 
			3 => new int[3] { 45, 40, 15 }, 
			4 => new int[4] { 32, 30, 26, 12 }, 
			5 => new int[5] { 25, 25, 22, 18, 10 }, 
			6 => new int[6] { 22, 22, 20, 16, 10, 10 }, 
			_ => BuildAmmoWeights(maxAmmo), 
		};
	}

	private static int[] BuildAmmoWeights(int maxAmmo)
	{
		int[] array = new int[maxAmmo];
		array[maxAmmo - 1] = 10;
		int num = maxAmmo - 1;
		int num2 = 90 / num;
		int num3 = 90 - num2 * num;
		for (int i = 0; i < num; i++)
		{
			array[i] = num2 + ((i < num3) ? 1 : 0);
		}
		return array;
	}
}
internal sealed class HuntsmanLootAmmoState : MonoBehaviour
{
	internal int finalAmmo;

	internal int maxAmmo;

	internal bool applied;

	internal string source;
}
[HarmonyPatch]
internal static class HuntsmanPatches
{
	private const string SHOTGUN_PATH = "Items/Item Gun Shotgun";

	private static void ClearPendingVisual()
	{
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(ItemBattery), "Start")]
	private static void OnItemBatteryStartPost(ItemBattery __instance)
	{
		try
		{
			HuntsmanLootAmmoState componentInParent = ((Component)__instance).GetComponentInParent<HuntsmanLootAmmoState>();
			if (!((Object)(object)componentInParent == (Object)null))
			{
				HuntsmanLootPlugin.ApplyAmmoState(__instance, componentInParent, "ItemBattery.StartPostfix");
			}
		}
		catch (Exception ex)
		{
			HuntsmanLootPlugin.Log.LogWarning((object)("[HuntsmanLoot] Ammo apply failed: expected=unknown actual=exception source=ItemBattery.StartPostfix error=" + ex.Message));
		}
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(EnemyParent), "Despawn")]
	private static void OnHuntsmanDespawnPost(EnemyParent __instance)
	{
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0073: Expected O, but got Unknown
		//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fb: Expected O, but got Unknown
		if (__instance.enemyName != "Huntsman")
		{
			return;
		}
		HuntsmanLootPlugin.DebugLog("[HuntsmanLoot] Huntsman detectado no Despawn.");
		if (HuntsmanLootPlugin.MasterClientOnly.Value && !SemiFunc.IsMasterClientOrSingleplayer())
		{
			ClearPendingVisual();
			HuntsmanLootPlugin.DebugLog("[HuntsmanLoot] Nao eh master client — drop ignorado.");
			return;
		}
		if (HuntsmanLootPlugin._enemyParentField == null)
		{
			ClearPendingVisual();
			HuntsmanLootPlugin.Log.LogError((object)"[HuntsmanLoot] _enemyParentField null — drop abortado.");
			return;
		}
		Enemy val = (Enemy)HuntsmanLootPlugin._enemyParentField.GetValue(__instance);
		if ((Object)(object)val == (Object)null)
		{
			ClearPendingVisual();
			HuntsmanLootPlugin.Log.LogWarning((object)"[HuntsmanLoot] enemy null — drop abortado.");
			return;
		}
		if (HuntsmanLootPlugin._hasHealthField == null || HuntsmanLootPlugin._healthField == null || HuntsmanLootPlugin._hpCurrentField == null)
		{
			ClearPendingVisual();
			HuntsmanLootPlugin.Log.LogError((object)"[HuntsmanLoot] Campos de saude inacessiveis — drop abortado.");
			return;
		}
		if (!(bool)HuntsmanLootPlugin._hasHealthField.GetValue(val))
		{
			HuntsmanLootPlugin.DebugLog("[HuntsmanLoot] Enemy sem health component — ignorando.");
			return;
		}
		EnemyHealth val2 = (EnemyHealth)HuntsmanLootPlugin._healthField.GetValue(val);
		if ((Object)(object)val2 == (Object)null)
		{
			ClearPendingVisual();
			HuntsmanLootPlugin.Log.LogWarning((object)"[HuntsmanLoot] EnemyHealth null — drop abortado.");
			return;
		}
		int num = (int)HuntsmanLootPlugin._hpCurrentField.GetValue(val2);
		HuntsmanLootPlugin.DebugLog($"[HuntsmanLoot] HP ao despawnar: {num}");
		if (num > 0)
		{
			HuntsmanLootPlugin.DebugLog("[HuntsmanLoot] HP > 0 — despawn normal. Sem drop.");
			return;
		}
		int num2 = Random.Range(1, 101);
		if (num2 > HuntsmanLootPlugin.DropChance.Value)
		{
			ClearPendingVisual();
			HuntsmanLootPlugin.DebugLog($"[HuntsmanLoot] Chance falhou (roll={num2} > {HuntsmanLootPlugin.DropChance.Value}%) — sem drop.");
			return;
		}
		HuntsmanLootPlugin.Log.LogInfo((object)$"[HuntsmanLoot] Morte confirmada! roll={num2} — iniciando drop.");
		if (HuntsmanLootPlugin.BerserkerOnly.Value)
		{
			AttemptBerserkerDrop(val);
		}
		else
		{
			DropRifle(val);
		}
	}

	private static void AttemptBerserkerDrop(Enemy enemy)
	{
		Assembly assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault((Assembly a) => a.GetName().Name == "BerserkerEnemies");
		if (assembly == null)
		{
			HuntsmanLootPlugin.Log.LogWarning((object)"[HuntsmanLoot] BerserkerOnly=true mas BerserkerEnemies nao detectado — dropando mesmo assim.");
			DropRifle(enemy);
			return;
		}
		Type type = assembly.GetType("BerserkerController");
		if (type == null)
		{
			HuntsmanLootPlugin.Log.LogWarning((object)"[HuntsmanLoot] BerserkerController nao encontrado.");
			ClearPendingVisual();
			return;
		}
		Component componentInParent = ((Component)enemy).GetComponentInParent(type);
		if ((Object)(object)componentInParent == (Object)null)
		{
			ClearPendingVisual();
			return;
		}
		object obj = type.GetField("isBerserkerFlag")?.GetValue(componentInParent);
		bool flag = default(bool);
		int num;
		if (obj is bool)
		{
			flag = (bool)obj;
			num = 1;
		}
		else
		{
			num = 0;
		}
		if (((uint)num & (flag ? 1u : 0u)) != 0)
		{
			DropRifle(enemy);
		}
		else
		{
			ClearPendingVisual();
		}
	}

	private static void DropRifle(Enemy enemy)
	{
		//IL_0030: 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_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_0049: Unknown result type (might be due to invalid IL or missing references)
		//IL_0099: 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_007b: 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)
		Transform val = enemy.CustomValuableSpawnTransform ?? enemy.CenterTransform;
		if ((Object)(object)val == (Object)null)
		{
			ClearPendingVisual();
			HuntsmanLootPlugin.Log.LogError((object)"[HuntsmanLoot] Posicao de spawn invalida — drop abortado.");
			return;
		}
		Vector3 val2 = val.position + Vector3.up * 0.3f;
		GameObject val4;
		if (!SemiFunc.IsMultiplayer())
		{
			GameObject val3 = Resources.Load<GameObject>("Items/Item Gun Shotgun");
			if ((Object)(object)val3 == (Object)null)
			{
				ClearPendingVisual();
				HuntsmanLootPlugin.Log.LogError((object)"[HuntsmanLoot] Resources.Load falhou para 'Items/Item Gun Shotgun'.");
				return;
			}
			val4 = Object.Instantiate<GameObject>(val3, val2, Quaternion.identity);
			HuntsmanLootPlugin.DebugLog("[HuntsmanLoot] Arma spawnada (singleplayer).");
		}
		else
		{
			try
			{
				val4 = PhotonNetwork.InstantiateRoomObject("Items/Item Gun Shotgun", val2, Quaternion.identity, (byte)0, (object[])null);
			}
			catch (Exception ex)
			{
				ClearPendingVisual();
				HuntsmanLootPlugin.Log.LogError((object)("[HuntsmanLoot] InstantiateRoomObject excecao: " + ex.Message));
				return;
			}
			if ((Object)(object)val4 == (Object)null)
			{
				ClearPendingVisual();
				HuntsmanLootPlugin.Log.LogError((object)"[HuntsmanLoot] InstantiateRoomObject retornou null.");
				return;
			}
			HuntsmanLootPlugin.DebugLog("[HuntsmanLoot] Arma spawnada (multiplayer).");
		}
		ClearPendingVisual();
		HuntsmanLootPlugin.DebugLog("[HuntsmanLoot] Customizer START");
		try
		{
			HuntsmanRifleCustomizer.Apply(val4, ((Component)enemy).gameObject, HuntsmanLootPlugin.Log);
			HuntsmanLootPlugin.DebugLog("[HuntsmanLoot] Customizer DONE");
		}
		catch (Exception ex2)
		{
			HuntsmanLootPlugin.Log.LogError((object)("[HuntsmanLoot] Customizer ERROR: " + ex2.Message));
		}
		try
		{
			HuntsmanLootPlugin.ApplyAmmoSync(val4);
		}
		catch (Exception ex3)
		{
			HuntsmanLootPlugin.Log.LogError((object)("[HuntsmanLoot] ApplyAmmo ERROR: " + ex3.Message));
		}
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(Debug), "LogWarning", new Type[] { typeof(object) })]
	private static bool SuppressGunHunterWarning(object message)
	{
		if (message is string text && text.Contains("Gun Hunter") && text.Contains("not found in the itemDictionary"))
		{
			return false;
		}
		return true;
	}
}
internal static class HuntsmanRifleCustomizer
{
	private struct CollisionEnvelopeResult
	{
		internal bool Created;

		internal bool AttachedRigidbody;

		internal Vector3 Center;

		internal Vector3 Size;

		internal string Reason;

		internal static CollisionEnvelopeResult Success(bool attachedRigidbody, Vector3 center, Vector3 size)
		{
			//IL_001a: 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_0022: 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)
			return new CollisionEnvelopeResult
			{
				Created = true,
				AttachedRigidbody = attachedRigidbody,
				Center = center,
				Size = size,
				Reason = "created"
			};
		}

		internal static CollisionEnvelopeResult Skip(string reason)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: 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)
			return new CollisionEnvelopeResult
			{
				Created = false,
				AttachedRigidbody = false,
				Center = Vector3.zero,
				Size = Vector3.zero,
				Reason = reason
			};
		}
	}

	private static class NativeHunterGunVisualResolver
	{
		internal sealed class ResolveResult
		{
			internal Mesh Mesh;

			internal Material[] Materials;
		}

		internal sealed class VisualAttachResult
		{
			internal bool Pass;

			internal string Reason;

			internal GameObject Root;

			internal static VisualAttachResult Success(GameObject root)
			{
				return new VisualAttachResult
				{
					Pass = true,
					Reason = "mesh-renderer",
					Root = root
				};
			}

			internal static VisualAttachResult Fail(string reason)
			{
				return new VisualAttachResult
				{
					Pass = false,
					Reason = reason
				};
			}
		}

		private const string NativeMeshName = "Hunter Gun";

		private const string NativeMaterialName = "Enemy Hunter";

		internal static ResolveResult Resolve(GameObject sourceEnemy, ManualLogSource log)
		{
			ResolveResult resolveResult = new ResolveResult();
			TryResolveFromGameObject(sourceEnemy, resolveResult);
			if ((Object)(object)resolveResult.Mesh == (Object)null)
			{
				resolveResult.Mesh = FindNativeMesh();
			}
			if ((Object)(object)resolveResult.Mesh == (Object)null)
			{
				return resolveResult;
			}
			log.LogInfo((object)$"[HuntsmanLoot] Native Hunter Gun mesh found: name={((Object)resolveResult.Mesh).name} vertices={resolveResult.Mesh.vertexCount}");
			return resolveResult;
		}

		internal static Material[] CreateNativeCloneMaterials(Mesh mesh, ManualLogSource log)
		{
			Material[] array = FindNativeMaterials();
			if (HasAnyMaterial(array))
			{
				Material[] array2 = CloneMaterialsForMesh(mesh, array);
				NeutralizeProblematicTint(array2);
				log.LogInfo((object)"[HuntsmanLoot] Visual material mode: native-clone");
				return array2;
			}
			log.LogWarning((object)"[HuntsmanLoot] Native material unavailable — using fallback-neutral.");
			Material[] result = CreateFallbackNeutralMaterials(mesh, log);
			log.LogInfo((object)"[HuntsmanLoot] Visual material mode: fallback-neutral");
			return result;
		}

		private static Material[] CloneMaterialsForMesh(Mesh mesh, Material[] nativeMaterials)
		{
			//IL_0033: 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_004f: Expected O, but got Unknown
			Material[] array = (Material[])(object)new Material[Mathf.Max(1, (!((Object)(object)mesh != (Object)null)) ? 1 : mesh.subMeshCount)];
			for (int i = 0; i < array.Length; i++)
			{
				Material val = nativeMaterials[Mathf.Min(i, nativeMaterials.Length - 1)];
				array[i] = new Material(val)
				{
					name = $"HuntsmanLoot_NativeHunterGunClone_{i}"
				};
			}
			return array;
		}

		private static void NeutralizeProblematicTint(Material[] materials)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			if (materials == null)
			{
				return;
			}
			foreach (Material val in materials)
			{
				if (!((Object)(object)val == (Object)null))
				{
					if (val.HasProperty("_EmissionColor"))
					{
						val.SetColor("_EmissionColor", Color.black);
					}
					if (val.HasProperty("_Color"))
					{
						NeutralizeRedColor(val, "_Color");
					}
					if (val.HasProperty("_BaseColor"))
					{
						NeutralizeRedColor(val, "_BaseColor");
					}
					val.DisableKeyword("_EMISSION");
					val.globalIlluminationFlags = (MaterialGlobalIlluminationFlags)4;
				}
			}
		}

		private static void NeutralizeRedColor(Material material, string property)
		{
			//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_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: 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)
			Color color = material.GetColor(property);
			if (IsStrongRedTint(color))
			{
				material.SetColor(property, new Color(0.62f, 0.58f, 0.49f, color.a));
			}
		}

		private static bool IsStrongRedTint(Color color)
		{
			//IL_0000: 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_0013: 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_0027: Unknown result type (might be due to invalid IL or missing references)
			if (color.r > 0.65f && color.r > color.g * 1.6f)
			{
				return color.r > color.b * 1.6f;
			}
			return false;
		}

		private static Material[] CreateFallbackNeutralMaterials(Mesh mesh, ManualLogSource log)
		{
			//IL_0071: 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_008d: Expected O, but got Unknown
			//IL_00c0: 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_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: 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_010e: Unknown result type (might be due to invalid IL or missing references)
			Shader val = Shader.Find("Standard") ?? Shader.Find("Universal Render Pipeline/Lit") ?? Shader.Find("HDRP/Lit") ?? Shader.Find("Diffuse");
			if ((Object)(object)val == (Object)null)
			{
				log.LogError((object)"[HuntsmanLoot] Runtime neutral material failed: no compatible shader found");
				return null;
			}
			Material[] array = (Material[])(object)new Material[Mathf.Max(1, (!((Object)(object)mesh != (Object)null)) ? 1 : mesh.subMeshCount)];
			for (int i = 0; i < array.Length; i++)
			{
				Material val2 = new Material(val)
				{
					name = $"HuntsmanLoot_FallbackHunterGunNeutral_{i}"
				};
				Color val3 = ((i == 1) ? new Color(0.42f, 0.34f, 0.23f, 1f) : new Color(0.4f, 0.39f, 0.34f, 1f));
				if (val2.HasProperty("_Color"))
				{
					val2.SetColor("_Color", val3);
				}
				if (val2.HasProperty("_BaseColor"))
				{
					val2.SetColor("_BaseColor", val3);
				}
				if (val2.HasProperty("_EmissionColor"))
				{
					val2.SetColor("_EmissionColor", Color.black);
				}
				if (val2.HasProperty("_Metallic"))
				{
					val2.SetFloat("_Metallic", 0.15f);
				}
				if (val2.HasProperty("_Glossiness"))
				{
					val2.SetFloat("_Glossiness", 0.28f);
				}
				val2.DisableKeyword("_EMISSION");
				val2.globalIlluminationFlags = (MaterialGlobalIlluminationFlags)4;
				array[i] = val2;
			}
			return array;
		}

		internal static Material CreateFallbackMaterial(ManualLogSource log)
		{
			//IL_0057: 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_0067: 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_0087: Expected O, but got Unknown
			log.LogWarning((object)"[HuntsmanLoot] Native material not found — using runtime fallback material.");
			Shader val = Shader.Find("Standard") ?? Shader.Find("Diffuse") ?? Shader.Find("Universal Render Pipeline/Lit") ?? Shader.Find("HDRP/Lit");
			if ((Object)(object)val == (Object)null)
			{
				log.LogError((object)"[HuntsmanLoot] Runtime fallback material failed: no compatible shader found");
				return null;
			}
			return new Material(val)
			{
				name = "HuntsmanLoot_RuntimeHunterGunFallback",
				color = new Color(0.015f, 0.013f, 0.011f, 1f)
			};
		}

		private static Mesh FindNativeMesh()
		{
			Mesh[] array = Resources.FindObjectsOfTypeAll<Mesh>();
			foreach (Mesh val in array)
			{
				if (IsHunterGunMesh(val))
				{
					return val;
				}
			}
			GameObject[] array2 = Resources.FindObjectsOfTypeAll<GameObject>();
			foreach (GameObject val2 in array2)
			{
				if (!((Object)(object)val2 == (Object)null) && NameSuggestsHunterGunContainer(((Object)val2).name))
				{
					Mesh val3 = FindMeshInGameObject(val2);
					if ((Object)(object)val3 != (Object)null)
					{
						return val3;
					}
				}
			}
			return null;
		}

		private static Material[] FindNativeMaterials()
		{
			List<Material> list = new List<Material>();
			List<Material> list2 = new List<Material>();
			List<Material> list3 = new List<Material>();
			Material[] array = Resources.FindObjectsOfTypeAll<Material>();
			foreach (Material val in array)
			{
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				string text = CleanName(((Object)val).name);
				if (text == "Enemy Hunter")
				{
					if (IsInstanceName(((Object)val).name))
					{
						list2.Add(val);
					}
					else
					{
						list.Add(val);
					}
				}
				else if (text.IndexOf("Enemy Hunter", StringComparison.OrdinalIgnoreCase) >= 0 && text.IndexOf("Shoot", StringComparison.OrdinalIgnoreCase) < 0)
				{
					list3.Add(val);
				}
			}
			if (list.Count > 0)
			{
				return list.ToArray();
			}
			if (list2.Count > 0)
			{
				return list2.ToArray();
			}
			if (list3.Count > 0)
			{
				return list3.ToArray();
			}
			return null;
		}

		private static void TryResolveFromGameObject(GameObject source, ResolveResult result)
		{
			if ((Object)(object)source == (Object)null)
			{
				return;
			}
			MeshFilter[] componentsInChildren = source.GetComponentsInChildren<MeshFilter>(true);
			foreach (MeshFilter val in componentsInChildren)
			{
				if (!((Object)(object)val == (Object)null) && IsHunterGunMesh(val.sharedMesh))
				{
					result.Mesh = val.sharedMesh;
					MeshRenderer component = ((Component)val).GetComponent<MeshRenderer>();
					if ((Object)(object)component != (Object)null && HasAnyMaterial(((Renderer)component).sharedMaterials))
					{
						result.Materials = ((Renderer)component).sharedMaterials;
					}
					break;
				}
			}
		}

		private static Mesh FindMeshInGameObject(GameObject go)
		{
			MeshFilter[] componentsInChildren = go.GetComponentsInChildren<MeshFilter>(true);
			foreach (MeshFilter val in componentsInChildren)
			{
				if ((Object)(object)val != (Object)null && IsHunterGunMesh(val.sharedMesh))
				{
					return val.sharedMesh;
				}
			}
			return null;
		}

		private static bool IsHunterGunMesh(Mesh mesh)
		{
			if ((Object)(object)mesh != (Object)null && CleanName(((Object)mesh).name) == "Hunter Gun")
			{
				return mesh.vertexCount > 0;
			}
			return false;
		}

		private static bool NameSuggestsHunterGunContainer(string name)
		{
			if (string.IsNullOrEmpty(name))
			{
				return false;
			}
			if (name.IndexOf("Enemy - Hunter", StringComparison.OrdinalIgnoreCase) < 0 && name.IndexOf("ANIM GUN", StringComparison.OrdinalIgnoreCase) < 0)
			{
				return name.IndexOf("mesh gun", StringComparison.OrdinalIgnoreCase) >= 0;
			}
			return true;
		}

		private static string CleanName(string name)
		{
			if (string.IsNullOrEmpty(name))
			{
				return string.Empty;
			}
			if (!name.EndsWith(" (Instance)", StringComparison.Ordinal))
			{
				return name;
			}
			return name.Substring(0, name.Length - " (Instance)".Length);
		}

		private static bool IsInstanceName(string name)
		{
			if (!string.IsNullOrEmpty(name))
			{
				return name.EndsWith(" (Instance)", StringComparison.Ordinal);
			}
			return false;
		}

		private static string FormatMaterialNames(Material[] materials)
		{
			List<string> list = new List<string>();
			foreach (Material val in materials)
			{
				if (!((Object)(object)val == (Object)null))
				{
					list.Add(((Object)val).name);
				}
			}
			if (list.Count <= 0)
			{
				return "none";
			}
			return string.Join(",", list.ToArray());
		}
	}

	private sealed class VisualValidationResult
	{
		internal bool Pass;

		internal string Reason;

		internal static VisualValidationResult Success(string reason)
		{
			return new VisualValidationResult
			{
				Pass = true,
				Reason = reason
			};
		}

		internal static VisualValidationResult Fail(string reason)
		{
			return new VisualValidationResult
			{
				Pass = false,
				Reason = reason
			};
		}
	}

	private static readonly string[] _preserveKeywords = new string[7] { "battery", "ammo", "bar", "ui", "icon", "screen", "text" };

	private static readonly Vector3 NativeGunLocalPosition = new Vector3(0f, 0f, 0f);

	private static readonly Vector3 NativeGunLocalEuler = new Vector3(-8f, 180f, 90f);

	private static readonly Vector3 NativeGunLocalScale = new Vector3(0.75f, 0.75f, 0.75f);

	private const string NativeCollisionEnvelopeName = "HuntsmanNativeGunCollisionEnvelope";

	private const float CollisionLengthScale = 1.08f;

	private const float CollisionWidthScale = 1.05f;

	private const float CollisionThicknessScale = 1.1f;

	private const float CollisionMinThickness = 0.04f;

	private const string DisplayName = "Huntsman Rifle";

	private const float IconFramingPadding = 1.16f;

	private const float IconCameraDistanceMultiplier = 2.5f;

	private const float IconCameraMinDistance = 1.25f;

	private static bool _generatedIconCacheCleared;

	internal static void Apply(GameObject spawned, GameObject sourceEnemy, ManualLogSource log)
	{
		if ((Object)(object)spawned == (Object)null)
		{
			return;
		}
		NativeHunterGunVisualResolver.VisualAttachResult visualAttachResult = null;
		try
		{
			visualAttachResult = AttachNativeWeaponVisual(spawned, sourceEnemy, log);
		}
		catch (Exception ex)
		{
			log.LogError((object)("[HuntsmanLoot] Customizer/NativeMesh: " + ex.Message));
			log.LogInfo((object)"[HuntsmanLoot] Native Hunter Gun visual created: FAIL reason=exception");
			visualAttachResult = NativeHunterGunVisualResolver.VisualAttachResult.Fail("exception");
		}
		if (visualAttachResult == null || !visualAttachResult.Pass)
		{
			if (visualAttachResult == null || visualAttachResult.Reason == "mesh-not-found")
			{
				log.LogWarning((object)"[HuntsmanLoot] Native Hunter Gun mesh not found — keeping native shotgun visible");
			}
			else
			{
				log.LogWarning((object)("[HuntsmanLoot] Keeping native shotgun visible because native visual failed: " + visualAttachResult.Reason));
			}
			HuntsmanLootPlugin.DebugLog("[HuntsmanLoot] Original shotgun renderers hidden: 0");
		}
		else
		{
			try
			{
				HideOriginalRenderers(spawned, visualAttachResult.Root, log);
			}
			catch (Exception ex2)
			{
				log.LogError((object)("[HuntsmanLoot] Customizer/Hide: " + ex2.Message));
			}
		}
		try
		{
			ApplyIdentity(spawned, log);
		}
		catch (Exception ex3)
		{
			log.LogError((object)("[HuntsmanLoot] Customizer/Identity: " + ex3.Message));
		}
	}

	private static NativeHunterGunVisualResolver.VisualAttachResult AttachNativeWeaponVisual(GameObject spawned, GameObject sourceEnemy, ManualLogSource log)
	{
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0062: Expected O, but got Unknown
		//IL_007a: 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_00b8: 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_011b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0136: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d7: Unknown result type (might be due to invalid IL or missing references)
		NativeHunterGunVisualResolver.ResolveResult resolveResult = NativeHunterGunVisualResolver.Resolve(sourceEnemy, log);
		if ((Object)(object)resolveResult.Mesh == (Object)null)
		{
			log.LogInfo((object)"[HuntsmanLoot] Native Hunter Gun visual created: FAIL reason=mesh-not-found");
			return NativeHunterGunVisualResolver.VisualAttachResult.Fail("mesh-not-found");
		}
		Material[] array = NativeHunterGunVisualResolver.CreateNativeCloneMaterials(resolveResult.Mesh, log);
		if (!HasAnyMaterial(array))
		{
			log.LogInfo((object)"[HuntsmanLoot] Native Hunter Gun visual created: FAIL reason=material-not-found");
			return NativeHunterGunVisualResolver.VisualAttachResult.Fail("material-not-found");
		}
		GameObject val = new GameObject("HuntsmanNativeGunVisualRoot");
		val.transform.SetParent(spawned.transform, false);
		val.transform.localPosition = NativeGunLocalPosition;
		val.transform.localRotation = Quaternion.Euler(NativeGunLocalEuler.x, NativeGunLocalEuler.y, NativeGunLocalEuler.z);
		val.transform.localScale = NativeGunLocalScale;
		MeshFilter obj = val.AddComponent<MeshFilter>();
		MeshRenderer val2 = val.AddComponent<MeshRenderer>();
		obj.sharedMesh = resolveResult.Mesh;
		((Renderer)val2).sharedMaterials = array;
		((Renderer)val2).enabled = true;
		val.SetActive(true);
		log.LogInfo((object)("[HuntsmanLoot] Native visual transform: pos=" + FormatVector(val.transform.localPosition) + " euler=" + FormatVector(NativeGunLocalEuler) + " scale=" + FormatVector(val.transform.localScale)));
		VisualValidationResult visualValidationResult = HasRenderableVisual(val);
		log.LogInfo((object)("[HuntsmanLoot] Native Hunter Gun visual created: " + (visualValidationResult.Pass ? "PASS" : "FAIL") + " reason=" + visualValidationResult.Reason));
		if (!visualValidationResult.Pass)
		{
			Object.Destroy((Object)(object)val);
			return NativeHunterGunVisualResolver.VisualAttachResult.Fail(visualValidationResult.Reason);
		}
		CollisionEnvelopeResult collisionEnvelopeResult = CreateNativeCollisionEnvelope(val, spawned, resolveResult.Mesh, log);
		if (collisionEnvelopeResult.Created)
		{
			log.LogInfo((object)("[HuntsmanLoot] Native collision envelope created: attachedRigidbody=" + collisionEnvelopeResult.AttachedRigidbody.ToString().ToLowerInvariant() + " size=" + FormatVector(collisionEnvelopeResult.Size)));
		}
		else
		{
			log.LogWarning((object)("[HuntsmanLoot] Native collision envelope skipped: reason=" + collisionEnvelopeResult.Reason));
		}
		ConfigureNativeIconCamera(spawned, val, log);
		return NativeHunterGunVisualResolver.VisualAttachResult.Success(val);
	}

	private static bool HasValidRenderer(GameObject go)
	{
		MeshRenderer[] componentsInChildren = go.GetComponentsInChildren<MeshRenderer>(true);
		for (int i = 0; i < componentsInChildren.Length; i++)
		{
			MeshFilter component = ((Component)componentsInChildren[i]).GetComponent<MeshFilter>();
			if ((Object)(object)component != (Object)null && (Object)(object)component.sharedMesh != (Object)null)
			{
				return true;
			}
		}
		SkinnedMeshRenderer[] componentsInChildren2 = go.GetComponentsInChildren<SkinnedMeshRenderer>(true);
		for (int i = 0; i < componentsInChildren2.Length; i++)
		{
			if ((Object)(object)componentsInChildren2[i].sharedMesh != (Object)null)
			{
				return true;
			}
		}
		return false;
	}

	private static void HideOriginalRenderers(GameObject spawned, GameObject protectedVisualRoot, ManualLogSource log)
	{
		int num = 0;
		int num2 = 0;
		MeshRenderer[] componentsInChildren = spawned.GetComponentsInChildren<MeshRenderer>(true);
		foreach (MeshRenderer val in componentsInChildren)
		{
			if (IsProtectedVisual(((Component)val).transform, protectedVisualRoot) || ShouldPreserve(((Component)val).transform))
			{
				num2++;
				continue;
			}
			((Renderer)val).enabled = false;
			num++;
		}
		SkinnedMeshRenderer[] componentsInChildren2 = spawned.GetComponentsInChildren<SkinnedMeshRenderer>(true);
		foreach (SkinnedMeshRenderer val2 in componentsInChildren2)
		{
			if (IsProtectedVisual(((Component)val2).transform, protectedVisualRoot) || ShouldPreserve(((Component)val2).transform))
			{
				num2++;
				continue;
			}
			((Renderer)val2).enabled = false;
			num++;
		}
		HuntsmanLootPlugin.DebugLog($"[HuntsmanLoot] Original shotgun renderers hidden: {num}");
		HuntsmanLootPlugin.DebugLog($"[HuntsmanLoot] Original shotgun renderers preserved: {num2}");
	}

	private static bool IsProtectedVisual(Transform t, GameObject protectedVisualRoot)
	{
		if ((Object)(object)protectedVisualRoot != (Object)null && (Object)(object)t != (Object)null)
		{
			return t.IsChildOf(protectedVisualRoot.transform);
		}
		return false;
	}

	private static bool ShouldPreserve(Transform t)
	{
		Transform val = t;
		while ((Object)(object)val != (Object)null)
		{
			string text = ((Object)val).name.ToLowerInvariant();
			string[] preserveKeywords = _preserveKeywords;
			foreach (string value in preserveKeywords)
			{
				if (text.Contains(value))
				{
					return true;
				}
			}
			val = val.parent;
		}
		return false;
	}

	private static void ConfigureNativeIconCamera(GameObject spawned, GameObject visualRoot, ManualLogSource log)
	{
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_007b: Unknown result type (might be due to invalid IL or missing references)
		//IL_008b: 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_0094: Unknown result type (might be due to invalid IL or missing references)
		//IL_0099: Unknown result type (might be due to invalid IL or missing references)
		//IL_009b: 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_009f: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a4: 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_00ad: 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_00cf: 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_00da: Unknown result type (might be due to invalid IL or missing references)
		//IL_00df: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e3: 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_00cb: 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_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_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_0166: Unknown result type (might be due to invalid IL or missing references)
		//IL_016e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0170: Unknown result type (might be due to invalid IL or missing references)
		//IL_0175: Unknown result type (might be due to invalid IL or missing references)
		//IL_0179: Unknown result type (might be due to invalid IL or missing references)
		//IL_017e: 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_0188: Unknown result type (might be due to invalid IL or missing references)
		//IL_018d: 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_0196: 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_01a4: 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_01e4: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e9: 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_020b: Unknown result type (might be due to invalid IL or missing references)
		//IL_020f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0214: Unknown result type (might be due to invalid IL or missing references)
		//IL_0224: Unknown result type (might be due to invalid IL or missing references)
		//IL_0226: Unknown result type (might be due to invalid IL or missing references)
		//IL_0228: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f8: 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_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)
		try
		{
			SemiIconMaker componentInChildren = spawned.GetComponentInChildren<SemiIconMaker>(true);
			if ((Object)(object)componentInChildren == (Object)null)
			{
				HuntsmanLootPlugin.DebugLog("[HuntsmanLoot] Inventory icon framing skipped: reason=SemiIconMaker not found");
				return;
			}
			Camera val = componentInChildren.iconCamera ?? ((Component)componentInChildren).GetComponentInChildren<Camera>(true);
			if ((Object)(object)val == (Object)null)
			{
				HuntsmanLootPlugin.DebugLog("[HuntsmanLoot] Inventory icon framing skipped: reason=icon camera not found");
				return;
			}
			if (!TryGetLocalRendererBounds(spawned.transform, visualRoot, out var bounds, out var corners))
			{
				HuntsmanLootPlugin.DebugLog("[HuntsmanLoot] Inventory icon framing skipped: reason=visual bounds unavailable");
				return;
			}
			int num = LongestAxis(((Bounds)(ref bounds)).size);
			int num2 = SmallestAxis(((Bounds)(ref bounds)).size, num);
			Vector3 val2 = AxisVector(num);
			Vector3 val3 = AxisVector(num2);
			Vector3 val4 = Vector3.Cross(val3, val2);
			Vector3 val5 = ((Vector3)(ref val4)).normalized;
			if (((Vector3)(ref val5)).sqrMagnitude < 0.0001f)
			{
				val5 = AxisVector(NextAxis(num, num2));
			}
			val4 = Vector3.Cross(val5, val3);
			Vector3 val6 = ((Vector3)(ref val4)).normalized;
			if (Vector3.Dot(val6, val2) < 0f)
			{
				val6 = -val6;
				val5 = -val5;
			}
			float num3 = ProjectSpan(corners, ((Bounds)(ref bounds)).center, val6);
			float num4 = ProjectSpan(corners, ((Bounds)(ref bounds)).center, val5);
			float iconCameraAspect = GetIconCameraAspect(componentInChildren, val);
			float orthographicSize = Mathf.Max(Mathf.Max(num4 * 0.5f, num3 / (2f * iconCameraAspect)) * 1.16f, 0.05f);
			Vector3 val7 = spawned.transform.TransformPoint(((Bounds)(ref bounds)).center);
			val4 = spawned.transform.TransformDirection(val3);
			Vector3 normalized = ((Vector3)(ref val4)).normalized;
			val4 = spawned.transform.TransformDirection(val5);
			Vector3 val8 = -((Vector3)(ref val4)).normalized;
			val4 = ((Bounds)(ref bounds)).size;
			float num5 = Mathf.Max(1.25f, ((Vector3)(ref val4)).magnitude * 2.5f);
			val.orthographic = true;
			val.orthographicSize = orthographicSize;
			val.nearClipPlane = 0.01f;
			float farClipPlane = val.farClipPlane;
			val4 = ((Bounds)(ref bounds)).size;
			val.farClipPlane = Mathf.Max(farClipPlane, num5 + ((Vector3)(ref val4)).magnitude * 3f);
			((Component)val).transform.position = val7 - normalized * num5;
			((Component)val).transform.rotation = Quaternion.LookRotation(normalized, val8);
			componentInChildren.iconCamera = val;
			componentInChildren.iconCameraPlacementDone = true;
			HuntsmanLootPlugin.DebugLog("[HuntsmanLoot] Inventory icon framing adjusted: " + string.Format("lengthAxis={0} viewAxis={1} ortho={2}", num, num2, orthographicSize.ToString("0.###", CultureInfo.InvariantCulture)));
		}
		catch (Exception ex)
		{
			HuntsmanLootPlugin.DebugWarning("[HuntsmanLoot] Inventory icon framing failed: " + ex.Message);
		}
	}

	private static bool TryGetLocalRendererBounds(Transform itemRoot, GameObject visualRoot, out Bounds bounds, out Vector3[] corners)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0069: Unknown result type (might be due to invalid IL or missing references)
		//IL_006e: Unknown result type (might be due to invalid IL or missing references)
		//IL_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_0047: 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_00a2: 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_00c0: 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)
		bounds = default(Bounds);
		corners = null;
		if ((Object)(object)itemRoot == (Object)null || (Object)(object)visualRoot == (Object)null)
		{
			return false;
		}
		List<Vector3> list = new List<Vector3>();
		Renderer[] componentsInChildren = visualRoot.GetComponentsInChildren<Renderer>(true);
		foreach (Renderer val in componentsInChildren)
		{
			if (!((Object)(object)val == (Object)null) && val.enabled)
			{
				AddLocalBoundsCorners(itemRoot, val.bounds, list);
			}
		}
		if (list.Count == 0)
		{
			return false;
		}
		bounds = new Bounds(list[0], Vector3.zero);
		for (int j = 1; j < list.Count; j++)
		{
			((Bounds)(ref bounds)).Encapsulate(list[j]);
		}
		corners = BoundsCorners(bounds);
		if (((Bounds)(ref bounds)).size.x > 0f && ((Bounds)(ref bounds)).size.y > 0f)
		{
			return ((Bounds)(ref bounds)).size.z > 0f;
		}
		return false;
	}

	private static void AddLocalBoundsCorners(Transform itemRoot, Bounds worldBounds, List<Vector3> points)
	{
		//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_0035: 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_0041: 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_004c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0058: Unknown result type (might be due to invalid IL or missing references)
		//IL_005e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0064: 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_007b: 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_0087: Unknown result type (might be due to invalid IL or missing references)
		//IL_008d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0092: Unknown result type (might be due to invalid IL or missing references)
		//IL_009e: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a4: 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_00b0: 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_00c1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cd: 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_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)
		//IL_0107: 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_0119: 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)
		Vector3 min = ((Bounds)(ref worldBounds)).min;
		Vector3 max = ((Bounds)(ref worldBounds)).max;
		points.Add(itemRoot.InverseTransformPoint(new Vector3(min.x, min.y, min.z)));
		points.Add(itemRoot.InverseTransformPoint(new Vector3(min.x, min.y, max.z)));
		points.Add(itemRoot.InverseTransformPoint(new Vector3(min.x, max.y, min.z)));
		points.Add(itemRoot.InverseTransformPoint(new Vector3(min.x, max.y, max.z)));
		points.Add(itemRoot.InverseTransformPoint(new Vector3(max.x, min.y, min.z)));
		points.Add(itemRoot.InverseTransformPoint(new Vector3(max.x, min.y, max.z)));
		points.Add(itemRoot.InverseTransformPoint(new Vector3(max.x, max.y, min.z)));
		points.Add(itemRoot.InverseTransformPoint(new Vector3(max.x, max.y, max.z)));
	}

	private static Vector3[] BoundsCorners(Bounds bounds)
	{
		//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_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_002a: 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_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_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_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_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_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_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_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_00a2: 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_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_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_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_00de: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e3: 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_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)
		Vector3 min = ((Bounds)(ref bounds)).min;
		Vector3 max = ((Bounds)(ref bounds)).max;
		return (Vector3[])(object)new Vector3[8]
		{
			new Vector3(min.x, min.y, min.z),
			new Vector3(min.x, min.y, max.z),
			new Vector3(min.x, max.y, min.z),
			new Vector3(min.x, max.y, max.z),
			new Vector3(max.x, min.y, min.z),
			new Vector3(max.x, min.y, max.z),
			new Vector3(max.x, max.y, min.z),
			new Vector3(max.x, max.y, max.z)
		};
	}

	private static float ProjectSpan(Vector3[] points, Vector3 center, Vector3 axis)
	{
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		float num = float.MaxValue;
		float num2 = float.MinValue;
		for (int i = 0; i < points.Length; i++)
		{
			float num3 = Vector3.Dot(points[i] - center, axis);
			if (num3 < num)
			{
				num = num3;
			}
			if (num3 > num2)
			{
				num2 = num3;
			}
		}
		return Mathf.Max(0.01f, num2 - num);
	}

	private static float GetIconCameraAspect(SemiIconMaker iconMaker, Camera camera)
	{
		if ((Object)(object)iconMaker != (Object)null && (Object)(object)iconMaker.renderTexture != (Object)null && ((Texture)iconMaker.renderTexture).height > 0)
		{
			return Mathf.Max(0.01f, (float)((Texture)iconMaker.renderTexture).width / (float)((Texture)iconMaker.renderTexture).height);
		}
		if (!((Object)(object)camera != (Object)null) || !(camera.aspect > 0f))
		{
			return 1f;
		}
		return camera.aspect;
	}

	private static Vector3 AxisVector(int axis)
	{
		//IL_0009: 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_0015: Unknown result type (might be due to invalid IL or missing references)
		return (Vector3)(axis switch
		{
			0 => Vector3.right, 
			1 => Vector3.up, 
			_ => Vector3.forward, 
		});
	}

	private static int NextAxis(int first, int second)
	{
		for (int i = 0; i < 3; i++)
		{
			if (i != first && i != second)
			{
				return i;
			}
		}
		return 1;
	}

	private static VisualValidationResult HasRenderableVisual(GameObject root)
	{
		MeshRenderer[] componentsInChildren = root.GetComponentsInChildren<MeshRenderer>(true);
		foreach (MeshRenderer val in componentsInChildren)
		{
			MeshFilter component = ((Component)val).GetComponent<MeshFilter>();
			if (((Renderer)val).enabled && ((Component)val).gameObject.activeInHierarchy && (Object)(object)component != (Object)null && (Object)(object)component.sharedMesh != (Object)null && component.sharedMesh.vertexCount > 0 && HasAnyMaterial(((Renderer)val).sharedMaterials))
			{
				return VisualValidationResult.Success("mesh-renderer");
			}
		}
		SkinnedMeshRenderer[] componentsInChildren2 = root.GetComponentsInChildren<SkinnedMeshRenderer>(true);
		foreach (SkinnedMeshRenderer val2 in componentsInChildren2)
		{
			if (((Renderer)val2).enabled && ((Component)val2).gameObject.activeInHierarchy && (Object)(object)val2.sharedMesh != (Object)null && val2.sharedMesh.vertexCount > 0 && HasAnyMaterial(((Renderer)val2).sharedMaterials))
			{
				return VisualValidationResult.Success("skinned-mesh-renderer");
			}
		}
		return VisualValidationResult.Fail("no-enabled-renderer-with-mesh-and-material");
	}

	private static CollisionEnvelopeResult CreateNativeCollisionEnvelope(GameObject visualRoot, GameObject spawned, Mesh mesh, ManualLogSource log)
	{
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_0045: 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_006b: 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_009b: Expected O, but got Unknown
		//IL_00b3: 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_00d3: Unknown result type (might be due to invalid IL or missing references)
		//IL_0118: Unknown result type (might be due to invalid IL or missing references)
		//IL_0126: Unknown result type (might be due to invalid IL or missing references)
		//IL_0136: Unknown result type (might be due to invalid IL or missing references)
		//IL_013f: 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_0154: 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_019c: 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_01cc: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)visualRoot == (Object)null)
		{
			return CollisionEnvelopeResult.Skip("visual-root-null");
		}
		if ((Object)(object)spawned == (Object)null)
		{
			return CollisionEnvelopeResult.Skip("spawned-null");
		}
		if ((Object)(object)mesh == (Object)null)
		{
			return CollisionEnvelopeResult.Skip("mesh-null");
		}
		Bounds bounds = mesh.bounds;
		if (((Bounds)(ref bounds)).size.x <= 0f || ((Bounds)(ref bounds)).size.y <= 0f || ((Bounds)(ref bounds)).size.z <= 0f)
		{
			return CollisionEnvelopeResult.Skip("invalid-mesh-bounds");
		}
		try
		{
			Collider val = FindNativeSourceCollider(spawned, visualRoot);
			GameObject val2 = new GameObject("HuntsmanNativeGunCollisionEnvelope");
			val2.transform.SetParent(visualRoot.transform, false);
			val2.transform.localPosition = Vector3.zero;
			val2.transform.localRotation = Quaternion.identity;
			val2.transform.localScale = Vector3.one;
			CopyCollisionIdentity(val2, val, spawned);
			BoxCollider val3 = val2.AddComponent<BoxCollider>();
			((Collider)val3).isTrigger = false;
			if ((Object)(object)val != (Object)null && (Object)(object)val.sharedMaterial != (Object)null)
			{
				((Collider)val3).sharedMaterial = val.sharedMaterial;
			}
			int num = LongestAxis(((Bounds)(ref bounds)).size);
			int num2 = SmallestAxis(((Bounds)(ref bounds)).size, num);
			Vector3 size = ExpandEnvelopeSize(((Bounds)(ref bounds)).size, num, num2);
			val3.center = ((Bounds)(ref bounds)).center;
			val3.size = size;
			bool flag = (Object)(object)((Collider)val3).attachedRigidbody != (Object)null;
			if (!flag)
			{
				Object.Destroy((Object)(object)val2);
				return CollisionEnvelopeResult.Skip("attached-rigidbody-null");
			}
			HuntsmanLootPlugin.DebugLog("[HuntsmanLoot] Native collision envelope center=" + FormatVector(val3.center) + " " + $"size={FormatVector(val3.size)} lengthAxis={num} thicknessAxis={num2}");
			return CollisionEnvelopeResult.Success(flag, val3.center, val3.size);
		}
		catch (Exception ex)
		{
			return CollisionEnvelopeResult.Skip(ex.Message);
		}
	}

	private static int LongestAxis(Vector3 size)
	{
		//IL_0000: 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_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_000e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		if (size.x >= size.y && size.x >= size.z)
		{
			return 0;
		}
		if (size.y >= size.x && size.y >= size.z)
		{
			return 1;
		}
		return 2;
	}

	private static int SmallestAxis(Vector3 size, int excludedAxis)
	{
		int num = -1;
		for (int i = 0; i < 3; i++)
		{
			if (i != excludedAxis && (num < 0 || ((Vector3)(ref size))[i] < ((Vector3)(ref size))[num]))
			{
				num = i;
			}
		}
		if (num >= 0)
		{
			return num;
		}
		return 0;
	}

	private static Vector3 ExpandEnvelopeSize(Vector3 sourceSize, int lengthAxis, int thicknessAxis)
	{
		//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_0046: Unknown result type (might be due to invalid IL or missing references)
		Vector3 result = sourceSize;
		for (int i = 0; i < 3; i++)
		{
			float num = 1.05f;
			if (i == lengthAxis)
			{
				num = 1.08f;
			}
			else if (i == thicknessAxis)
			{
				num = 1.1f;
			}
			((Vector3)(ref result))[i] = Mathf.Max(((Vector3)(ref sourceSize))[i] * num, 0.04f);
		}
		return result;
	}

	private static Collider FindNativeSourceCollider(GameObject spawned, GameObject visualRoot)
	{
		if ((Object)(object)spawned == (Object)null)
		{
			return null;
		}
		Collider[] componentsInChildren = spawned.GetComponentsInChildren<Collider>(true);
		foreach (Collider val in componentsInChildren)
		{
			if (!((Object)(object)val == (Object)null) && (!((Object)(object)visualRoot != (Object)null) || !((Component)val).transform.IsChildOf(visualRoot.transform)))
			{
				return val;
			}
		}
		return null;
	}

	private static void CopyCollisionIdentity(GameObject envelope, Collider sourceCollider, GameObject spawned)
	{
		GameObject val = (((Object)(object)sourceCollider != (Object)null) ? ((Component)sourceCollider).gameObject : spawned);
		envelope.layer = val.layer;
		envelope.tag = val.tag;
	}

	private static bool HasAnyMaterial(Material[] materials)
	{
		if (materials == null || materials.Length == 0)
		{
			return false;
		}
		for (int i = 0; i < materials.Length; i++)
		{
			if ((Object)(object)materials[i] != (Object)null)
			{
				return true;
			}
		}
		return false;
	}

	private static string FormatVector(Vector3 value)
	{
		return "(" + value.x.ToString("0.###", CultureInfo.InvariantCulture) + "," + value.y.ToString("0.###", CultureInfo.InvariantCulture) + "," + value.z.ToString("0.###", CultureInfo.InvariantCulture) + ")";
	}

	private static string FormatQuaternion(Quaternion value)
	{
		//IL_000d: 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_0029: 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)
		return $"({value.x:0.###},{value.y:0.###},{value.z:0.###},{value.w:0.###})";
	}

	private static void ApplyIdentity(GameObject spawned, ManualLogSource log)
	{
		ItemAttributes componentInChildren = spawned.GetComponentInChildren<ItemAttributes>();
		if ((Object)(object)componentInChildren == (Object)null)
		{
			HuntsmanLootPlugin.DebugLog("[HuntsmanLoot] Inventory identity fields found: none");
			HuntsmanLootPlugin.DebugLog("[HuntsmanLoot] Inventory display name updated: fail field=ItemAttributes");
			HuntsmanLootPlugin.DebugLog("[HuntsmanLoot] Inventory icon update: fail reason=ItemAttributes not found");
			return;
		}
		List<string> list = new List<string>();
		List<string> list2 = new List<string>();
		TryRecordField(typeof(ItemAttributes), "itemName", list);
		TryRecordField(typeof(ItemAttributes), "promptName", list);
		TryRecordField(typeof(ItemAttributes), "instanceName", list);
		TryRecordField(typeof(ItemAttributes), "icon", list);
		TryRecordField(typeof(ItemAttributes), "hasIcon", list);
		TryRecordField(typeof(ItemAttributes), "item", list);
		if (TrySetStringField(componentInChildren, typeof(ItemAttributes), "itemName", "Huntsman Rifle"))
		{
			list2.Add("ItemAttributes.itemName");
		}
		if (TrySetStringField(componentInChildren, typeof(ItemAttributes), "promptName", "Huntsman Rifle"))
		{
			list2.Add("ItemAttributes.promptName");
		}
		if (TrySetStringField(componentInChildren, typeof(ItemAttributes), "instanceName", "Huntsman Rifle"))
		{
			list2.Add("ItemAttributes.instanceName");
		}
		((Object)((Component)componentInChildren).gameObject).name = "Huntsman Rifle";
		ItemEquippable itemEquippable = GetItemEquippable(componentInChildren, spawned);
		if ((Object)(object)itemEquippable != (Object)null)
		{
			TryRecordField(typeof(ItemEquippable), "ItemIcon", list);
			TryRecordField(typeof(ItemEquippable), "itemEmojiIcon", list);
			TryRecordField(typeof(ItemEquippable), "itemEmoji", list);
		}
		bool flag = ApplyInventoryIconOverride(componentInChildren, itemEquippable, log);
		try
		{
			FieldInfo fieldInfo = AccessTools.Field(typeof(ItemAttributes), "item");
			object? obj = fieldInfo?.GetValue(componentInChildren);
			Item val = (Item)((obj is Item) ? obj : null);
			if ((Object)(object)val != (Object)null)
			{
				Item val2 = Object.Instantiate<Item>(val);
				FieldInfo fieldInfo2 = AccessTools.Field(typeof(Item), "itemName") ?? AccessTools.Field(typeof(Item), "<itemName>k__BackingField");
				if (fieldInfo2 != null)
				{
					list.Add("Item.itemName");
					fieldInfo2.SetValue(val2, "Huntsman Rifle");
					list2.Add("Item.itemName");
				}
				FieldInfo fieldInfo3 = AccessTools.Field(typeof(Item), "itemNameLocalized");
				if (fieldInfo3 != null)
				{
					list.Add("Item.itemNameLocalized");
					fieldInfo3.SetValue(val2, null);
					list2.Add("Item.itemNameLocalized");
				}
				fieldInfo.SetValue(componentInChildren, val2);
			}
		}
		catch (Exception ex)
		{
			HuntsmanLootPlugin.DebugWarning("[HuntsmanLoot] Inventory item metadata clone failed: " + ex.Message);
		}
		HuntsmanLootPlugin.DebugLog("[HuntsmanLoot] Inventory identity fields found: " + ((list.Count > 0) ? string.Join(",", list.ToArray()) : "none"));
		if (list2.Count > 0)
		{
			HuntsmanLootPlugin.DebugLog("[HuntsmanLoot] Inventory display name updated: success field=" + string.Join(",", list2.ToArray()));
		}
		else
		{
			HuntsmanLootPlugin.DebugLog("[HuntsmanLoot] Inventory display name updated: fail field=none");
		}
		HuntsmanLootPlugin.DebugLog("[HuntsmanLoot] Inventory icon update: " + (flag ? "success" : "fail"));
	}

	private static bool ApplyInventoryIconOverride(ItemAttributes attr, ItemEquippable equippable, ManualLogSource log)
	{
		try
		{
			attr.icon = null;
			AccessTools.Field(typeof(ItemAttributes), "hasIcon")?.SetValue(attr, false);
			if ((Object)(object)equippable != (Object)null)
			{
				equippable.ItemIcon = null;
			}
			ClearGeneratedIconCacheOnce();
			HuntsmanLootPlugin.DebugLog("[HuntsmanLoot] Inventory icon override disabled; native item icon generation enabled.");
			return true;
		}
		catch (Exception ex)
		{
			HuntsmanLootPlugin.DebugWarning("[HuntsmanLoot] Inventory icon override failed: " + ex.Message);
			return false;
		}
	}

	private static void ClearGeneratedIconCacheOnce()
	{
		if (_generatedIconCacheCleared)
		{
			return;
		}
		_generatedIconCacheCleared = true;
		try
		{
			string text = Path.Combine(Application.persistentDataPath, "Cache", "Icons", "Items", "Huntsman Rifle".ToLowerInvariant() + ".png");
			if (File.Exists(text))
			{
				File.Delete(text);
				HuntsmanLootPlugin.DebugLog("[HuntsmanLoot] Inventory icon cache cleared: " + text);
			}
		}
		catch (Exception ex)
		{
			HuntsmanLootPlugin.DebugWarning("[HuntsmanLoot] Inventory icon cache clear failed: " + ex.Message);
		}
	}

	private static void TryRecordField(Type type, string fieldName, List<string> fields)
	{
		if (AccessTools.Field(type, fieldName) != null)
		{
			fields.Add(type.Name + "." + fieldName);
		}
	}

	private static bool TrySetStringField(object target, Type type, string fieldName, string value)
	{
		FieldInfo fieldInfo = AccessTools.Field(type, fieldName);
		if (fieldInfo == null || fieldInfo.FieldType != typeof(string))
		{
			return false;
		}
		try
		{
			fieldInfo.SetValue(target, value);
			return true;
		}
		catch
		{
			return false;
		}
	}

	private static ItemEquippable GetItemEquippable(ItemAttributes attr, GameObject spawned)
	{
		try
		{
			object? obj = AccessTools.Field(typeof(ItemAttributes), "itemEquippable")?.GetValue(attr);
			ItemEquippable val = (ItemEquippable)((obj is ItemEquippable) ? obj : null);
			if (val != null)
			{
				return val;
			}
		}
		catch
		{
		}
		return spawned.GetComponentInChildren<ItemEquippable>();
	}
}