Decompiled source of CW Climb Again v2.2.0

plugins/CW_MOD_LEGACY.dll

Decompiled 2 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyVersion("0.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace LegacyClimbAndWalls
{
	[BepInPlugin("com.custom.legacyclimbwalls", "Legacy Colliders", "2.2.0")]
	public sealed class LegacyClimbAndWallsPlugin : BaseUnityPlugin
	{
		public const string PluginGuid = "com.custom.legacyclimbwalls";

		public const string PluginName = "Legacy Colliders";

		public const string PluginVersion = "2.2.0";

		internal static ManualLogSource? ModLogger { get; private set; }

		internal static ConfigEntry<bool> EnabledConfig { get; private set; }

		internal static ConfigEntry<bool> VerboseLogging { get; private set; }

		private void Awake()
		{
			ModLogger = ((BaseUnityPlugin)this).Logger;
			EnabledConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Restaura automaticamente las colisiones originales (legacy) al cargar cada mapa.");
			VerboseLogging = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "VerboseLogging", false, "Registra en el log cada objeto restaurado individualmente.");
			SceneManager.sceneLoaded += OnSceneLoaded;
			ModLogger.LogInfo((object)string.Format("{0} v{1} cargado ({2} mallas legacy listas).", "Legacy Colliders", "2.2.0", LegacyMeshStore.EnsureLoaded()));
		}

		private void OnDestroy()
		{
			SceneManager.sceneLoaded -= OnSceneLoaded;
			((MonoBehaviour)this).StopAllCoroutines();
		}

		private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			if (!EnabledConfig.Value)
			{
				return;
			}
			if ((int)mode == 0)
			{
				((MonoBehaviour)this).StopAllCoroutines();
				LegacyColliderRestorer.ResetForNewScene();
			}
			if (IsNonGameplayScene(((Scene)(ref scene)).name))
			{
				return;
			}
			try
			{
				int num = LegacyColliderRestorer.RestoreScene(scene);
				if (num > 0)
				{
					ManualLogSource? modLogger = ModLogger;
					if (modLogger != null)
					{
						modLogger.LogInfo((object)$"[Legacy] Escena '{((Scene)(ref scene)).name}': {num} colisiones legacy restauradas.");
					}
				}
				((MonoBehaviour)this).StartCoroutine(DelayedPass(scene, 3f));
			}
			catch (Exception arg)
			{
				ManualLogSource? modLogger2 = ModLogger;
				if (modLogger2 != null)
				{
					modLogger2.LogError((object)$"[Legacy] Error al procesar la escena '{((Scene)(ref scene)).name}': {arg}");
				}
			}
		}

		private static bool IsNonGameplayScene(string sceneName)
		{
			if (!string.IsNullOrEmpty(sceneName) && !string.Equals(sceneName, "Bootstrap", StringComparison.OrdinalIgnoreCase))
			{
				return sceneName.IndexOf("Menu", StringComparison.OrdinalIgnoreCase) >= 0;
			}
			return true;
		}

		private IEnumerator DelayedPass(Scene scene, float delaySeconds)
		{
			//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)
			yield return (object)new WaitForSeconds(delaySeconds);
			if (!EnabledConfig.Value || !((Scene)(ref scene)).IsValid() || !((Scene)(ref scene)).isLoaded)
			{
				yield break;
			}
			try
			{
				int num = LegacyColliderRestorer.RestoreScene(scene);
				if (num > 0)
				{
					ManualLogSource? modLogger = ModLogger;
					if (modLogger != null)
					{
						modLogger.LogInfo((object)$"[Legacy] Escena '{((Scene)(ref scene)).name}' (pasada +{delaySeconds:0.0}s): +{num} colisiones restauradas.");
					}
				}
			}
			catch (Exception arg)
			{
				ManualLogSource? modLogger2 = ModLogger;
				if (modLogger2 != null)
				{
					modLogger2.LogError((object)$"[Legacy] Error en pasada diferida de '{((Scene)(ref scene)).name}': {arg}");
				}
			}
		}
	}
	internal static class LegacyMeshStore
	{
		internal sealed class Variant
		{
			public string Name = string.Empty;

			public bool Convex;

			public Vector3 Center;

			public Vector3 Extents;

			public int Offset;

			public int CompressedLength;

			public Mesh? SharedMesh;

			public bool LoadFailed;
		}

		private const string PakResourceName = "LegacyMeshes.pak";

		private const float BoundsTolerance = 0.05f;

		private static Dictionary<string, List<Variant>>? _byName;

		private static int _variantCount;

		private static readonly Dictionary<int, Variant?> _meshDecisions = new Dictionary<int, Variant>(256);

		public static int EnsureLoaded()
		{
			//IL_0177: Unknown result type (might be due to invalid IL or missing references)
			//IL_017c: 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)
			if (_byName != null)
			{
				return _variantCount;
			}
			_byName = new Dictionary<string, List<Variant>>(64, StringComparer.Ordinal);
			_variantCount = 0;
			using Stream stream = typeof(LegacyMeshStore).Assembly.GetManifestResourceStream("LegacyMeshes.pak");
			if (stream == null)
			{
				ManualLogSource? modLogger = LegacyClimbAndWallsPlugin.ModLogger;
				if (modLogger != null)
				{
					modLogger.LogWarning((object)"[Legacy] No se encontro el paquete 'LegacyMeshes.pak' dentro de la DLL.");
				}
				return 0;
			}
			using BinaryReader binaryReader = new BinaryReader(stream, Encoding.UTF8);
			byte[] array = binaryReader.ReadBytes(4);
			if (array.Length != 4 || array[0] != 76 || array[1] != 77 || array[2] != 80 || array[3] != 75)
			{
				ManualLogSource? modLogger2 = LegacyClimbAndWallsPlugin.ModLogger;
				if (modLogger2 != null)
				{
					modLogger2.LogError((object)"[Legacy] Encabezado invalido en LegacyMeshes.pak.");
				}
				return 0;
			}
			ushort num = binaryReader.ReadUInt16();
			ushort num2 = binaryReader.ReadUInt16();
			if (num != 1)
			{
				ManualLogSource? modLogger3 = LegacyClimbAndWallsPlugin.ModLogger;
				if (modLogger3 != null)
				{
					modLogger3.LogError((object)$"[Legacy] Version de paquete no soportada: {num}");
				}
				return 0;
			}
			for (int i = 0; i < num2; i++)
			{
				ushort count = binaryReader.ReadUInt16();
				string text = Encoding.UTF8.GetString(binaryReader.ReadBytes(count));
				bool convex = binaryReader.ReadByte() != 0;
				float num3 = binaryReader.ReadSingle();
				float num4 = binaryReader.ReadSingle();
				float num5 = binaryReader.ReadSingle();
				float num6 = binaryReader.ReadSingle();
				float num7 = binaryReader.ReadSingle();
				float num8 = binaryReader.ReadSingle();
				int offset = (int)binaryReader.ReadUInt32();
				int compressedLength = (int)binaryReader.ReadUInt32();
				Variant item = new Variant
				{
					Name = text,
					Convex = convex,
					Center = new Vector3(num3, num4, num5),
					Extents = new Vector3(num6, num7, num8),
					Offset = offset,
					CompressedLength = compressedLength
				};
				if (!_byName.TryGetValue(text, out List<Variant> value))
				{
					value = new List<Variant>(2);
					_byName[text] = value;
				}
				value.Add(item);
				_variantCount++;
			}
			return _variantCount;
		}

		public static void ClearSceneCache()
		{
			_meshDecisions.Clear();
		}

		public static Variant? Resolve(Mesh visualMesh)
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			int instanceID = ((Object)visualMesh).GetInstanceID();
			if (_meshDecisions.TryGetValue(instanceID, out Variant value))
			{
				return value;
			}
			EnsureLoaded();
			Variant variant = null;
			if (_byName != null && _byName.TryGetValue(((Object)visualMesh).name, out List<Variant> value2))
			{
				Bounds bounds = visualMesh.bounds;
				for (int i = 0; i < value2.Count; i++)
				{
					Variant variant2 = value2[i];
					if (BoundsNear(variant2.Center, ((Bounds)(ref bounds)).center) && BoundsNear(variant2.Extents, ((Bounds)(ref bounds)).extents))
					{
						variant = variant2;
						break;
					}
				}
			}
			_meshDecisions[instanceID] = variant;
			return variant;
		}

		public static Mesh? GetOrCreateMesh(Variant variant)
		{
			if ((Object)(object)variant.SharedMesh != (Object)null || variant.LoadFailed)
			{
				return variant.SharedMesh;
			}
			try
			{
				using Stream stream = typeof(LegacyMeshStore).Assembly.GetManifestResourceStream("LegacyMeshes.pak");
				if (stream == null)
				{
					variant.LoadFailed = true;
					return null;
				}
				stream.Seek(variant.Offset, SeekOrigin.Begin);
				byte[] array = new byte[variant.CompressedLength];
				ReadExact(stream, array, 0, array.Length);
				using MemoryStream stream2 = new MemoryStream(array, writable: false);
				using DeflateStream stream3 = new DeflateStream(stream2, CompressionMode.Decompress);
				Mesh val = ReadDecompressedMesh(stream3, "Legacy_" + variant.Name);
				Physics.BakeMesh(((Object)val).GetInstanceID(), variant.Convex);
				variant.SharedMesh = val;
			}
			catch (Exception ex)
			{
				variant.LoadFailed = true;
				ManualLogSource? modLogger = LegacyClimbAndWallsPlugin.ModLogger;
				if (modLogger != null)
				{
					modLogger.LogError((object)("[Legacy] Error al cargar la malla '" + variant.Name + "': " + ex.Message));
				}
			}
			return variant.SharedMesh;
		}

		private static bool BoundsNear(Vector3 a, Vector3 b)
		{
			//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_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: 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)
			if (Mathf.Abs(a.x - b.x) <= 0.05f && Mathf.Abs(a.y - b.y) <= 0.05f)
			{
				return Mathf.Abs(a.z - b.z) <= 0.05f;
			}
			return false;
		}

		private static Mesh ReadDecompressedMesh(Stream stream, string meshName)
		{
			//IL_0081: 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_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_0125: Expected O, but got Unknown
			byte[] array = new byte[9];
			ReadExact(stream, array, 0, 9);
			int num = BitConverter.ToInt32(array, 0);
			int num2 = BitConverter.ToInt32(array, 4);
			bool flag = array[8] != 0;
			int num3 = num * 12;
			byte[] array2 = new byte[num3];
			ReadExact(stream, array2, 0, num3);
			float[] array3 = new float[num * 3];
			Buffer.BlockCopy(array2, 0, array3, 0, num3);
			Vector3[] array4 = (Vector3[])(object)new Vector3[num];
			int num4 = 0;
			int num5 = 0;
			while (num4 < num)
			{
				array4[num4] = new Vector3(array3[num5], array3[num5 + 1], array3[num5 + 2]);
				num4++;
				num5 += 3;
			}
			int[] array5 = new int[num2];
			if (flag)
			{
				int num6 = num2 * 2;
				byte[] array6 = new byte[num6];
				ReadExact(stream, array6, 0, num6);
				ushort[] array7 = new ushort[num2];
				Buffer.BlockCopy(array6, 0, array7, 0, num6);
				for (int i = 0; i < num2; i++)
				{
					array5[i] = array7[i];
				}
			}
			else
			{
				int num7 = num2 * 4;
				byte[] array8 = new byte[num7];
				ReadExact(stream, array8, 0, num7);
				Buffer.BlockCopy(array8, 0, array5, 0, num7);
			}
			Mesh val = new Mesh
			{
				name = meshName
			};
			if (num > 65000)
			{
				val.indexFormat = (IndexFormat)1;
			}
			val.vertices = array4;
			val.triangles = array5;
			val.RecalculateBounds();
			((Object)val).hideFlags = (HideFlags)32;
			return val;
		}

		private static void ReadExact(Stream stream, byte[] buffer, int offset, int count)
		{
			int num = count;
			int num2 = offset;
			while (num > 0)
			{
				int num3 = stream.Read(buffer, num2, num);
				if (num3 <= 0)
				{
					throw new EndOfStreamException("Fin inesperado leyendo LegacyMeshes.pak.");
				}
				num2 += num3;
				num -= num3;
			}
		}
	}
	internal static class LegacyColliderRestorer
	{
		private readonly struct BoxSpec
		{
			public readonly Vector3 Position;

			public readonly Quaternion Rotation;

			public readonly Vector3 Scale;

			public readonly bool IsRotated;

			public BoxSpec(Vector3 pos, Quaternion rot, Vector3 scale, bool isRotated = false)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				//IL_0008: Unknown result type (might be due to invalid IL or missing references)
				//IL_0009: Unknown result type (might be due to invalid IL or missing references)
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0010: Unknown result type (might be due to invalid IL or missing references)
				Position = pos;
				Rotation = rot;
				Scale = scale;
				IsRotated = isRotated;
			}
		}

		private const string HolderObjectName = "LegacyCollider";

		private static readonly Quaternion RotZ90 = new Quaternion(0f, 0f, 0.7071068f, 0.7071068f);

		private static readonly BoxSpec[] GeneratorBoxes = new BoxSpec[11]
		{
			new BoxSpec(new Vector3(-2.13f, -2.18f, 7.82f), Quaternion.identity, new Vector3(1.016f, 1.015f, 3.85f)),
			new BoxSpec(new Vector3(-2.13f, 2.22f, 7.82f), Quaternion.identity, new Vector3(1.016f, 1.015f, 3.85f)),
			new BoxSpec(new Vector3(-0.31f, -3.69f, 2.49f), Quaternion.identity, new Vector3(5.72f, 3.295f, 3.207f)),
			new BoxSpec(new Vector3(-0.2f, -2.57f, 3.7f), Quaternion.identity, new Vector3(4.755f, 4.433f, 4.55f)),
			new BoxSpec(new Vector3(-0.184f, 0f, 4.02f), Quaternion.identity, new Vector3(6.609f, 8.188f, 8.405f)),
			new BoxSpec(new Vector3(-0.06f, 3.23f, 4.7f), Quaternion.identity, new Vector3(4.966f, 2.931f, 2.549f)),
			new BoxSpec(new Vector3(-0.06f, 3.66f, 2.49f), Quaternion.identity, new Vector3(5.973f, 3.44f, 3.349f)),
			new BoxSpec(new Vector3(0f, 0f, -0.46f), Quaternion.identity, new Vector3(8.148f, 10.076f, 0.98f)),
			new BoxSpec(new Vector3(0.27f, -2.18f, 7.94f), Quaternion.identity, new Vector3(1.016f, 1.015f, 3.85f)),
			new BoxSpec(new Vector3(0.27f, 2.23f, 7.94f), Quaternion.identity, new Vector3(1.016f, 1.015f, 3.85f)),
			new BoxSpec(new Vector3(2.14f, -0.09f, 2.49f), RotZ90, new Vector3(6.779f, 4.136f, 3.462f), isRotated: true)
		};

		private static readonly BoxSpec[] BeltWheelsBoxes = new BoxSpec[6]
		{
			new BoxSpec(new Vector3(0f, 4.003f, -0.729f), Quaternion.identity, new Vector3(15.949f, 12.132f, 1.513f)),
			new BoxSpec(new Vector3(0.485f, 2.94f, 3.946f), Quaternion.identity, new Vector3(13.108f, 4.322f, 8.619f)),
			new BoxSpec(new Vector3(1.97f, 7.28f, 8.86f), RotZ90, new Vector3(1.295f, 1.371f, 2.273f), isRotated: true),
			new BoxSpec(new Vector3(3.836f, 6.522f, 3.946f), RotZ90, new Vector3(4.911f, 6.435f, 8.619f), isRotated: true),
			new BoxSpec(new Vector3(4.31f, 7.28f, 8.86f), RotZ90, new Vector3(1.295f, 1.371f, 2.273f), isRotated: true),
			new BoxSpec(new Vector3(4.89f, 5.02f, 2.56f), RotZ90, new Vector3(7.116f, 6.719f, 3.085f), isRotated: true)
		};

		private static readonly List<GameObject> _rootsBuffer = new List<GameObject>(32);

		private static readonly List<MeshFilter> _filtersBuffer = new List<MeshFilter>(512);

		private static readonly List<Collider> _ownCollidersBuffer = new List<Collider>(8);

		private static readonly HashSet<int> _processedObjects = new HashSet<int>();

		public static void ResetForNewScene()
		{
			_processedObjects.Clear();
			LegacyMeshStore.ClearSceneCache();
		}

		public static int RestoreScene(Scene scene)
		{
			if (!((Scene)(ref scene)).IsValid() || !((Scene)(ref scene)).isLoaded)
			{
				return 0;
			}
			int num = 0;
			try
			{
				_rootsBuffer.Clear();
				((Scene)(ref scene)).GetRootGameObjects(_rootsBuffer);
				for (int i = 0; i < _rootsBuffer.Count; i++)
				{
					GameObject val = _rootsBuffer[i];
					if ((Object)(object)val == (Object)null || IsProtectedName(((Object)val).name))
					{
						continue;
					}
					_filtersBuffer.Clear();
					val.GetComponentsInChildren<MeshFilter>(true, _filtersBuffer);
					for (int j = 0; j < _filtersBuffer.Count; j++)
					{
						MeshFilter val2 = _filtersBuffer[j];
						if ((Object)(object)val2 == (Object)null)
						{
							continue;
						}
						string name = ((Object)val2).name;
						if (name == "FactoryGenerator" && (Object)(object)((Component)val2).transform.parent != (Object)null)
						{
							if (TryRestoreCompoundBoxes(((Component)((Component)val2).transform.parent).gameObject, GeneratorBoxes, restoreBeltChildren: false))
							{
								num++;
							}
							continue;
						}
						if (name == "FactoryBeltWheels" && (Object)(object)((Component)val2).transform.parent != (Object)null)
						{
							if (TryRestoreCompoundBoxes(((Component)((Component)val2).transform.parent).gameObject, BeltWheelsBoxes, restoreBeltChildren: true))
							{
								num++;
							}
							continue;
						}
						Mesh sharedMesh = val2.sharedMesh;
						if (!((Object)(object)sharedMesh == (Object)null))
						{
							LegacyMeshStore.Variant variant = LegacyMeshStore.Resolve(sharedMesh);
							if (variant != null && TryRestoreMeshCollider(ResolveColliderTarget(((Component)val2).gameObject), variant, requirePrimitiveCollider: true))
							{
								num++;
							}
						}
					}
				}
				return num;
			}
			finally
			{
				_rootsBuffer.Clear();
				_filtersBuffer.Clear();
				_ownCollidersBuffer.Clear();
			}
		}

		private static GameObject ResolveColliderTarget(GameObject meshGo)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)meshGo).name.EndsWith("LOD_0", StringComparison.Ordinal))
			{
				return meshGo;
			}
			Transform val = meshGo.transform;
			for (int i = 0; i < 2; i++)
			{
				Transform parent = val.parent;
				if ((Object)(object)parent == (Object)null)
				{
					break;
				}
				Vector3 val2 = val.localPosition;
				if (((Vector3)(ref val2)).sqrMagnitude > 0.0001f)
				{
					break;
				}
				val2 = val.localScale - Vector3.one;
				if (((Vector3)(ref val2)).sqrMagnitude > 0.0001f)
				{
					break;
				}
				val = parent;
				if (HasAnyActivePrimitive(((Component)val).gameObject))
				{
					return ((Component)val).gameObject;
				}
			}
			return meshGo;
		}

		private static bool HasAnyActivePrimitive(GameObject go)
		{
			_ownCollidersBuffer.Clear();
			go.GetComponents<Collider>(_ownCollidersBuffer);
			for (int i = 0; i < _ownCollidersBuffer.Count; i++)
			{
				Collider val = _ownCollidersBuffer[i];
				if ((Object)(object)val != (Object)null && val.enabled && !val.isTrigger && IsReplaceablePrimitive(val))
				{
					return true;
				}
			}
			return false;
		}

		private static bool TryRestoreMeshCollider(GameObject go, LegacyMeshStore.Variant variant, bool requirePrimitiveCollider)
		{
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: 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_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			int instanceID = ((Object)go).GetInstanceID();
			if (!_processedObjects.Add(instanceID))
			{
				return false;
			}
			if (IsProtectedHierarchy(go.transform))
			{
				return false;
			}
			_ownCollidersBuffer.Clear();
			go.GetComponents<Collider>(_ownCollidersBuffer);
			Collider val = null;
			int num = 0;
			for (int i = 0; i < _ownCollidersBuffer.Count; i++)
			{
				Collider val2 = _ownCollidersBuffer[i];
				if ((Object)(object)val2 == (Object)null || !val2.enabled || val2.isTrigger)
				{
					continue;
				}
				if (val2 is MeshCollider)
				{
					return false;
				}
				if (IsReplaceablePrimitive(val2))
				{
					if (val == null)
					{
						val = val2;
					}
					num++;
				}
			}
			if (requirePrimitiveCollider && (num == 0 || (Object)(object)val == (Object)null))
			{
				return false;
			}
			Rigidbody val3 = (((Object)(object)val != (Object)null) ? val.attachedRigidbody : go.GetComponentInParent<Rigidbody>());
			if ((Object)(object)val3 != (Object)null && !val3.isKinematic && !variant.Convex)
			{
				return false;
			}
			Mesh orCreateMesh = LegacyMeshStore.GetOrCreateMesh(variant);
			if ((Object)(object)orCreateMesh == (Object)null)
			{
				return false;
			}
			GameObject val4 = new GameObject("LegacyCollider")
			{
				layer = go.layer,
				tag = go.tag
			};
			Transform transform = val4.transform;
			transform.SetParent(go.transform, false);
			transform.localPosition = Vector3.zero;
			transform.localRotation = Quaternion.identity;
			transform.localScale = Vector3.one;
			MeshCollider val5 = val4.AddComponent<MeshCollider>();
			val5.sharedMesh = orCreateMesh;
			val5.convex = variant.Convex;
			if ((Object)(object)val != (Object)null)
			{
				((Collider)val5).sharedMaterial = val.sharedMaterial;
			}
			for (int j = 0; j < _ownCollidersBuffer.Count; j++)
			{
				Collider val6 = _ownCollidersBuffer[j];
				if ((Object)(object)val6 != (Object)null && val6.enabled && !val6.isTrigger && IsReplaceablePrimitive(val6))
				{
					val6.enabled = false;
				}
			}
			if (LegacyClimbAndWallsPlugin.VerboseLogging.Value)
			{
				ManualLogSource? modLogger = LegacyClimbAndWallsPlugin.ModLogger;
				if (modLogger != null)
				{
					modLogger.LogInfo((object)$"[Legacy] {((Object)go).name} -> {variant.Name} (verts={orCreateMesh.vertexCount}, convex={variant.Convex}, reemplazados={num})");
				}
			}
			return true;
		}

		private static bool TryRestoreCompoundBoxes(GameObject rootGo, BoxSpec[] legacyBoxes, bool restoreBeltChildren)
		{
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Expected O, but got Unknown
			//IL_0107: 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_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: 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_01a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			int instanceID = ((Object)rootGo).GetInstanceID();
			if (!_processedObjects.Add(instanceID))
			{
				return false;
			}
			if (IsProtectedHierarchy(rootGo.transform))
			{
				return false;
			}
			Transform transform = rootGo.transform;
			int childCount = transform.childCount;
			int num = 0;
			int layer = rootGo.layer;
			string tag = rootGo.tag;
			PhysicsMaterial val = null;
			for (int i = 0; i < childCount; i++)
			{
				Transform child = transform.GetChild(i);
				if (!string.Equals(((Object)child).name, "COLLIDER", StringComparison.OrdinalIgnoreCase))
				{
					continue;
				}
				BoxCollider component = ((Component)child).GetComponent<BoxCollider>();
				if ((Object)(object)component != (Object)null && ((Collider)component).enabled && !((Collider)component).isTrigger)
				{
					if (num == 0)
					{
						layer = ((Component)child).gameObject.layer;
						tag = ((Component)child).gameObject.tag;
						val = ((Collider)component).sharedMaterial;
					}
					((Collider)component).enabled = false;
					num++;
				}
			}
			if (num == 0)
			{
				return false;
			}
			GameObject val2 = new GameObject("LegacyCollider")
			{
				layer = layer,
				tag = tag
			};
			Transform transform2 = val2.transform;
			transform2.SetParent(transform, false);
			transform2.localPosition = Vector3.zero;
			transform2.localRotation = Quaternion.identity;
			transform2.localScale = Vector3.one;
			for (int j = 0; j < legacyBoxes.Length; j++)
			{
				BoxSpec boxSpec = legacyBoxes[j];
				if (!boxSpec.IsRotated)
				{
					BoxCollider obj = val2.AddComponent<BoxCollider>();
					obj.center = boxSpec.Position;
					obj.size = boxSpec.Scale;
					((Collider)obj).sharedMaterial = val;
					continue;
				}
				GameObject val3 = new GameObject("LegacyBox")
				{
					layer = layer,
					tag = tag
				};
				Transform transform3 = val3.transform;
				transform3.SetParent(transform2, false);
				transform3.localPosition = boxSpec.Position;
				transform3.localRotation = boxSpec.Rotation;
				transform3.localScale = boxSpec.Scale;
				BoxCollider obj2 = val3.AddComponent<BoxCollider>();
				obj2.center = Vector3.zero;
				obj2.size = Vector3.one;
				((Collider)obj2).sharedMaterial = val;
			}
			if (restoreBeltChildren)
			{
				RestoreBeltWheelsChildren(transform, val);
			}
			if (LegacyClimbAndWallsPlugin.VerboseLogging.Value)
			{
				ManualLogSource? modLogger = LegacyClimbAndWallsPlugin.ModLogger;
				if (modLogger != null)
				{
					modLogger.LogInfo((object)$"[Legacy] Compuesto '{((Object)rootGo).name}': {num} cajas simplificadas -> {legacyBoxes.Length} cajas legacy.");
				}
			}
			return true;
		}

		private static void RestoreBeltWheelsChildren(Transform beltRoot, PhysicsMaterial? fallbackMat)
		{
			//IL_0041: 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_0095: 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)
			int childCount = beltRoot.childCount;
			for (int i = 0; i < childCount; i++)
			{
				Transform child = beltRoot.GetChild(i);
				switch (((Object)child).name)
				{
				case "Factory_Grate":
				{
					BoxCollider component2 = ((Component)child).GetComponent<BoxCollider>();
					if ((Object)(object)component2 != (Object)null)
					{
						component2.center = Vector3.zero;
						component2.size = new Vector3(10f, 2f, 0.2f);
					}
					break;
				}
				case "Factory_Grate (1)":
					if ((Object)(object)((Component)child).GetComponent<Collider>() == (Object)null)
					{
						BoxCollider obj = ((Component)child).gameObject.AddComponent<BoxCollider>();
						obj.center = Vector3.zero;
						obj.size = new Vector3(10f, 2f, 0.2f);
						((Collider)obj).sharedMaterial = fallbackMat;
					}
					break;
				case "FactorySpinner":
				case "BigWheel":
				case "megamachine (3)":
				{
					MeshFilter component = ((Component)child).GetComponent<MeshFilter>();
					if ((Object)(object)component != (Object)null && (Object)(object)component.sharedMesh != (Object)null)
					{
						LegacyMeshStore.Variant variant = LegacyMeshStore.Resolve(component.sharedMesh);
						if (variant != null)
						{
							TryRestoreMeshCollider(((Component)child).gameObject, variant, requirePrimitiveCollider: false);
						}
					}
					break;
				}
				}
			}
		}

		private static bool IsReplaceablePrimitive(Collider col)
		{
			if (!(col is BoxCollider) && !(col is CapsuleCollider))
			{
				return col is SphereCollider;
			}
			return true;
		}

		private static bool IsProtectedHierarchy(Transform transform)
		{
			Transform val = transform;
			while ((Object)(object)val != (Object)null)
			{
				if (IsProtectedName(((Object)val).name))
				{
					return true;
				}
				val = val.parent;
			}
			return false;
		}

		private static bool IsProtectedName(string name)
		{
			if (name.IndexOf("player", StringComparison.OrdinalIgnoreCase) < 0 && name.IndexOf("camera", StringComparison.OrdinalIgnoreCase) < 0 && name.IndexOf("rigcreator", StringComparison.OrdinalIgnoreCase) < 0 && name.IndexOf("armature", StringComparison.OrdinalIgnoreCase) < 0)
			{
				return name.IndexOf("ragdoll", StringComparison.OrdinalIgnoreCase) >= 0;
			}
			return true;
		}
	}
}