Decompiled source of ModernizationPortComplete v1.7.0
BepInEx\plugins\ModernizationPort\ModernizationPort.dll
Decompiled 7 hours ago
The result has been truncated due to the large size, download it to view full contents!
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.Logging; using DM; using HarmonyLib; using Landfall.TABS; using Landfall.TABS.UnitPlacement; using Microsoft.CodeAnalysis; using ModernizationPort; using ModernizationPort.Legacy; using TFBGames; using UModLoader; using UnityEngine; using UnityEngine.AI; using UnityEngine.Events; using UnityEngine.Rendering; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyFileVersion("1.7.0.0")] [assembly: AssemblyTitle("Modernization Port")] [assembly: AssemblyProduct("Modernization Port")] [assembly: AssemblyCompany("ModernizationPort")] [assembly: AssemblyVersion("1.7.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace UModLoader { public static class ULoader { internal static ContentDatabase Content; internal static LandfallContentDatabase Native; internal static readonly List<UnitBlueprint> CreatedUnits = new List<UnitBlueprint>(); internal static readonly List<Faction> CreatedFactions = new List<Faction>(); internal static readonly Dictionary<DatabaseID, string> Names = new Dictionary<DatabaseID, string>(); private static Dictionary<string, string> language; private const int ModId = 1459449901; public static Dictionary<string, Dictionary<string, object>> VDic { get; private set; } public static Dictionary<string, Dictionary<string, Dictionary<string, object>>> MDic { get; private set; } internal static void Prepare(ContentDatabase content) { Content = content; Native = content.LandfallContentDatabase; VDic = new Dictionary<string, Dictionary<string, object>>(); string[] array = new string[7] { "blueprints", "weapons", "clothes", "moves", "bases", "explosions", "effects" }; foreach (string key in array) { VDic.Add(key, new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase)); } MDic = new Dictionary<string, Dictionary<string, Dictionary<string, object>>> { { "Modernization", new Dictionary<string, Dictionary<string, object>> { { "blueprints", new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase) }, { "factions", new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase) } } } }; language = Localizer.GetLanguage((Language)0); foreach (UnitBlueprint unitBlueprint in Native.GetUnitBlueprints()) { Add("blueprints", unitBlueprint.Entity.Name, unitBlueprint); if (language.TryGetValue(unitBlueprint.Entity.Name, out var value)) { Add("blueprints", value, unitBlueprint); } } Index("weapons", Native.GetWeapons()); Index("clothes", Native.GetCharacterProps()); Index("moves", Native.GetCombatMoves()); Index("bases", Native.GetUnitBases()); foreach (GameObject projectile in Native.GetProjectiles()) { if (Object.op_Implicit((Object)(object)projectile)) { Add("projectiles-unused", ((Object)projectile).name, projectile); } } Explosion[] array2 = Resources.FindObjectsOfTypeAll<Explosion>(); foreach (Explosion val in array2) { if (Object.op_Implicit((Object)(object)val)) { Add("explosions", ((Object)((Component)val).gameObject).name, ((Component)val).gameObject); } } UnitEffectBase[] array3 = Resources.FindObjectsOfTypeAll<UnitEffectBase>(); foreach (UnitEffectBase val2 in array3) { if (Object.op_Implicit((Object)(object)val2) && Object.op_Implicit((Object)(object)((Component)val2).gameObject)) { Add("effects", ((Object)((Component)val2).gameObject).name, ((Component)((Component)val2).transform.root).gameObject); Add("effects", ((Object)((Component)val2).transform.root).name, ((Component)((Component)val2).transform.root).gameObject); } } Alias("blueprints", "CavalryKnight", "Cavalry", "Cavalry Knight"); NativeTemplateAdapter.Apply(); string[] array4 = (from pair in RequiredTemplates.Items where !VDic[pair[0]].ContainsKey(pair[1]) select pair[0] + "/" + pair[1]).ToArray(); if (array4.Length != 0) { throw new MissingMemberException("Vanilla templates unavailable: " + string.Join(", ", array4)); } PortPlugin.Info("Template preflight complete: " + RequiredTemplates.Items.Length + " required names resolved."); } private static void Index(string category, IEnumerable<GameObject> objects) { foreach (GameObject @object in objects) { if (!Object.op_Implicit((Object)(object)@object)) { continue; } Add(category, ((Object)@object).name, @object); Component[] componentsInChildren = @object.GetComponentsInChildren<Component>(true); foreach (Component obj in componentsInChildren) { IDatabaseEntity val = (IDatabaseEntity)(object)((obj is IDatabaseEntity) ? obj : null); if (val != null && val.Entity != null) { Add(category, val.Entity.Name, @object); if (language.TryGetValue(val.Entity.Name, out var value)) { Add(category, value, @object); } } } } } private static void Add(string category, string key, object value) { if (string.IsNullOrEmpty(key) || !VDic.TryGetValue(category, out var value2)) { return; } key = key.Replace("(Clone)", "").Trim(); if (!value2.ContainsKey(key)) { value2.Add(key, value); } string text = key; bool flag; do { flag = false; string[] array = new string[7] { "CP_", "P_", "W_", "WP_", "Move_", "E_", "B_" }; foreach (string text2 in array) { if (text.StartsWith(text2, StringComparison.OrdinalIgnoreCase)) { text = text.Substring(text2.Length); flag = true; break; } } } while (flag); if (!value2.ContainsKey(text)) { value2.Add(text, value); } string key2 = text.Replace(" ", ""); if (!value2.ContainsKey(key2)) { value2.Add(key2, value); } string key3 = key.Replace(" ", ""); if (!value2.ContainsKey(key3)) { value2.Add(key3, value); } } internal static void Alias(string category, string key, params string[] alternatives) { Dictionary<string, object> dictionary = VDic[category]; if (dictionary.ContainsKey(key)) { return; } foreach (string key2 in alternatives) { if (dictionary.TryGetValue(key2, out var value)) { dictionary.Add(key, value); break; } } } private static int StableId(string text) { uint num = 2166136261u; foreach (char c in text) { num ^= c; num *= 16777619; } return (int)(num & 0x7FFFFFFF); } internal static void Identity(IDatabaseEntity owner, string kind, string name) { //IL_0023: 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) DatabaseEntity val = owner.Entity.ShallowCopy(); val.GUID = new DatabaseID(1459449901, StableId(kind + "/" + name)); val.Name = name; AccessTools.Field(typeof(DatabaseEntity), "m_unlockKey").SetValue(val, ""); AccessTools.Field(((object)owner).GetType(), "m_entity").SetValue(owner, val); Names.Add(val.GUID, name); } internal static void Register(IDatabaseEntity entity, Object obj, string field) { //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: 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) IDictionary dictionary = (IDictionary)AccessTools.Field(typeof(LandfallContentDatabase), field).GetValue(Native); IDictionary dictionary2 = (IDictionary)AccessTools.Field(((object)Content.AssetLoader).GetType(), "m_nonStreamableAssets").GetValue(Content.AssetLoader); if (dictionary.Contains(entity.Entity.GUID) || dictionary2.Contains(entity.Entity.GUID)) { throw new InvalidOperationException("Modernization ID already registered: " + entity.Entity.Name); } dictionary.Add(entity.Entity.GUID, obj); try { dictionary2.Add(entity.Entity.GUID, obj); } catch { dictionary.Remove(entity.Entity.GUID); throw; } } internal static void Rollback() { //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Unknown result type (might be due to invalid IL or missing references) if (Content == null) { return; } IDictionary dictionary = (IDictionary)AccessTools.Field(((object)Content.AssetLoader).GetType(), "m_nonStreamableAssets").GetValue(Content.AssetLoader); foreach (UnitBlueprint createdUnit in CreatedUnits) { ((IDictionary)AccessTools.Field(typeof(LandfallContentDatabase), "m_unitBlueprints").GetValue(Native)).Remove(createdUnit.Entity.GUID); dictionary.Remove(createdUnit.Entity.GUID); Object.Destroy((Object)(object)createdUnit); } foreach (Faction createdFaction in CreatedFactions) { ((IDictionary)AccessTools.Field(typeof(LandfallContentDatabase), "m_factions").GetValue(Native)).Remove(createdFaction.Entity.GUID); dictionary.Remove(createdFaction.Entity.GUID); Object.Destroy((Object)(object)createdFaction); } CreatedUnits.Clear(); CreatedFactions.Clear(); Names.Clear(); } } public static class UFunctions { public static string AssemName() { return "Modernization"; } public static string ModNamify(string name) { return "Modernization/" + name; } public static string ModName(DatabaseEntity entity) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) if (entity == null || !ULoader.Names.TryGetValue(entity.GUID, out var value)) { if (entity != null) { return entity.Name; } return ""; } return ModNamify(value); } public static Faction CreateFaction(string name, UnitBlueprint[] units, Sprite icon) { Faction val = Object.Instantiate<Faction>(ULoader.Native.GetFactions().First((Faction x) => Object.op_Implicit((Object)(object)x) && x.m_displayFaction)); ULoader.Identity((IDatabaseEntity)(object)val, "faction", name); ((Object)val).name = "Modernization/" + name; val.Units = (UnitBlueprint[])(((object)units) ?? ((object)new UnitBlueprint[0])); val.m_displayFaction = true; val.index = ULoader.Native.GetFactions().Count(); if (Object.op_Implicit((Object)(object)icon)) { val.Entity.SetSpriteIcon(icon); } ULoader.Register((IDatabaseEntity)(object)val, (Object)(object)val, "m_factions"); ULoader.CreatedFactions.Add(val); ULoader.MDic[AssemName()]["factions"].Add(name, val); return val; } public static UnitBlueprint CreateUnit(string name, UnitBlueprint original, Faction faction, Sprite icon) { UnitBlueprint val = Object.Instantiate<UnitBlueprint>(original); ULoader.Identity((IDatabaseEntity)(object)val, "unit", name); ((Object)val).name = "Modernization/" + name; if (Object.op_Implicit((Object)(object)original.voiceBundle)) { val.voiceBundle = Object.Instantiate<VoiceBundle>(original.voiceBundle); ((Object)val.voiceBundle).hideFlags = (HideFlags)52; } val.SetNoCustomRider(); if (Object.op_Implicit((Object)(object)icon)) { val.Entity.SetSpriteIcon(icon); } ULoader.Register((IDatabaseEntity)(object)val, (Object)(object)val, "m_unitBlueprints"); ULoader.CreatedUnits.Add(val); ULoader.MDic[AssemName()]["blueprints"].Add(name, val); List<UnitBlueprint> list = faction.Units.ToList(); list.Add(val); faction.Units = list.ToArray(); return val; } } public sealed class UPool { private static UPool instance; private readonly Dictionary<string, GameObject> objects = new Dictionary<string, GameObject>(StringComparer.OrdinalIgnoreCase); private readonly GameObject root; public static UPool MyPool => instance ?? (instance = new UPool()); private UPool() { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Expected O, but got Unknown root = new GameObject("Modernization prefab pool"); root.SetActive(false); ((Object)root).hideFlags = (HideFlags)61; Object.DontDestroyOnLoad((Object)(object)root); } public GameObject AddObject(string name, GameObject original, bool clone = true, HideFlags flags = (HideFlags)52) { //IL_0041: Unknown result type (might be due to invalid IL or missing references) GameObject val = (clone ? Object.Instantiate<GameObject>(original, root.transform) : original); val.transform.SetParent(root.transform, false); ((Object)val).name = "Modernization/" + name; ((Object)val).hideFlags = flags; objects.Add(name, val); return val; } public GameObject GetObject(string name) { return objects[name]; } internal GameObject ClonePrivate(GameObject original) { GameObject obj = Object.Instantiate<GameObject>(original, root.transform); ((Object)obj).hideFlags = (HideFlags)52; return obj; } } public enum TriggerType { Still, Moving, All } public sealed class USpawner : MonoBehaviour { public GameObject[] objectsToSpawn; public UnitBlueprint[] unitsToSpawn; public int u_numOfObjects = 1; public float u_startDelay; public float u_cd; public TriggerType u_triggerType; public int o_numOfObjects; public float o_startDelay; public float o_cd; public TriggerType o_triggerType; private ProjectileHit hit; private TeamHolder holder; private float counter; private float delayCounter; private int iterations; private float o_counter; private float o_startDelayCounter; private int o_iterations; private void Start() { hit = ((Component)this).GetComponentInChildren<ProjectileHit>(); holder = ((Component)this).GetComponentInParent<TeamHolder>(); if (!Object.op_Implicit((Object)(object)hit) || !Object.op_Implicit((Object)(object)holder)) { Object.Destroy((Object)(object)this); } } private static bool Satisfied(TriggerType type, ProjectileHit hit) { return type switch { TriggerType.Still => hit.done, TriggerType.Moving => !hit.done, _ => true, }; } private void Update() { //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_0197: 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_01ad: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)hit) || !Object.op_Implicit((Object)(object)holder)) { return; } if (Satisfied(o_triggerType, hit)) { o_startDelayCounter += Time.deltaTime; } if (o_startDelayCounter > o_startDelay) { o_counter += Time.deltaTime; } if (o_counter > o_cd && objectsToSpawn != null && objectsToSpawn.Length != 0 && o_iterations < o_numOfObjects) { o_counter = 0f; o_iterations++; for (int i = 0; i < objectsToSpawn.Length; i++) { if (Object.op_Implicit((Object)(object)objectsToSpawn[i])) { Object.Instantiate<GameObject>(objectsToSpawn[i], ((Component)this).transform.position, ((Component)this).transform.rotation); } } } if (!Satisfied(u_triggerType, hit)) { return; } delayCounter += Time.deltaTime; if (delayCounter <= u_startDelay) { return; } counter += Time.deltaTime; if (counter <= u_cd || iterations >= u_numOfObjects || unitsToSpawn == null || unitsToSpawn.Length == 0) { return; } counter = 0f; iterations++; for (int j = 0; j < unitsToSpawn.Length; j++) { UnitBlueprint val = unitsToSpawn[j]; if (Object.op_Implicit((Object)(object)val)) { PortRuntime.SpawnNative(val, ((Component)this).transform.position, ((Component)this).transform.rotation, holder.team); } } } } } namespace ModernizationPort { public sealed class PortVisual : MonoBehaviour { } public static class PinaCollada { internal sealed class Model { internal Mesh Mesh; internal Material[] Materials; } internal static readonly Dictionary<string, Model> Models = new Dictionary<string, Model>(StringComparer.OrdinalIgnoreCase); internal static readonly Dictionary<string, Texture2D> Textures = new Dictionary<string, Texture2D>(StringComparer.OrdinalIgnoreCase); internal static readonly Dictionary<string, SoundEffectInstance> Sounds = new Dictionary<string, SoundEffectInstance>(StringComparer.OrdinalIgnoreCase); private static readonly Dictionary<string, Sprite> Sprites = new Dictionary<string, Sprite>(StringComparer.OrdinalIgnoreCase); private static bool loaded; private static readonly Dictionary<string, AssetBundle> Bundles = new Dictionary<string, AssetBundle>(StringComparer.OrdinalIgnoreCase); private static readonly Dictionary<string, GameObject> Prefabs = new Dictionary<string, GameObject>(StringComparer.OrdinalIgnoreCase); private static readonly Dictionary<GearType, string[]> BoneNames = new Dictionary<GearType, string[]> { { (GearType)0, new string[1] { "M_Head" } }, { (GearType)1, new string[1] { "M_Neck" } }, { (GearType)2, new string[2] { "M_Shoulder_Right", "M_Shoulder_Left" } }, { (GearType)3, new string[1] { "M_Torso" } }, { (GearType)4, new string[2] { "M_Arm_Right", "M_Arm_Left" } }, { (GearType)5, new string[2] { "M_Wrist_Right", "M_Wrist_Left" } }, { (GearType)7, new string[1] { "M_Waist" } }, { (GearType)8, new string[2] { "M_Leg_Right", "M_Leg_Left" } }, { (GearType)9, new string[2] { "M_Foot_Right", "M_Foot_Left" } } }; private static int Count(BinaryReader r, int maximum = 20000000) { int num = r.ReadInt32(); if (num < 0 || num > maximum) { throw new InvalidDataException("Invalid asset count: " + num); } return num; } private static string String(BinaryReader r) { int num = Count(r, 65536); byte[] array = r.ReadBytes(num); if (array.Length != num) { throw new EndOfStreamException(); } return Encoding.UTF8.GetString(array); } private static Vector3[] Vectors3(BinaryReader r) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) Vector3[] array = (Vector3[])(object)new Vector3[Count(r)]; for (int i = 0; i < array.Length; i++) { array[i] = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()); } return array; } private static Vector2[] Vectors2(BinaryReader r) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) Vector2[] array = (Vector2[])(object)new Vector2[Count(r)]; for (int i = 0; i < array.Length; i++) { array[i] = new Vector2(r.ReadSingle(), r.ReadSingle()); } return array; } private static byte[] Bytes(BinaryReader r, int count) { byte[] array = r.ReadBytes(count); if (array.Length != count) { throw new EndOfStreamException(); } return array; } public static void EnsureLoaded() { //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Expected O, but got Unknown //IL_0312: Unknown result type (might be due to invalid IL or missing references) //IL_0317: Unknown result type (might be due to invalid IL or missing references) //IL_0329: Unknown result type (might be due to invalid IL or missing references) //IL_0331: Unknown result type (might be due to invalid IL or missing references) //IL_033a: Expected O, but got Unknown //IL_038c: Unknown result type (might be due to invalid IL or missing references) //IL_0391: Unknown result type (might be due to invalid IL or missing references) //IL_039b: Expected O, but got Unknown //IL_03a9: Unknown result type (might be due to invalid IL or missing references) //IL_03ae: Unknown result type (might be due to invalid IL or missing references) //IL_03c1: Unknown result type (might be due to invalid IL or missing references) //IL_03c6: Unknown result type (might be due to invalid IL or missing references) //IL_0221: Unknown result type (might be due to invalid IL or missing references) //IL_0226: Unknown result type (might be due to invalid IL or missing references) //IL_0244: Unknown result type (might be due to invalid IL or missing references) //IL_024c: Unknown result type (might be due to invalid IL or missing references) //IL_024d: Unknown result type (might be due to invalid IL or missing references) //IL_0256: Expected O, but got Unknown //IL_0484: Unknown result type (might be due to invalid IL or missing references) //IL_0489: Unknown result type (might be due to invalid IL or missing references) //IL_0490: Unknown result type (might be due to invalid IL or missing references) //IL_0495: Unknown result type (might be due to invalid IL or missing references) //IL_04ad: Expected O, but got Unknown if (loaded) { return; } using (FileStream stream = File.OpenRead(Path.Combine(Path.GetDirectoryName(typeof(PinaCollada).Assembly.Location), "Modernization.assets.gz"))) { using GZipStream input = new GZipStream(stream, CompressionMode.Decompress); using BinaryReader binaryReader = new BinaryReader(input); if (Encoding.ASCII.GetString(Bytes(binaryReader, 8)) != "MODPORT1") { throw new InvalidDataException("Incorrect Modernization resources."); } int num = Count(binaryReader, 1000); Shader val = Shader.Find("Standard"); if (!Object.op_Implicit((Object)(object)val)) { val = Shader.Find("Diffuse"); } if (!Object.op_Implicit((Object)(object)val)) { Material val2 = ((IEnumerable<Material>)Resources.FindObjectsOfTypeAll<Material>()).FirstOrDefault((Func<Material, bool>)((Material x) => Object.op_Implicit((Object)(object)x) && Object.op_Implicit((Object)(object)x.shader) && x.HasProperty("_Color") && ((Object)x.shader).name.IndexOf("UI", StringComparison.OrdinalIgnoreCase) < 0)); if (Object.op_Implicit((Object)(object)val2)) { val = val2.shader; } } if (!Object.op_Implicit((Object)(object)val)) { throw new InvalidOperationException("A material shader is unavailable."); } Color color = default(Color); for (int num2 = 0; num2 < num; num2++) { string text = String(binaryReader); Mesh val3 = new Mesh { name = "Modernization/" + text, hideFlags = (HideFlags)52 }; Vector3[] array = Vectors3(binaryReader); if (array.Length > 65535) { val3.indexFormat = (IndexFormat)1; } val3.vertices = array; Vector3[] array2 = Vectors3(binaryReader); if (array2.Length != 0) { val3.normals = array2; } Vector2[] array3 = Vectors2(binaryReader); if (array3.Length != 0) { val3.uv = array3; } int num3 = (val3.subMeshCount = Count(binaryReader, 1000)); for (int num5 = 0; num5 < num3; num5++) { int[] array4 = new int[Count(binaryReader)]; for (int num6 = 0; num6 < array4.Length; num6++) { array4[num6] = binaryReader.ReadInt32(); } val3.SetTriangles(array4, num5, false); } val3.RecalculateBounds(); if (array2.Length == 0) { val3.RecalculateNormals(); } Material[] array5 = (Material[])(object)new Material[Count(binaryReader, 1000)]; for (int num7 = 0; num7 < array5.Length; num7++) { ((Color)(ref color))..ctor(binaryReader.ReadSingle(), binaryReader.ReadSingle(), binaryReader.ReadSingle(), binaryReader.ReadSingle()); Material val4 = new Material(val) { name = "Modernization/" + text + "/" + num7, hideFlags = (HideFlags)52, color = color }; val4.SetFloat("_Glossiness", 0f); if (val4.HasProperty("_Metallic")) { val4.SetFloat("_Metallic", 0f); } array5[num7] = val4; } Models.Add(text, new Model { Mesh = val3, Materials = array5.Take(RuntimeCompatibilityRules.MaterialSlots(num3, array5.Length)).ToArray() }); } num = Count(binaryReader, 1000); for (int num8 = 0; num8 < num; num8++) { string text2 = String(binaryReader); byte[] array6 = Bytes(binaryReader, Count(binaryReader)); Texture2D val5 = new Texture2D(2, 2, (TextureFormat)4, false) { name = "Modernization/" + text2, hideFlags = (HideFlags)52, filterMode = (FilterMode)0 }; if (!ImageConversion.LoadImage(val5, array6)) { throw new InvalidDataException("Invalid texture: " + text2); } Textures.Add(text2, val5); } num = Count(binaryReader, 1000); for (int num9 = 0; num9 < num; num9++) { string text3 = String(binaryReader); SoundEffectInstance val6 = new SoundEffectInstance { soundRef = text3 }; val6.volume = new Vector2(binaryReader.ReadSingle(), binaryReader.ReadSingle()); val6.pitch = new Vector2(binaryReader.ReadSingle(), binaryReader.ReadSingle()); val6.maxInstances = binaryReader.ReadInt32(); val6.cooldown = binaryReader.ReadSingle(); val6.spatialBlend = binaryReader.ReadSingle(); val6.reverbZoneMix = binaryReader.ReadSingle(); val6.minDistance = binaryReader.ReadSingle(); val6.maxDistance = binaryReader.ReadSingle(); val6.lengthInMeasures = binaryReader.ReadInt32(); val6.transitionMeasures = new int[Count(binaryReader, 1000)]; for (int num10 = 0; num10 < val6.transitionMeasures.Length; num10++) { val6.transitionMeasures[num10] = binaryReader.ReadInt32(); } val6.clipTypes = (SoundEffectVariations[])(object)new SoundEffectVariations[Count(binaryReader, 1000)]; for (int num11 = 0; num11 < val6.clipTypes.Length; num11++) { SoundEffectVariations val7 = new SoundEffectVariations { materialType = (MaterialType)binaryReader.ReadInt32(), clips = (AudioClip[])(object)new AudioClip[Count(binaryReader, 1000)] }; for (int num12 = 0; num12 < val7.clips.Length; num12++) { string text4 = String(binaryReader); int num13 = binaryReader.ReadInt32(); int num14 = binaryReader.ReadInt32(); int num15 = binaryReader.ReadInt32(); int num16 = Count(binaryReader); if (num16 != num14 * num15 || num13 <= 0 || num15 < 1 || num15 > 2) { throw new InvalidDataException("Invalid audio: " + text4); } float[] array7 = new float[num16]; byte[] array8 = Bytes(binaryReader, checked(num16 * 4)); Buffer.BlockCopy(array8, 0, array7, 0, array8.Length); AudioClip val8 = AudioClip.Create("Modernization/" + text4, num14, num15, num13, false); ((Object)val8).hideFlags = (HideFlags)52; if (!val8.SetData(array7, 0)) { throw new InvalidDataException("Could not create audio: " + text4); } val7.clips[num12] = val8; } val6.clipTypes[num11] = val7; } Sounds.Add(text3, val6); } if (Encoding.ASCII.GetString(Bytes(binaryReader, 8)) != "ENDPORT1" || binaryReader.BaseStream.ReadByte() != -1) { throw new InvalidDataException("Incomplete resource package."); } } Alias(Sounds, "artileryfire", "artillery"); loaded = true; PortPlugin.Info("Original resources ready: " + Models.Count + " models, " + Textures.Count + " images, 29 sound sets."); } private static void Alias<T>(Dictionary<string, T> items, string name, string original) { if (!items.ContainsKey(name) && items.ContainsKey(original)) { items.Add(name, items[original]); } } private static string Key(string path) { int num = path.LastIndexOf('/'); if (num >= 0) { return path.Substring(num + 1); } return path; } public static Sprite GetSprite(string path, int? size = null, FilterMode filter = (FilterMode)0) { //IL_003e: 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_006c: Unknown result type (might be due to invalid IL or missing references) EnsureLoaded(); string text = Key(path); if (Sprites.TryGetValue(text, out var value)) { return value; } if (!Textures.TryGetValue(text, out var value2)) { throw new KeyNotFoundException("Original icon missing: " + path); } ((Texture)value2).filterMode = filter; value = Sprite.Create(value2, new Rect(0f, 0f, (float)((Texture)value2).width, (float)((Texture)value2).height), new Vector2(0.5f, 0.5f), (float)(size ?? 100)); ((Object)value).name = "Modernization/" + text; ((Object)value).hideFlags = (HideFlags)52; Sprites.Add(text, value); return value; } private static GameObject Create(string path, string name) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003f: 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_0062: Expected O, but got Unknown EnsureLoaded(); string text = Key(path); if (!Models.TryGetValue(text, out var value)) { PortPlugin.Info("[PinaCollada] Mesh with key '" + text + "' couldn't be found"); return null; } GameObject val = new GameObject(name); val.AddComponent<PortVisual>(); val.AddComponent<MeshFilter>().sharedMesh = value.Mesh; ((Renderer)val.AddComponent<MeshRenderer>()).sharedMaterials = value.Materials; return val; } private static void Place(GameObject go, Transform parent, Vector3? rotation, Vector3? position) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) if (rotation.HasValue) { go.transform.localRotation = Quaternion.Euler(rotation.Value); } if (position.HasValue) { go.transform.localPosition = position.Value; } go.layer = ((Component)parent).gameObject.layer; } private static GameObject Attach(Transform parent, string path, float scale, Vector3? rotation, Vector3? position, string name) { //IL_0026: 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) GameObject val = Create(path, name); if (!Object.op_Implicit((Object)(object)val)) { return null; } val.transform.SetParent(parent, false); val.transform.localScale = Vector3.one * scale; Place(val, parent, rotation, position); return val; } public static void SetMeshRenderers(GameObject go, bool enabled) { Renderer[] componentsInChildren = go.GetComponentsInChildren<Renderer>(true); foreach (Renderer val in componentsInChildren) { if (!(val is ParticleSystemRenderer) && !(val is LineRenderer) && !(val is TrailRenderer) && !Object.op_Implicit((Object)(object)((Component)val).GetComponentInParent<PortVisual>())) { val.enabled = enabled; } } } public static void HideTemplateEffects(GameObject go) { Transform transform = go.transform; Renderer[] componentsInChildren = go.GetComponentsInChildren<Renderer>(true); foreach (Renderer val in componentsInChildren) { if (!Object.op_Implicit((Object)(object)((Component)val).GetComponentInParent<PortVisual>()) && !((Object)(object)((Component)val).transform == (Object)(object)transform)) { val.enabled = false; } } Collider[] componentsInChildren2 = go.GetComponentsInChildren<Collider>(true); foreach (Collider val2 in componentsInChildren2) { if (!Object.op_Implicit((Object)(object)((Component)val2).GetComponentInParent<PortVisual>())) { val2.enabled = false; } } } public static AssetBundle LoadBundle(string bundle) { EnsureLoaded(); if (Bundles.TryGetValue(bundle, out var value)) { return value; } string text = Path.Combine(Path.GetDirectoryName(typeof(PinaCollada).Assembly.Location), "Modernization." + bundle + ".bundle"); if (!File.Exists(text)) { throw new FileNotFoundException("Original bundle missing: " + text); } AssetBundle val = AssetBundle.LoadFromFile(text); if (!Object.op_Implicit((Object)(object)val)) { throw new InvalidDataException("Could not open original bundle: " + text); } Bundles.Add(bundle, val); PortPlugin.Info("Original bundle ready: " + bundle + " (" + new FileInfo(text).Length + " bytes)"); return val; } public static GameObject BundlePrefab(string bundleKey) { string[] array = bundleKey.Split(new char[1] { '/' }, StringSplitOptions.RemoveEmptyEntries); if (array.Length < 2) { throw new ArgumentException("A bundle key needs bundle and object: " + bundleKey); } string text = array[^2]; string text2 = array[^1]; string text3 = text + "/" + text2; if (Prefabs.TryGetValue(text3, out var value)) { return value; } AssetBundle val = LoadBundle(text); GameObject val2 = val.LoadAsset<GameObject>("assets/" + text2.ToLowerInvariant() + ".prefab"); if (!Object.op_Implicit((Object)(object)val2)) { val2 = val.LoadAsset<GameObject>(text2); } if (!Object.op_Implicit((Object)(object)val2)) { string value2 = text2.ToLowerInvariant() + ".prefab"; string[] allAssetNames = val.GetAllAssetNames(); foreach (string text4 in allAssetNames) { if (text4.EndsWith(value2, StringComparison.Ordinal)) { val2 = val.LoadAsset<GameObject>(text4); if (Object.op_Implicit((Object)(object)val2)) { break; } } } } if (!Object.op_Implicit((Object)(object)val2)) { string text5 = string.Join(", ", val.GetAllAssetNames()); PortPlugin.Info("[PinaCollada] Bundle object with key '" + text3 + "' couldn't be found (bundle has: " + text5 + ")"); return null; } Prefabs.Add(text3, val2); return val2; } public static GameObject SetBundleObject(GameObject go, string bundleKey, float scale, Vector3? rotation = null, Vector3? position = null, string name = "PinaCollada Bundle Object") { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) GameObject val = BundlePrefab(bundleKey); if (!Object.op_Implicit((Object)(object)val)) { return null; } SetMeshRenderers(go, enabled: false); Transform transform = go.transform; GameObject val2 = Object.Instantiate<GameObject>(val, transform.position, transform.rotation); ((Object)val2).name = name; val2.AddComponent<PortVisual>(); Transform transform2 = val2.transform; transform2.localScale *= scale; val2.transform.SetParent(transform, true); if (rotation.HasValue) { val2.transform.localRotation = Quaternion.Euler(rotation.Value); } if (position.HasValue) { val2.transform.localPosition = position.Value; } val2.layer = ((Component)transform).gameObject.layer; Transform[] componentsInChildren = val2.GetComponentsInChildren<Transform>(true); for (int i = 0; i < componentsInChildren.Length; i++) { ((Component)componentsInChildren[i]).gameObject.layer = ((Component)transform).gameObject.layer; } return val2; } public static void SetStaticMesh(GameObject go, string path, float scale, Vector3? rotation = null, Vector3? position = null, string name = "PinaCollada Mesh Object") { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) GameObject val = Create(path, name); if (Object.op_Implicit((Object)(object)val)) { SetMeshRenderers(go, enabled: false); Transform transform = go.transform; val.transform.SetPositionAndRotation(transform.position, transform.rotation); val.transform.localScale = Vector3.one * scale; if (RuntimeCompatibilityRules.CanKeepWorldScale(transform.lossyScale.x, transform.lossyScale.y, transform.lossyScale.z)) { val.transform.SetParent(transform, true); } else { val.transform.SetParent(transform, false); val.transform.localScale = Vector3.one * scale; } Place(val, transform, rotation, position); } } public unsafe static void SetBundleObjecToBone(GameObject go, string bundleKey, float scale, Vector3? rotation, Vector3? position, string name, GearType gear, EquipType equip) { //IL_0033: 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_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Invalid comparison between Unknown and I4 //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_0118: Invalid comparison between Unknown and I4 //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Invalid comparison between Unknown and I4 //IL_01e7: 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_021d: Unknown result type (might be due to invalid IL or missing references) //IL_0223: Unknown result type (might be due to invalid IL or missing references) //IL_023f: Unknown result type (might be due to invalid IL or missing references) //IL_0244: Unknown result type (might be due to invalid IL or missing references) //IL_013f: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Invalid comparison between Unknown and I4 //IL_0260: Unknown result type (might be due to invalid IL or missing references) SetMeshRenderers(go, enabled: false); List<Transform> list = new List<Transform>(); SkinnedMeshRenderer componentInChildren = go.GetComponentInChildren<SkinnedMeshRenderer>(true); string[] value; if (!Object.op_Implicit((Object)(object)componentInChildren)) { list.Add(go.transform); } else if (BoneNames.TryGetValue(gear, out value)) { Transform[] array = (Transform[])(((object)componentInChildren.bones) ?? ((object)new Transform[0])); foreach (Transform val in array) { if (Object.op_Implicit((Object)(object)val) && Array.IndexOf(value, ((Object)val).name) >= 0 && !list.Contains(val)) { list.Add(val); } } if ((int)equip == 1 && list.Count > 1) { list.RemoveAt(1); } if ((int)equip == 2 && list.Count > 1) { list.RemoveAt(0); } } if (list.Count == 0) { UnitRig val2 = go.GetComponentInParent<UnitRig>(); if (!Object.op_Implicit((Object)(object)val2)) { val2 = ((Component)go.transform.root).GetComponentInChildren<UnitRig>(); } Transform val3 = null; Transform val4 = null; if (Object.op_Implicit((Object)(object)val2)) { val2.GetBonesForEquip(gear, ref val3, ref val4); } if (Object.op_Implicit((Object)(object)val3) && ((int)equip != 2 || !Object.op_Implicit((Object)(object)val4))) { list.Add(val3); } if (Object.op_Implicit((Object)(object)val4) && (Object)(object)val4 != (Object)(object)val3 && (int)equip != 1) { list.Add(val4); } if (list.Count == 0) { throw new InvalidOperationException("No attachment bone for " + bundleKey + " (" + ((object)(*(GearType*)(&gear))/*cast due to .constrained prefix*/).ToString() + ")"); } PortDiagnostics.Info(go.GetComponentInParent<Unit>(), "clothing has no " + ((object)(*(GearType*)(&gear))/*cast due to .constrained prefix*/).ToString() + " bone named as in the original; model attached to the native rig bone", Key(bundleKey)); } GameObject val5 = BundlePrefab(bundleKey); if (!Object.op_Implicit((Object)(object)val5)) { return; } foreach (Transform item in list) { GameObject val6 = Object.Instantiate<GameObject>(val5, item.position, item.rotation, item); val6.SetActive(true); ((Object)val6).name = name; val6.AddComponent<PortVisual>(); Transform transform = val6.transform; transform.localScale *= scale; if (rotation.HasValue) { val6.transform.localRotation = Quaternion.Euler(rotation.Value); } if (position.HasValue) { val6.transform.localPosition = position.Value; } val6.layer = ((Component)item).gameObject.layer; Transform[] array = val6.GetComponentsInChildren<Transform>(true); for (int i = 0; i < array.Length; i++) { ((Component)array[i]).gameObject.layer = ((Component)item).gameObject.layer; } } } public unsafe static void SetStaticMeshToBone(GameObject go, string path, float scale, Vector3? rotation, Vector3? position, string name, GearType gear, EquipType equip) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Invalid comparison between Unknown and I4 //IL_010f: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Invalid comparison between Unknown and I4 //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Invalid comparison between Unknown and I4 //IL_0139: Unknown result type (might be due to invalid IL or missing references) //IL_013c: Invalid comparison between Unknown and I4 SetMeshRenderers(go, enabled: false); List<Transform> list = new List<Transform>(); SkinnedMeshRenderer componentInChildren = go.GetComponentInChildren<SkinnedMeshRenderer>(true); string[] value; if (!Object.op_Implicit((Object)(object)componentInChildren)) { list.Add(go.transform); } else if (BoneNames.TryGetValue(gear, out value)) { Transform[] array = (Transform[])(((object)componentInChildren.bones) ?? ((object)new Transform[0])); foreach (Transform val in array) { if (Object.op_Implicit((Object)(object)val) && Array.IndexOf(value, ((Object)val).name) >= 0 && !list.Contains(val)) { list.Add(val); } } if ((int)equip == 1 && list.Count > 1) { list.RemoveAt(1); } if ((int)equip == 2 && list.Count > 1) { list.RemoveAt(0); } } if (list.Count == 0) { UnitRig val2 = go.GetComponentInParent<UnitRig>(); if (!Object.op_Implicit((Object)(object)val2)) { val2 = ((Component)go.transform.root).GetComponentInChildren<UnitRig>(); } Transform val3 = null; Transform val4 = null; if (Object.op_Implicit((Object)(object)val2)) { val2.GetBonesForEquip(gear, ref val3, ref val4); } if (Object.op_Implicit((Object)(object)val3) && ((int)equip != 2 || !Object.op_Implicit((Object)(object)val4))) { list.Add(val3); } if (Object.op_Implicit((Object)(object)val4) && (Object)(object)val4 != (Object)(object)val3 && (int)equip != 1) { list.Add(val4); } if (list.Count == 0) { throw new InvalidOperationException("No attachment bone for " + path + " (" + ((object)(*(GearType*)(&gear))/*cast due to .constrained prefix*/).ToString() + ")"); } PortDiagnostics.Info(go.GetComponentInParent<Unit>(), "clothing has no " + ((object)(*(GearType*)(&gear))/*cast due to .constrained prefix*/).ToString() + " bone named as in the original; model attached to the native rig bone", Key(path)); } foreach (Transform item in list) { Attach(item, path, scale, rotation, position, name); } } } internal static class NativeTemplateAdapter { internal static void Apply() { TemplateCompatibility.Apply(ULoader.VDic, Valid, Replacement, delegate(TemplateAlias rule, object value) { GameObject val = (GameObject)((value is GameObject) ? value : null); PortPlugin.Info(Object.op_Implicit((Object)(object)val) ? ("Template resolved: " + rule.Category + "/" + rule.LegacyName + " -> " + ((Object)val).name) : ("Optional footwear omitted: " + rule.Category + "/" + rule.LegacyName)); }); } private static bool Valid(TemplateAlias rule, object value) { //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Invalid comparison between Unknown and I4 GameObject val = (GameObject)((value is GameObject) ? value : null); if (!Object.op_Implicit((Object)(object)val)) { return false; } switch (rule.Role) { case TemplateRole.Ranged: return Object.op_Implicit((Object)(object)val.GetComponent<RangeWeapon>()); case TemplateRole.Melee: return Object.op_Implicit((Object)(object)val.GetComponent<MeleeWeapon>()); case TemplateRole.Shoes: { CharacterItem componentInChildren2 = val.GetComponentInChildren<CharacterItem>(true); if (Object.op_Implicit((Object)(object)componentInChildren2)) { return (int)componentInChildren2.GearT == 9; } return false; } case TemplateRole.Shield: { if (!Object.op_Implicit((Object)(object)val.GetComponent<Weapon>()) || Object.op_Implicit((Object)(object)val.GetComponent<RangeWeapon>())) { return false; } if (Object.op_Implicit((Object)(object)val.GetComponentInChildren<ShieldWobble>(true))) { return true; } WeaponItem componentInChildren = val.GetComponentInChildren<WeaponItem>(true); if (!HasShieldName(((Object)val).name)) { if (Object.op_Implicit((Object)(object)componentInChildren) && ((CharacterItem)componentInChildren).Entity != null) { return HasShieldName(((CharacterItem)componentInChildren).Entity.Name); } return false; } return true; } default: return false; } } private static bool HasShieldName(string name) { if (name != null) { return name.IndexOf("shield", StringComparison.OrdinalIgnoreCase) >= 0; } return false; } private static object Replacement(TemplateAlias rule) { string[] units = rule.Units; for (int i = 0; i < units.Length; i++) { UnitBlueprint unit = NativeUnit(units[i]); GameObject val = FromUnit(rule, unit); if (Object.op_Implicit((Object)(object)val)) { return val; } } if (rule.Role == TemplateRole.Shoes) { return (from p in ULoader.Native.GetCharacterProps() where Valid(rule, p) select p).OrderBy<GameObject, string>((GameObject p) => ((Object)p).name, StringComparer.Ordinal).FirstOrDefault(); } if (rule.LegacyName == "Thrower_WheelBarrowApple") { units = new string[2] { "SpearThrower", "Musketeer" }; foreach (string name in units) { GameObject val2 = FromUnit(rule, NativeUnit(name)); if (Object.op_Implicit((Object)(object)val2)) { return val2; } } } return null; } private static UnitBlueprint NativeUnit(string name) { if (!TemplateCompatibility.TryFind(ULoader.VDic["blueprints"], name, out var value)) { return null; } return (UnitBlueprint)((value is UnitBlueprint) ? value : null); } private static GameObject FromUnit(TemplateAlias rule, UnitBlueprint unit) { if (!Object.op_Implicit((Object)(object)unit)) { return null; } if (rule.Role == TemplateRole.Shoes) { return ((IEnumerable<GameObject>)(((object)unit.m_props) ?? ((object)new GameObject[0]))).FirstOrDefault((Func<GameObject, bool>)((GameObject p) => Valid(rule, p))); } return Weapons(unit, new HashSet<UnitBlueprint>()).FirstOrDefault((Func<GameObject, bool>)((GameObject p) => Valid(rule, p))); } private static IEnumerable<GameObject> Weapons(UnitBlueprint unit, HashSet<UnitBlueprint> seen) { if (!Object.op_Implicit((Object)(object)unit) || !seen.Add(unit)) { yield break; } if (Object.op_Implicit((Object)(object)unit.LeftWeapon)) { yield return unit.LeftWeapon; } if (Object.op_Implicit((Object)(object)unit.RightWeapon)) { yield return unit.RightWeapon; } UnitBlueprint[] array = (UnitBlueprint[])(((object)unit.UnitRiders) ?? ((object)new UnitBlueprint[0])); foreach (UnitBlueprint unit2 in array) { foreach (GameObject item in Weapons(unit2, seen)) { yield return item; } } if (!Object.op_Implicit((Object)(object)unit.UnitBase)) { yield break; } Weapon[] componentsInChildren = unit.UnitBase.GetComponentsInChildren<Weapon>(true); foreach (Weapon val in componentsInChildren) { if (Object.op_Implicit((Object)(object)val)) { yield return ((Component)val).gameObject; } } } } [AttributeUsage(AttributeTargets.Class)] internal sealed class DiagnosticPatchAttribute : Attribute { } internal static class PortDiagnostics { private static readonly DiagnosticGate gate = new DiagnosticGate(200); internal static string Name(Unit unit) { //IL_0030: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)unit)) { return "?"; } UnitBlueprint unitBlueprint = unit.unitBlueprint; if (Object.op_Implicit((Object)(object)unitBlueprint) && unitBlueprint.Entity != null && ULoader.Names.TryGetValue(unitBlueprint.Entity.GUID, out var value)) { return value; } return ((Object)unit).name; } internal static void Info(Unit unit, string issue, string detail) { string text = gate.Admit(Name(unit), issue, detail); if (text != null) { PortPlugin.Info(text); } } internal static void Warn(Unit unit, string issue, string detail) { string text = gate.Admit(Name(unit), issue, detail); if (text != null) { PortPlugin.Warn(text); } } internal static void Failure(string method, IEnumerable<Unit> units, Exception exception) { if (exception == null) { return; } try { Unit[] array = units.Where(PortRuntime.Owns).Distinct().ToArray(); if (array.Length != 0) { string unit = string.Join(", ", array.Select(Name).ToArray()); string text = gate.Admit(unit, method + " threw " + exception.GetType().Name, exception.ToString()); if (text != null) { PortPlugin.Error(text); } } } catch (Exception exception2) { PortPlugin.Report("Diagnostics for " + method, exception2); } } internal static Unit Of(Component component) { if (!Object.op_Implicit((Object)(object)component)) { return null; } return component.GetComponentInParent<Unit>(); } internal static Unit Of(DataHandler data) { if (!Object.op_Implicit((Object)(object)data)) { return null; } return data.unit; } } [HarmonyPatch(typeof(BlockMove), "GetAcceptableRigs")] internal static class BlockMoveAnchorHook { private static readonly FieldInfo Handler = AccessTools.Field(typeof(BlockMove), "weaponHandler"); private static readonly FieldInfo Rigs = AccessTools.Field(typeof(BlockMove), "acceptableRigs"); private static bool Prefix(BlockMove __instance) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected O, but got Unknown Unit val = PortDiagnostics.Of((Component)(object)__instance); if (!PortRuntime.Owns(val)) { return true; } WeaponHandler val2 = (WeaponHandler)Handler.GetValue(__instance); List<Rigidbody> list = (List<Rigidbody>)Rigs.GetValue(__instance); bool meleeRight = Object.op_Implicit((Object)(object)val2) && Object.op_Implicit((Object)(object)val2.rightWeapon) && Object.op_Implicit((Object)(object)((Component)val2.rightWeapon).GetComponent<MeleeWeapon>()); bool meleeLeft = Object.op_Implicit((Object)(object)val2) && Object.op_Implicit((Object)(object)val2.leftWeapon) && Object.op_Implicit((Object)(object)((Component)val2.leftWeapon).GetComponent<MeleeWeapon>()); bool hasLeftHand = Object.op_Implicit((Object)(object)((Component)((Component)__instance).transform.root).GetComponentInChildren<HandLeft>()); if (!RuntimeCompatibilityRules.NeedsBlockAnchor(Object.op_Implicit((Object)(object)val2), meleeRight, meleeLeft, list?.Count ?? 0, hasLeftHand)) { return true; } Rigidbody val3 = (Object.op_Implicit((Object)(object)val.data) ? val.data.mainRig : null); if (!Object.op_Implicit((Object)(object)val3) || list == null) { PortDiagnostics.Warn(val, "BlockMove has neither hands nor a main rigidbody", ((Object)__instance).name); return true; } list.Add(val3); PortDiagnostics.Info(val, "BlockMove anchored to the vehicle body because its base has no hands", ((Object)__instance).name); return false; } } [HarmonyPatch] [DiagnosticPatch] internal static class MountFailureReport { private static IEnumerable<MethodBase> TargetMethods() { yield return AccessTools.Method(typeof(Mount), "Update", (Type[])null, (Type[])null); yield return AccessTools.Method(typeof(Mount), "EnterMount", (Type[])null, (Type[])null); } private static void Finalizer(Exception __exception, Mount __instance, MethodBase __originalMethod) { if (__exception != null) { List<Unit> units = new List<Unit> { PortDiagnostics.Of((Component)(object)__instance), PortDiagnostics.Of(Object.op_Implicit((Object)(object)__instance) ? __instance.OtherData : null) }; PortDiagnostics.Failure("Mount." + __originalMethod.Name, units, __exception); } } } [HarmonyPatch(typeof(DodgeMove), "DoMove", new Type[] { typeof(Rigidbody), typeof(Rigidbody), typeof(DataHandler) })] [DiagnosticPatch] internal static class DodgeMoveFailureReport { private static void Finalizer(Exception __exception, DodgeMove __instance) { if (__exception != null) { PortDiagnostics.Failure("DodgeMove.DoMove", (IEnumerable<Unit>)(object)new Unit[1] { PortDiagnostics.Of((Component)(object)__instance) }, __exception); } } } [HarmonyPatch] [DiagnosticPatch] internal static class DodgeSequenceFailureReport { private static FieldInfo owner; private static MethodBase TargetMethod() { Type type = typeof(DodgeMove).GetNestedTypes(BindingFlags.NonPublic).Single((Type t) => t.Name.StartsWith("<DoMoveSequence>")); owner = AccessTools.Field(type, "<>4__this"); return AccessTools.Method(type, "MoveNext", (Type[])null, (Type[])null); } private static void Finalizer(Exception __exception, object __instance) { if (__exception != null) { DodgeMove component = (DodgeMove)((owner == null) ? null : /*isinst with value type is only supported in some contexts*/); PortDiagnostics.Failure("DodgeMove.DoMoveSequence", (IEnumerable<Unit>)(object)new Unit[1] { PortDiagnostics.Of((Component)(object)component) }, __exception); } } } [HarmonyPatch(typeof(BlockMove), "ProjectileBlock")] [DiagnosticPatch] internal static class BlockMoveFailureReport { private static void Finalizer(Exception __exception, BlockMove __instance) { if (__exception != null) { PortDiagnostics.Failure("BlockMove.ProjectileBlock", (IEnumerable<Unit>)(object)new Unit[1] { PortDiagnostics.Of((Component)(object)__instance) }, __exception); } } } [HarmonyPatch(typeof(UnitPlacementBrush), "RemoveUnitInternal")] [DiagnosticPatch] internal static class RemoveUnitFailureReport { private static void Finalizer(Exception __exception, Unit unit) { if (__exception == null) { return; } List<Unit> list = new List<Unit> { unit }; RiderHolder val = (Object.op_Implicit((Object)(object)unit) ? ((Component)unit).GetComponent<RiderHolder>() : null); if (Object.op_Implicit((Object)(object)val) && val.riders != null) { foreach (GameObject rider in val.riders) { if (Object.op_Implicit((Object)(object)rider)) { list.Add(rider.GetComponent<Unit>()); } } } PortDiagnostics.Failure("UnitPlacement.RemoveUnitInternal", list, __exception); } } [HarmonyPatch] [DiagnosticPatch] internal static class CharacterMovementFailureReport { private static bool Prepare() { return AccessTools.TypeByName("CharacterMovement") != null; } private static IEnumerable<MethodBase> TargetMethods() { Type type = AccessTools.TypeByName("CharacterMovement"); string[] array = new string[3] { "Start", "Update", "FixedUpdate" }; foreach (string text in array) { MethodInfo methodInfo = AccessTools.Method(type, text, (Type[])null, (Type[])null); if (methodInfo != null) { yield return methodInfo; } } } private static void Finalizer(Exception __exception, MonoBehaviour __instance, MethodBase __originalMethod) { if (__exception != null) { PortDiagnostics.Failure("CharacterMovement." + __originalMethod.Name, (IEnumerable<Unit>)(object)new Unit[1] { PortDiagnostics.Of((Component)(object)__instance) }, __exception); } } } [BepInPlugin("modernization.port.bepinex", "Modernization Port", "1.7.0")] public sealed class PortPlugin : BaseUnityPlugin { public const string Guid = "modernization.port.bepinex"; public const string Version = "1.7.0"; internal static readonly UManager Manager = new UManager(); private static ManualLogSource log; internal static bool Ready; private bool attempted; private float nextCheck; private static readonly HashSet<string> errors = new HashSet<string>(); internal static void Info(string message) { if (log != null) { log.LogInfo((object)message); } } internal static void Warn(string message) { if (log != null) { log.LogWarning((object)message); } } internal static void Error(string message) { if (log != null) { log.LogError((object)message); } } internal static void Report(string context, Exception exception) { if (log != null && errors.Add(context)) { log.LogError((object)(context + ": " + exception)); } } private void Awake() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown log = ((BaseUnityPlugin)this).Logger; Harmony val = new Harmony("modernization.port.bepinex"); Type[] typesFromAssembly = AccessTools.GetTypesFromAssembly(typeof(PortPlugin).Assembly); foreach (Type type in typesFromAssembly) { if (!type.IsDefined(typeof(HarmonyPatch), inherit: false)) { continue; } try { val.CreateClassProcessor(type).Patch(); } catch (Exception exception) { if (type.IsDefined(typeof(DiagnosticPatchAttribute), inherit: false)) { Report("Diagnostic hook " + type.Name + " unavailable", exception); continue; } attempted = true; Report("Could not install native API hook " + type.Name, exception); } } if (!attempted) { Info("Modernization Port 1.7.0 loaded; waiting for native content."); } } private void Update() { //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Expected O, but got Unknown //IL_0160: Unknown result type (might be due to invalid IL or missing references) //IL_016d: Expected O, but got Unknown if (attempted || Time.realtimeSinceStartup < nextCheck) { return; } nextCheck = Time.realtimeSinceStartup + 1f; ContentDatabase val = (ContentDatabase)AccessTools.Field(typeof(ContentDatabase), "m_instance").GetValue(null); if (val == null || val.LandfallContentDatabase == null || !val.LandfallContentDatabase.GetUnitBlueprints().Any() || !val.LandfallContentDatabase.GetFactions().Any((Faction x) => Object.op_Implicit((Object)(object)x) && x.m_displayFaction)) { return; } SoundPlayer service = ServiceLocator.GetService<SoundPlayer>(); if (!Object.op_Implicit((Object)(object)service) || !Object.op_Implicit((Object)(object)service.soundBank)) { return; } attempted = true; try { PinaCollada.EnsureLoaded(); ULoader.Prepare(val); LegacyTemplates.Validate(); Info("Native weapon/base/turning templates ready; registering Modernization factions."); Manager.Init(null); foreach (UnitBlueprint createdUnit in ULoader.CreatedUnits) { Manager.EditBlueprint(createdUnit, ULoader.MDic["Modernization"], null); if (createdUnit.m_props == null) { createdUnit.m_props = (GameObject[])(object)new GameObject[0]; } PropItemData[] propData = createdUnit.m_propData; createdUnit.m_propData = (PropItemData[])(object)new PropItemData[createdUnit.m_props.Length]; for (int num = 0; num < createdUnit.m_propData.Length; num++) { createdUnit.m_propData[num] = (PropItemData)((propData != null && num < propData.Length && propData[num] != null) ? ((object)propData[num]) : ((object)new PropItemData())); } createdUnit.rightProjectile = null; createdUnit.leftProjectile = null; VehicleCompatibility.PrepareBlueprint(createdUnit); } PortRuntime.RegisterSounds(service.soundBank); Ready = true; Info("MODERNIZATION READY: " + ULoader.CreatedUnits.Count + " blueprints, " + ULoader.CreatedFactions.Count + " factions; game MVID=" + typeof(UnitBlueprint).Assembly.ManifestModule.ModuleVersionId); } catch (Exception exception) { Ready = false; ULoader.Rollback(); Report("Modernization initialization rolled back", exception); } } } [HarmonyPatch(typeof(UnitBlueprint), "SetWeapon")] internal static class WeaponHook { private static void Prefix(Unit unit) { if (PortRuntime.Owns(unit)) { PortRuntime.SetIdentity(unit); } } private unsafe static void Postfix(Weapon __result, Unit unit, Team team, HandType handType) { //IL_004a: 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) if (!PortPlugin.Ready || !Object.op_Implicit((Object)(object)__result) || !PortRuntime.Owns(unit)) { return; } string text = Name(unit) + "/" + ((object)(*(HandType*)(&handType))/*cast due to .constrained prefix*/).ToString(); RangeWeapon val = null; try { val = ((Component)__result).GetComponentInChildren<RangeWeapon>(); PortPlugin.Manager.EditWeapons(((Component)__result).gameObject, handType, team, unit, ((Component)__result).GetComponentInChildren<MeleeWeapon>(), val, null); } catch (Exception exception) { PortPlugin.Report("Weapon setup for " + text, exception); } try { PortRuntime.IsolateProjectile(val, unit); PortRuntime.RestoreVisuals(((Component)__result).gameObject); } catch (Exception exception2) { PortPlugin.Report("Visual setup for " + text, exception2); } try { RefreshUnitAttackGate(unit, __result); } catch (Exception exception3) { PortPlugin.Report("Attack gate refresh for " + text, exception3); } } private static string Name(Unit unit) { if (!Object.op_Implicit((Object)(object)unit) || !Object.op_Implicit((Object)(object)unit.unitBlueprint) || unit.unitBlueprint.Entity == null) { return "?"; } return unit.unitBlueprint.Entity.Name; } private static void RefreshUnitAttackGate(Unit unit, Weapon weapon) { if (!Object.op_Implicit((Object)(object)unit)) { return; } WeaponHandler val = unit.WeaponHandler; if (!Object.op_Implicit((Object)(object)val) && Object.op_Implicit((Object)(object)weapon)) { val = ((Component)weapon).GetComponentInParent<WeaponHandler>(); } if (Object.op_Implicit((Object)(object)val)) { float num = float.PositiveInfinity; if (Object.op_Implicit((Object)(object)val.rightWeapon)) { num = Mathf.Min(num, val.rightWeapon.GetLowestAttackTimeOfWeapons()); } if (Object.op_Implicit((Object)(object)val.leftWeapon)) { num = Mathf.Min(num, val.leftWeapon.GetLowestAttackTimeOfWeapons()); } if (!float.IsNaN(num) && !float.IsInfinity(num) && !(num >= unit.lowestAttackTimeOfWeapons)) { unit.lowestAttackTimeOfWeapons = num; } } } } [HarmonyPatch] internal static class SpawnHook { private static MethodBase TargetMethod() { return typeof(UnitBlueprint).GetMethods().Single((MethodInfo x) => x.Name == "Spawn" && x.GetParameters().Length == 9); } private static void Postfix(UnitBlueprint __instance, Unit unitToSpawn) { if (!PortPlugin.Ready || !PortRuntime.Owns(__instance) || !Object.op_Implicit((Object)(object)unitToSpawn)) { return; } PortRuntime.SetIdentity(unitToSpawn); PortRuntime.SecureStructure(unitToSpawn); PortUnitState portUnitState = PortRuntime.Ensure<PortUnitState>(((Component)unitToSpawn).gameObject); if (portUnitState.SpawnConfigured) { return; } portUnitState.SpawnConfigured = true; try { PortPlugin.Manager.CodeOnSpawn(unitToSpawn, null); GameObject[] moves = (GameObject[])(((object)__instance.objectsToSpawnAsChildren) ?? ((object)new GameObject[0])); Transform[] source = ((IEnumerable)((Component)unitToSpawn).transform).Cast<Transform>().ToArray(); HashSet<Transform> used = new HashSet<Transform>(); int i; for (i = 0; i < moves.Length; i++) { if (Object.op_Implicit((Object)(object)moves[i])) { Transform val = ((IEnumerable<Transform>)source).FirstOrDefault((Func<Transform, bool>)((Transform x) => !used.Contains(x) && ((Object)x).name.Replace("(Clone)", "") == ((Object)moves[i]).name)); if (Object.op_Implicit((Object)(object)val)) { used.Add(val); PortPlugin.Manager.EditCombatMoves(((Component)val).gameObject, i, unitToSpawn, null); } } } PortRuntime.RestoreVisuals(((Component)unitToSpawn).gameObject); } catch (Exception exception) { PortPlugin.Report("Abilities for " + __instance.Entity.Name, exception); } } } [HarmonyPatch(typeof(UnitRig), "SpawnProps")] internal static class PropsHook { private static void Prefix(UnitRig __instance) { Unit componentInParent = ((Component)__instance).GetComponentInParent<Unit>(); if (PortPlugin.Ready && PortRuntime.Owns(componentInParent)) { PortRuntime.SetIdentity(componentInParent); PortRuntime.Ensure<PortUnitState>(((Component)componentInParent).gameObject).NextPropIndex = 0; } } } [HarmonyPatch(typeof(UnitRig), "SpawnProp")] internal static class PropHook { private static void Prefix(UnitRig __instance, CharacterItem prop, out int __state) { __state = -1; Unit componentInParent = ((Component)__instance).GetComponentInParent<Unit>(); if (!PortPlugin.Ready || !PortRuntime.Owns(componentInParent) || !Object.op_Implicit((Object)(object)prop)) { return; } PortUnitState portUnitState = PortRuntime.Ensure<PortUnitState>(((Component)componentInParent).gameObject); GameObject[] props = componentInParent.unitBlueprint.m_props; int num = portUnitState.NextPropIndex; while (props != null && num < props.Length) { if ((Object)(object)props[num] == (Object)(object)((Component)prop).gameObject) { __state = num; portUnitState.NextPropIndex = num + 1; break; } num++; } } private static void Postfix(UnitRig __instance, GameObject __result, PropItemData propData, int __state) { if (__state < 0 || !Object.op_Implicit((Object)(object)__result)) { return; } Unit componentInParent = ((Component)__instance).GetComponentInParent<Unit>(); try { PortPlugin.Manager.EditClothes(__result, __result.GetComponent<CharacterItem>(), propData, componentInParent, __state, null); PortRuntime.MirrorClothingColours(__result); PortRuntime.RestoreVisuals(__result); } catch (Exception exception) { PortPlugin.Report("Clothing for " + componentInParent.unitBlueprint.Entity.Name + "/" + __state, exception); } } } [HarmonyPatch(typeof(Unit), "Start")] internal static class UnitStartHook { private static void Prefix(Unit __instance) { if (PortRuntime.Owns(__instance)) { PortRuntime.SetIdentity(__instance); } } private static void Postfix(Unit __instance) { if (!PortPlugin.Ready || !PortRuntime.Owns(__instance)) { return; } PortRuntime.SecureStructure(__instance); PortUnitState portUnitState = PortRuntime.Ensure<PortUnitState>(((Component)__instance).gameObject); if (portUnitState.AfterSpawnConfigured) { return; } portUnitState.AfterSpawnConfigured = true; try { PortPlugin.Manager.CodeAfterSpawn(__instance, null); PortRuntime.RestoreVisuals(((Component)__instance).gameObject); } catch (Exception exception) { PortPlugin.Report("After-spawn setup for " + __instance.unitBlueprint.Entity.Name, exception); } } } [HarmonyPatch(typeof(RangeWeapon), "SetProjectileStats")] internal static class ProjectileHook { private static void Prefix(RangeWeapon __instance, GameObject spawnedObject) { if (!PortPlugin.Ready || !Object.op_Implicit((Object)(object)spawnedObject)) { return; } Unit val = (Object.op_Implicit((Object)(object)((Weapon)__instance).connectedData) ? ((Weapon)__instance).connectedData.unit : ((Component)__instance).GetComponentInParent<Unit>()); if (!PortRuntime.Owns(val) || Object.op_Implicit((Object)(object)spawnedObject.GetComponent<PortProjectile>())) { return; } spawnedObject.AddComponent<PortProjectile>(); ProjectileHit val2 = spawnedObject.GetComponentInChildren<ProjectileHit>(); if (!Object.op_Implicit((Object)(object)val2) && IsRocketTemplate(spawnedObject)) { val2 = spawnedObject.AddComponent<ProjectileHit>(); val2.damage = 0f; val2.force = 0f; PortDiagnostics.Info(val, "rocket template had no ProjectileHit; added a damage-free one so its EditProjectiles branch can run", ((Object)spawnedObject).name.Replace("(Clone)", "")); } if (!Object.op_Implicit((Object)(object)val2)) { PortDiagnostics.Info(val, "projectile has no ProjectileHit; EditProjectiles skipped", ((Object)spawnedObject).name.Replace("(Clone)", "")); return; } try { PortPlugin.Manager.EditProjectiles(spawnedObject, val2, val, null); PortRuntime.RestoreVisuals(spawnedObject); } catch (Exception exception) { PortPlugin.Report("Projectile setup for " + val.unitBlueprint.Entity.Name, exception); } } private static bool IsRocketTemplate(GameObject spawnedObject) { string name = ((Object)spawnedObject).name; if (!string.IsNullOrEmpty(name)) { return name.StartsWith("Modernization/rocket", StringComparison.OrdinalIgnoreCase); } return false; } } [HarmonyPatch(typeof(RangeWeapon), "Start")] internal static class MagazineStartHook { private static void Postfix(RangeWeapon __instance) { LegacyMagazine component = ((Component)__instance).GetComponent<LegacyMagazine>(); if (Object.op_Implicit((Object)(object)component) && component.StartingAmmo >= 0) { AccessTools.Field(typeof(RangeWeapon), "ammo").SetValue(__instance, component.StartingAmmo); } } } [HarmonyPatch(typeof(RangeWeapon), "Reload")] internal static class ReloadHook { private static void Prefix(RangeWeapon __instance) { PortRuntime.PlayReload(((Component)__instance).GetComponent<LegacyMagazine>()); } } public sealed class LegacyBlueprint { private readonly UnitBlueprint unit; public UnitBlueprint[] Riders { get { return unit.UnitRiders; } set { unit.SetNoCustomRider(); AccessTools.Field(typeof(UnitBlueprint), "Riders").SetValue(unit, value); } } public string VocalRef { get { return unit.VocalRef; } set { if (!Object.op_Implicit((Object)(object)unit.voiceBundle)) { unit.voiceBundle = ScriptableObject.CreateInstance<VoiceBundle>(); } unit.voiceBundle.VocalRef = value; AccessTools.Field(typeof(UnitBlueprint), "vocalPathData").SetValue(unit, null); } } private LegacyBlueprint(UnitBlueprint value) { unit = value; } public static LegacyBlueprint For(UnitBlueprint value) { return new LegacyBlueprint(value); } } public sealed class LegacyMagazine : MonoBehaviour { internal int StartingAmmo = -1; public string ReloadSound; private RangeWeapon Weapon => ((Component)this).GetComponent<RangeWeapon>(); public int InitialAmmo { get { return StartingAmmo; } set { StartingAmmo = value; } } public int Capacity { get { return Weapon.magSize; } set { Weapon.magSize = Math.Max(1, value); } } public float ReloadSeconds { get { return Weapon.reloadTime; } set { Weapon.reloadTime = Math.Max(0f, value); } } public float ShotInterval { get { return ((Weapon)Weapon).internalCooldown; } set { ((Weapon)Weapon).internalCooldown = Math.Max(0.001f, value); } } public static LegacyMagazine For(RangeWeapon weapon) { if (!Object.op_Implicit((Object)(object)weapon)) { throw new ArgumentNullException("weapon"); } return PortRuntime.Ensure<LegacyMagazine>(((Component)weapon).gameObject); } } public static class LegacyTemplates { private static LandfallUnitDatabase dbAsset; private static UnitBlueprint Named(params string[] names) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Expected O, but got Unknown foreach (string key in names) { if (ULoader.VDic["blueprints"].TryGetValue(key, out var value)) { return (UnitBlueprint)value; } } throw new MissingMemberException("Required vanilla blueprint: " + string.Join(" / ", names)); } public static UnitBlueprint Blueprint(int legacyIndex) { return (UnitBlueprint)(legacyIndex switch { 17 => Named("Healer"), 81 => Named("Valkyrie", "ValkyrieUnit"), _ => throw new NotSupportedException("Unmapped legacy blueprint " + legacyIndex), }); } public static GameObject Base(int legacyIndex) { GameObject val = NativeBase(legacyIndex); if (Object.op_Implicit((Object)(object)val)) { return val; } GameObject val2 = NativeBaseByName(LegacyBaseName(legacyIndex)); if (Object.op_Implicit((Object)(object)val2)) { return val2; } return (GameObject)(legacyIndex switch { 4 => Named("Wheelbarrow").UnitBase, 12 => Named("Cannon").UnitBase, 13 => Named("Stiffy").UnitBase, _ => throw new NotSupportedException("Unmapped legacy base " + legacyIndex), }); } private static string LegacyBaseName(int legacyIndex) { return legacyIndex switch { 4 => "Catapult_1", 12 => "Cannon_1", 13 => "Stiffy_1", _ => null, }; } private static GameObject NativeBaseByName(string prefabName) { if (string.IsNullOrEmpty(prefabName)) { return null; } IList<GameObject> list = NativeBaseList(); if (list == null) { return null; } foreach (GameObject item in list) { if (Object.op_Implicit((Object)(object)item) && string.Equals(((Object)item).name, prefabName, StringComparison.OrdinalIgnoreCase)) { return item; } } return null; } private static IList<GameObject> NativeBaseList() { try { if (!Object.op_Implicit((Object)(object)dbAsset)) { dbAsset = Resources.Load<LandfallUnitDatabase>("Landfall Unit Database"); } if (!Object.op_Implicit((Object)(object)dbAsset)) { return null; } return AccessTools.Field(typeof(LandfallUnitDatabase), "UnitBases").GetValue(dbAsset) as IList<GameObject>; } catch (Exception) { return null; } } private static GameObject NativeBase(int legacyIndex) { IList<GameObject> list = NativeBaseList(); if (list == null || legacyIndex < 0 || legacyIndex >= list.Count) { return null; } return list[legacyIndex]; } public static GameObject Weapon(int legacyIndex) { UnitBlueprint val = (UnitBlueprint)(legacyIndex switch { 2 => Named("Archer"), 14 => Named("Cannon"), 44 => Named("Musketeer"), 49 => Named("BombThrower", "Bomb Thrower"), 50 => Named("BombCannon", "Bomb Cannon"), 70 => Named("Musketeer"), _ => throw new NotSupportedException("Unmapped legacy weapon " + legacyIndex), }); GameObject val2 = val.RightWeapon; if (!Object.op_Implicit((Object)(object)val2) && Object.op_Implicit((Object)(object)val.UnitBase)) { RangeWeapon componentInChildren = val.UnitBase.GetComponentInChildren<RangeWeapon>(true); if (Object.op_Implicit((Object)(object)componentInChildren)) { val2 = ((Component)componentInChildren).gameObject; } } if (!Object.op_Implicit((Object)(object)val2)) { throw new MissingMemberException("Vanilla weapon unavailable: " + val.Entity.Name); } return val2; } internal static void Validate() { int[] array = new int[6] { 2, 14, 44, 49, 50, 70 }; for (int i = 0; i < array.Length; i++) { GameObject val = Weapon(array[i]); if (!Object.op_Implicit((Object)(object)val.GetComponent<RangeWeapon>())) { throw new MissingMemberException("Template is not a ranged weapon: " + ((Object)val).name); } } Base(4); Base(12); Base(13); Blueprint(17); Blueprint(81); } } public sealed class PortUnitState : MonoBehaviour { internal bool SpawnConfigured; internal bool AfterSpawnConfigured; internal int NextPropIndex; internal readonly List<GameObject> ProjectilePrefabs = new List<GameObject>(); private void OnDestroy() { foreach (GameObject projectilePrefab in ProjectilePrefabs) { if (Object.op_Implicit((Object)(object)projectilePrefab)) { Object.Destroy((Object)(object)projectilePrefab); } } } } public sealed class PortProjectile : MonoBehaviour { } public static class PortRuntime { private static FieldInfo mirroredObjectsField; private static bool mirroredObjectsFieldResolved; internal static bool Owns(UnitBlueprint blueprint) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) if (Object.op_Implicit((Object)(object)blueprint) && blueprint.Entity != null) { return ULoader.Names.ContainsKey(blueprint.Entity.GUID); } return false; } internal static bool Owns(Unit unit) { if (Object.op_Implicit((Object)(object)unit)) { return Owns(unit.unitBlueprint); } return false; } internal static void SetIdentity(Unit unit) { if (Owns(unit)) { AccessTools.Field(typeof(Unit), "m_entity").SetValue(unit, unit.unitBlueprint.Entity.ShallowCopy()); } } public static T Ensure<T>(GameObject go) where T : Component { T component = go.GetComponent<T>(); if (!Object.op_Implicit((Object)(object)component)) { return go.AddComponent<T>(); } return component; } public static void SetFootSound(UnitSounds sounds, string path) { //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Expected O, but got Unknown if (!Object.op_Implicit((Object)(object)sounds)) { return; } if (string.IsNullOrWhiteSpace(path)) { sounds.FootPathData = null; return; } string[] array = path.Split(new char[1] { '/' }); if (array.Length != 2) { throw new FormatException("Invalid foot sound: " + path); } sounds.FootPathData = new AudioPathData(array[0], array[1], 1f, 1f); } public static void SetConditionalRange(ConditionalEvent move, float range) { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Invalid comparison between Unknown and I4 //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Invalid comparison between Unknown and I4 //IL_005b: Unknown result type (might be due to invalid IL or missing references) move.extraRange = 0f; ConditionalEventInstance[] array = (ConditionalEventInstance[])(((object)move.events) ?? ((object)new ConditionalEventInstance[0])); for (int i = 0; i < array.Length; i++) { EventCondition[] array2 = (EventCondition[])(((object)array[i].conditions) ?? ((object)new EventCondition[0])); foreach (EventCondition val in array2) { if ((int)val.conditionType == 1 && (int)val.valueType == 1) { val.value = range; val.rangeType = (RangeType)0; } if ((int)val.conditionType == 0) { val.onlyCountWhenUnitInRange = false; } } } } public static GameObject[] SpawnNative(UnitBlueprint blueprint, Vector3 position, Quaternion rotation, Team team) { //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_0003: Unknown result type (might be due to invalid IL or missing references) return blueprint.Spawn(position, rotation, team, 1f, (UnitPoolInfo?)null); } internal static void Optional<T>(GameObject go, Unit unit, Action<T> edit) where T : Component { T componentInChildren = go.GetComponentInChildren<T>(); if (Object.op_Implicit((Object)(object)componentInChildren)) { edit(componentInChildren); } else { PortDiagnostics.Info(unit, "projectile has no " + typeof(T).Name + "; that setting is skipped", ((Object)go).name.Replace("(Clone)", "")); } } internal static void SecureStructure(Unit unit) { if (Owns(unit) && Object.op_Implicit((Object)(object)unit.data) && RuntimeCompatibilityRules.IsIndestructible(unit.unitBlueprint.health)) { DataHandler data = unit.data; data.health = RuntimeCompatibilityRules.FiniteHealth(data.health); if (data.maxHealth != 0f) { data.maxHealth = RuntimeCompatibilityRules.FiniteHealth(data.maxHealth); } if (Object.op_Implicit((Object)(object)data.healthHandler)) { data.healthHandler.SetInvulnerable(true); } } } internal static void RestoreVisuals(GameObject go) { PortVisual[] componentsInChildren = go.GetComponentsInChildren<PortVisual>(true); for (int i = 0; i < componentsInChildren.Length; i++) { Renderer[] componentsInChildren2 = ((Component)componentsInChildren[i]).GetComponentsInChildren<Renderer>(true); for (int j = 0; j < componentsInChildren2.Length; j++) { componentsInChildren2[j].enabled = true; } } } private static FieldInfo MirroredObjectsField() { if (!mirroredObjectsFieldResolved) { mirroredObjectsFieldResolved = true; try { mirroredObjectsField = AccessTools.Field(typeof(CharacterItem), "m_gameObjects"); } catch (Exception exception) { PortPlugin.Report("CharacterItem.m_gameObjects is not reachable", exception); } } return mirroredObjectsField; } internal static void MirrorClothingColours(GameObject cloth) { //IL_00a8: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)cloth)) { return; } FieldInfo fieldInfo = MirroredObjectsField(); if (fieldInfo == null) { return; } CharacterItem component = cloth.GetComponent<CharacterItem>(); if (!Object.op_Implicit((Object)(object)component) || !(fieldInfo.GetValue(component) is GameObject[] array) || array.Length < 2) { return; } for (int i = 1; i < array.Length; i++) { GameObject val = array[i]; if (!Object.op_Implicit((Object)(object)val)) { continue; } Renderer[] componentsInChildren = cloth.GetComponentsInChildren<Renderer>(true); Renderer[] componentsInChildren2 = val.GetComponentsInChildren<Renderer>(true); if (componentsInChildren.Length != componentsInChildren2.Length) { continue; } for (int j = 0; j < componentsInChildren.Length; j++) { Material[] materials = componentsInChildren[j].materials; Material[] materials2 = componentsInChildren2[j].materials; if (materials.Length == materials2.Length) { for (int k = 0; k < materials.Length; k++) { materials2[k].color = materials[k].color; } } } } } internal static void IsolateProjectile(RangeWeapon weapon, Unit owner) { if (!Object.op_Implicit((Object)(object)weapon) || !Object.op_Implicit((Object)(object)weapon.ObjectToSpawn)) { return; } GameObject objectToSpawn = weapon.ObjectToSpawn; if (Object.op_Implicit((Object)(object)objectToSpawn.GetComponent<PooledProjectile>())) { GameObject val = UPool.MyPool.ClonePrivate(objectToSpawn); PooledProjectile[] componentsInChildren = val.GetComponentsInChildren<PooledProjectile>(true); for (int i = 0; i < componentsInChildren.Length; i++) { Object.DestroyImmediate((Object)(object)componentsInChildren[i]); } PortRuntime.Ensure<PortUnitState>(((Component)owner).gameObject).ProjectilePrefabs.Add(val); weapon.ObjectToSpawn = val; } } internal static void RegisterSounds(SoundBank bank) { //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Expected O, but got Unknown //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_0121: 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_013f: Unknown result type (might be due to invalid IL or missing references) //IL_014a: Unknown result type (might be due to invalid IL or missing references) //IL_0155: 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_0170: Expected O, but got Unknown List<SoundBankCategory> list = ((IEnumerable<SoundBankCategory>)(((object)bank.Categories) ?? ((object)new SoundBankCategory[0]))).ToList(); if (list.Any((SoundBankCategory x) => x.categoryName == "Modernization")) { throw new InvalidOperationException("Another Modernization audio category is already installed."); } SoundBankCategory val = ((IEnumerable<SoundBankCategory>)list).FirstOrDefault((Func<SoundBankCategory, bool>)((SoundBankCategory x) => x.categoryName.IndexOf("weapon", StringComparison.OrdinalIgnoreCase) >= 0)) ?? list.FirstOrDefault(); List<SoundEffectInstance> list2 = new List<SoundEffectInstance>(); foreach (KeyValuePair<string, SoundEffectInstance> sound in PinaCollada.Sounds) { SoundEffectInstance value = sound.Value; SoundEffectInstance val2 = new SoundEffectInstance(); FieldInfo[] fields = typeof(SoundEffectInstance).GetFields(); foreach (FieldInfo fieldInfo in fields) { fieldInfo.SetValue(val2, fieldInfo.GetValue(value)); } val2.soundRef = sound.Key; list2.Add(val2); } list.Add(new SoundBankCategory { categoryName = "Modernization", soundEffects = list2.ToArray(), categoryMixerGroup = val?.categoryMixerGroup, volumeMultiplier = 1f, pitchMultiplier = 1f, minDistanceMultiplier = 1f, maxDistanceMultiplier = 1f }); bank.Categories = list.ToArray(); } internal static void PlayReload(LegacyMagazine magazine) { //IL_0036: Unknown result type (might be due to invalid IL or missing references) if (Object.op_Implicit((Object)(object)magazine) && !string.IsNullOrEmpty(magazine.ReloadSound)) { SoundPlayer service = ServiceLocator.GetService<SoundPlayer>(); if (Object.op_Implicit((Object)(object)service)) { service.PlaySoundEffect(magazine.ReloadSound, 1f, ((Component)magazine).transform.position, (MaterialType)0, (Transform)null, 1f); } } } } internal static class RequiredTemplates { internal static readonly string[][] Items = new string[48][] { new string[2] { "blueprints", "Cannon" }, new string[2] { "blueprints", "CavalryKnight" }, new string[2] { "blueprints", "Clubber" }, new string[2] { "blueprints", "Healer" }, new string[2] { "blueprints", "Musketeer" }, new string[2] { "blueprints", "Wheelbarrow" }, new string[2] { "clothes", "Ancient_Belt001" }, new string[2] { "clothes", "Ancient_Belt004" }, new string[2] { "clothes", "Ancient_ChestArmor003" }, new string[2] { "clothes", "Ancient_Helmet004" }, new string[2] { "clothes", "Ancient_Shirt002" }, new string[2] { "clothes", "Halloween_Archer_Glove002" }, new string[2] { "clothes", "Halloween_Archer_Wrist" }, new string[2] { "clothes", "Medieval_Pants002" }, new string[2] { "clothes", "NinjaShoes001" }, new string[2] { "clothes", "Renaissance_HandGuard" }, new string[2] { "clothes", "Renaissance_Shirt005" }, new string[2] { "explosions", "E_ExplosionBombCannon" }, new string[2] { "explosions", "E_ExplosionSamuraiGiant" }, new string[2] { "moves", "BarrelArmor_ArmLeft" }, new string[2] { "moves", "BarrelArmor_ArmRight" }, new string[2] { "moves", "BarrelArmor_ElbowLeft" }, new string[2] { "moves", "BarrelArmor_ElbowRight" }, new string[2] { "moves", "BarrelArmor_Head" }, new string[2] { "moves", "BarrelArmor_Hip" }, new string[2] { "moves", "BarrelArmor_KneeLeft" }, new string[2] { "moves", "BarrelArmor_KneeRight" }, new string[2] { "moves", "BarrelArmor_LegLeft" }, new string[2] { "moves", "BarrelArmor_LegRight" }, new string[2] { "moves", "BarrelArmor_Torso" }, new string[2] { "moves", "CavalryCharge" }, new string[2] { "moves", "Chukonu_Walk" }, new string[2] { "moves", "Fencer_Dodge" }, new string[2] { "moves", "FireBreath" }, new string[2] { "moves", "FireBreath_Wheelbarrow" }, new string[2] { "moves", "MinotaurCharge" }, new string[2] { "moves", "SwordArtParry" }, new string[2] { "moves", "Wings" }, new string[2] { "weapons", "BrawlerAxe" }, new string[2] { "weapons", "Chukonu" }, new string[2] { "weapons", "Minigun" }, new string[2] { "weapons", "Musket" }, new string[2] { "weapons", "PriestStaff" }, new string[2] { "weapons", "Shield_Tower" }, new string[2] { "weapons", "Stick" }, new string[2] { "weapons", "Sword" }, new string[2] { "weapons", "Thrower_WheelBarrowApple" }, new string[2] { "weapons", "Thrown_Spear" } }; } public sealed class RotorSpin : MonoBehaviour { public Vector3 RotateAxis = Vector3.zero; private void Update() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) ((Component)this).transform.Rotate(RotateAxis * Time.deltaTime); } } internal static class RuntimeCompatibilityRules { internal const float StructureHealth = 100000f; internal static int RequiredSeats<T>(T[] riders, Func<T, bool> exists) { int num = ((riders != null) ? riders.Length : 0); while (num > 0 && !exists(riders[num - 1])) { num--; } return num; } internal static int MaterialSlots(int submeshes, int materials) { if (submeshes < 0 || materials < 0) { throw new ArgumentOutOfRangeException(); } return Math.Min(submeshes, materials); } internal static bool CanDodge(bool enabled, bool data, bool rigidbodies) { return enabled && data && rigidbodies; } internal static bool CanUpdateMount(bool mounted, bool otherData) { return mounted || otherData; } internal static bool NeedsBlockAnchor(bool hasWeaponHandler, bool meleeRight, bool meleeLeft, int collectedRigs, bool hasLeftHand) { if (hasWeaponHandler && !meleeRight && !meleeLeft && collectedRigs == 0) { return !hasLeftHand; } return false; } internal static bool IsIndestructible(float blueprintHealth) { return float.IsPositiveInfinity(blueprintHealth); } internal static bool CanKeepWorldScale(float x, float y, float z) { if (Math.Abs(x) > 1E-06f && Math.Abs(y) > 1E-06f && Math.Abs(z) > 1E-06f && !float.IsNaN(x + y + z)) { return !float.IsInfinity(x + y + z); } return false; } internal static float FiniteHealth(float value) { if (!float.IsNaN(value) && !float.IsInfinity(value)) { return value; } return 100000f; } } internal sealed class DiagnosticGate { private readonly HashSet<string> seen = new HashSet<string>(StringComparer.Ordinal); private readonly int limit; private bool overflowReported; internal int Count => seen.Count; internal DiagnosticGate(int limit) { this.limit = Math.Max(1, limit); } internal string Admit(string unit, string issue, string detail) { string item = (unit ?? "?") + "\n" + (issue ?? "?"); if (seen.Contains(item)) { return null; } if (seen.Count >= limit) { if (overflowReported) { return null; } overflowReported = true; int num = limit; return "Further unit diagnostics suppressed after " + num + " distinct reports."; } seen.Add(item); return "[unit: " + (string.IsNullOrEmpty(unit) ? "?" : unit) + "] " + issue + (string.IsNullOrEmpty(detail) ? "" : (": " + detail)); } } internal enum TemplateRole { Ranged, Melee, Shield, Shoes } internal sealed class TemplateAlias { internal readonly string Category; internal readonly string LegacyName; internal readonly string[] AlternateNames; internal readonly string[] Units; internal readonly TemplateRole Role; internal readonly bool Optional; internal TemplateAlias(string category, string name, TemplateRole role, string[] alternatives, string[] units, bool optional = false) { Category = category; LegacyName = name; Role = role; AlternateNames = alternatives; Units = units; Optional = optional; } } internal static class TemplateCompatibility { internal static readonly TemplateAlias[] Rules = new TemplateAlias[6] { new TemplateAlias("clothes", "NinjaShoes001", TemplateRole.Shoes, new string[4] { "Ninja_Shoes001", "Ninja_Shoes_001", "NinjaShoes", "ShoesNinja" }, new string[4] { "Ninja", "Shogun", "Samurai", "Musketeer" }, optional: true), new TemplateAlias("weapons", "Minigun", TemplateRole.Ranged, new string[1] { "Minigun_1" }, new string[0]), new TemplateAlias("weapons", "Shield_Tower", TemplateRole.Shield, new string[4] { "TowerShield", "Tower_Shield", "Shield Tower", "Tower Shield" }, new string[2] { "ShieldBearer", "Shield Bearer" }), new TemplateAlias("weapons", "Sword", TemplateRole.Melee, new string[4] { "SquireSword", "SwordSquire", "Sword_Squire", "Sword_OneHanded" }, new string[2] { "Squire", "Knight" }), new TemplateAlias("weapons", "Thrower_WheelBarrowApple", TemplateRole.Ranged, new string[5] { "Thrower_Wheelbarrow_Apple", "WheelbarrowApple", "Wheelbarrow_Apple", "AppleThrower", "Apple" }, new string[1] { "Wheelbarrow" }), new TemplateAlias("weapons", "Thrown_Spear", TemplateRole.Ranged, new string[4] { "ThrownSpear", "Spear_Thrown", "SpearThrower", "ThrowingSpear" }, new string[2] { "SpearThrower", "Spear Thrower" }) }; internal static string Canonical(string name) { if (string.IsNullOrEmpty(name)) { return ""; } name = name.Replace("(Clone)", "").Trim(); bool flag; do { flag = false; string[] array = new string[7] { "CP_", "WP_", "W_", "P_", "Move_", "E_", "B_" }; foreach (string text in array) { if (name.StartsWith(text, StringComparison.OrdinalIgnoreCase)) { name = name.Substring(text.Length); flag = true; break; } } } while (flag); StringBuilder stringBuilder = new StringBuilder(); string text2 = name; foreach (char c in text2) { if (char.IsLetterOrDigit(c)) { stringBuilder.Append(char.ToLowerInvariant(c)); } } return stringBuilder.ToString(); } internal static bool TryFind<T>(IDictionary<string, T> catalog, string name, out T value) where T : class { if (catalog.TryGetValue(name, out value)) { return true; } string wanted = Canonical(name); T[] array = (from p in catalog where Canonical(p.Key) == wanted select p.Value into p where p != null select p).Distinct().Take(2).ToArray(); value = ((array.Length == 1) ? array[0] : null); return array.Length == 1; } internal static void Apply<T>(IDictionary<string, Dictionary<string, T>> catalogs, Func<TemplateAlias, T, bool> valid, Func<TemplateAlias, T> nativeReplacement, Action<TemplateAlias, T> resolved) where T : class { TemplateAlias[] rules = Rules; foreach (TemplateAlias templateAlias in rules) { Dictionary<string, T> dictionary = catalogs[templateAlias.Category]; T val = null; foreach (string item in new string[1] { templateAlias.LegacyName }.Concat(templateAlias.AlternateNames)) { if (TryFind(dictionary, item, out var value) && valid(templateAlias, value)) { val = value; break; } } if (val == null) { T val2 = nativeReplacement(templateAlias); if (valid(templateAlias, val2)) { val = val2; } } if (val == null && !templateAlias.Optional) { throw new MissingMemberException("Required vanilla " + templateAlias.Role.ToString() + " template unavailable: " + templateAlias.Category + "/" + templateAlias.LegacyName + "; source units: " + string.Join(", ", templateAlias.Units)); } dictionary[templateAlias.LegacyName] = val; resolved?.Invoke(templateAlias, val); } } } internal static class VehicleCompatibility { internal static void PrepareBlueprint(UnitBlueprint blueprint) { //IL_0176: Unknown result type (might be due to invalid IL or missing references) //IL_017b: Unknown result type (might be due to invalid IL or missing references) //IL_0189: Unknown result type (might be due to invalid IL or missing references) //IL_01a4: Unknown result type (might be due to invalid IL or missing references) //IL_0197: Unknown result type (might be due to invalid IL or missing references) //IL_01ae: Unknown result type (might be due to invalid IL or missing references) //IL_01c9: Unknown result type (might be due to invalid IL or missing references) //IL_01bc: Unknown result type (might be due to invalid IL or missing references) //IL_024b: Unknown result type (might be due to invalid IL or missing references) //IL_0255: Expected O, but got Unknown int num = RuntimeCompatibilityRules.RequiredSeats(blueprint.UnitRiders, (UnitBlueprint rider) => Object.op_Implicit((Object)(object)rider)); if (num == 0) { return; } if (!Object.op_Implicit((Object)(object)blueprint.UnitBase)) { throw new InvalidOperationException("Vehicle base unavailable: " + blueprint.Entity.Name); } GameObject original = blueprint.UnitBase; MountPos[] array = (from p in original.GetComponentsInChildren<MountPos>(true) where ActiveUnder(((Component)p).transform, original.transform) select p).ToArray(); if (array.Length >= num) { return; } GameObject prefab = UPool.MyPool.ClonePrivate(original); ((Object)prefab).name = "Modernization/base/" + bl