Decompiled source of MonsterMetamorphosis v0.3.1

plugins/MonsterMetamorphosis/MonsterMetamorphosis.dll

Decompiled 2 days ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HG.Reflection;
using HarmonyLib;
using R2API;
using R2API.Networking;
using R2API.Networking.Interfaces;
using R2API.Utils;
using RoR2;
using RoR2.ExpansionManagement;
using RoR2.UI;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.AddressableAssets.ResourceLocators;
using UnityEngine.Networking;
using UnityEngine.ResourceManagement.ResourceLocations;
using UnityEngine.UI;

[assembly: OptIn]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyVersion("0.3.0.0")]
namespace MonsterMetamorphosis;

internal static class ModContent
{
	internal static ArtifactDef Artifact;

	internal static ItemDef Essence;

	internal static ItemTierDef Tier;

	internal static readonly Color EssenceColor = new Color(0.73f, 0.47f, 1f);

	internal static string AssetDirectory => Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Assets");

	internal static void Register()
	{
		//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ee: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f8: Expected O, but got Unknown
		AddLanguage();
		Artifact = ScriptableObject.CreateInstance<ArtifactDef>();
		Artifact.cachedName = "MonsterMetamorphosis";
		Artifact.nameToken = "MM_ARTIFACT_NAME";
		Artifact.descriptionToken = "MM_ARTIFACT_DESCRIPTION";
		Artifact.unlockableDef = null;
		Artifact.smallIconSelectedSprite = LoadSprite("artifact icon.png", dim: false);
		Artifact.smallIconDeselectedSprite = LoadSprite("artifact icon.png", dim: true);
		if (!ContentAddition.AddArtifactDef(Artifact))
		{
			throw new Exception("Artifact registration rejected");
		}
		Tier = ScriptableObject.CreateInstance<ItemTierDef>();
		((Object)Tier).name = "MetamorphicEssenceTier";
		Tier.tier = (ItemTier)1000;
		Tier.isDroppable = true;
		Tier.canScrap = false;
		Tier.canRestack = false;
		Tier.canRebirth = false;
		Tier.pickupRules = (PickupRules)0;
		Tier.colorIndex = (ColorIndex)4;
		Tier.darkColorIndex = (ColorIndex)21;
		ContentAddition.AddItemTierDef(Tier);
		Essence = ScriptableObject.CreateInstance<ItemDef>();
		((Object)Essence).name = "UnstableEssence";
		Essence.nameToken = "MM_ESSENCE_NAME";
		Essence.pickupToken = "MM_ESSENCE_PICKUP";
		Essence.descriptionToken = "MM_ESSENCE_DESCRIPTION";
		Essence.loreToken = "MM_ESSENCE_LORE";
		AccessTools.Field(typeof(ItemDef), "_itemTierDef").SetValue(Essence, Tier);
		Essence.pickupIconSprite = LoadSprite("item_icon.png", dim: false);
		Essence.pickupModelPrefab = ModelAssets.CreateModel();
		Essence.canRemove = true;
		Essence.tags = (ItemTag[])(object)new ItemTag[7]
		{
			(ItemTag)3,
			(ItemTag)4,
			(ItemTag)13,
			(ItemTag)15,
			(ItemTag)12,
			(ItemTag)44,
			(ItemTag)27
		};
		if (!ItemAPI.Add(new CustomItem(Essence, (ItemDisplayRule[])(object)new ItemDisplayRule[0])))
		{
			throw new Exception("Item registration rejected");
		}
	}

	internal static void FinishCatalog()
	{
		//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_00a2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bc: 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_0058: Unknown result type (might be due to invalid IL or missing references)
		//IL_005d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0063: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Unknown result type (might be due to invalid IL or missing references)
		ItemTierDef itemTierDef = ItemTierCatalog.GetItemTierDef((ItemTier)1);
		if (Object.op_Implicit((Object)(object)itemTierDef))
		{
			Tier.highlightPrefab = itemTierDef.highlightPrefab;
			Tier.dropletDisplayPrefab = itemTierDef.dropletDisplayPrefab;
			Tier.bgIconTexture = itemTierDef.bgIconTexture;
		}
		PickupDef pickupDef = PickupCatalog.GetPickupDef(PickupCatalog.FindPickupIndex(Essence.itemIndex));
		if (pickupDef != null)
		{
			pickupDef.baseColor = EssenceColor;
			pickupDef.darkColor = EssenceColor * 0.5f;
			pickupDef.dropletDisplayPrefab = Tier.dropletDisplayPrefab;
		}
		Plugin.Log.LogInfo((object)string.Concat("Content ready: artifact=", Artifact.artifactIndex, ", essence=", Essence.itemIndex, ", custom tier=", Tier.tier));
	}

	private static Sprite LoadSprite(string name, bool dim)
	{
		//IL_0004: Unknown result type (might be due to invalid IL or missing references)
		//IL_000a: Expected O, but got Unknown
		//IL_00d2: 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_0091: 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)
		Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false);
		((Object)val).name = name;
		if (!ImageConversion.LoadImage(val, File.ReadAllBytes(Path.Combine(AssetDirectory, name))))
		{
			throw new Exception("Invalid PNG: " + name);
		}
		if (dim)
		{
			Color[] pixels = val.GetPixels();
			for (int i = 0; i < pixels.Length; i++)
			{
				ref Color reference = ref pixels[i];
				reference = new Color(pixels[i].r * 0.3f, pixels[i].g * 0.3f, pixels[i].b * 0.3f, pixels[i].a);
			}
			val.SetPixels(pixels);
			val.Apply();
		}
		((Texture)val).wrapMode = (TextureWrapMode)1;
		return Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f));
	}

	private static void AddLanguage()
	{
		TextSettings.RegisterLanguage();
	}
}
[Serializable]
internal class MeshDocument
{
	public MeshPart[] meshes;
}
[Serializable]
internal class MeshPart
{
	public string name;

	public float[] vertices;

	public float[] position;

	public float[] rotation;

	public float[] scale;

	public float[] color;

	public int[] triangles;
}
internal static class ModelAssets
{
	internal static GameObject CreateModel()
	{
		//IL_001f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0025: Expected O, but got Unknown
		//IL_0037: Unknown result type (might be due to invalid IL or missing references)
		//IL_003d: Expected O, but got Unknown
		//IL_0078: Unknown result type (might be due to invalid IL or missing references)
		//IL_007f: Expected O, but got Unknown
		//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
		//IL_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_00ca: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
		//IL_0103: Unknown result type (might be due to invalid IL or missing references)
		//IL_0108: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a7: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ac: Unknown result type (might be due to invalid IL or missing references)
		//IL_0139: Unknown result type (might be due to invalid IL or missing references)
		//IL_013e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0143: Unknown result type (might be due to invalid IL or missing references)
		//IL_0164: Unknown result type (might be due to invalid IL or missing references)
		//IL_0169: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c2: Unknown result type (might be due to invalid IL or missing references)
		//IL_02dc: Unknown result type (might be due to invalid IL or missing references)
		//IL_02e8: Unknown result type (might be due to invalid IL or missing references)
		//IL_02f4: Unknown result type (might be due to invalid IL or missing references)
		//IL_0324: Unknown result type (might be due to invalid IL or missing references)
		//IL_032b: Unknown result type (might be due to invalid IL or missing references)
		//IL_033d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0342: Unknown result type (might be due to invalid IL or missing references)
		//IL_0349: Unknown result type (might be due to invalid IL or missing references)
		//IL_0362: Unknown result type (might be due to invalid IL or missing references)
		//IL_0367: Unknown result type (might be due to invalid IL or missing references)
		//IL_036f: Unknown result type (might be due to invalid IL or missing references)
		//IL_037c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0384: Unknown result type (might be due to invalid IL or missing references)
		//IL_0389: Unknown result type (might be due to invalid IL or missing references)
		//IL_03c0: Unknown result type (might be due to invalid IL or missing references)
		//IL_03ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ed: Expected O, but got Unknown
		//IL_0233: Unknown result type (might be due to invalid IL or missing references)
		//IL_023a: Expected O, but got Unknown
		//IL_025c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0261: Unknown result type (might be due to invalid IL or missing references)
		//IL_0265: Unknown result type (might be due to invalid IL or missing references)
		MeshDocument meshDocument = JsonUtility.FromJson<MeshDocument>(File.ReadAllText(Path.Combine(ModContent.AssetDirectory, "item.mesh.json")));
		GameObject val = new GameObject("UnstableEssencePickupModel");
		val.SetActive(false);
		Object.DontDestroyOnLoad((Object)(object)val);
		GameObject val2 = new GameObject("Model");
		val2.transform.SetParent(val.transform, false);
		Shader val3 = Shader.Find("Hopoo Games/Deferred/Standard");
		MeshPart[] meshes = meshDocument.meshes;
		foreach (MeshPart meshPart in meshes)
		{
			GameObject val4 = new GameObject(meshPart.name);
			val4.transform.SetParent(val2.transform, false);
			Vector3[] array = (Vector3[])(object)new Vector3[meshPart.vertices.Length / 3];
			Quaternion val5 = Quaternion.AngleAxis(meshPart.rotation[2], Vector3.forward) * Quaternion.AngleAxis(meshPart.rotation[1], Vector3.up) * Quaternion.AngleAxis(meshPart.rotation[0], Vector3.right);
			Matrix4x4 val6 = Matrix4x4.TRS(V(meshPart.position), val5, V(meshPart.scale));
			for (int j = 0; j < array.Length; j++)
			{
				Vector3 val7 = ((Matrix4x4)(ref val6)).MultiplyPoint3x4(new Vector3(meshPart.vertices[j * 3], meshPart.vertices[j * 3 + 1], meshPart.vertices[j * 3 + 2]));
				ref Vector3 reference = ref array[j];
				reference = new Vector3(0f - val7.x, val7.y, val7.z);
			}
			int[] array2 = (int[])meshPart.triangles.Clone();
			if (meshPart.scale[0] * meshPart.scale[1] * meshPart.scale[2] < 0f)
			{
				for (int k = 0; k < array2.Length; k += 3)
				{
					int num = array2[k + 1];
					array2[k + 1] = array2[k + 2];
					array2[k + 2] = num;
				}
			}
			Mesh val8 = new Mesh();
			((Object)val8).name = meshPart.name;
			val8.vertices = array;
			val8.triangles = array2;
			val8.RecalculateNormals();
			val8.RecalculateBounds();
			val4.AddComponent<MeshFilter>().sharedMesh = val8;
			MeshRenderer val9 = val4.AddComponent<MeshRenderer>();
			Material val10 = new Material(val3);
			Color val11 = new Color(meshPart.color[0], meshPart.color[1], meshPart.color[2], 1f);
			val10.color = ((Color)(ref val11)).gamma;
			val10.SetTexture("_MainTex", (Texture)(object)Texture2D.whiteTexture);
			((Renderer)val9).sharedMaterial = val10;
		}
		Renderer[] componentsInChildren = val.GetComponentsInChildren<Renderer>(true);
		Bounds bounds = componentsInChildren[0].bounds;
		Renderer[] array3 = componentsInChildren;
		foreach (Renderer val12 in array3)
		{
			((Bounds)(ref bounds)).Encapsulate(val12.bounds);
		}
		float num2 = Mathf.Max(((Bounds)(ref bounds)).size.x, Mathf.Max(((Bounds)(ref bounds)).size.y, ((Bounds)(ref bounds)).size.z));
		float num3 = 1.6f / Mathf.Max(num2, 0.001f);
		val2.transform.localScale = Vector3.one * num3;
		val2.transform.localPosition = -((Bounds)(ref bounds)).center * num3;
		Quaternion val13 = Quaternion.Euler(0f, -90f, 0f);
		val2.transform.localRotation = val13;
		val2.transform.localPosition = val13 * val2.transform.localPosition;
		val.AddComponent<ModelPanelParameters>().focusPointTransform = val2.transform;
		val.SetActive(true);
		val.transform.position = new Vector3(0f, -100000f, 0f);
		Plugin.Log.LogInfo((object)("Loaded original FBX geometry: " + meshDocument.meshes.Length + " material groups; bounds=" + ((Bounds)(ref bounds)).size));
		return val;
	}

	private static Vector3 V(float[] v)
	{
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		return new Vector3(v[0], v[1], v[2]);
	}
}
internal sealed class MonsterForm
{
	internal GameObject Prefab;

	internal float Weight;

	internal string Name => Util.GetBestBodyName(Prefab);
}
internal static class MonsterPoolProvider
{
	internal static readonly List<MonsterForm> Forms = new List<MonsterForm>();

	internal static int Revision;

	internal static int ReadyStage = -1;

	private static string lastDescription;

	internal static void Clear()
	{
		Forms.Clear();
		Revision++;
		lastDescription = null;
		ReadyStage = -1;
	}

	internal static void MarkReady()
	{
		ReadyStage = (Object.op_Implicit((Object)(object)Run.instance) ? Run.instance.stageClearCount : (-1));
		Refresh();
	}

	internal static void Refresh()
	{
		//IL_0058: Unknown result type (might be due to invalid IL or missing references)
		//IL_005d: Unknown result type (might be due to invalid IL or missing references)
		if (!NetworkServer.active)
		{
			return;
		}
		Forms.Clear();
		Revision++;
		ClassicStageInfo instance = ClassicStageInfo.instance;
		if (!Object.op_Implicit((Object)(object)instance) || instance.monsterSelection == null || !Object.op_Implicit((Object)(object)Run.instance))
		{
			return;
		}
		WeightedSelection<DirectorCard> monsterSelection = instance.monsterSelection;
		for (int i = 0; i < monsterSelection.Count; i++)
		{
			ChoiceInfo<DirectorCard> choice = monsterSelection.GetChoice(i);
			DirectorCard value = choice.value;
			if (value == null || choice.weight <= 0f || !value.IsAvailable())
			{
				continue;
			}
			SpawnCard spawnCard = value.GetSpawnCard();
			CharacterSpawnCard val = (CharacterSpawnCard)(object)((spawnCard is CharacterSpawnCard) ? spawnCard : null);
			if (!Object.op_Implicit((Object)(object)val) || !Object.op_Implicit((Object)(object)((SpawnCard)val).prefab))
			{
				continue;
			}
			CharacterMaster master = ((SpawnCard)val).prefab.GetComponent<CharacterMaster>();
			if (!Object.op_Implicit((Object)(object)master) || !Object.op_Implicit((Object)(object)master.bodyPrefab) || SpecialBossRegistry.IsStoryBoss(((Object)master.bodyPrefab).name))
			{
				continue;
			}
			if (!MonsterCompatibility.IsSupported(master.bodyPrefab, out var reason))
			{
				MonsterCompatibility.ReportExclusion(((Object)master.bodyPrefab).name, reason);
				continue;
			}
			MonsterForm monsterForm = Forms.Find((MonsterForm f) => (Object)(object)f.Prefab == (Object)(object)master.bodyPrefab);
			if (monsterForm == null)
			{
				Forms.Add(new MonsterForm
				{
					Prefab = master.bodyPrefab,
					Weight = choice.weight
				});
			}
			else
			{
				monsterForm.Weight += choice.weight;
			}
		}
		string text = Describe();
		if (text != lastDescription)
		{
			Plugin.Log.LogInfo((object)text);
			lastDescription = text;
			PoolCatalogExport.RecordLive();
		}
	}

	internal static GameObject Pick()
	{
		if (!Object.op_Implicit((Object)(object)Run.instance) || !NetworkServer.active)
		{
			return null;
		}
		Refresh();
		if (Forms.Count == 0)
		{
			Plugin.Log.LogWarning((object)"No eligible Director cards; current form and essence are retained.");
			return null;
		}
		WeightedSelection<GameObject> val = new WeightedSelection<GameObject>(8);
		foreach (MonsterForm form in Forms)
		{
			val.AddChoice(form.Prefab, form.Weight);
		}
		return val.Evaluate(Run.instance.runRNG.nextNormalizedFloat);
	}

	internal static string Describe()
	{
		return "Director forms: " + ((Forms.Count == 0) ? "(empty)" : string.Join(", ", Forms.Select((MonsterForm f) => ((Object)f.Prefab).name + " [" + f.Weight.ToString("0.###") + "]").ToArray()));
	}
}
internal static class SpecialBossRegistry
{
	private static readonly Dictionary<string, string[]> Registry = new Dictionary<string, string[]>
	{
		{
			"moon2",
			new string[1] { "BrotherBody" }
		},
		{
			"moon",
			new string[1] { "BrotherBody" }
		},
		{
			"voidraid",
			new string[2] { "MiniVoidRaidCrabBodyPhase1", "MiniVoidRaidCrabBodyBase" }
		},
		{
			"meridian",
			new string[1] { "FalseSonBossBody" }
		},
		{
			"goldshores",
			new string[1] { "TitanGoldBody" }
		}
	};

	internal static bool IsStoryBoss(string name)
	{
		if (!name.StartsWith("Brother") && !name.Contains("VoidRaidCrab") && !name.StartsWith("FalseSonBoss") && !(name == "TitanGoldBody"))
		{
			return name.StartsWith("ScavLunar");
		}
		return true;
	}

	internal static GameObject TryPick()
	{
		if (!Object.op_Implicit((Object)(object)Run.instance) || !Object.op_Implicit((Object)(object)SceneInfo.instance) || !Object.op_Implicit((Object)(object)SceneInfo.instance.sceneDef))
		{
			return null;
		}
		if (!Registry.TryGetValue(SceneInfo.instance.sceneDef.baseSceneName, out var value))
		{
			return null;
		}
		if (Run.instance.runRNG.nextNormalizedFloat >= Plugin.BossChance.Value)
		{
			return null;
		}
		string[] array = value;
		foreach (string text in array)
		{
			GameObject val = BodyCatalog.FindBodyPrefab(text);
			if (Object.op_Implicit((Object)(object)val) && MonsterCompatibility.IsSupported(val, out var _))
			{
				ExpansionRequirementComponent component = val.GetComponent<ExpansionRequirementComponent>();
				if (!Object.op_Implicit((Object)(object)component) || Run.instance.IsExpansionEnabledOrWaived(component.requiredExpansion))
				{
					return val;
				}
			}
		}
		Plugin.Log.LogWarning((object)"Boss roll selected but no controllable enabled boss body on this stage. Using normal Director pool.");
		return null;
	}
}
internal static class MonsterCompatibility
{
	private static readonly HashSet<string> Reported = new HashSet<string>();

	internal static bool IsSupported(GameObject prefab, out string reason)
	{
		reason = null;
		if (!Object.op_Implicit((Object)(object)prefab) || !Object.op_Implicit((Object)(object)prefab.GetComponent<CharacterBody>()))
		{
			reason = "no CharacterBody";
		}
		else if (!Object.op_Implicit((Object)(object)prefab.GetComponent<InputBankTest>()) || !Object.op_Implicit((Object)(object)prefab.GetComponent<SkillLocator>()))
		{
			reason = "no input bank or skill locator";
		}
		else if (((Object)prefab).name.Contains("WormBody"))
		{
			reason = "WormBodyPositions uses AI navigation rather than player movement";
		}
		else if (((Object)prefab).name == "GupBody" || ((Object)prefab).name == "GeepBody")
		{
			reason = "death splits create separate AI masters, not the player's original master";
		}
		else if (!Object.op_Implicit((Object)(object)prefab.GetComponent<CharacterMotor>()) && !Object.op_Implicit((Object)(object)prefab.GetComponent<RigidbodyMotor>()))
		{
			reason = "no native player-compatible movement motor (stationary/segmented body)";
		}
		else if (prefab.GetComponent<CharacterBody>().baseMoveSpeed <= 0f)
		{
			reason = "stationary body has zero native movement speed";
		}
		else if (!prefab.GetComponents<GenericSkill>().Any((GenericSkill s) => Object.op_Implicit((Object)(object)s.skillFamily) && s.skillFamily.variants.Length > 0))
		{
			reason = "no native skill family";
		}
		return reason == null;
	}

	internal static void ReportExclusion(string name, string reason)
	{
		if (Reported.Add(name))
		{
			Plugin.Log.LogInfo((object)("Excluded " + name + ": " + reason));
		}
	}

	internal static void PrepareCatalog()
	{
		int num = 0;
		GameObject val = BodyCatalog.FindBodyPrefab("CommandoBody");
		CameraTargetParams val2 = (Object.op_Implicit((Object)(object)val) ? val.GetComponent<CameraTargetParams>() : null);
		foreach (GameObject allBodyPrefab in BodyCatalog.allBodyPrefabs)
		{
			if (!IsSupported(allBodyPrefab, out var _))
			{
				continue;
			}
			if (!Object.op_Implicit((Object)(object)allBodyPrefab.GetComponent<Interactor>()))
			{
				allBodyPrefab.AddComponent<Interactor>();
			}
			if (!Object.op_Implicit((Object)(object)allBodyPrefab.GetComponent<EquipmentSlot>()))
			{
				allBodyPrefab.AddComponent<EquipmentSlot>();
			}
			if (!Object.op_Implicit((Object)(object)allBodyPrefab.GetComponent<CameraTargetParams>()))
			{
				CameraTargetParams val3 = allBodyPrefab.AddComponent<CameraTargetParams>();
				if (Object.op_Implicit((Object)(object)val2))
				{
					val3.cameraParams = val2.cameraParams;
				}
			}
			num++;
		}
		Plugin.Log.LogInfo((object)("Prepared native controls/interactions on " + num + " catalog bodies; MonsterMash is optional and not installed by this mod."));
	}

	internal static void AdaptInstance(CharacterBody body)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		GameObject bodyPrefab = BodyCatalog.GetBodyPrefab(body.bodyIndex);
		if (!IsSupported(bodyPrefab, out var _) || Object.op_Implicit((Object)(object)SurvivorCatalog.GetSurvivorDef(SurvivorCatalog.GetSurvivorIndexFromBodyIndex(body.bodyIndex))))
		{
			return;
		}
		if (!Object.op_Implicit((Object)(object)((Component)body).GetComponent<AdaptedMonster>()))
		{
			((Component)body).gameObject.AddComponent<AdaptedMonster>();
		}
		Interactor component = ((Component)body).GetComponent<Interactor>();
		if (Object.op_Implicit((Object)(object)component))
		{
			component.maxInteractionDistance = Mathf.Max(component.maxInteractionDistance, 5f + body.radius * 2f);
		}
		SkillLocator component2 = ((Component)body).GetComponent<SkillLocator>();
		if (Object.op_Implicit((Object)(object)component2))
		{
			HashSet<GenericSkill> used = new HashSet<GenericSkill>((IEnumerable<GenericSkill>)(object)new GenericSkill[4] { component2.primary, component2.secondary, component2.utility, component2.special });
			Queue<GenericSkill> queue = new Queue<GenericSkill>(from s in ((Component)body).GetComponents<GenericSkill>()
				where Object.op_Implicit((Object)(object)s.skillFamily) && s.skillFamily.variants.Length > 0 && !used.Contains(s)
				select s);
			if (!Object.op_Implicit((Object)(object)component2.primary) && queue.Count > 0)
			{
				component2.primary = queue.Dequeue();
			}
			if (!Object.op_Implicit((Object)(object)component2.secondary) && queue.Count > 0)
			{
				component2.secondary = queue.Dequeue();
			}
			if (!Object.op_Implicit((Object)(object)component2.utility) && queue.Count > 0)
			{
				component2.utility = queue.Dequeue();
			}
			if (!Object.op_Implicit((Object)(object)component2.special) && queue.Count > 0)
			{
				component2.special = queue.Dequeue();
			}
			if (!Object.op_Implicit((Object)(object)component2.primary))
			{
				if (Object.op_Implicit((Object)(object)component2.secondary))
				{
					component2.primary = component2.secondary;
					component2.secondary = null;
				}
				else if (Object.op_Implicit((Object)(object)component2.utility))
				{
					component2.primary = component2.utility;
					component2.utility = null;
				}
				else if (Object.op_Implicit((Object)(object)component2.special))
				{
					component2.primary = component2.special;
					component2.special = null;
				}
			}
		}
		body.hideCrosshair = false;
	}
}
internal sealed class AdaptedMonster : MonoBehaviour
{
}
[HarmonyPatch(typeof(HUD), "Awake")]
internal static class HudCreatedPatch
{
	private static void Postfix(HUD __instance)
	{
		((Component)__instance).gameObject.AddComponent<MonsterPoolHUD>();
	}
}
[HarmonyPatch(typeof(EnemyInfoPanel), "SetDisplayDataForViewer")]
internal static class NativeMonsterIconsPatch
{
	private static void Prefix(List<BodyIndex> bodyIndices)
	{
		//IL_0039: Unknown result type (might be due to invalid IL or missing references)
		//IL_003e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0040: Unknown result type (might be due to invalid IL or missing references)
		//IL_0049: Unknown result type (might be due to invalid IL or missing references)
		if (!Plugin.ShowHUD.Value || !Object.op_Implicit((Object)(object)Run.instance))
		{
			return;
		}
		foreach (MonsterForm form in MonsterPoolProvider.Forms)
		{
			BodyIndex bodyIndex = form.Prefab.GetComponent<CharacterBody>().bodyIndex;
			if (!bodyIndices.Contains(bodyIndex))
			{
				bodyIndices.Add(bodyIndex);
			}
		}
	}
}
public sealed class MonsterPoolHUD : MonoBehaviour
{
	private HUD hud;

	private float nextUpdate;

	internal EnemyInfoPanel Panel;

	private void Awake()
	{
		hud = ((Component)this).GetComponent<HUD>();
	}

	private void Update()
	{
		//IL_0185: Unknown result type (might be due to invalid IL or missing references)
		//IL_018a: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
		if (Time.unscaledTime < nextUpdate || !Object.op_Implicit((Object)(object)Run.instance) || !Object.op_Implicit((Object)(object)hud.targetMaster))
		{
			return;
		}
		nextUpdate = Time.unscaledTime + 1f;
		MonsterPoolProvider.Refresh();
		AccessTools.Method(typeof(EnemyInfoPanel), "RefreshHUD", (Type[])null, (Type[])null).Invoke(null, new object[1] { hud });
		Panel = ((IEnumerable<EnemyInfoPanel>)InstanceTracker.GetInstancesList<EnemyInfoPanel>()).FirstOrDefault((Func<EnemyInfoPanel, bool>)((EnemyInfoPanel p) => (Object)(HUD)AccessTools.Field(typeof(EnemyInfoPanel), "hud").GetValue(p) == (Object)(object)hud));
		if (!Object.op_Implicit((Object)(object)Panel) || !Panel.monsterBodiesContainer.activeInHierarchy)
		{
			return;
		}
		if (Plugin.ShowHUD.Value)
		{
			LanguageTextMeshController[] componentsInChildren = Panel.monsterBodiesContainer.GetComponentsInChildren<LanguageTextMeshController>(true);
			foreach (LanguageTextMeshController val in componentsInChildren)
			{
				val.token = "MM_MONSTERS";
			}
		}
		BodyIndex[] array = (BodyIndex[])AccessTools.Field(typeof(EnemyInfoPanel), "currentMonsterBodyIndices").GetValue(Panel);
		UIElementAllocator<RawImage> val2 = (UIElementAllocator<RawImage>)AccessTools.Field(typeof(EnemyInfoPanel), "monsterBodyIconAllocator").GetValue(Panel);
		for (int num2 = 0; num2 < array.Length; num2++)
		{
			RawImage val3 = val2.elements[num2];
			((Graphic)val3).raycastTarget = true;
			TooltipProvider val4 = ((Component)val3).GetComponent<TooltipProvider>() ?? ((Component)val3).gameObject.AddComponent<TooltipProvider>();
			val4.overrideTitleText = Util.GetBestBodyName(BodyCatalog.GetBodyPrefab(array[num2]));
			val4.titleColor = ModContent.EssenceColor;
			val4.overrideBodyText = Language.GetString("MM_POOL");
			val4.bodyColor = Color.white;
		}
	}
}
public sealed class MonsterPoolMessage : INetMessage, ISerializableObject
{
	private int stage;

	private string scene;

	private readonly List<MonsterForm> forms = new List<MonsterForm>();

	internal static void Broadcast()
	{
		if (NetworkServer.active && Object.op_Implicit((Object)(object)Run.instance) && Object.op_Implicit((Object)(object)SceneInfo.instance) && Object.op_Implicit((Object)(object)SceneInfo.instance.sceneDef) && MonsterPoolProvider.ReadyStage == Run.instance.stageClearCount)
		{
			MonsterPoolMessage monsterPoolMessage = new MonsterPoolMessage();
			monsterPoolMessage.stage = Run.instance.stageClearCount;
			monsterPoolMessage.scene = SceneInfo.instance.sceneDef.cachedName;
			MonsterPoolMessage monsterPoolMessage2 = monsterPoolMessage;
			monsterPoolMessage2.forms.AddRange(MonsterPoolProvider.Forms);
			NetMessageExtensions.Send((INetMessage)(object)monsterPoolMessage2, (NetworkDestination)1);
			NetMessageExtensions.Send((INetMessage)(object)new TuningMessage(TuningSettings.Json), (NetworkDestination)1);
		}
	}

	public void Serialize(NetworkWriter writer)
	{
		//IL_004c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0056: Expected I4, but got Unknown
		writer.Write(stage);
		writer.Write(scene);
		writer.Write((ushort)forms.Count);
		foreach (MonsterForm form in forms)
		{
			writer.Write((int)form.Prefab.GetComponent<CharacterBody>().bodyIndex);
			writer.Write(form.Weight);
		}
	}

	public void Deserialize(NetworkReader reader)
	{
		stage = reader.ReadInt32();
		scene = reader.ReadString();
		int num = reader.ReadUInt16();
		for (int i = 0; i < num; i++)
		{
			GameObject bodyPrefab = BodyCatalog.GetBodyPrefab((BodyIndex)reader.ReadInt32());
			float num2 = reader.ReadSingle();
			if (Object.op_Implicit((Object)(object)bodyPrefab) && num2 > 0f)
			{
				forms.Add(new MonsterForm
				{
					Prefab = bodyPrefab,
					Weight = num2
				});
			}
		}
	}

	public void OnReceived()
	{
		if (!NetworkServer.active && Object.op_Implicit((Object)(object)Run.instance) && Run.instance.stageClearCount == stage && Object.op_Implicit((Object)(object)SceneInfo.instance) && Object.op_Implicit((Object)(object)SceneInfo.instance.sceneDef) && !(SceneInfo.instance.sceneDef.cachedName != scene))
		{
			MonsterPoolProvider.Forms.Clear();
			MonsterPoolProvider.Forms.AddRange(forms);
			MonsterPoolProvider.Revision++;
		}
	}
}
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
[BepInPlugin("local.monstermetamorphosis", "Monster Metamorphosis", "0.3.0")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public sealed class Plugin : BaseUnityPlugin
{
	public const string Guid = "local.monstermetamorphosis";

	public const string Version = "0.3.0";

	internal static Plugin Instance;

	internal static ManualLogSource Log;

	internal static ConfigEntry<bool> Reroll;

	internal static ConfigEntry<bool> ShowHUD;

	internal static ConfigEntry<float> DropChance;

	internal static ConfigEntry<float> BossChance;

	private Harmony harmony;

	private float nextTick;

	private float nextPoolBroadcast;

	private void Awake()
	{
		//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ad: Expected O, but got Unknown
		//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f5: Expected O, but got Unknown
		//IL_0116: Unknown result type (might be due to invalid IL or missing references)
		//IL_0120: Expected O, but got Unknown
		Instance = this;
		Log = ((BaseUnityPlugin)this).Logger;
		TextSettings.Initialize();
		Reroll = ((BaseUnityPlugin)this).Config.Bind<bool>("Artifact", "RerollOnEachStage", false, TextSettings.Get("MM_CONFIG_REROLL", "en"));
		ShowHUD = ((BaseUnityPlugin)this).Config.Bind<bool>("HUD", "ShowMonsterPool", true, TextSettings.Get("MM_CONFIG_HUD", "en"));
		DropChance = ((BaseUnityPlugin)this).Config.Bind<float>("Loot", "EssenceDropChance", 0.03f, new ConfigDescription(TextSettings.Get("MM_CONFIG_DROP", "en"), (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), new object[0]));
		BossChance = ((BaseUnityPlugin)this).Config.Bind<float>("Loot", "SpecialBossChance", 0.002f, new ConfigDescription(TextSettings.Get("MM_CONFIG_BOSS", "en"), (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), new object[0]));
		TuningSettings.Initialize();
		ModContent.Register();
		NetworkingAPI.RegisterMessageType<MonsterPoolMessage>();
		NetworkingAPI.RegisterMessageType<TuningMessage>();
		harmony = new Harmony("local.monstermetamorphosis");
		harmony.PatchAll(typeof(Plugin).Assembly);
		RoR2Application.onLoad = (Action)Delegate.Combine(RoR2Application.onLoad, new Action(OnLoaded));
		CharacterBody.onBodyStartGlobal += OnBodyStarted;
		Stage.onStageStartGlobal += OnStage;
		Run.onRunDestroyGlobal += OnRunEnded;
		Inventory.onInventoryChangedGlobal += EssenceConsumption.OnInventoryChanged;
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Monster Metamorphosis registered; waiting for game catalogs.");
	}

	private void OnLoaded()
	{
		MonsterCompatibility.PrepareCatalog();
		ModContent.FinishCatalog();
		((BaseUnityPlugin)this).Logger.LogInfo((object)("Game " + RoR2Application.GetBuildId() + "; Unity " + Application.unityVersion));
		if (Environment.GetCommandLineArgs().Contains("--mm-export"))
		{
			((MonoBehaviour)this).StartCoroutine(PoolCatalogExport.Export(quit: true));
		}
	}

	private static void OnRunEnded(Run run)
	{
		PlayerTransformationService.Reset();
		EssenceConsumption.Reset();
		MonsterPoolProvider.Clear();
		SurvivorStats.Reset();
	}

	private static void OnStage(Stage stage)
	{
		MonsterPoolProvider.Refresh();
		EssenceConsumption.OnStage();
		if (!NetworkServer.active)
		{
			return;
		}
		foreach (PlayerCharacterMasterController instance in PlayerCharacterMasterController.instances)
		{
			if (Object.op_Implicit((Object)(object)instance) && Object.op_Implicit((Object)(object)instance.master))
			{
				PlayerTransformationService.TryInitial(instance.master);
			}
		}
	}

	private static void OnBodyStarted(CharacterBody body)
	{
		if (!Object.op_Implicit((Object)(object)body) || !Object.op_Implicit((Object)(object)body.master) || !Object.op_Implicit((Object)(object)body.master.playerCharacterMasterController))
		{
			return;
		}
		MonsterCompatibility.AdaptInstance(body);
		if (SurvivorStats.Apply(body))
		{
			body.RecalculateStats();
		}
		if (SurvivorStats.IsPlayerMonster(body))
		{
			GenericSkill[] components = ((Component)body).GetComponents<GenericSkill>();
			foreach (GenericSkill val in components)
			{
				if (Object.op_Implicit((Object)(object)val.skillDef))
				{
					val.RecalculateValues();
				}
			}
		}
		if (NetworkServer.active)
		{
			PlayerTransformationService.TryInitial(body.master);
			EssenceConsumption.Queue(body.master.inventory);
		}
	}

	private void Update()
	{
		TuningSettings.Poll();
		TextSettings.Poll();
	}

	private void FixedUpdate()
	{
		if (NetworkServer.active && Object.op_Implicit((Object)(object)Run.instance) && !(Time.fixedTime < nextTick))
		{
			nextTick = Time.fixedTime + 0.2f;
			EssenceConsumption.Tick();
			if (Time.fixedTime >= nextPoolBroadcast)
			{
				nextPoolBroadcast = Time.fixedTime + 3f;
				MonsterPoolMessage.Broadcast();
			}
		}
	}

	private void OnDestroy()
	{
		RoR2Application.onLoad = (Action)Delegate.Remove(RoR2Application.onLoad, new Action(OnLoaded));
		CharacterBody.onBodyStartGlobal -= OnBodyStarted;
		Stage.onStageStartGlobal -= OnStage;
		Run.onRunDestroyGlobal -= OnRunEnded;
		Inventory.onInventoryChangedGlobal -= EssenceConsumption.OnInventoryChanged;
		if (harmony != null)
		{
			harmony.UnpatchSelf();
		}
	}
}
[HarmonyPatch(typeof(ClassicStageInfo), "RebuildCards")]
internal static class DirectorReadyPatch
{
	private static void Postfix()
	{
		MonsterPoolProvider.MarkReady();
	}
}
[HarmonyPatch(typeof(Stage), "RespawnCharacter")]
internal static class BeforeSpawnPatch
{
	private static void Prefix(CharacterMaster characterMaster)
	{
		PlayerTransformationService.TryInitial(characterMaster);
	}
}
internal static class DebugCommands
{
	[ConCommand(/*Could not decode attribute arguments.*/)]
	private static void Pool(ConCommandArgs args)
	{
		Debug.Log((object)MonsterPoolProvider.Describe());
	}

	[ConCommand(/*Could not decode attribute arguments.*/)]
	private static void Essence(ConCommandArgs args)
	{
		if (NetworkServer.active && Object.op_Implicit((Object)(object)((ConCommandArgs)(ref args)).senderMaster))
		{
			((ConCommandArgs)(ref args)).senderMaster.inventory.GiveItemPermanent(ModContent.Essence, 1);
		}
	}

	[ConCommand(/*Could not decode attribute arguments.*/)]
	private static void Transform(ConCommandArgs args)
	{
		if (NetworkServer.active && Object.op_Implicit((Object)(object)((ConCommandArgs)(ref args)).senderMaster))
		{
			GameObject prefab = ((((ConCommandArgs)(ref args)).Count > 0) ? BodyCatalog.FindBodyPrefab(((ConCommandArgs)(ref args)).GetArgString(0)) : MonsterPoolProvider.Pick());
			PlayerTransformationService.Transform(((ConCommandArgs)(ref args)).senderMaster, prefab, "console");
		}
	}
}
[Serializable]
public class BodyCatalogRow
{
	public string body;

	public string name;

	public string reason;

	public bool playable;

	public bool storyBoss;

	public bool survivor;
}
[Serializable]
public class SceneCatalogRow
{
	public string scene;

	public string name;

	public string type;

	public string expansion;
}
[Serializable]
public class PoolCatalogRow
{
	public string pool;

	public string asset;

	public string entry;

	public string condition;

	public string category;

	public string body;

	public string name;

	public string reason;

	public string requiredUnlock;

	public string forbiddenUnlock;

	public float poolWeight;

	public float entryWeight;

	public float categoryWeight;

	public float cardWeight;

	public int minStage;

	public int cost;

	public bool playable;

	public bool storyBoss;
}
[Serializable]
public class PoolCatalogDocument
{
	public int schemaVersion = 1;

	public string game;

	public string exportedUtc;

	public BodyCatalogRow[] bodies;

	public SceneCatalogRow[] scenes;

	public PoolCatalogRow[] cards;

	public string[] warnings;
}
[Serializable]
public class LivePoolRow
{
	public string scene;

	public string name;

	public string exportedUtc;

	public int stage;

	public LiveFormRow[] forms;
}
[Serializable]
public class LiveFormRow
{
	public string body;

	public string name;

	public float weight;
}
[Serializable]
public class LivePoolDocument
{
	public LivePoolRow[] pools;
}
internal static class PoolCatalogExport
{
	internal static bool Running;

	private static readonly Dictionary<string, LivePoolRow> Live = new Dictionary<string, LivePoolRow>();

	internal static void RecordLive()
	{
		if (!Object.op_Implicit((Object)(object)SceneInfo.instance) || !Object.op_Implicit((Object)(object)SceneInfo.instance.sceneDef) || !Object.op_Implicit((Object)(object)Run.instance))
		{
			return;
		}
		try
		{
			string path = Path.Combine(TuningSettings.DirectoryPath, "live-pools.json");
			if (Live.Count == 0 && File.Exists(path))
			{
				LivePoolDocument livePoolDocument = JsonUtility.FromJson<LivePoolDocument>(File.ReadAllText(path));
				if (livePoolDocument != null && livePoolDocument.pools != null)
				{
					LivePoolRow[] pools = livePoolDocument.pools;
					foreach (LivePoolRow livePoolRow in pools)
					{
						Live[livePoolRow.scene] = livePoolRow;
					}
				}
			}
			SceneDef sceneDef = SceneInfo.instance.sceneDef;
			Live[sceneDef.cachedName] = new LivePoolRow
			{
				scene = sceneDef.cachedName,
				name = Language.GetString(sceneDef.nameToken),
				stage = Run.instance.stageClearCount,
				exportedUtc = DateTime.UtcNow.ToString("o"),
				forms = MonsterPoolProvider.Forms.Select((MonsterForm f) => new LiveFormRow
				{
					body = ((Object)f.Prefab).name,
					name = f.Name,
					weight = f.Weight
				}).ToArray()
			};
			Write(path, JsonUtility.ToJson((object)new LivePoolDocument
			{
				pools = Live.Values.ToArray()
			}, true));
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Live pool export: " + ex.Message));
		}
	}

	internal static IEnumerator Export(bool quit)
	{
		if (Running)
		{
			yield break;
		}
		Running = true;
		IEnumerator work = ExportCore();
		bool success = false;
		yield return null;
		while (true)
		{
			bool more;
			try
			{
				more = work.MoveNext();
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("MM_EXPORT_FAIL " + ex));
				break;
			}
			if (!more)
			{
				success = true;
				break;
			}
			yield return work.Current;
		}
		Running = false;
		if (success)
		{
			Plugin.Log.LogInfo((object)("MM_EXPORT_PASS " + TuningSettings.DirectoryPath));
		}
		if (quit)
		{
			Application.Quit();
		}
	}

	private static Dictionary<string, IResourceLocation> Locations(Type type)
	{
		Dictionary<string, IResourceLocation> dictionary = new Dictionary<string, IResourceLocation>();
		IList<IResourceLocation> list = default(IList<IResourceLocation>);
		foreach (IResourceLocator resourceLocator in Addressables.ResourceLocators)
		{
			foreach (string item in resourceLocator.Keys.OfType<string>())
			{
				if (!item.EndsWith(".asset", StringComparison.OrdinalIgnoreCase) || !resourceLocator.Locate((object)item, type, ref list))
				{
					continue;
				}
				foreach (IResourceLocation item2 in list)
				{
					if (!dictionary.ContainsKey(item2.InternalId))
					{
						dictionary.Add(item2.InternalId, item2);
					}
				}
			}
		}
		return dictionary;
	}

	private static IEnumerator ExportCore()
	{
		Plugin.Log.LogInfo((object)"MM_EXPORT_BEGIN loading all addressable DccsPool and DCCS assets");
		List<PoolCatalogRow> rows = new List<PoolCatalogRow>();
		List<string> warnings = new List<string>();
		foreach (IResourceLocation location in Locations(typeof(DccsPool)).Values)
		{
			try
			{
				DccsPool val = Addressables.LoadAssetAsync<DccsPool>(location).WaitForCompletion();
				if (Object.op_Implicit((Object)(object)val) && val.poolCategories != null)
				{
					Category[] poolCategories = val.poolCategories;
					foreach (Category val2 in poolCategories)
					{
						if (val2 != null)
						{
							AddEntries(rows, ((Object)val).name, location.PrimaryKey, val2.name, val2.categoryWeight, val2.alwaysIncluded, "always");
							AddEntries(rows, ((Object)val).name, location.PrimaryKey, val2.name, val2.categoryWeight, (PoolEntry[])(object)val2.includedIfConditionsMet, "conditional DLC");
							AddEntries(rows, ((Object)val).name, location.PrimaryKey, val2.name, val2.categoryWeight, val2.includedIfNoConditionsMet, "fallback if no conditional entries match");
						}
					}
				}
			}
			catch (Exception ex)
			{
				warnings.Add(location.PrimaryKey + ": " + ex.Message);
			}
			yield return null;
		}
		foreach (IResourceLocation location2 in Locations(typeof(DirectorCardCategorySelection)).Values)
		{
			try
			{
				DirectorCardCategorySelection val3 = Addressables.LoadAssetAsync<DirectorCardCategorySelection>(location2).WaitForCompletion();
				AddSelection(rows, "[DCCS] " + ((Object)val3).name, location2.PrimaryKey, ((Object)val3).name, 1f, 1f, val3, "standalone asset; selection conditions depend on its pool");
			}
			catch (Exception ex2)
			{
				warnings.Add(location2.PrimaryKey + ": " + ex2.Message);
			}
			yield return null;
		}
		PoolCatalogDocument document = new PoolCatalogDocument
		{
			game = RoR2Application.GetBuildId(),
			exportedUtc = DateTime.UtcNow.ToString("o"),
			cards = rows.ToArray(),
			warnings = warnings.ToArray(),
			bodies = BodyCatalog.allBodyPrefabs.Select(delegate(GameObject p)
			{
				//IL_0056: 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)
				string reason;
				bool playable = MonsterCompatibility.IsSupported(p, out reason);
				return new BodyCatalogRow
				{
					body = ((Object)p).name,
					name = Util.GetBestBodyName(p),
					playable = playable,
					reason = (reason ?? ""),
					storyBoss = SpecialBossRegistry.IsStoryBoss(((Object)p).name),
					survivor = Object.op_Implicit((Object)(object)SurvivorCatalog.GetSurvivorDef(SurvivorCatalog.GetSurvivorIndexFromBodyIndex(p.GetComponent<CharacterBody>().bodyIndex)))
				};
			}).ToArray(),
			scenes = ((IEnumerable<SceneDef>)(object)SceneCatalog.allSceneDefs).Select((SceneDef s) => new SceneCatalogRow
			{
				scene = s.cachedName,
				name = Language.GetString(s.nameToken),
				type = ((object)s.sceneType).ToString(),
				expansion = (Object.op_Implicit((Object)(object)s.requiredExpansion) ? ((Object)s.requiredExpansion).name : "")
			}).ToArray()
		};
		Write(Path.Combine(TuningSettings.DirectoryPath, "catalog.json"), JsonUtility.ToJson((object)document, true));
		Plugin.Log.LogInfo((object)("Exported bodies=" + document.bodies.Length + " enemy cards=" + rows.Count + " pools=" + rows.Select((PoolCatalogRow r) => r.pool).Distinct().Count() + " warnings=" + warnings.Count));
	}

	private static void AddEntries(List<PoolCatalogRow> rows, string pool, string asset, string category, float weight, PoolEntry[] entries, string condition)
	{
		if (entries == null)
		{
			return;
		}
		foreach (PoolEntry val in entries)
		{
			if (val == null || !Object.op_Implicit((Object)(object)val.dccs))
			{
				continue;
			}
			ConditionalPoolEntry val2 = (ConditionalPoolEntry)(object)((val is ConditionalPoolEntry) ? val : null);
			string text = category + "; " + condition;
			if (val2 != null && val2.requiredExpansions != null)
			{
				text = text + ": " + string.Join(", ", (from e in val2.requiredExpansions
					where Object.op_Implicit((Object)(object)e)
					select ((Object)e).name).ToArray());
			}
			AddSelection(rows, pool, asset, ((Object)val.dccs).name, weight, val.weight, val.dccs, text);
		}
	}

	private static void AddSelection(List<PoolCatalogRow> rows, string pool, string asset, string entry, float poolWeight, float entryWeight, DirectorCardCategorySelection selection, string condition)
	{
		//IL_00af: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
		if (!Object.op_Implicit((Object)(object)selection) || selection.categories == null)
		{
			return;
		}
		FamilyDirectorCardCategorySelection val = (FamilyDirectorCardCategorySelection)(object)((selection is FamilyDirectorCardCategorySelection) ? selection : null);
		if (Object.op_Implicit((Object)(object)val))
		{
			object obj = condition;
			condition = string.Concat(obj, "; family stages completed [", AccessTools.Field(typeof(FamilyDirectorCardCategorySelection), "minimumStageCompletion").GetValue(val), ", ", AccessTools.Field(typeof(FamilyDirectorCardCategorySelection), "maximumStageCompletion").GetValue(val), ")");
		}
		Category[] categories = selection.categories;
		for (int i = 0; i < categories.Length; i++)
		{
			Category val2 = categories[i];
			DirectorCard[] array = (DirectorCard[])(((object)val2.cards) ?? ((object)new DirectorCard[0]));
			foreach (DirectorCard val3 in array)
			{
				if (val3 == null)
				{
					continue;
				}
				SpawnCard spawnCard = val3.GetSpawnCard();
				CharacterSpawnCard val4 = (CharacterSpawnCard)(object)((spawnCard is CharacterSpawnCard) ? spawnCard : null);
				CharacterMaster val5 = ((Object.op_Implicit((Object)(object)val4) && Object.op_Implicit((Object)(object)((SpawnCard)val4).prefab)) ? ((SpawnCard)val4).prefab.GetComponent<CharacterMaster>() : null);
				if (!Object.op_Implicit((Object)(object)val5) || !Object.op_Implicit((Object)(object)val5.bodyPrefab))
				{
					continue;
				}
				string reason;
				bool playable = MonsterCompatibility.IsSupported(val5.bodyPrefab, out reason);
				string text = condition;
				ExpansionRequirementComponent val6 = ((SpawnCard)val4).prefab.GetComponent<ExpansionRequirementComponent>() ?? val5.bodyPrefab.GetComponent<ExpansionRequirementComponent>();
				if (Object.op_Implicit((Object)(object)val6) && Object.op_Implicit((Object)(object)val6.requiredExpansion))
				{
					text = text + "; body DLC: " + ((Object)val6.requiredExpansion).name;
				}
				IDirectorAvailability[] components = ((SpawnCard)val4).prefab.GetComponents<IDirectorAvailability>();
				if (components.Length > 0)
				{
					text = text + "; dynamic availability: " + string.Join(", ", components.Select((IDirectorAvailability a) => ((object)a).GetType().Name).ToArray());
				}
				rows.Add(new PoolCatalogRow
				{
					pool = pool,
					asset = asset,
					entry = entry,
					condition = text,
					category = val2.name,
					body = ((Object)val5.bodyPrefab).name,
					name = Util.GetBestBodyName(val5.bodyPrefab),
					reason = (reason ?? ""),
					playable = playable,
					storyBoss = SpecialBossRegistry.IsStoryBoss(((Object)val5.bodyPrefab).name),
					poolWeight = poolWeight,
					entryWeight = entryWeight,
					categoryWeight = val2.selectionWeight,
					cardWeight = val3.selectionWeight,
					minStage = val3.minimumStageCompletions,
					cost = ((SpawnCard)val4).directorCreditCost,
					requiredUnlock = (Object.op_Implicit((Object)(object)val3.requiredUnlockableDef) ? val3.requiredUnlockableDef.cachedName : val3.requiredUnlockable),
					forbiddenUnlock = (Object.op_Implicit((Object)(object)val3.forbiddenUnlockableDef) ? val3.forbiddenUnlockableDef.cachedName : val3.forbiddenUnlockable)
				});
			}
		}
	}

	private static void Write(string path, string text)
	{
		string text2 = path + ".tmp";
		File.WriteAllText(text2, text);
		if (File.Exists(path))
		{
			File.Replace(text2, path, null);
		}
		else
		{
			File.Move(text2, path);
		}
	}
}
internal static class SurvivorStats
{
	private static readonly Dictionary<CharacterMaster, object[]> Originals = new Dictionary<CharacterMaster, object[]>();

	private static readonly string[] Names = new string[22]
	{
		"baseMaxHealth", "baseRegen", "baseMaxShield", "baseMoveSpeed", "baseAcceleration", "baseJumpPower", "baseDamage", "baseAttackSpeed", "baseCrit", "baseArmor",
		"baseVisionDistance", "baseJumpCount", "sprintingSpeedMultiplier", "levelMaxHealth", "levelRegen", "levelMaxShield", "levelMoveSpeed", "levelJumpPower", "levelDamage", "levelAttackSpeed",
		"levelCrit", "levelArmor"
	};

	private static readonly FieldInfo[] Fields = Array.ConvertAll(Names, (string n) => AccessTools.Field(typeof(CharacterBody), n));

	internal static string[] StatNames => Names;

	internal static void Reset()
	{
		Originals.Clear();
	}

	internal static void Capture(CharacterMaster master)
	{
		//IL_003e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0044: Invalid comparison between Unknown and I4
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
		if (!Object.op_Implicit((Object)(object)master) || !Object.op_Implicit((Object)(object)master.playerCharacterMasterController) || Originals.ContainsKey(master))
		{
			return;
		}
		NetworkUser networkUser = master.playerCharacterMasterController.networkUser;
		GameObject val = ((Object.op_Implicit((Object)(object)networkUser) && (int)networkUser.bodyIndexPreference != -1) ? BodyCatalog.GetBodyPrefab(networkUser.bodyIndexPreference) : null);
		if (!Object.op_Implicit((Object)(object)val))
		{
			val = (Object.op_Implicit((Object)(object)master.originalBodyPrefab) ? master.originalBodyPrefab : master.bodyPrefab);
		}
		if (!Object.op_Implicit((Object)(object)val))
		{
			return;
		}
		CharacterBody source = val.GetComponent<CharacterBody>();
		if (Object.op_Implicit((Object)(object)source) && Object.op_Implicit((Object)(object)SurvivorCatalog.GetSurvivorDef(SurvivorCatalog.GetSurvivorIndexFromBodyIndex(source.bodyIndex))))
		{
			Originals.Add(master, Array.ConvertAll(Fields, (FieldInfo f) => f.GetValue(source)));
		}
	}

	internal static bool IsPlayerMonster(CharacterBody body)
	{
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		if (Object.op_Implicit((Object)(object)body) && Object.op_Implicit((Object)(object)body.master) && Object.op_Implicit((Object)(object)body.master.playerCharacterMasterController))
		{
			return !Object.op_Implicit((Object)(object)SurvivorCatalog.GetSurvivorDef(SurvivorCatalog.GetSurvivorIndexFromBodyIndex(body.bodyIndex)));
		}
		return false;
	}

	internal static bool Apply(CharacterBody body)
	{
		if (!IsPlayerMonster(body))
		{
			return false;
		}
		Capture(body.master);
		if (!Originals.TryGetValue(body.master, out var value))
		{
			return false;
		}
		for (int i = 0; i < Fields.Length; i++)
		{
			Fields[i].SetValue(body, value[i]);
		}
		TuningSettings.Apply(body);
		return true;
	}
}
[HarmonyPatch(typeof(CharacterBody), "RecalculateStats")]
internal static class SurvivorStatsPatch
{
	private static void Prefix(CharacterBody __instance)
	{
		SurvivorStats.Apply(__instance);
	}
}
[HarmonyPatch(typeof(GenericSkill), "CalculateFinalRechargeInterval")]
internal static class MonsterRechargePatch
{
	private static void Postfix(GenericSkill __instance, ref float __result)
	{
		if (SurvivorStats.IsPlayerMonster(__instance.characterBody))
		{
			__result /= TuningSettings.RechargeRate(__instance.characterBody);
		}
	}
}
[HarmonyPatch(typeof(GenericSkill), "RechargeBaseSkill")]
internal static class MonsterBaseRechargePatch
{
	private static void Prefix(GenericSkill __instance, ref float dt)
	{
		if (SurvivorStats.IsPlayerMonster(__instance.characterBody))
		{
			dt *= TuningSettings.RechargeRate(__instance.characterBody);
		}
	}
}
[Serializable]
public class ModText
{
	public string token;

	public string label;

	public string en;

	public string ru;
}
[Serializable]
public class TextDocument
{
	public int schemaVersion = 1;

	public ModText[] texts = new ModText[0];
}
internal static class TextSettings
{
	internal static string Json;

	private static DateTime lastWrite;

	private static float nextPoll;

	private static LanguageOverlay overlay;

	private static TextDocument current;

	internal static string FilePath => Path.Combine(TuningSettings.DirectoryPath, "localization.json");

	private static ModText T(string token, string label, string en, string ru)
	{
		ModText modText = new ModText();
		modText.token = token;
		modText.label = label;
		modText.en = en;
		modText.ru = ru;
		return modText;
	}

	internal static TextDocument Defaults()
	{
		TextDocument textDocument = new TextDocument();
		textDocument.texts = new ModText[13]
		{
			T("MM_ARTIFACT_NAME", "Название артефакта", "Artifact of Monster Metamorphosis", "Артефакт чудовищной метаморфозы"),
			T("MM_ARTIFACT_DESCRIPTION", "Описание артефакта", "Begin the run as a random monster from the first stage's enemy pool.", "Начните забег случайным монстром из пула врагов первой локации."),
			T("MM_ESSENCE_NAME", "Название предмета", "Unstable Essence", "Нестабильная сущность"),
			T("MM_ESSENCE_PICKUP", "Текст при подборе предмета", "Transform into a monster from this stage. Consumed on use.", "Превращает в монстра текущей локации. Расходуется при использовании."),
			T("MM_ESSENCE_DESCRIPTION", "Полное описание предмета", "On pickup, <style=cIsUtility>transform</style> into a random monster from the current stage's enemy pool. <style=cIsUtility>Consumed</style> after a successful transformation.", "При подборе <style=cIsUtility>превращает</style> вас в случайного монстра из пула врагов текущей локации. <style=cIsUtility>Расходуется</style> после успешного превращения."),
			T("MM_ESSENCE_LORE", "История предмета", "A possibility, impatient to become flesh.", "Возможность, которой не терпится обрести плоть."),
			T("MM_MONSTERS", "Заголовок панели монстров", "Monsters", "Монстры"),
			T("MM_POOL", "Подсказка пула форм", "STAGE FORMS", "ФОРМЫ ЛОКАЦИИ"),
			T("MM_EMPTY", "Сообщение о пустом пуле", "No eligible forms on this stage", "На этой локации нет доступных форм"),
			T("MM_CONFIG_REROLL", "Подсказка настройки повторного выбора", "Choose a new monster at every stage. Otherwise retain the current form.", "Выбирать нового монстра на каждом этапе. Иначе текущая форма сохраняется."),
			T("MM_CONFIG_HUD", "Подсказка настройки панели", "Display the current Director pool below the timer.", "Показывать действующий пул форм Director под таймером."),
			T("MM_CONFIG_DROP", "Подсказка вероятности предмета", "Chance per eligible normal/large chest or chance shrine reward; replaces the reward.", "Шанс замены обычной награды сундука, большого сундука или святилища удачи на сущность."),
			T("MM_CONFIG_BOSS", "Подсказка вероятности босса", "Separate roll on the matching boss stage when consuming essence.", "Отдельный шанс при расходовании сущности на соответствующей локации босса.")
		};
		return textDocument;
	}

	internal static void Initialize()
	{
		Directory.CreateDirectory(TuningSettings.DirectoryPath);
		File.WriteAllText(Path.Combine(TuningSettings.DirectoryPath, "text-defaults.json"), JsonUtility.ToJson((object)Defaults(), true));
		if (!File.Exists(FilePath))
		{
			string path = Path.Combine(ModContent.AssetDirectory, "localization.json");
			File.WriteAllText(FilePath, File.Exists(path) ? File.ReadAllText(path) : JsonUtility.ToJson((object)Defaults(), true));
		}
		current = Defaults();
		Json = JsonUtility.ToJson((object)current, true);
		Load(File.ReadAllText(FilePath));
		lastWrite = File.GetLastWriteTimeUtc(FilePath);
	}

	internal static bool Load(string json)
	{
		try
		{
			TextDocument textDocument = JsonUtility.FromJson<TextDocument>(json);
			if (textDocument == null || textDocument.schemaVersion != 1 || textDocument.texts == null)
			{
				throw new Exception("Invalid localization document");
			}
			Dictionary<string, ModText> dictionary = Defaults().texts.ToDictionary((ModText t) => t.token);
			HashSet<string> hashSet = new HashSet<string>();
			ModText[] texts = textDocument.texts;
			foreach (ModText modText in texts)
			{
				if (modText == null || string.IsNullOrEmpty(modText.token) || !modText.token.StartsWith("MM_", StringComparison.Ordinal) || !hashSet.Add(modText.token) || modText.en == null || modText.ru == null || modText.en.Length > 16000 || modText.ru.Length > 16000)
				{
					throw new Exception("Invalid localization entry");
				}
				dictionary[modText.token] = modText;
			}
			TextDocument textDocument2 = new TextDocument();
			textDocument2.texts = dictionary.Values.ToArray();
			TextDocument textDocument3 = textDocument2;
			Dictionary<string, Dictionary<string, string>> dictionary2 = new Dictionary<string, Dictionary<string, string>>();
			dictionary2.Add("generic", textDocument3.texts.ToDictionary((ModText t) => t.token, (ModText t) => t.en));
			dictionary2.Add("en", textDocument3.texts.ToDictionary((ModText t) => t.token, (ModText t) => t.en));
			dictionary2.Add("ru", textDocument3.texts.ToDictionary((ModText t) => t.token, (ModText t) => t.ru));
			Dictionary<string, Dictionary<string, string>> dictionary3 = dictionary2;
			LanguageOverlay val = LanguageAPI.AddOverlay(dictionary3);
			if (overlay != null)
			{
				overlay.Remove();
			}
			overlay = val;
			current = textDocument3;
			Json = JsonUtility.ToJson((object)textDocument3, true);
			LanguageTextMeshController[] array = Object.FindObjectsOfType<LanguageTextMeshController>();
			foreach (LanguageTextMeshController val2 in array)
			{
				if (val2.token != null && val2.token.StartsWith("MM_", StringComparison.Ordinal))
				{
					val2.formatArgs = val2.formatArgs;
				}
			}
			return true;
		}
		catch (Exception ex)
		{
			Plugin.Log.LogError((object)("Localization rejected; previous text retained: " + ex.Message));
			return false;
		}
	}

	internal static void RegisterLanguage()
	{
		ModText[] texts = Defaults().texts;
		foreach (ModText modText in texts)
		{
			LanguageAPI.Add(modText.token, modText.en);
			LanguageAPI.Add(modText.token, modText.en, "en");
			LanguageAPI.Add(modText.token, modText.ru, "ru");
		}
	}

	internal static string Get(string token, string language)
	{
		ModText modText = current.texts.First((ModText v) => v.token == token);
		if (!(language == "ru"))
		{
			return modText.en;
		}
		return modText.ru;
	}

	internal static void Poll()
	{
		if (Time.unscaledTime < nextPoll)
		{
			return;
		}
		nextPoll = Time.unscaledTime + 2f;
		try
		{
			DateTime lastWriteTimeUtc = File.GetLastWriteTimeUtc(FilePath);
			if (lastWriteTimeUtc != lastWrite && File.Exists(FilePath))
			{
				lastWrite = lastWriteTimeUtc;
				if (Load(File.ReadAllText(FilePath)))
				{
					Plugin.Log.LogInfo((object)"Mod localization reloaded.");
				}
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Localization reload: " + ex.Message));
		}
	}
}
[HarmonyPatch(typeof(Run), "BuildDropTable")]
internal static class EssenceAvailability
{
	private static void Prefix(Run __instance)
	{
		//IL_0011: Unknown result type (might be due to invalid IL or missing references)
		//IL_0017: Invalid comparison between Unknown and I4
		//IL_0030: Unknown result type (might be due to invalid IL or missing references)
		if (Object.op_Implicit((Object)(object)ModContent.Essence) && (int)ModContent.Essence.itemIndex != -1 && RuleCatalog.FindRuleDef("Items.UnstableEssence") == null)
		{
			__instance.availableItems.Add(ModContent.Essence.itemIndex);
		}
	}
}
internal static class PlayerTransformationService
{
	private static readonly HashSet<CharacterMaster> Busy = new HashSet<CharacterMaster>();

	private static readonly Dictionary<CharacterMaster, int> InitialStages = new Dictionary<CharacterMaster, int>();

	internal static void Reset()
	{
		Busy.Clear();
		InitialStages.Clear();
	}

	internal static bool IsBusy(CharacterMaster master)
	{
		return Busy.Contains(master);
	}

	internal static void TryInitial(CharacterMaster master)
	{
		if (!NetworkServer.active || !Object.op_Implicit((Object)(object)master) || !Object.op_Implicit((Object)(object)master.playerCharacterMasterController) || !Object.op_Implicit((Object)(object)Run.instance) || !Object.op_Implicit((Object)(object)Stage.instance) || !Object.op_Implicit((Object)(object)RunArtifactManager.instance) || !RunArtifactManager.instance.IsArtifactEnabled(ModContent.Artifact))
		{
			return;
		}
		int stageClearCount = Run.instance.stageClearCount;
		if (MonsterPoolProvider.ReadyStage == stageClearCount && (!InitialStages.TryGetValue(master, out var value) || (Plugin.Reroll.Value && value != stageClearCount)) && Object.op_Implicit((Object)(object)ClassicStageInfo.instance) && ClassicStageInfo.instance.monsterSelection != null)
		{
			GameObject val = MonsterPoolProvider.Pick();
			if (Object.op_Implicit((Object)(object)val))
			{
				InitialStages[master] = stageClearCount;
				Transform(master, val, "artifact");
			}
		}
	}

	internal static bool Transform(CharacterMaster master, GameObject prefab, string source)
	{
		//IL_015b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0153: Unknown result type (might be due to invalid IL or missing references)
		//IL_0160: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c3: Expected O, but got Unknown
		//IL_0187: Unknown result type (might be due to invalid IL or missing references)
		//IL_0192: Unknown result type (might be due to invalid IL or missing references)
		//IL_0200: Unknown result type (might be due to invalid IL or missing references)
		if (!NetworkServer.active || !Object.op_Implicit((Object)(object)master) || !Object.op_Implicit((Object)(object)master.playerCharacterMasterController) || !Object.op_Implicit((Object)(object)prefab) || Busy.Contains(master))
		{
			return false;
		}
		if (!MonsterCompatibility.IsSupported(prefab, out var reason))
		{
			Plugin.Log.LogWarning((object)("Cannot transform to " + ((Object)prefab).name + ": " + reason));
			return false;
		}
		Busy.Add(master);
		try
		{
			SurvivorStats.Capture(master);
			CharacterBody body = master.GetBody();
			if (Object.op_Implicit((Object)(object)body) && Object.op_Implicit((Object)(object)body.healthComponent) && !body.healthComponent.alive)
			{
				return false;
			}
			if (!Object.op_Implicit((Object)(object)body))
			{
				master.PushBodyHandlingConfig(new BodyHandlingConfig(prefab.GetComponent<CharacterBody>().bodyIndex, (BodyHandlingPresetIndex)1), prefab, true);
				return true;
			}
			float num = (Object.op_Implicit((Object)(object)body.healthComponent) ? (body.healthComponent.health / Mathf.Max(1f, body.healthComponent.fullHealth)) : 1f);
			GameObject bodyPrefab = master.bodyPrefab;
			try
			{
				master.TransformBody(((Object)prefab).name);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("TransformBody failed: " + ex));
				if (!Object.op_Implicit((Object)(object)master.GetBody()) && Object.op_Implicit((Object)(object)bodyPrefab))
				{
					master.bodyPrefab = bodyPrefab;
					master.Respawn(Object.op_Implicit((Object)(object)body) ? body.footPosition : Vector3.zero, Quaternion.identity, false);
				}
				return false;
			}
			CharacterBody body2 = master.GetBody();
			if (!Object.op_Implicit((Object)(object)body2) || body2.bodyIndex != prefab.GetComponent<CharacterBody>().bodyIndex)
			{
				return false;
			}
			body2.RecalculateStats();
			if (Object.op_Implicit((Object)(object)body2.healthComponent))
			{
				body2.healthComponent.Networkhealth = Mathf.Max(1f, body2.healthComponent.fullHealth * Mathf.Clamp01(num));
			}
			MonsterCompatibility.AdaptInstance(body2);
			Plugin.Log.LogInfo((object)string.Concat("Transformed master ", ((NetworkBehaviour)master).netId, " -> ", ((Object)prefab).name, " (", source, ") health=", num.ToString("P0")));
			return true;
		}
		finally
		{
			Busy.Remove(master);
		}
	}
}
internal static class EssenceConsumption
{
	private static readonly HashSet<Inventory> Pending = new HashSet<Inventory>();

	private static readonly HashSet<Inventory> Processing = new HashSet<Inventory>();

	private static readonly HashSet<Inventory> Failed = new HashSet<Inventory>();

	internal static void Reset()
	{
		Pending.Clear();
		Processing.Clear();
		Failed.Clear();
	}

	internal static void OnStage()
	{
		if (!NetworkServer.active)
		{
			return;
		}
		Failed.Clear();
		foreach (PlayerCharacterMasterController instance in PlayerCharacterMasterController.instances)
		{
			if (Object.op_Implicit((Object)(object)instance) && Object.op_Implicit((Object)(object)instance.master))
			{
				Queue(instance.master.inventory);
			}
		}
	}

	internal static void OnInventoryChanged(Inventory inventory)
	{
		if (NetworkServer.active && Object.op_Implicit((Object)(object)inventory) && Object.op_Implicit((Object)(object)ModContent.Essence) && !Processing.Contains(inventory) && inventory.GetItemCountPermanent(ModContent.Essence) > 0)
		{
			Failed.Remove(inventory);
			Queue(inventory);
		}
	}

	internal static void Queue(Inventory inventory)
	{
		if (NetworkServer.active && Object.op_Implicit((Object)(object)inventory) && inventory.GetItemCountPermanent(ModContent.Essence) > 0 && !Processing.Contains(inventory) && !Failed.Contains(inventory))
		{
			Pending.Add(inventory);
		}
	}

	internal static void Tick()
	{
		List<Inventory> list = new List<Inventory>(Pending);
		Pending.Clear();
		foreach (Inventory item in list)
		{
			if (!Object.op_Implicit((Object)(object)item) || item.GetItemCountPermanent(ModContent.Essence) <= 0)
			{
				continue;
			}
			CharacterMaster component = ((Component)item).GetComponent<CharacterMaster>();
			if (!Object.op_Implicit((Object)(object)component) || !Object.op_Implicit((Object)(object)component.playerCharacterMasterController))
			{
				continue;
			}
			CharacterBody body = component.GetBody();
			if (!Object.op_Implicit((Object)(object)body) || !Object.op_Implicit((Object)(object)body.healthComponent) || !body.healthComponent.alive)
			{
				continue;
			}
			if (PlayerTransformationService.IsBusy(component))
			{
				Pending.Add(item);
				continue;
			}
			Processing.Add(item);
			try
			{
				GameObject val = SpecialBossRegistry.TryPick() ?? MonsterPoolProvider.Pick();
				if (Object.op_Implicit((Object)(object)val) && PlayerTransformationService.Transform(component, val, "essence"))
				{
					item.RemoveItemPermanent(ModContent.Essence, 1);
					if (item.GetItemCountPermanent(ModContent.Essence) > 0)
					{
						Pending.Add(item);
					}
				}
				else
				{
					Failed.Add(item);
					Plugin.Log.LogWarning((object)"Unstable Essence retained: no valid transformation. Retrying only on a later inventory/body/stage event.");
				}
			}
			finally
			{
				Processing.Remove(item);
			}
		}
	}
}
[HarmonyPatch(typeof(BasicPickupDropTable), "GeneratePickupPreReplacement")]
internal static class EssenceDropController
{
	internal static readonly Dictionary<string, string> TableAddresses = new Dictionary<string, string>
	{
		{ "dtChest1", "RoR2/Base/Chest1/dtChest1.asset" },
		{ "dtChest2", "RoR2/Base/Chest2/dtChest2.asset" },
		{ "dtShrineChance", "RoR2/Base/ShrineChance/dtShrineChance.asset" }
	};

	internal static bool Eligible(BasicPickupDropTable table, UniquePickup pickup)
	{
		//IL_003b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0040: Unknown result type (might be due to invalid IL or missing references)
		//IL_0050: Unknown result type (might be due to invalid IL or missing references)
		//IL_005f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0076: 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: Invalid comparison between Unknown and I4
		//IL_0087: Unknown result type (might be due to invalid IL or missing references)
		//IL_008d: Invalid comparison between Unknown and I4
		if (!Object.op_Implicit((Object)(object)table) || !TableAddresses.ContainsKey(((Object)table).name) || !((UniquePickup)(ref pickup)).isValid || ((UniquePickup)(ref pickup)).isTempItem || pickup.isRental || !table.PassesFilter(PickupCatalog.FindPickupIndex(ModContent.Essence.itemIndex)))
		{
			return false;
		}
		PickupDef pickupDef = PickupCatalog.GetPickupDef(pickup.pickupIndex);
		ItemDef val = ((pickupDef == null) ? null : ItemCatalog.GetItemDef(pickupDef.itemIndex));
		if (Object.op_Implicit((Object)(object)val))
		{
			if ((int)val.tier != 0 && (int)val.tier != 1)
			{
				return (int)val.tier == 2;
			}
			return true;
		}
		return false;
	}

	private static void Postfix(BasicPickupDropTable __instance, Xoroshiro128Plus rng, ref UniquePickup __result)
	{
		//IL_0015: 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_0051: Unknown result type (might be due to invalid IL or missing references)
		//IL_0056: Unknown result type (might be due to invalid IL or missing references)
		//IL_005b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0060: Unknown result type (might be due to invalid IL or missing references)
		if (NetworkServer.active && Object.op_Implicit((Object)(object)Run.instance) && Eligible(__instance, __result) && Run.instance.IsItemAvailable(ModContent.Essence.itemIndex) && rng.nextNormalizedFloat < Plugin.DropChance.Value)
		{
			__result = ((UniquePickup)(ref __result)).WithPickupIndex(PickupCatalog.FindPickupIndex(ModContent.Essence.itemIndex));
		}
	}
}
[HarmonyPatch(typeof(Inventory), "GiveItemTemp", new Type[]
{
	typeof(ItemIndex),
	typeof(float)
})]
internal static class TemporaryEssenceGuard
{
	private static bool Prefix(ItemIndex itemIndex, float countToAdd)
	{
		//IL_000c: 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)
		if (Object.op_Implicit((Object)(object)ModContent.Essence) && itemIndex == ModContent.Essence.itemIndex)
		{
			return countToAdd <= 0f;
		}
		return true;
	}
}
public sealed class TuningMessage : INetMessage, ISerializableObject
{
	private string json;

	public TuningMessage()
	{
	}

	internal TuningMessage(string value)
	{
		json = value;
	}

	public void Serialize(NetworkWriter writer)
	{
		using MemoryStream memoryStream = new MemoryStream();
		using (GZipStream gZipStream = new GZipStream(memoryStream, CompressionMode.Compress, leaveOpen: true))
		{
			byte[] bytes = Encoding.UTF8.GetBytes(json);
			gZipStream.Write(bytes, 0, bytes.Length);
		}
		writer.WriteBytesFull(memoryStream.ToArray());
	}

	public void Deserialize(NetworkReader reader)
	{
		using MemoryStream stream = new MemoryStream(reader.ReadBytesAndSize());
		using GZipStream stream2 = new GZipStream(stream, CompressionMode.Decompress);
		using StreamReader streamReader = new StreamReader(stream2);
		json = streamReader.ReadToEnd();
	}

	public void OnReceived()
	{
		if (!NetworkServer.active)
		{
			TuningSettings.ReceiveFromHost(json);
		}
	}
}
[Serializable]
public class StatModifier
{
	public string stat;

	public float multiplier = 1f;
}
[Serializable]
public class MonsterModifier
{
	public string body;

	public float rechargeRate = 1.3f;

	public StatModifier[] stats = new StatModifier[0];
}
[Serializable]
public class ModifierDocument
{
	public int schemaVersion = 1;

	public MonsterModifier[] monsters = new MonsterModifier[0];
}
internal static class TuningSettings
{
	internal static string Json = "{\"schemaVersion\":1,\"monsters\":[]}";

	private static Dictionary<string, MonsterModifier> modifiers = new Dictionary<string, MonsterModifier>(StringComparer.Ordinal);

	private static DateTime lastWrite;

	private static float nextPoll;

	private static bool receivedFromHost;

	internal static string DirectoryPath => Path.Combine(Paths.ConfigPath, "MonsterMetamorphosis");

	internal static string FilePath => Path.Combine(DirectoryPath, "monster-modifiers.json");

	internal static void ReceiveFromHost(string json)
	{
		receivedFromHost = true;
		if (json != Json)
		{
			Load(json);
		}
	}

	internal static void Initialize()
	{
		Directory.CreateDirectory(DirectoryPath);
		if (!File.Exists(FilePath))
		{
			string path = Path.Combine(ModContent.AssetDirectory, "monster-modifiers.json");
			File.WriteAllText(FilePath, File.Exists(path) ? File.ReadAllText(path) : Json);
		}
		Load(File.ReadAllText(FilePath));
		lastWrite = File.GetLastWriteTimeUtc(FilePath);
	}

	internal static bool Load(string json)
	{
		try
		{
			ModifierDocument modifierDocument = JsonUtility.FromJson<ModifierDocument>(json);
			if (modifierDocument == null || modifierDocument.schemaVersion != 1 || modifierDocument.monsters == null)
			{
				throw new Exception("Unsupported modifier document");
			}
			Dictionary<string, MonsterModifier> dictionary = new Dictionary<string, MonsterModifier>(StringComparer.Ordinal);
			MonsterModifier[] monsters = modifierDocument.monsters;
			foreach (MonsterModifier monsterModifier in monsters)
			{
				if (monsterModifier == null || string.IsNullOrEmpty(monsterModifier.body) || dictionary.ContainsKey(monsterModifier.body) || !Valid(monsterModifier.rechargeRate, 0.05f, 100f) || monsterModifier.stats == null)
				{
					throw new Exception("Invalid monster modifier");
				}
				HashSet<string> hashSet = new HashSet<string>();
				StatModifier[] stats = monsterModifier.stats;
				foreach (StatModifier statModifier in stats)
				{
					if (statModifier == null || !SurvivorStats.StatNames.Contains(statModifier.stat) || !hashSet.Add(statModifier.stat) || !Valid(statModifier.multiplier, (statModifier.stat == "baseMaxHealth") ? 0.01f : 0f, 100f))
					{
						throw new Exception("Invalid stat multiplier for " + monsterModifier.body);
					}
				}
				dictionary.Add(monsterModifier.body, monsterModifier);
			}
			modifiers = dictionary;
			Json = json;
			foreach (CharacterBody readOnlyInstances in CharacterBody.readOnlyInstancesList)
			{
				if (!SurvivorStats.IsPlayerMonster(readOnlyInstances))
				{
					continue;
				}
				readOnlyInstances.RecalculateStats();
				GenericSkill[] components = ((Component)readOnlyInstances).GetComponents<GenericSkill>();
				foreach (GenericSkill val in components)
				{
					if (Object.op_Implicit((Object)(object)val.skillDef))
					{
						val.RecalculateValues();
					}
				}
			}
			return true;
		}
		catch (Exception ex)
		{
			Plugin.Log.LogError((object)("Modifiers rejected; previous settings retained: " + ex.Message));
			return false;
		}
	}

	private static bool Valid(float value, float min, float max)
	{
		if (!float.IsNaN(value) && !float.IsInfinity(value) && value >= min)
		{
			return value <= max;
		}
		return false;
	}

	internal static void Poll()
	{
		if (Time.unscaledTime < nextPoll)
		{
			return;
		}
		nextPoll = Time.unscaledTime + 2f;
		if (NetworkClient.active && !NetworkServer.active)
		{
			return;
		}
		if (receivedFromHost)
		{
			lastWrite = DateTime.MinValue;
			receivedFromHost = false;
		}
		try
		{
			DateTime lastWriteTimeUtc = File.GetLastWriteTimeUtc(FilePath);
			if (lastWriteTimeUtc != lastWrite && File.Exists(FilePath))
			{
				lastWrite = lastWriteTimeUtc;
				if (Load(File.ReadAllText(FilePath)))
				{
					Plugin.Log.LogInfo((object)"Monster modifiers reloaded from utility.");
				}
			}
			string path = Path.Combine(DirectoryPath, "export-request.txt");
			if (File.Exists(path) && !PoolCatalogExport.Running)
			{
				File.Delete(path);
				((MonoBehaviour)Plugin.Instance).StartCoroutine(PoolCatalogExport.Export(quit: false));
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Modifier reload/export: " + ex.Message));
		}
	}

	internal static void Apply(CharacterBody body)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		GameObject bodyPrefab = BodyCatalog.GetBodyPrefab(body.bodyIndex);
		if (!Object.op_Implicit((Object)(object)bodyPrefab) || !modifiers.TryGetValue(((Object)bodyPrefab).name, out var value))
		{
			return;
		}
		StatModifier[] stats = value.stats;
		foreach (StatModifier statModifier in stats)
		{
			FieldInfo field = typeof(CharacterBody).GetField(statModifier.stat, BindingFlags.Instance | BindingFlags.Public);
			if (field.FieldType == typeof(int))
			{
				field.SetValue(body, Mathf.RoundToInt((float)(int)field.GetValue(body) * statModifier.multiplier));
			}
			else
			{
				field.SetValue(body, (float)field.GetValue(body) * statModifier.multiplier);
			}
		}
	}

	internal static float RechargeRate(CharacterBody body)
	{
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		GameObject val = (Object.op_Implicit((Object)(object)body) ? BodyCatalog.GetBodyPrefab(body.bodyIndex) : null);
		if (!Object.op_Implicit((Object)(object)val) || !modifiers.TryGetValue(((Object)val).name, out var value))
		{
			return 1.3f;
		}
		return value.rechargeRate;
	}
}