using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using APIPlugin; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using DiskCardGame; using HarmonyLib; using InscryptionAPI.Ascension; using InscryptionAPI.Card; using InscryptionAPI.Dialogue; using InscryptionAPI.Encounters; using InscryptionAPI.Guid; using InscryptionAPI.Helpers; using InscryptionAPI.Items; using InscryptionAPI.Items.Extensions; using InscryptionAPI.Localizing; using InscryptionAPI.Masks; using InscryptionAPI.Regions; using InscryptionAPI.Saves; using InscryptionAPI.Sound; using InscryptionAPI.TalkingCards; using InscryptionAPI.TalkingCards.Animation; using InscryptionAPI.TalkingCards.Create; using InscryptionAPI.TalkingCards.Helpers; using InscryptionAPI.Triggers; using JLPlugin; using JLPlugin.ConfigilFunctions; using JLPlugin.Data; using JLPlugin.Hotkeys; using JLPlugin.SigilCode; using JLPlugin.Utils; using JLPlugin.V2.Data; using JSONLoader.API; using JSONLoader.Data; using JSONLoader.Data.TalkingCards; using JSONLoader.V2Code; using Microsoft.CodeAnalysis; using MonoMod.Utils; using NCalc; using PanoramicData.NCalcExtensions; using Sirenix.Utilities; using TMPro; using TinyJson; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: IgnoresAccessChecksTo("Antlr3.Runtime")] [assembly: IgnoresAccessChecksTo("InscryptionAPI")] [assembly: IgnoresAccessChecksTo("InscryptionCommunityPatch")] [assembly: IgnoresAccessChecksTo("NCalc")] [assembly: IgnoresAccessChecksTo("PanoramicData.NCalcExtensions")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyCompany("MADH95, JamesVeug, LilySylvee, kbmackenzie, Chaosyr, divisionbyz0rro, IngoHHacks, Khaomi, vladdeSV, TVFLabs, UwUMacaroniTime, Windows10CE")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyDescription("This is the DLL File that handles JSON Loading for Inscryption Mods, originally created by MadH95 with the help of several AMAZING Contributors!!")] [assembly: AssemblyFileVersion("2.7.0.0")] [assembly: AssemblyInformationalVersion("2.7.0+c1f6160e1641a8bddc93884883bfb8bd3d713c73")] [assembly: AssemblyProduct("JSONLoader")] [assembly: AssemblyTitle("JSONLoader")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("2.7.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] internal sealed class IsUnmanagedAttribute : Attribute { } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } public abstract class AConfigilData : IInitializable { public activationCost activationCost; public List abilityBehaviour; public static List DefaultActionOrder = new List { "chooseSlots", "showMessage", "gainCurrency", "dealScaleDamage", "drawCards", "placeCards", "transformCards", "changeAppearance", "buffCards", "moveCards", "damageSlots", "attackSlots", "customActions" }; public abstract string Name { get; } protected AConfigilData() { Initialize(); } public abstract void Initialize(); public static void UpdateVariables(AbilityBehaviourData abilitydata, PlayableCard self) { if (abilitydata.variables == null) { abilitydata.variables = new Dictionary(); } if (abilitydata.generatedVariables == null) { abilitydata.generatedVariables = new Dictionary(); } Dictionary second = new Dictionary { { "EnergyAmount", Singleton.Instance.PlayerEnergy.ToString() }, { "BoneAmount", Singleton.Instance.PlayerBones.ToString() }, { "Turn", Singleton.Instance.TurnNumber.ToString() }, { "TurnsInPlay", abilitydata.TurnsInPlay.GetValueOrDefault().ToString() }, { "ScaleBalance", Singleton.Instance.Balance.ToString() } }; abilitydata.variables.Append(second); abilitydata.variables = JSONLoaderAPI.GetModifiedVariableList(abilitydata.variables); Dictionary second2 = new Dictionary { { "LastDrawnCard", null }, { "DamageAmount", null }, { "DeathSlot", null }, { "HitSlot", null }, { "AttackerCard", null }, { "VictimCard", null }, { "ChooseableSlot", null }, { "RandomCardInfo", null }, { "TriggerCard", null }, { "BaseCard", self } }; abilitydata.generatedVariables.Append(second2); } public static object ConvertArgumentToType(string value, AbilityBehaviourData abilitydata, Type type, bool sendDebug = true) { if (value == null) { return null; } object obj = null; try { obj = Interpreter.Process(in value, abilitydata, type, sendDebug); } catch (Exception) { Plugin.Log.LogError((object)$"[{abilitydata.GetType()}] Error converting argument '{value}' to '{type}'"); throw; } if (type.IsAssignableFrom(obj.GetType())) { return obj; } Plugin.Log.LogError((object)$"{obj} is not of type {type}"); return null; } public static string ConvertArgument(string value, AbilityBehaviourData abilitydata, bool sendDebug = true) { if (string.IsNullOrEmpty(value)) { return null; } try { return Interpreter.Process(in value, abilitydata, null, sendDebug).ToString(); } catch (Exception) { Plugin.Log.LogError((object)$"[{abilitydata.GetType()}] Error converting argument '{value}' to string"); throw; } } public static IEnumerator RunActions(AbilityBehaviourData abilitydata, PlayableCard self, object ability = null) { abilitydata.self = self; if (ability.GetType().IsEnum) { if (ability is Ability) { abilitydata.ability = (Ability)ability; } else if (ability is SpecialTriggeredAbility) { abilitydata.specialAbility = (SpecialTriggeredAbility)ability; } else { abilitydata.specialStatIcon = (SpecialStatIcon?)ability; } } else { abilitydata.consumableItem = (string)ability; } List defaultActionOrder = DefaultActionOrder; if (abilitydata.actionOrder != null) { for (int i = 0; i < abilitydata.actionOrder.Count - 1; i++) { string item = abilitydata.actionOrder[i]; string item2 = abilitydata.actionOrder[i + 1]; if (defaultActionOrder.IndexOf(item) > defaultActionOrder.IndexOf(item2)) { defaultActionOrder.Remove(item); defaultActionOrder.Insert(defaultActionOrder.IndexOf(item2), item); } } } View OriginalView = Singleton.Instance.CurrentView; Singleton.Instance.Controller.LockState = (ViewLockState)1; using (List.Enumerator enumerator = defaultActionOrder.GetEnumerator()) { while (enumerator.MoveNext()) { switch (enumerator.Current) { case "chooseSlots": if (abilitydata.chooseSlots == null) { break; } foreach (chooseSlot chooseslotdata in abilitydata.chooseSlots) { CoroutineWithData chosenslotdata = new CoroutineWithData(chooseSlot.ChooseSlot(abilitydata, chooseslotdata, self.slot)); yield return chooseSlot.ChooseSlot(abilitydata, chooseslotdata, self.slot); Dictionary generatedVariables = abilitydata.generatedVariables; string key = "ChosenSlot(" + (abilitydata.chooseSlots.IndexOf(chooseslotdata) + 1) + ")"; object result = chosenslotdata.result; generatedVariables[key] = ((result is CardSlot) ? result : null); } break; case "showMessage": if (abilitydata.showMessage != null) { yield return messageData.showMessage(abilitydata); } break; case "gainCurrency": if (abilitydata.gainCurrency != null) { yield return gainCurrency.GainCurrency(abilitydata); } break; case "dealScaleDamage": if (abilitydata.dealScaleDamage != null) { yield return dealScaleDamage.DealScaleDamage(abilitydata); } break; case "drawCards": if (abilitydata.drawCards != null) { yield return drawCards.DrawCards(abilitydata); } break; case "placeCards": if (abilitydata.placeCards != null) { yield return placeCards.PlaceCards(abilitydata); } break; case "transformCards": if (abilitydata.transformCards != null) { yield return transformCards.TransformCards(abilitydata); } break; case "changeAppearance": if (abilitydata.changeAppearance != null) { yield return changeAppearance.ChangeAppearance(abilitydata); } break; case "buffCards": if (abilitydata.buffCards != null) { yield return buffCards.BuffCards(abilitydata); } break; case "moveCards": if (abilitydata.moveCards != null) { yield return moveCards.MoveCards(abilitydata); } break; case "damageSlots": if (abilitydata.damageSlots != null) { yield return damageSlots.DamageSlots(abilitydata); } break; case "attackSlots": if (abilitydata.attackSlots != null) { yield return attackSlots.AttackSlots(abilitydata); } break; case "customActions": yield return customActions.runCustomActions(abilitydata); break; } } } Singleton.Instance.SwitchToView(OriginalView, false, false); Singleton.Instance.Controller.LockState = (ViewLockState)0; } public static LineSet SetAbilityInfoDialogue(string dialogue) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Expected O, but got Unknown //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Expected O, but got Unknown return new LineSet(new List { new Line { text = dialogue } }); } } public abstract class ABaseConfigilLogic { private readonly AConfigilData data; private readonly Dictionary> abilityBehaviours; public abstract object ability { get; } public abstract object Instance { get; } public abstract PlayableCard PlayableCard { get; } public abstract Card Card { get; } public ABaseConfigilLogic(AConfigilData data) { this.data = data; abilityBehaviours = new Dictionary>(); for (int i = 0; i < data.abilityBehaviour.Count; i++) { AbilityBehaviourData abilityBehaviourData = data.abilityBehaviour[i]; string text = abilityBehaviourData.trigger?.triggerType; if (string.IsNullOrEmpty(text)) { Plugin.Log.LogError((object)$"AbilityBehaviourData {i} has no triggerType {data.Name}!"); continue; } if (text.StartsWith("OnHealthLevel")) { text = "OnHealthLevel"; } if (!abilityBehaviours.ContainsKey(text)) { abilityBehaviours[text] = new List(); } abilityBehaviours[text].Add(abilityBehaviourData); } } public IEnumerator Activate() { int valueOrDefault = (data.activationCost?.bloodCost).GetValueOrDefault(); if (valueOrDefault > 0) { List list = Singleton.Instance.PlayerSlotsCopy.FindAll((CardSlot x) => (Object)(object)x.Card != (Object)null && (Object)(object)x.Card != (Object)(object)PlayableCard); if (!((Object)(object)Singleton.Instance != (Object)null) || Singleton.Instance.AvailableSacrificeValueInSlots(list) < valueOrDefault) { ((Card)PlayableCard).Anim.LightNegationEffect(); AudioController.Instance.PlaySound2D("toneless_negate", (MixerGroup)10, 0.2f, 0f, (Pitch)null, (Repetition)null, (Randomization)null, (Distortion)null, false); yield return (object)new WaitForSeconds(0.25f); yield break; } Singleton.Instance.CancelledSacrifice = false; yield return Singleton.Instance.ChooseSacrificesForCard(list, PlayableCard, valueOrDefault); if (Singleton.Instance.CancelledSacrifice) { yield break; } } List list2 = data.activationCost?.gemsCost?.Select(ImportExportUtils.ParseEnum).ToList() ?? new List(); foreach (GemType item in list2) { if (!Singleton.Instance.HasGem(item)) { ((Card)PlayableCard).Anim.LightNegationEffect(); AudioController.Instance.PlaySound2D("toneless_negate", (MixerGroup)10, 0.2f, 0f, (Pitch)null, (Repetition)null, (Randomization)null, (Distortion)null, false); yield return (object)new WaitForSeconds(0.25f); yield break; } } yield return TriggerSigil("OnActivate"); } public IEnumerator Start() { if (data?.abilityBehaviour == null) { yield break; } foreach (AbilityBehaviourData item in data.abilityBehaviour) { item.TurnsInPlay = 0; if ((Object)(object)PlayableCard != (Object)null) { string extendedProperty = CardExtensions.GetExtendedProperty(((Card)PlayableCard).Info, "JSONFilePath"); if (extendedProperty != null) { if (!CachedCardData.Contains(extendedProperty)) { CachedCardData.Add(extendedProperty, extendedProperty.FromFilePath()); } CardSerializeInfo cardSerializeInfo = CachedCardData.Get(extendedProperty); if (cardSerializeInfo.extensionProperties != null) { foreach (KeyValuePair extensionProperty in cardSerializeInfo.extensionProperties) { MatchCollection matchCollection = Regex.Matches(extensionProperty.Key, "variable: " + Interpreter.RegexStrings.Variable); if (matchCollection.Cast().Any((Match v) => v.Success)) { item.variables[matchCollection[0].Groups[1].Value] = extensionProperty.Value; } } } } } AConfigilData.UpdateVariables(item, PlayableCard); } yield return TriggerSigil("OnLoad"); } public bool RespondsToOtherCardResolve(PlayableCard otherCard) { if (!abilityBehaviours.ContainsKey("OnDetect")) { return abilityBehaviours.ContainsKey("OnResolveOnBoard"); } return true; } public IEnumerator OnOtherCardResolve(PlayableCard otherCard) { if ((Object)(object)otherCard.Slot.opposingSlot.Card == (Object)(object)PlayableCard) { yield return TriggerSigil("OnDetect", null, otherCard.Slot.opposingSlot.Card); } yield return TriggerSigil("OnResolveOnBoard", null, otherCard); } public bool RespondsToOtherCardAssignedToSlot(PlayableCard otherCard) { return abilityBehaviours.ContainsKey("OnDetect"); } public IEnumerator OnOtherCardAssignedToSlot(PlayableCard otherCard) { if ((Object)(object)otherCard.Slot.opposingSlot.Card == (Object)(object)PlayableCard) { yield return TriggerSigil("OnDetect", null, otherCard.Slot.opposingSlot.Card); } } public bool RespondsToTurnEnd(bool playerTurnEnd) { if (!abilityBehaviours.ContainsKey("OnPlayerEndOfTurn") && !abilityBehaviours.ContainsKey("OnOpponentEndOfTurn")) { return abilityBehaviours.ContainsKey("OnEndOfTurn"); } return true; } public IEnumerator OnTurnEnd(bool playerTurnEnd) { if (playerTurnEnd) { yield return TriggerSigil("OnPlayerEndOfTurn"); } else { yield return TriggerSigil("OnOpponentEndOfTurn"); } if (PlayableCard.OpponentCard != playerTurnEnd) { for (int i = 0; i < data.abilityBehaviour.Count; i++) { data.abilityBehaviour[i].TurnsInPlay++; } yield return TriggerSigil("OnEndOfTurn"); } } public bool RespondsToUpkeep(bool playerUpkeep) { if (!abilityBehaviours.ContainsKey("OnPlayerStartOfTurn") && !abilityBehaviours.ContainsKey("OnOpponentStartOfTurn")) { return abilityBehaviours.ContainsKey("OnStartOfTurn"); } return true; } public IEnumerator OnUpkeep(bool playerUpkeep) { if (playerUpkeep) { yield return TriggerSigil("OnPlayerStartOfTurn"); } else { yield return TriggerSigil("OnOpponentStartOfTurn"); } if (PlayableCard.OpponentCard != playerUpkeep) { yield return TriggerSigil("OnStartOfTurn"); } } public bool RespondsToOtherCardDealtDamage(PlayableCard attacker, int amount, PlayableCard target) { if (!abilityBehaviours.ContainsKey("OnStruck") && !abilityBehaviours.ContainsKey("OnDamage")) { return abilityBehaviours.ContainsKey("OnHealthLevel"); } return true; } public IEnumerator OnOtherCardDealtDamage(PlayableCard attacker, int amount, PlayableCard target) { if (abilityBehaviours.TryGetValue("OnHealthLevel", out var value)) { foreach (AbilityBehaviourData item in value) { MatchCollection source = Regex.Matches(item.trigger.triggerType, "OnHealthLevel\\((.*?)\\)"); if (source.Cast().ToList().Count > 0) { int num = int.Parse(source.Cast().ToList()[0].Groups[1].Value); if (target.Health <= num) { yield return TriggerBehaviour(item, ("AttackerCard", attacker), target); } } } } yield return TriggerSigil("OnStruck", ("AttackerCard", attacker, "DamageAmount", amount), target); yield return TriggerSigil("OnDamage", ("VictimCard", target, "DamageAmount", amount), attacker); } public bool RespondsToOtherCardDie(PlayableCard card, CardSlot deathSlot, bool fromCombat, PlayableCard killer) { if (!abilityBehaviours.ContainsKey("OnDie")) { return abilityBehaviours.ContainsKey("OnKill"); } return true; } public IEnumerator OnOtherCardDie(PlayableCard card, CardSlot deathSlot, bool fromCombat, PlayableCard killer) { yield return (object)new WaitForSeconds(0.3f); if (fromCombat) { yield return TriggerSigil("OnDie", ("AttackerCard", killer, "DeathSlot", deathSlot), card); if ((Object)(object)killer != (Object)null) { yield return TriggerSigil("OnKill", ("VictimCard", card, "DeathSlot", deathSlot), killer); } } } public bool RespondsToSacrifice() { return abilityBehaviours.ContainsKey("OnSacrifice"); } public IEnumerator OnSacrifice() { yield return TriggerSigil("OnSacrifice", ("SacrificeTargetCard", Singleton.Instance.CurrentSacrificeDemandingCard)); } public bool RespondsToOtherCardPreDeath(CardSlot deathSlot, bool fromCombat, PlayableCard killer) { if (fromCombat) { if (!abilityBehaviours.ContainsKey("OnPreDeath")) { return abilityBehaviours.ContainsKey("OnPreKill"); } return true; } return false; } public IEnumerator OnOtherCardPreDeath(CardSlot deathSlot, bool fromCombat, PlayableCard killer) { if ((Object)(object)deathSlot.Card != (Object)null) { yield return TriggerSigil("OnPreDeath", ("AttackerCard", killer, "DeathSlot", deathSlot), deathSlot.Card); } yield return TriggerSigil("OnPreKill", ("VictimCard", deathSlot.Card, "DeathSlot", deathSlot), killer); } public bool RespondsToSlotTargetedForAttack(CardSlot slot, PlayableCard attacker) { return abilityBehaviours.ContainsKey("OnAttack"); } public IEnumerator OnSlotTargetedForAttack(CardSlot slot, PlayableCard attacker) { yield return TriggerSigil("OnAttack", ("HitSlot", slot), attacker); } public bool RespondsToBellRung(bool playerCombatPhase) { if (!abilityBehaviours.ContainsKey("OnCombatStart")) { return abilityBehaviours.ContainsKey("OnEnemyCombatStart"); } return true; } public IEnumerator OnBellRung(bool playerCombatPhase) { if (playerCombatPhase) { yield return TriggerSigil("OnCombatStart"); } else { yield return TriggerSigil("OnEnemyCombatStart"); } } public bool RespondsToOtherCardAddedToHand(PlayableCard card) { return abilityBehaviours.ContainsKey("OnAddedToHand"); } public IEnumerator OnOtherCardAddedToHand(PlayableCard card) { yield return TriggerSigil("OnAddedToHand", null, card); } public bool RespondsToCardAssignedToSlotContext(PlayableCard card, CardSlot oldSlot, CardSlot newSlot) { return abilityBehaviours.ContainsKey("OnMove"); } public IEnumerator OnCardAssignedToSlotContext(PlayableCard card, CardSlot oldSlot, CardSlot newSlot) { if ((Object)(object)oldSlot != (Object)null) { yield return TriggerSigil("OnMove", ("OldSlot", oldSlot), card); } } public bool RespondsToCardDealtDamageDirectly(PlayableCard attacker, CardSlot opposingSlot, int damage) { return abilityBehaviours.ContainsKey("OnDamageDirectly"); } public IEnumerator OnCardDealtDamageDirectly(PlayableCard attacker, CardSlot opposingSlot, int damage) { yield return TriggerSigil("OnDamageDirectly", ("HitSlot", opposingSlot, "DamageAmount", damage), attacker); } public IEnumerator TriggerSigil(string trigger, TriggerVariables variableList = null, PlayableCard cardToCheck = null) { if (!abilityBehaviours.TryGetValue(trigger, out var value)) { yield break; } foreach (AbilityBehaviourData behaviourData in value) { if (behaviourData.trigger.activatesForCardsWithCondition != null && (Object)(object)cardToCheck == (Object)null) { foreach (PlayableCard item in Singleton.Instance.AllSlots.Select((CardSlot x) => x.Card).OfType().ToList()) { yield return TriggerBehaviour(behaviourData, variableList, item); } } else { yield return TriggerBehaviour(behaviourData, variableList, cardToCheck ?? PlayableCard); } } } public IEnumerator TriggerBehaviour(AbilityBehaviourData behaviourData, TriggerVariables variableList = null, PlayableCard cardToCheck = null) { if (Instance == null) { yield break; } AConfigilData.UpdateVariables(behaviourData, PlayableCard); if (behaviourData.trigger.activatesForCardsWithCondition != null) { if ((Object)(object)cardToCheck != (Object)null && !CheckCard(ref behaviourData, cardToCheck)) { yield break; } } else if ((Object)(object)cardToCheck != (Object)(object)PlayableCard && (Object)(object)cardToCheck != (Object)null) { yield break; } if (variableList != null) { foreach (KeyValuePair variable in variableList) { behaviourData.generatedVariables[variable.Key] = variable.Value; } } yield return LearnAbility(); yield return AConfigilData.RunActions(behaviourData, PlayableCard, ability); } private bool CheckCard(ref AbilityBehaviourData behaviourData, PlayableCard card) { behaviourData.generatedVariables["TriggerCard"] = card; return AConfigilData.ConvertArgument(behaviourData.trigger?.activatesForCardsWithCondition, behaviourData) == "true"; } public bool CanActivate() { if (!abilityBehaviours.TryGetValue("OnActivate", out var value)) { return false; } AbilityBehaviourData abilityBehaviourData = value[0]; AConfigilData.UpdateVariables(abilityBehaviourData, PlayableCard); return (AConfigilData.ConvertArgument(abilityBehaviourData.trigger?.activatesForCardsWithCondition, abilityBehaviourData) ?? "true") == "true"; } public int[] GetStatValues() { int[] array = new int[2]; if (!abilityBehaviours.TryGetValue("GetStatValues", out var value)) { return array; } foreach (AbilityBehaviourData item in value) { AConfigilData.UpdateVariables(item, PlayableCard); if (item.trigger?.activatesForCardsWithCondition == null || !(AConfigilData.ConvertArgument(item.trigger?.activatesForCardsWithCondition, item, sendDebug: false) != "true")) { if (!string.IsNullOrEmpty(item.getStatValues?.health) && int.TryParse(AConfigilData.ConvertArgument(item.getStatValues.health, item, sendDebug: false), out var result)) { array[1] += result; } if (!string.IsNullOrEmpty(item.getStatValues?.attack) && int.TryParse(AConfigilData.ConvertArgument(item.getStatValues.attack, item, sendDebug: false), out var result2)) { array[0] += result2; } } } return array; } public virtual IEnumerator LearnAbility(float startDelay = 0f) { yield break; } } public class ConfigilAbilityLogic : ABaseConfigilLogic { private readonly ActivatedAbilityBehaviour activatedAbilityBehaviour; public override object ability => ((AbilityBehaviour)activatedAbilityBehaviour).Ability; public override object Instance => activatedAbilityBehaviour; public override PlayableCard PlayableCard => ((Component)activatedAbilityBehaviour).GetComponent(); public override Card Card => (Card)(object)((AbilityBehaviour)activatedAbilityBehaviour).Card; public ConfigilAbilityLogic(ActivatedAbilityBehaviour triggerReceiver, SigilData sigilData) : base(sigilData) { activatedAbilityBehaviour = triggerReceiver; } public override IEnumerator LearnAbility(float startDelay = 0f) { yield return ((AbilityBehaviour)activatedAbilityBehaviour).LearnAbility(startDelay); } } public class ConfigConsumableItemLogic : ABaseConfigilLogic { private readonly ConfigurableConsumableItem consumableItem; public override object ability => "ConsumableItem"; public override object Instance => consumableItem; public override PlayableCard PlayableCard => null; public override Card Card => null; public ConfigConsumableItemLogic(ConfigurableConsumableItem triggerReceiver, ItemData data) : base(data) { consumableItem = triggerReceiver; } } public class ConfigPowerStateBehaviour : ABaseConfigilLogic { private SpecialCardBehaviour specialCardBehaviour; private SpecialStatIcon id; public override object ability => id; public override object Instance => specialCardBehaviour; public override PlayableCard PlayableCard => ((Component)specialCardBehaviour).GetComponent(); public override Card Card => specialCardBehaviour.Card; public ConfigPowerStateBehaviour(SpecialCardBehaviour triggerReceiver, SigilData sigilData, SpecialStatIcon ability) : base(sigilData) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) specialCardBehaviour = triggerReceiver; id = ability; } public override IEnumerator LearnAbility(float startDelay = 0f) { yield break; } } public class ConfigilSpecialAbilityLogic : ABaseConfigilLogic { private SpecialCardBehaviour specialCardBehaviour; private SpecialTriggeredAbility specialTriggeredAbility; public override object ability => specialTriggeredAbility; public override object Instance => specialCardBehaviour; public override PlayableCard PlayableCard => ((Component)specialCardBehaviour).GetComponent(); public override Card Card => specialCardBehaviour.Card; public ConfigilSpecialAbilityLogic(SpecialCardBehaviour triggerReceiver, SigilData sigilData, SpecialTriggeredAbility ability) : base(sigilData) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) specialCardBehaviour = triggerReceiver; specialTriggeredAbility = ability; } public override IEnumerator LearnAbility(float startDelay = 0f) { yield break; } } public class TriggerVariables : Dictionary { public TriggerVariables(string key, object value) { Add(key, value); } public TriggerVariables(string key, object value, string key2, object value2) { Add(key, value); Add(key2, value2); } public TriggerVariables(string key, object value, string key2, object value2, string key3, object value3) { Add(key, value); Add(key2, value2); Add(key3, value3); } public static implicit operator TriggerVariables((string, object) a) { return new TriggerVariables(a.Item1, a.Item2); } public static implicit operator TriggerVariables((string, object, string, object) a) { return new TriggerVariables(a.Item1, a.Item2, a.Item3, a.Item4); } public static implicit operator TriggerVariables((string, object, string, object, string, object) a) { return new TriggerVariables(a.Item1, a.Item2, a.Item3, a.Item4, a.Item5, a.Item6); } } public static class ImportExportUtils { private static string ID; private static string DebugPath; private static string LoggingSuffix; public static void SetID(string id) { ID = id; } public static void SetDebugPath(string path) { DebugPath = path.Substring(Plugin.BepInExDirectory.Length); LoggingSuffix = ""; } public static T ParseEnum(string value) where T : unmanaged, Enum { if (Enum.TryParse(value, out var result)) { return result; } int num = Math.Max(value.LastIndexOf('_'), value.LastIndexOf('.')); if (num < 0) { throw new InvalidCastException("Cannot parse " + value + " as " + typeof(T).FullName); } string text = value.Substring(0, num); string text2 = value.Substring(num + 1); return GuidManager.GetEnumValue(text, text2); } public static void ApplyProperty(Func getter, Action setter, ref Y serializeInfoValue, bool toCardInfo, string category, string suffix) { if (toCardInfo) { T a = default(T); ApplyValue(ref a, ref serializeInfoValue, toA: true, category, suffix); setter(a); } else { T a2 = getter(); ApplyValue(ref a2, ref serializeInfoValue, toA: false, category, suffix); } } public static void ApplyProperty(ref T serializeInfoValue, Func getter, Action setter, bool toCardInfo, string category, string suffix) { if (toCardInfo) { Y b = getter(); ApplyValue(ref serializeInfoValue, ref b, toA: false, category, suffix); } else { Y b2 = default(Y); ApplyValue(ref serializeInfoValue, ref b2, toA: true, category, suffix); setter(b2); } } public static void ApplyValue(ref T a, ref Y b, bool toA, string category, string suffix) { if (toA) { ConvertValue(ref b, ref a, category, suffix); } else { ConvertValue(ref a, ref b, category, suffix); } } private static void ConvertValue(ref FromType from, ref ToType to, string category, string suffix) { //IL_07d2: Unknown result type (might be due to invalid IL or missing references) //IL_07d9: Expected O, but got Unknown //IL_08c5: Unknown result type (might be due to invalid IL or missing references) //IL_08cc: Expected O, but got Unknown //IL_09b8: Unknown result type (might be due to invalid IL or missing references) //IL_09bd: Unknown result type (might be due to invalid IL or missing references) //IL_09d8: Expected O, but got Unknown //IL_09d8: Unknown result type (might be due to invalid IL or missing references) //IL_0a28: Unknown result type (might be due to invalid IL or missing references) //IL_0a2d: Unknown result type (might be due to invalid IL or missing references) //IL_0b51: Unknown result type (might be due to invalid IL or missing references) //IL_0b56: Unknown result type (might be due to invalid IL or missing references) //IL_0b66: Unknown result type (might be due to invalid IL or missing references) //IL_0b7b: Unknown result type (might be due to invalid IL or missing references) //IL_0b90: Unknown result type (might be due to invalid IL or missing references) //IL_0ba5: Unknown result type (might be due to invalid IL or missing references) //IL_0b06: Unknown result type (might be due to invalid IL or missing references) //IL_0c93: Unknown result type (might be due to invalid IL or missing references) //IL_0c98: Unknown result type (might be due to invalid IL or missing references) //IL_0ca0: Unknown result type (might be due to invalid IL or missing references) //IL_0cac: Unknown result type (might be due to invalid IL or missing references) //IL_0c33: Unknown result type (might be due to invalid IL or missing references) LoggingSuffix = suffix; Type typeFromHandle = typeof(FromType); Type typeFromHandle2 = typeof(ToType); try { if (typeFromHandle == typeFromHandle2) { to = (ToType)(object)from; return; } if (AreNullableTypesEqual(from, to, out var a, out var _, out var aHasValue, out var _)) { if (aHasValue) { to = (ToType)a; } return; } if (typeFromHandle.IsGenericType && typeFromHandle.GetGenericTypeDefinition() == typeof(List<>) && typeFromHandle2.IsGenericType && typeFromHandle2.GetGenericTypeDefinition() == typeof(List<>)) { if (from != null) { IList list = (IList)Activator.CreateInstance(typeFromHandle2); to = (ToType)list; IList list2 = (IList)(object)from; for (int i = 0; i < list2.Count; i++) { object o = list2[i]; object o2 = GetDefault(typeFromHandle2.GetGenericArguments().Single()); object value = ConvertType(typeFromHandle, typeFromHandle2, o, o2, category, $"{suffix}_{i + 1}"); list.Add(value); } } return; } if (typeFromHandle.IsGenericType && typeFromHandle.GetGenericTypeDefinition() == typeof(List<>) && typeFromHandle2.IsArray) { if (from != null) { IList list3 = (IList)(object)from; int length = ((from != null) ? list3.Count : 0); Array array = Array.CreateInstance(typeFromHandle2.GetElementType(), length); to = (ToType)(object)array; for (int j = 0; j < list3.Count; j++) { object obj = list3[j]; object obj2 = GetDefault(typeFromHandle2.GetElementType()); object[] array2 = new object[4] { obj, obj2, category, $"{suffix}_{j + 1}" }; typeof(ImportExportUtils).GetMethod("ConvertValue", BindingFlags.Static | BindingFlags.NonPublic).MakeGenericMethod(typeFromHandle.GetGenericArguments().Single(), typeFromHandle2.GetElementType()).Invoke(null, array2); array.SetValue(array2[1], j); } } return; } if (typeFromHandle.IsArray && typeFromHandle2.IsGenericType && typeFromHandle2.GetGenericTypeDefinition() == typeof(List<>)) { if (from != null) { IList list4 = (IList)Activator.CreateInstance(typeFromHandle2); to = (ToType)list4; Array array3 = (Array)(object)from; for (int k = 0; k < array3.Length; k++) { object value2 = array3.GetValue(k); object obj3 = GetDefault(typeFromHandle2.GetGenericArguments().Single()); object[] array4 = new object[4] { value2, obj3, category, $"{suffix}_{k + 1}" }; typeof(ImportExportUtils).GetMethod("ConvertValue", BindingFlags.Static | BindingFlags.NonPublic).MakeGenericMethod(typeFromHandle.GetElementType(), typeFromHandle2.GetGenericArguments().Single()).Invoke(null, array4); list4.Add(array4[1]); } } return; } if (typeFromHandle.IsEnum && typeFromHandle2 == typeof(string)) { string text = from.ToString(); if (int.TryParse(text, out var result)) { if (Enum.GetValues(typeFromHandle).Cast().Contains(result)) { to = (ToType)(object)text; return; } object[] array5 = new object[3] { result, "guid", "name" }; if ((bool)typeof(GuidManager).GetMethod("TryGetGuidAndKeyEnumValue", BindingFlags.Static | BindingFlags.Public).MakeGenericMethod(typeFromHandle).Invoke(null, array5)) { string text2 = (string)array5[1]; string text3 = (string)array5[2]; to = (ToType)(object)(text2 + "_" + text3); } else { Error($"Failed to convert enum to string! '{from}' int '{result}'"); to = (ToType)(object)text; } } else { to = (ToType)(object)text; } return; } if (typeFromHandle == typeof(string) && typeFromHandle2.IsEnum) { if (!string.IsNullOrEmpty((string)(object)from)) { object obj4 = typeof(ImportExportUtils).GetMethod("ParseEnum", BindingFlags.Static | BindingFlags.Public).MakeGenericMethod(typeFromHandle2).Invoke(null, new object[1] { from }); to = (ToType)obj4; } return; } if (typeFromHandle == typeof(CardInfo) && typeFromHandle2 == typeof(string)) { if (from != null) { object obj5 = from; to = (ToType)(object)((Object)((obj5 is CardInfo) ? obj5 : null)).name; } return; } if (typeFromHandle == typeof(string) && typeFromHandle2 == typeof(CardInfo)) { string text4 = (string)(object)from; if (text4 != null) { text4 = text4.Trim(); } if (string.IsNullOrEmpty(text4)) { return; } to = (ToType)(object)CardExtensions.CardByName((IEnumerable)CardManager.AllCardsCopy, text4); if (to != null) { return; } CardInfo[] array6 = FindSimilarCards(text4); if (array6.Length == 0) { string text5 = string.Join(", ", CardManager.AllCardsCopy.Select((CardInfo c) => ((Object)c).name)); Error("Could not find CardInfo with name '" + text4 + "'!\nAllCards: " + text5); return; } to = (ToType)(object)array6[0]; string text6 = string.Join(" or ", array6.Select((CardInfo val5) => "'" + ((Object)val5).name + "'")); Warning("Could not find CardInfo with name '" + text4 + "'. Did you mean " + text6 + "?"); return; } if (typeFromHandle == typeof(string) && (typeFromHandle2 == typeof(Texture) || typeFromHandle2.IsSubclassOf(typeof(Texture)))) { string text7 = (string)(object)from; if (!string.IsNullOrEmpty(text7)) { try { to = (ToType)(object)GetTextureFromString(text7); return; } catch (FileNotFoundException) { Error("Failed to find texture " + text7 + "!"); return; } } return; } if ((typeFromHandle == typeof(Texture) || typeFromHandle.IsSubclassOf(typeof(Texture))) && typeFromHandle2 == typeof(string)) { Texture val = (Texture)(object)from; if ((Object)(object)val != (Object)null) { string path = Path.Combine(Plugin.ExportDirectory, category, "Assets", ID + "_" + suffix + ".png"); to = (ToType)(object)ExportTexture(val, path); } return; } if (typeFromHandle == typeof(string) && typeFromHandle2 == typeof(Sprite)) { string text8 = (string)(object)from; if (!string.IsNullOrEmpty(text8)) { Texture2D textureFromString = GetTextureFromString(text8); if ((Object)(object)textureFromString != (Object)null) { to = (ToType)(object)TextureHelper.ConvertTexture(textureFromString, (Vector2?)null); } } return; } if (typeFromHandle == typeof(Sprite) && typeFromHandle2 == typeof(string)) { Sprite val2 = (Sprite)(object)from; if ((Object)(object)val2 != (Object)null) { string path2 = Path.Combine(Plugin.ExportDirectory, category, "Assets", ID + "_" + suffix + ".png"); to = (ToType)(object)ExportTexture(val2.texture, path2); } return; } if (typeFromHandle.GetInterfaces().Contains(typeof(IConvertible)) && typeFromHandle2.GetInterfaces().Contains(typeof(IConvertible))) { IConvertible convertible = from as IConvertible; IConvertible convertible2 = to as IConvertible; if (convertible != null && convertible2 != null) { to = (ToType)Convert.ChangeType(convertible, typeFromHandle2); } return; } if (typeFromHandle == typeof(string) && typeFromHandle2 == typeof(LineSet)) { to = (ToType)(object)new LineSet(new List { new Line { text = (from as string) } }); return; } if (typeFromHandle == typeof(string) && typeFromHandle2 == typeof(Color)) { string text9 = (string)(object)from; Color white = Color.white; if (text9.StartsWith("#")) { if (!ColorUtility.TryParseHtmlString(text9, ref white)) { Error("Could not convert " + text9 + " to color!"); } } else { int[] array7 = (from text11 in text9.Split(new char[1] { ',' }) select int.Parse(text11.Trim())).ToArray(); if (array7.Length != 0) { white.r = (float)array7[0] / 255f; } if (array7.Length > 1) { white.g = (float)array7[1] / 255f; } if (array7.Length > 2) { white.b = (float)array7[2] / 255f; } if (array7.Length > 3) { white.a = (float)array7[3] / 255f; } } to = (ToType)(object)white; return; } if (typeFromHandle == typeof(Color) && typeFromHandle2 == typeof(string)) { Color val3 = (Color)(object)from; to = (ToType)(object)$"{val3.r * 255f:F0},{val3.g * 255f:F0},{val3.b * 255f:F0},{val3.a * 255f:F0}"; return; } if (typeFromHandle == typeof(string) && typeFromHandle2 == typeof(Vector2)) { string text10 = (string)(object)from; string[] array8 = text10.Split(new char[1] { ',' }); if (array8.Length == 2) { to = (ToType)(object)new Vector2(float.Parse(array8[0]), float.Parse(array8[1])); } else { Error("Could not convert " + text10 + " to Vector2!"); } return; } if (typeFromHandle == typeof(Vector2) && typeFromHandle2 == typeof(string)) { Vector2 val4 = (Vector2)(object)from; to = (ToType)(object)$"{val4.x},{val4.y}"; return; } if (typeFromHandle == typeof(LocalizableField) && typeFromHandle2 == typeof(string)) { Error("Use ApplyLocaleField when converted from LocalizableField to string!"); } else if (typeFromHandle == typeof(string) && typeFromHandle2 == typeof(LocalizableField)) { Error("Use ApplyLocaleField when converted from string to LocalizableField!"); } } catch (Exception e) { Error($"Failed to convert: {typeFromHandle} to {typeFromHandle2}"); Exception(e); return; } Error($"Unsupported conversion type: {typeFromHandle} to {typeFromHandle2}\n{Environment.StackTrace}"); } private static Texture2D GetTextureFromString(string path) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Expected O, but got Unknown //IL_003c: Expected O, but got Unknown if (path.StartsWith("base64:")) { try { byte[] array = Convert.FromBase64String(path.Substring("base64:".Length)); Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false) { filterMode = (FilterMode)0 }; ImageConversion.LoadImage(val, array); return val; } catch (Exception ex) { Error("Failed to convert base64 to texture: " + path); throw ex; } } return TextureHelper.GetImageAsTexture(path, (FilterMode)0); } public static CardInfo[] FindSimilarCards(string misspelledCardName) { return FindSimilar(misspelledCardName, CardManager.AllCardsCopy, (CardInfo a) => ((Object)a).name); } public static string[] FindSimilarStrings(string misspelledCardName, IEnumerable collection) { return FindSimilar(misspelledCardName, collection, (string a) => a); } public static T[] FindSimilar(string misspelledCardName, IEnumerable allElements, Func getter) { List> list = new List>(); string text = misspelledCardName.ToLower().Replace("-", "").Replace("_", ""); int num = Mathf.Clamp(text.Length - 1, 1, 4); foreach (T allElement in allElements) { string text2 = getter(allElement).ToLower().Replace("-", "").Replace("_", ""); if (Mathf.Abs(text.Length - text2.Length) > num) { continue; } int num2 = 0; int num3 = Mathf.Max(0, text.Length - text2.Length); int num4 = text2.Length - 1; int num5 = text.Length - 1; while (num5 >= 0 && num4 >= 0) { if (text2[num4] == text[num5]) { num2++; } else { num3++; if (num3 > num) { break; } if (num4 > 0 && text2[num4 - 1] == text[num5]) { num4--; num2++; } else if (num5 > 0 && text2[num4] == text[num5 - 1]) { num5--; num2++; } } num5--; num4--; } if (num2 > 0 && num3 < num) { list.Add(new Tuple(num2, allElement)); } } list.Sort((Tuple a, Tuple b) => b.Item1 - a.Item1); return list.Select((Tuple a) => a.Item2).ToArray(); } private static object ConvertType(Type fromType, Type toType, object o1, object o2, string category, string suffix) { object[] array = new object[4] { o1, o2, category, suffix }; typeof(ImportExportUtils).GetMethod("ConvertValue", BindingFlags.Static | BindingFlags.NonPublic).MakeGenericMethod(fromType.GetGenericArguments().Single(), toType.GetGenericArguments().Single()).Invoke(null, array); return array[1]; } private static bool AreNullableTypesEqual(T t, Y y, out object a, out object b, out bool aHasValue, out bool bHasValue) { aHasValue = false; bHasValue = false; a = null; b = null; bool flag = typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition() == typeof(Nullable<>); bool flag2 = typeof(Y).IsGenericType && typeof(Y).GetGenericTypeDefinition() == typeof(Nullable<>); if (!flag && !flag2) { return false; } Type? obj = (flag ? Nullable.GetUnderlyingType(typeof(T)) : typeof(T)); Type type = (flag2 ? Nullable.GetUnderlyingType(typeof(Y)) : typeof(Y)); if (obj == type) { if (flag) { a = GetValueFromNullable(t, out aHasValue); } else { a = t; aHasValue = true; } if (flag2) { b = GetValueFromNullable(y, out bHasValue); } else { b = y; bHasValue = true; } return true; } Error($"Not same types {typeof(T)} {typeof(Y)}"); return false; } private static string ExportTexture(Texture texture, string path) { Texture2D val = (Texture2D)(object)((texture is Texture2D) ? texture : null); if (val != null) { return ExportTexture(val, path); } return ExportTexture(Texture2D.CreateExternalTexture(texture.width, texture.height, (TextureFormat)4, false, false, texture.GetNativeTexturePtr()), path); } private static string ExportTexture(Texture2D texture, string path) { //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Expected O, but got Unknown if (!((Texture)texture).isReadable) { RenderTexture temporary = RenderTexture.GetTemporary(((Texture)texture).width, ((Texture)texture).height, 0, (RenderTextureFormat)7, (RenderTextureReadWrite)1); Graphics.Blit((Texture)(object)texture, temporary); RenderTexture active = RenderTexture.active; RenderTexture.active = temporary; Texture2D val = new Texture2D(((Texture)texture).width, ((Texture)texture).height); val.ReadPixels(new Rect(0f, 0f, (float)((Texture)temporary).width, (float)((Texture)temporary).height), 0, 0); val.Apply(); RenderTexture.active = active; RenderTexture.ReleaseTemporary(temporary); texture = val; } byte[] array = ImageConversion.EncodeToPNG(texture); if (array == null) { Error("Failed to turn into bytes??"); } if (string.IsNullOrEmpty(path)) { Error("path is empty????"); } string directoryName = Path.GetDirectoryName(path); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } File.WriteAllBytes(path, array); return Path.GetFileName(path); } public static string[] ExportTextures(IEnumerable texture, string type, string fileName) { int num = 0; List list = new List(); foreach (Texture2D item in texture) { num++; string path = Path.Combine(Plugin.ExportDirectory, type, "Assets", $"{fileName}_{num}.png"); list.Add(ExportTexture(item, path)); } return list.ToArray(); } public static void ApplyLocaleField(string field, ref LocalizableField rows, ref string cardInfoEnglishField, bool toCardInfo) { if (toCardInfo) { ApplyLocaleField(field, rows, ref cardInfoEnglishField); } else if (!string.IsNullOrEmpty(cardInfoEnglishField = cardInfoEnglishField)) { ImportLocaleField(rows, cardInfoEnglishField); } } private static void ImportLocaleField(LocalizableField rows, string cardInfoEnglishField) { //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) rows.rows.Clear(); rows.Initialize(cardInfoEnglishField); Translation val = Localization.Translations.Find((Translation a) => a.englishString == cardInfoEnglishField); if (val != null) { foreach (KeyValuePair value in val.values) { string text = LocalizationManager.LanguageToCode(value.Key); rows.SetValue(rows.englishFieldName + "_" + text, value.Value); VerboseLog($"Loaded {cardInfoEnglishField} translation for {text} => {value.Key}"); } return; } VerboseLog("ApplyLocaleField could not find any translations from english '" + cardInfoEnglishField + "'"); } private static void ApplyLocaleField(string field, LocalizableField rows, ref string cardInfoEnglishField) { //IL_0104: Unknown result type (might be due to invalid IL or missing references) //IL_0109: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Invalid comparison between Unknown and I4 //IL_0120: Unknown result type (might be due to invalid IL or missing references) if (rows.rows.TryGetValue(rows.englishFieldName, out var value)) { cardInfoEnglishField = value; } else { if (rows.rows.Count <= 0) { return; } cardInfoEnglishField = rows.rows.First().Value; } VerboseLog("ApplyLocaleField " + field + " english " + cardInfoEnglishField); foreach (KeyValuePair row in rows.rows) { if (row.Key == rows.englishFieldName) { continue; } int num = row.Key.LastIndexOf("_", StringComparison.Ordinal); if (num < 0) { VerboseError("Could not find _ of key " + row.Key + " in field " + field + "!"); continue; } int length = row.Key.Length - num - 1; string text = row.Key.Substring(num + 1, length); Language val = LocalizationManager.CodeToLanguage(text); if ((int)val != 12) { LocalizationManager.Translate("MADH.inscryption.JSONLoader", (string)null, cardInfoEnglishField, row.Value, val); VerboseLog("Translation " + cardInfoEnglishField + " to " + text + " = " + row.Value); } else { Error("Unknown language code " + text + " for card " + cardInfoEnglishField + " in field " + field); } } } private static object GetValueFromNullable(U u, out bool hasValue) { Type typeFromHandle = typeof(U); if (u != null && (bool)typeFromHandle.GetProperty("HasValue", BindingFlags.Instance | BindingFlags.Public).GetValue(u)) { hasValue = true; return typeFromHandle.GetProperty("Value", BindingFlags.Instance | BindingFlags.Public).GetValue(u); } hasValue = false; Type underlyingType = Nullable.GetUnderlyingType(typeFromHandle); if (underlyingType.IsValueType) { return Activator.CreateInstance(underlyingType); } return null; } private static object GetDefault(Type type) { if (type.IsValueType) { return Activator.CreateInstance(type); } return null; } private static void VerboseLog(string message) { Plugin.VerboseLog("[" + DebugPath + "][" + ID + "][" + LoggingSuffix + "] " + message); } private static void VerboseWarning(string message) { if (Configs.VerboseLogging) { Plugin.VerboseWarning("[" + DebugPath + "][" + ID + "][" + LoggingSuffix + "] " + message); } } private static void VerboseError(string message) { if (Configs.VerboseLogging) { Plugin.VerboseError("[" + DebugPath + "][" + ID + "][" + LoggingSuffix + "] " + message); } } private static void Warning(string message) { if (Configs.VerboseLogging) { VerboseWarning(message); return; } Plugin.Log.LogWarning((object)("[" + ID + "][" + LoggingSuffix + "] " + message)); } private static void Error(string message) { if (Configs.VerboseLogging) { VerboseError(message); return; } Plugin.Log.LogError((object)("[" + ID + "][" + LoggingSuffix + "] " + message)); } private static void Exception(Exception e) { Plugin.Log.LogError((object)("[" + DebugPath + "][" + ID + "][" + LoggingSuffix + "] " + e.Message + "\n" + e.StackTrace)); } } [Serializable] public class RegionSerializeInfo { public string name; public int tier; public bool addToPool = true; public List terrainCards; public List encounters; public List likelyCards; public List dominantTribes; public string bossPrepEncounter; public string boardLightColor; public string cardsLightColor; public string mapAlbedo; public List bosses; public List fillerScenery; public List scarceScenery; public List predefinedScenery; public DialogueEventStrings dialogueEvent; private string ambientLoopId; private List consumableItems; public static void LoadAllRegions(List files) { for (int num = files.Count - 1; num >= 0; num--) { string text = files[num]; string text2 = text.Substring(text.LastIndexOf(Path.DirectorySeparatorChar) + 1); if (text2.ToLower().EndsWith("_region.jldr2")) { files.RemoveAt(num--); Plugin.VerboseLog("Loading JLDR2 (region) " + text2); try { ImportExportUtils.SetDebugPath(text); RegionSerializeInfo data = text.FromFilePath(); RegionData val = RegionManager.AllRegionsCopy.Find((RegionData a) => ((Object)a).name == data.name); if ((Object)(object)val == (Object)null) { val = RegionManager.New(data.name, data.tier, data.addToPool); } Process(val, data, toRegion: true); Plugin.VerboseLog("Loaded JSON region from " + text2 + "!"); } catch (Exception ex) { Plugin.Log.LogError((object)("Failed to load JSON region from " + text2 + "!")); Plugin.Log.LogError((object)ex); } } } } private static void Process(RegionData region, RegionSerializeInfo data, bool toRegion) { //IL_0522: Unknown result type (might be due to invalid IL or missing references) //IL_052c: Expected O, but got Unknown ImportExportUtils.SetID(toRegion ? data.name : ((Object)region).name); GetFillerScenery(ref region.fillerScenery, ref data.fillerScenery, toRegion); GetScarceScenery(ref region.scarceScenery, ref data.scarceScenery, toRegion); List data2 = region.predefinedScenery?.scenery; GetPredefinedScenery(ref data2, ref data.predefinedScenery, toRegion); ImportExportUtils.ApplyValue(ref region.ambientLoopId, ref data.ambientLoopId, toRegion, "Regions", "ambientLoopId"); ImportExportUtils.ApplyValue(ref region.terrainCards, ref data.terrainCards, toRegion, "Regions", "terrainCards"); ImportExportUtils.ApplyValue(ref region.dominantTribes, ref data.dominantTribes, toRegion, "Regions", "dominantTribes"); ImportExportUtils.ApplyValue(ref region.boardLightColor, ref data.boardLightColor, toRegion, "Regions", "boardLightColor"); ImportExportUtils.ApplyValue(ref region.cardsLightColor, ref data.cardsLightColor, toRegion, "Regions", "cardsLightColor"); ImportExportUtils.ApplyValue(ref region.mapAlbedo, ref data.mapAlbedo, toRegion, "Regions", "mapAlbedo"); ImportExportUtils.ApplyValue(ref region.likelyCards, ref data.likelyCards, toRegion, "Regions", "likelyCards"); ImportExportUtils.ApplyValue(ref region.bosses, ref data.bosses, toRegion, "Regions", "bosses"); if (toRegion) { region.mapParticlesPrefabs = new List(); ((Object)region).name = data.name; if ((Object)(object)region.predefinedScenery == (Object)null) { region.predefinedScenery = ScriptableObject.CreateInstance(); } region.predefinedScenery.scenery = data2; if (data.bossPrepEncounter != null) { EncounterBlueprintData val = EncounterManager.AllEncountersCopy.Find((EncounterBlueprintData a) => ((Object)a).name == data.bossPrepEncounter); if ((Object)(object)val != (Object)null) { region.bossPrepEncounter = val; } else { Plugin.Log.LogError((object)("Could not find boss prep encounter " + data.bossPrepEncounter + " for region " + data.name + "!")); } } if (data.dialogueEvent != null) { DialogueManager.Add("MADH.inscryption.JSONLoader", CreateEvent(data.dialogueEvent)); } else { Plugin.Log.LogError((object)("No dialogue specified for region " + data.name + "!")); } region.encounters = new List(); if (data.encounters != null) { foreach (string encounter in data.encounters) { EncounterBlueprintData val2 = EncounterManager.AllEncountersCopy.Find((EncounterBlueprintData a) => ((Object)a).name == encounter); if ((Object)(object)val2 != (Object)null) { region.encounters.Add(val2); continue; } Plugin.Log.LogError((object)("Could not find encounter " + encounter + " for region " + data.name + "!")); } } region.consumableItems = new List(); if (data.consumableItems == null) { return; } List allConsumables = ItemsUtil.AllConsumables; { foreach (string consumableItem in data.consumableItems) { ConsumableItemData val3 = allConsumables.Find((ConsumableItemData a) => ((Object)a).name == consumableItem); if ((Object)(object)val3 != (Object)null) { region.consumableItems.Add(val3); continue; } Plugin.Log.LogError((object)("Could not find consumable item " + consumableItem + " for region " + data.name + "!")); } return; } } data.name = ((Object)region).name; if ((Object)(object)region.bossPrepEncounter != (Object)null) { data.bossPrepEncounter = ((Object)region.bossPrepEncounter).name; } DialogueEvent val4 = DialogueDataUtil.Data.GetEvent("Region" + ((Object)region).name); if (val4 != null) { string[] array = val4.mainLines.lines.Select((Line a) => a.text).ToArray(); string[][] array2 = val4.repeatLines.Select((LineSet a) => a.lines.Select((Line b) => b.text).ToArray()).ToArray(); data.dialogueEvent = new DialogueEventStrings(((Object)region).name, array, array2); } if (region.encounters != null) { data.encounters = new List(); foreach (EncounterBlueprintData encounter2 in region.encounters) { data.encounters.Add(((Object)encounter2).name); } } if (region.consumableItems == null) { return; } data.consumableItems = new List(); foreach (ConsumableItemData consumableItem2 in region.consumableItems) { data.consumableItems.Add(((Object)consumableItem2).name); } } private static DialogueEvent CreateEvent(DialogueEventStrings dialogueEvent) { List list = dialogueEvent.mainLines.Select((string x) => CustomLine.op_Implicit(x)).ToList(); List> list2 = dialogueEvent.repeatLines.Select((string[] x) => x.Select((string y) => CustomLine.op_Implicit(y)).ToList()).ToList(); return DialogueManager.GenerateEvent("MADH.inscryption.JSONLoader", "Region" + dialogueEvent.eventName, list, list2, (MaxRepeatsBehaviour)0, (Speaker)0); } private static void GetFillerScenery(ref List data, ref List info, bool toData) { //IL_0102: Unknown result type (might be due to invalid IL or missing references) //IL_011a: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) if (toData) { data = new List(); if (info == null || info.Count == 0) { return; } { foreach (SceneryEntrySerializedInfo item in info) { FillerSceneryEntry val = new FillerSceneryEntry(); ((SceneryEntry)val).data = ScriptableObject.CreateInstance(); ((SceneryEntry)val).data.minScale = item.minScale; ((SceneryEntry)val).data.maxScale = item.maxScale; ((SceneryEntry)val).data.prefabNames = item.prefabNames; ((SceneryEntry)val).data.radius = item.radius; ((SceneryEntry)val).data.perlinNoiseHeight = item.perlinNoiseHeight; data.Add(val); } return; } } info = new List(); if (data == null || data.Count == 0) { return; } foreach (FillerSceneryEntry datum in data) { SceneryEntrySerializedInfo sceneryEntrySerializedInfo = new SceneryEntrySerializedInfo(); sceneryEntrySerializedInfo.minScale = ((SceneryEntry)datum).data.minScale; sceneryEntrySerializedInfo.maxScale = ((SceneryEntry)datum).data.maxScale; sceneryEntrySerializedInfo.prefabNames = ((SceneryEntry)datum).data.prefabNames; sceneryEntrySerializedInfo.radius = ((SceneryEntry)datum).data.radius; sceneryEntrySerializedInfo.perlinNoiseHeight = ((SceneryEntry)datum).data.perlinNoiseHeight; info.Add(sceneryEntrySerializedInfo); } } private static void GetScarceScenery(ref List data, ref List info, bool toData) { //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) if (toData) { data = new List(); if (info == null || info.Count == 0) { return; } { foreach (ScarceSceneryEntrySerializedInfo item in info) { ScarceSceneryEntry val = new ScarceSceneryEntry(); ((SceneryEntry)val).data = ScriptableObject.CreateInstance(); ((SceneryEntry)val).data.minScale = item.minScale; ((SceneryEntry)val).data.maxScale = item.maxScale; ((SceneryEntry)val).data.prefabNames = item.prefabNames; ((SceneryEntry)val).data.radius = item.radius; ((SceneryEntry)val).data.perlinNoiseHeight = item.perlinNoiseHeight; val.minDensity = item.minDensity; val.minInstances = item.minInstances; val.maxInstances = item.maxInstances; data.Add(val); } return; } } info = new List(); if (data == null || data.Count == 0) { return; } foreach (ScarceSceneryEntry datum in data) { ScarceSceneryEntrySerializedInfo scarceSceneryEntrySerializedInfo = new ScarceSceneryEntrySerializedInfo(); scarceSceneryEntrySerializedInfo.minScale = ((SceneryEntry)datum).data.minScale; scarceSceneryEntrySerializedInfo.maxScale = ((SceneryEntry)datum).data.maxScale; scarceSceneryEntrySerializedInfo.prefabNames = ((SceneryEntry)datum).data.prefabNames; scarceSceneryEntrySerializedInfo.radius = ((SceneryEntry)datum).data.radius; scarceSceneryEntrySerializedInfo.perlinNoiseHeight = ((SceneryEntry)datum).data.perlinNoiseHeight; scarceSceneryEntrySerializedInfo.minDensity = datum.minDensity; scarceSceneryEntrySerializedInfo.minInstances = datum.minInstances; scarceSceneryEntrySerializedInfo.maxInstances = datum.maxInstances; info.Add(scarceSceneryEntrySerializedInfo); } } private static void GetPredefinedScenery(ref List data, ref List info, bool toData) { //IL_0124: Unknown result type (might be due to invalid IL or missing references) //IL_013c: Unknown result type (might be due to invalid IL or missing references) //IL_0188: Unknown result type (might be due to invalid IL or missing references) //IL_019b: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) if (toData) { data = new List(); if (info == null || info.Count == 0) { return; } { foreach (PredefinedEntrySerializedInfo item in info) { SceneryElementData val = new SceneryElementData(); val.data = ScriptableObject.CreateInstance(); val.data.minScale = item.minScale; val.data.maxScale = item.maxScale; val.data.prefabNames = item.prefabNames; val.data.radius = item.radius; val.data.perlinNoiseHeight = item.perlinNoiseHeight; val.rotation = item.rotation; val.scale = item.scale; data.Add(val); } return; } } info = new List(); if (data == null || data.Count == 0) { return; } foreach (SceneryElementData datum in data) { PredefinedEntrySerializedInfo predefinedEntrySerializedInfo = new PredefinedEntrySerializedInfo(); predefinedEntrySerializedInfo.minScale = datum.data.minScale; predefinedEntrySerializedInfo.maxScale = datum.data.maxScale; predefinedEntrySerializedInfo.prefabNames = datum.data.prefabNames; predefinedEntrySerializedInfo.radius = datum.data.radius; predefinedEntrySerializedInfo.perlinNoiseHeight = datum.data.perlinNoiseHeight; predefinedEntrySerializedInfo.rotation = datum.rotation; predefinedEntrySerializedInfo.scale = datum.scale; info.Add(predefinedEntrySerializedInfo); } } public static void ExportAllRegions() { Plugin.Log.LogInfo((object)$"Exporting {RegionManager.AllRegionsCopy.Count} Regions"); foreach (RegionData item in RegionManager.AllRegionsCopy) { RegionSerializeInfo regionSerializeInfo = new RegionSerializeInfo(); string text = Path.Combine(Plugin.ExportDirectory, "Regions", ((Object)item).name + "_region.jldr2"); ImportExportUtils.SetDebugPath(text); Process(item, regionSerializeInfo, toRegion: false); string directoryName = Path.GetDirectoryName(text); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } File.WriteAllText(text, JSONParser.ToJSON(regionSerializeInfo)); } } } [Serializable] public class SceneryEntrySerializedInfo { public Vector2SerializeInfo minScale = new Vector2SerializeInfo(0.05f, 0.05f); public Vector2SerializeInfo maxScale = new Vector2SerializeInfo(0.09f, 0.22f); public List prefabNames = new List { "Tree_3_Mossy" }; public float radius = 0.06f; public bool perlinNoiseHeight = true; } [Serializable] public class ScarceSceneryEntrySerializedInfo : SceneryEntrySerializedInfo { public float minDensity; public int minInstances; public int maxInstances; } [Serializable] public class PredefinedEntrySerializedInfo : SceneryEntrySerializedInfo { public Vector3SerializeInfo rotation; public Vector3SerializeInfo scale; } [Serializable] public class Vector2SerializeInfo { public float x; public float y; public Vector2SerializeInfo(float x, float y) { this.x = x; this.y = y; } public static implicit operator Vector2(Vector2SerializeInfo info) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) return new Vector2(info.x, info.y); } public static implicit operator Vector2SerializeInfo(Vector2 info) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) return new Vector2SerializeInfo(info.x, info.y); } } [Serializable] public class Vector3SerializeInfo : Vector2SerializeInfo { public float z; public Vector3SerializeInfo(float x, float y, float z) : base(x, y) { this.z = z; } public static implicit operator Vector3(Vector3SerializeInfo info) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) return new Vector3(info.x, info.y, info.z); } public static implicit operator Vector3SerializeInfo(Vector3 info) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) return new Vector3SerializeInfo(info.x, info.y, info.z); } } namespace TinyJson { public interface IFlexibleField { bool ContainsKey(string key); void SetValue(string key, string value); string ToJSON(string prefix); } public interface IInitializable { void Initialize(); } [Serializable] public class LocalizableField : IFlexibleField { public Dictionary rows; public string englishFieldName; public string englishFieldNameLower; public string EnglishValue { get { if (rows.TryGetValue(englishFieldName, out var value)) { return value; } Plugin.Log.LogError((object)("Field has not been initialized " + englishFieldName + "!")); return englishFieldName; } } public LocalizableField(string EnglishFieldName) { rows = new Dictionary(); englishFieldName = EnglishFieldName; englishFieldNameLower = EnglishFieldName.ToLower(); } public void Initialize(string englishValue) { rows[englishFieldName] = englishValue; } public bool ContainsKey(string key) { return key.StartsWith(englishFieldNameLower); } public void SetValue(string key, string value) { rows[key] = value; } public string ToJSON(string prefix) { string text = ""; int num = 0; foreach (KeyValuePair row in rows) { text = text + "\n" + prefix + "\"" + row.Key + "\": \"" + row.Value + "\""; if (num++ < rows.Count - 1) { text += ","; } } if (num == 0) { text = text + "\n" + prefix + "\"" + englishFieldName + "\": \"\""; } return text; } public override string ToString() { return rows.ToString(); } } public static class JSONParser { [ThreadStatic] private static Stack> splitArrayPool; [ThreadStatic] private static StringBuilder stringBuilder; [ThreadStatic] private static Dictionary> fieldInfoCache; [ThreadStatic] private static Dictionary> propertyInfoCache; [ThreadStatic] private static Dictionary publicFieldInfoCache; [ThreadStatic] private static Dictionary publicPropertyInfoCache; private static string LogPrefix = ""; public static T FromFilePath(this string filePath) { LogPrefix = filePath.Replace(Paths.PluginPath, ""); if (LogPrefix.StartsWith("/") || LogPrefix.StartsWith("\\")) { LogPrefix = LogPrefix.Substring(1); } return File.ReadAllText(filePath).FromJsonInternal(); } public static T FromJson(this string json) { LogPrefix = "Unspecified Path"; return json.FromJsonInternal(); } private static T FromJsonInternal(this string json) { if (propertyInfoCache == null) { propertyInfoCache = new Dictionary>(); } if (fieldInfoCache == null) { fieldInfoCache = new Dictionary>(); } if (stringBuilder == null) { stringBuilder = new StringBuilder(); } if (splitArrayPool == null) { splitArrayPool = new Stack>(); } if (publicFieldInfoCache == null) { publicFieldInfoCache = new Dictionary(); } if (publicPropertyInfoCache == null) { publicPropertyInfoCache = new Dictionary(); } stringBuilder.Length = 0; for (int i = 0; i < json.Length; i++) { char c = json[i]; switch (c) { case '"': i = AppendUntilStringEnd(appendEscapeCharacter: true, i, json); continue; case '/': if (i + 1 != json.Length && json[i + 1] == '/') { i = SkipUntilLineEnd(i, json); continue; } break; } if (!char.IsWhiteSpace(c)) { stringBuilder.Append(c); } } return (T)ParseValue(typeof(T), stringBuilder.ToString()); } private static int SkipUntilLineEnd(int startIdx, string json) { for (int i = startIdx + 2; i < json.Length; i++) { if (json[i] == '\n') { return i + 1; } } return json.Length - 1; } private static int AppendUntilStringEnd(bool appendEscapeCharacter, int startIdx, string json) { stringBuilder.Append(json[startIdx]); for (int i = startIdx + 1; i < json.Length; i++) { if (json[i] == '\\') { if (appendEscapeCharacter) { stringBuilder.Append(json[i]); } stringBuilder.Append(json[i + 1]); i++; } else { if (json[i] == '"') { stringBuilder.Append(json[i]); return i; } stringBuilder.Append(json[i]); } } return json.Length - 1; } private static List Split(string json, out int lastIndex) { List list = ((splitArrayPool.Count > 0) ? splitArrayPool.Pop() : new List()); list.Clear(); if (json.Length == 2) { lastIndex = -1; return list; } int num = 0; stringBuilder.Length = 0; lastIndex = 1; for (int i = 1; i < json.Length - 1; i++) { switch (json[i]) { case '[': case '{': num++; break; case ']': case '}': num--; break; case '"': i = AppendUntilStringEnd(appendEscapeCharacter: true, i, json); continue; case ',': case ':': lastIndex = i; if (num == 0) { list.Add(stringBuilder.ToString()); stringBuilder.Length = 0; continue; } break; } stringBuilder.Append(json[i]); } list.Add(stringBuilder.ToString()); return list; } internal static object ParseValue(Type type, string json) { if (type == typeof(string)) { if (json.Length <= 2) { return string.Empty; } StringBuilder stringBuilder = new StringBuilder(json.Length); for (int i = 1; i < json.Length - 1; i++) { if (json[i] == '\\' && i + 1 < json.Length - 1) { int num = "\"\\nrtbf/".IndexOf(json[i + 1]); if (num >= 0) { stringBuilder.Append("\"\\\n\r\t\b\f/"[num]); i++; continue; } if (json[i + 1] == 'u' && i + 5 < json.Length - 1) { uint result = 0u; if (uint.TryParse(json.Substring(i + 2, 4), NumberStyles.AllowHexSpecifier, null, out result)) { stringBuilder.Append((char)result); i += 5; continue; } } } stringBuilder.Append(json[i]); } return stringBuilder.ToString(); } if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { return Convert.ChangeType(json, type.GetGenericArguments().First(), CultureInfo.InvariantCulture); } if (type.IsPrimitive) { return Convert.ChangeType(json, type, CultureInfo.InvariantCulture); } if (type == typeof(decimal)) { decimal.TryParse(json, NumberStyles.Float, CultureInfo.InvariantCulture, out var result2); return result2; } if (type == typeof(DateTime)) { DateTime.TryParse(json.Replace("\"", ""), CultureInfo.InvariantCulture, DateTimeStyles.None, out var result3); return result3; } if (json == "null") { return null; } if (type.IsEnum) { if (json[0] == '"') { json = json.Substring(1, json.Length - 2); } try { return Enum.Parse(type, json, ignoreCase: false); } catch (Exception exception) { LogError(exception); return 0; } } int lastIndex; if (type.IsArray) { Type elementType = type.GetElementType(); if (json[0] != '[' || json[json.Length - 1] != ']') { return null; } List list = Split(json, out lastIndex); Array array = Array.CreateInstance(elementType, list.Count); for (int j = 0; j < list.Count; j++) { array.SetValue(ParseValue(elementType, list[j]), j); } splitArrayPool.Push(list); return array; } if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>)) { Type type2 = type.GetGenericArguments()[0]; if (json[0] != '[' || json[json.Length - 1] != ']') { return null; } List list2 = Split(json, out lastIndex); IList list3 = (IList)type.GetConstructor(new Type[1] { typeof(int) }).Invoke(new object[1] { list2.Count }); for (int k = 0; k < list2.Count; k++) { list3.Add(ParseValue(type2, list2[k])); } splitArrayPool.Push(list2); return list3; } if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<, >)) { Type[] genericArguments = type.GetGenericArguments(); Type type3 = genericArguments[0]; Type type4 = genericArguments[1]; if (type3 != typeof(string)) { return null; } if (json[0] != '{' || json[json.Length - 1] != '}') { return null; } List list4 = Split(json, out lastIndex); if (list4.Count % 2 != 0) { return null; } IDictionary dictionary = (IDictionary)type.GetConstructor(new Type[1] { typeof(int) }).Invoke(new object[1] { list4.Count / 2 }); for (int l = 0; l < list4.Count; l += 2) { if (list4[l].Length > 2) { string key = list4[l].Substring(1, list4[l].Length - 2); object value = ParseValue(type4, list4[l + 1]); dictionary[key] = value; } } return dictionary; } if (type == typeof(object)) { return ParseAnonymousValue(json); } if (json[0] == '{' && json[json.Length - 1] == '}') { return ParseObject(type, json); } return null; } private static object ParseAnonymousValue(string json) { if (json.Length == 0) { return null; } int lastIndex; if (json[0] == '{' && json[json.Length - 1] == '}') { List list = Split(json, out lastIndex); if (list.Count % 2 != 0) { return null; } Dictionary dictionary = new Dictionary(list.Count / 2); for (int i = 0; i < list.Count; i += 2) { dictionary[list[i].Substring(1, list[i].Length - 2)] = ParseAnonymousValue(list[i + 1]); } return dictionary; } if (json[0] == '[' && json[json.Length - 1] == ']') { List list2 = Split(json, out lastIndex); List list3 = new List(list2.Count); for (int j = 0; j < list2.Count; j++) { list3.Add(ParseAnonymousValue(list2[j])); } return list3; } if (json[0] == '"' && json[json.Length - 1] == '"') { return json.Substring(1, json.Length - 2).Replace("\\", string.Empty); } if (char.IsDigit(json[0]) || json[0] == '-') { if (json.Contains(".")) { double.TryParse(json, NumberStyles.Float, CultureInfo.InvariantCulture, out var result); return result; } int.TryParse(json, out var result2); return result2; } if (json == "true") { return true; } if (json == "false") { return false; } return null; } private static Dictionary CreateMemberNameDictionary(T[] members) where T : MemberInfo { Dictionary dictionary = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (T val in members) { if (val.IsDefined(typeof(IgnoreDataMemberAttribute), inherit: true)) { continue; } string name = val.Name; if (val.IsDefined(typeof(DataMemberAttribute), inherit: true)) { DataMemberAttribute dataMemberAttribute = (DataMemberAttribute)Attribute.GetCustomAttribute(val, typeof(DataMemberAttribute), inherit: true); if (!string.IsNullOrEmpty(dataMemberAttribute.Name)) { name = dataMemberAttribute.Name; } } dictionary.Add(name.ToLower(), val); } return dictionary; } private static object ParseObject(Type type, string json) { object uninitializedObject = FormatterServices.GetUninitializedObject(type); if (uninitializedObject is IInitializable initializable) { initializable.Initialize(); } int lastIndex; List list = Split(json, out lastIndex); if (list.Count % 2 != 0) { char[] source = new char[5] { '{', '}', '[', ']', ',' }; int num = lastIndex - 1; while (num >= 0 && !source.Contains(json[num])) { num--; } string text = ""; if (num < 0) { int num2 = Math.Max(0, lastIndex - 20); int length = Math.Min(json.Length - num2, 40); text = json.Substring(num2, length); } else { int num3 = num + 1; int length2 = Math.Min(json.Length - num3, lastIndex); text = json.Substring(num3, length2); } LogError($"Invalid JSON. Unexpected extra character found {json[lastIndex]} => {text}"); return uninitializedObject; } if (!fieldInfoCache.TryGetValue(type, out var value)) { value = CreateMemberNameDictionary(type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy)); fieldInfoCache.Add(type, value); } if (!propertyInfoCache.TryGetValue(type, out var value2)) { value2 = CreateMemberNameDictionary(type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy)); propertyInfoCache.Add(type, value2); } List allMembers = null; for (int i = 0; i < list.Count; i += 2) { if (list[i].Length <= 2) { continue; } string text2 = list[i].Substring(1, list[i].Length - 2); string key = text2.ToLower(); string text3 = list[i + 1]; if (value.TryGetValue(key, out var value3) && (!value3.IsPrivate || MemberInfoExtensions.GetAttribute((ICustomAttributeProvider)value3) != null)) { SetField(value3, uninitializedObject, text3); continue; } if (value2.TryGetValue(key, out var value4)) { SetProperty(value4, uninitializedObject, text3); continue; } bool flag = false; foreach (KeyValuePair item in value) { FieldInfo value5 = item.Value; if (value5.FieldType.GetInterfaces().Contains(typeof(IFlexibleField)) && value5.GetValue(uninitializedObject) is IFlexibleField flexibleField && flexibleField.ContainsKey(key)) { flexibleField.SetValue(key, (string)ParseValue(typeof(string), text3)); flag = true; break; } } if (flag) { continue; } string[] array = FindSimilarFields(key, value, value2); if (array != null && array.Length != 0) { if (allMembers == null) { allMembers = new List(); allMembers.AddRange(value.Values); allMembers.AddRange(value2.Values); } string[] source2 = array.Select((string a) => allMembers.Find((MemberInfo b) => b.Name.ToLower() == a).Name).ToArray(); string arg = string.Join(" or ", source2.Select((string a) => "'" + a + "'")); LogError($"{text2} field not found for {type}. Did you mean {arg}?"); } else { LogWarning($"{text2} field not found for {type}. Could not find a field with a similar name. Are you sure you need this field?"); } } return uninitializedObject; } private static void LogWarning(string message) { Plugin.Log.LogWarning((object)("[" + LogPrefix + "] " + message)); } private static void LogError(string message) { Plugin.Log.LogError((object)("[" + LogPrefix + "] " + message)); } private static void LogError(Exception exception) { Plugin.Log.LogError((object)$"[{LogPrefix}] {exception}"); } private static string[] FindSimilarFields(string key, Dictionary nameToField, Dictionary nameToProperty) { HashSet hashSet = new HashSet(); LinqExtensions.AddRange(hashSet, (IEnumerable)nameToField.Keys); LinqExtensions.AddRange(hashSet, (IEnumerable)nameToProperty.Keys); return ImportExportUtils.FindSimilarStrings(key, hashSet); } private static void SetField(FieldInfo info, object o, string v) { if (info.FieldType.GetInterfaces().Contains(typeof(IFlexibleField))) { object value = info.GetValue(o); if (value == null) { LogError($"{info.Name} field is null! Type: {info.FieldType} o:{o} instance:{o}"); } else if (value is IFlexibleField flexibleField) { flexibleField.SetValue(info.Name, (string)ParseValue(typeof(string), v)); } } else { info.SetValue(o, ParseValue(info.FieldType, v)); } } private static void SetProperty(PropertyInfo info, object o, string v) { info.SetValue(o, ParseValue(info.PropertyType, v), null); } public static string ToJSON(T t) { return ToJSONInternal(typeof(T), t, ""); } private static string ToJSONInternal(Type type, object t, string prefix) { try { if (type == typeof(string)) { string text = (string)t; if (text != null) { return "\"" + text + "\""; } return "\"\""; } if (type.IsArray) { if (t == null) { return "null"; } return JsonInternalArray(t, prefix); } if (type == typeof(int?)) { int? num = (int?)t; if (num.HasValue) { return num.Value.ToString(); } return "0"; } if (type == typeof(bool?)) { bool? flag = (bool?)t; if (flag.HasValue) { return flag.Value ? "true" : "false"; } return "false"; } if (type == typeof(bool)) { return ((bool)t) ? "true" : "false"; } if (type == typeof(int) || type == typeof(long)) { return t.ToString(); } if (type == typeof(float)) { return $"{t}"; } if (type == typeof(Dictionary)) { Dictionary dictionary = (Dictionary)t; if (dictionary != null && dictionary.Count > 0) { string text2 = "{"; int num2 = 0; foreach (KeyValuePair item in dictionary) { text2 = ((num2++ <= 0) ? (text2 + "\n\t" + prefix + "\"" + item.Key + "\": \"" + item.Value + "\"") : (text2 + ",\n\t" + prefix + "\"" + item.Key + "\": \"" + item.Value + "\"")); } if (num2 > 0) { return text2 + "\n" + prefix + "}"; } return text2 + "}"; } return "{}"; } if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>)) { IList list = (IList)t; if (list != null && list.Count > 0) { Type type2 = list.GetType().GetGenericArguments().Single(); string text3 = ""; string text4 = prefix + "\t"; for (int i = 0; i < list.Count; i++) { object t2 = list[i]; text3 = text3 + "\n" + text4 + ToJSONInternal(type2, t2, text4); if (i < list.Count - 1) { text3 += ","; } } return "[" + text3 + "\n" + prefix + "]"; } return "[]"; } if (!type.IsValueType) { if (t == null) { return "null"; } if (!publicFieldInfoCache.TryGetValue(type, out var value)) { value = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); publicFieldInfoCache[type] = value; } if (!publicPropertyInfoCache.TryGetValue(type, out var value2)) { value2 = type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty); publicPropertyInfoCache[type] = value2; } string text5 = "{"; int num3 = 0; string text6 = prefix + "\t"; FieldInfo[] array = value; foreach (FieldInfo fieldInfo in array) { if (fieldInfo.IsPrivate && MemberInfoExtensions.GetAttribute((ICustomAttributeProvider)fieldInfo) == null) { continue; } if (fieldInfo.FieldType.GetInterfaces().Contains(typeof(IFlexibleField))) { if (num3 > 0) { text5 += ","; } text5 += ((IFlexibleField)fieldInfo.GetValue(t)).ToJSON(text6); num3++; continue; } string text7 = ToJSONInternal(fieldInfo.FieldType, fieldInfo.GetValue(t), text6); if (num3++ > 0) { text5 += ","; } text5 = text5 + "\n" + text6 + "\"" + fieldInfo.Name + "\": " + text7; } PropertyInfo[] array2 = value2; foreach (PropertyInfo propertyInfo in array2) { string text8 = ToJSONInternal(propertyInfo.PropertyType, propertyInfo.GetValue(t), text6); if (num3++ > 0) { text5 += ","; } text5 = text5 + "\n" + text6 + "\"" + propertyInfo.Name + "\": " + text8; } if (num3 > 0) { return text5 + "\n" + prefix + "}"; } return text5 + prefix + "}"; } } catch (Exception exception) { LogError($"Something went wrong while serializing JSON type: {type} value: {t}"); LogError(exception); throw; } throw new NotImplementedException($"Type not supported for JSON serialization {type}"); } private static string JsonInternalArray(object t, string prefix) { Array array = (Array)t; if (array != null) { Type elementType = array.GetType().GetElementType(); string text = ""; text += "["; for (int i = 0; i < array.Length; i++) { text += ToJSONInternal(elementType, array.GetValue(i), prefix + "\t"); if (i < array.Length - 1) { text = text + ",\n" + prefix + "\t"; } } if (array.Length > 1) { text = text + "\n" + prefix; } return text + "]"; } return "[]"; } } } namespace JLPlugin { public static class Extensions { public static void Append(this IDictionary first, IDictionary second) { second.ToList().ForEach(delegate(KeyValuePair pair) { first[pair.Key] = pair.Value; }); } } internal static class Interpreter { public static class RegexStrings { public static string Function = "([a-zA-Z]+)(?\\((?)|[^()]+|\\)(?<-c>))*(?(c)(?!)))\\))"; public static string Variable = "\\[((?>\\[(?)|[^\\[\\]]+|\\](?<-c>))*(?(c)(?!)))\\]"; public static string GeneratedVariable = "\\[([^]]*?\\.[^[]*?)\\]"; public static string Expression = "\\(((?>\\((?)|[^()]+|\\)(?<-c>))*(?(c)(?!)))\\)"; } public static Random random = new Random(); public static object Process(in string input, AbilityBehaviourData abilityData, Type type = null, bool sendDebug = true, Dictionary additionalParameters = null) { //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Expected O, but got Unknown //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Expected O, but got Unknown //IL_00b2: Expected O, but got Unknown object obj = input; MatchCollection matchCollection = Regex.Matches(input, RegexStrings.Expression); if (matchCollection.Cast().Any((Match expressions) => expressions.Success)) { EvaluateFunctionHandler val2 = default(EvaluateFunctionHandler); foreach (Match item in matchCollection) { string value = item.Groups[0].Value; string value2 = item.Groups[1].Value; ExtendedExpression val = new ExtendedExpression(value2); EvaluateFunctionHandler obj3 = val2; if (obj3 == null) { EvaluateFunctionHandler val3 = delegate(string functionName, FunctionArgs functionArgs) { ConfigilExtensions.Extend(functionName, functionArgs, abilityData); }; EvaluateFunctionHandler val4 = val3; val2 = val3; obj3 = val4; } ((Expression)val).EvaluateFunction += obj3; if (additionalParameters != null) { Extensions.AddRange(((Expression)val).Parameters, additionalParameters); } foreach (KeyValuePair variable in abilityData.variables) { ((Expression)val).Parameters[variable.Key] = variable.Value; } foreach (KeyValuePair generatedVariable in abilityData.generatedVariables) { ((Expression)val).Parameters[generatedVariable.Key] = generatedVariable.Value; } MatchCollection matchCollection2 = Regex.Matches(value2, RegexStrings.GeneratedVariable); if (matchCollection2.Cast().Any((Match variables) => variables.Success)) { foreach (Match item2 in matchCollection2) { string value3 = item2.Groups[1].Value; ((Expression)val).Parameters[value3] = ProcessGeneratedVariable(value3, abilityData); } } if (sendDebug) { Plugin.Log.LogDebug((object)("input: " + value)); } object obj4 = ((Expression)val).Evaluate(); if (type == null || matchCollection.Count > 1) { if (obj4.GetType() == typeof(bool)) { obj4 = obj4.ToString().ToLower(); } obj = obj.ToString().Replace(value, obj4.ToString()); } else { obj = obj4; } if (sendDebug) { Plugin.Log.LogDebug((object)$"output: {obj4}"); } } } return obj; } public static object ProcessGeneratedVariable(string contents, AbilityBehaviourData abilityData = null, object variable = null) { //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_011a: Unknown result type (might be due to invalid IL or missing references) //IL_0184: Unknown result type (might be due to invalid IL or missing references) List list = contents.Split(new char[1] { '.' }).ToList(); object value = variable; if (variable == null && abilityData != null && !abilityData.generatedVariables.TryGetValue(list[0], out value)) { throw new Exception(list[0] + " is an invalid generated variable"); } for (int i = 1; i < list.Count; i++) { if (value == null) { return null; } if (value.GetType() == typeof(PlayableCard)) { if (list[i] == "TemporaryAbilities") { List list2 = new List(); foreach (List item in ((PlayableCard)value).TemporaryMods.Select((CardModificationInfo x) => x.abilities).ToList()) { list2.AddRange(item); } value = list2; break; } if (list[i] == "AllAbilities") { List list3 = new List(); foreach (List item2 in ((PlayableCard)value).TemporaryMods.Select((CardModificationInfo x) => x.abilities).ToList()) { list3.AddRange(item2); } list3.AddRange(((Card)(PlayableCard)value).Info.Abilities); value = list3; break; } } PropertyInfo property = value.GetType().GetProperty(list[i]); if ((object)property == null) { FieldInfo field = value.GetType().GetField(list[i]); if ((object)field == null) { return null; } value = field.GetValue(value); } else { if (property.GetIndexParameters().Length >= 1) { break; } value = property.GetValue(value); } } return value; } } internal static class Configs { private static ConfigEntry betaCompatibility; private static ConfigEntry verboseLogging; private static ConfigEntry exportAllLanguages; private static ConfigEntry reloadHotkey; private static ConfigEntry exportHotkey; private static ConfigFile configFile; private static Version oldConfigVersion; private static Version currentVersion; internal static bool BetaCompatibility => betaCompatibility.Value; internal static bool VerboseLogging => verboseLogging.Value; internal static string ReloadHotkey => reloadHotkey.Value; internal static string ExportHotkey => exportHotkey.Value; internal static bool ExportAllLanguages => exportAllLanguages.Value; public static void InitializeConfigs(ConfigFile config) { configFile = config; currentVersion = new Version("2.7.0"); oldConfigVersion = GetOldConfigVersion(); betaCompatibility = config.Bind("JSONLoader", "JDLR Backwards Compatibility", true, "Set this to true if your using a mod that utilizes the old `.jldr` system. If the mod your using uses `.json` use JSON Rename Utility by MadH95Mods on Thunderstore to convert them to `.jldr`."); verboseLogging = config.Bind("JSONLoader", "Verbose Logging", false, "Set this to true if you wish to enable debug logging that tells you exactly what JSONLoader is reading and a bit more in depth info on when its erroring, or just to fill your log while you wait."); exportAllLanguages = config.Bind("JSONLoader Exporting", "Export All Languages", false, "Set this to true if you wish to export all of the base games languages for everything you can do within JSONLoader."); reloadHotkey = config.Bind("Hotkeys", "Reload JLDR2 and game", "LeftShift+R", "Reloads the game whenever the keybind this is set to is pressed to re register all `.jldr2` files."); exportHotkey = config.Bind("Hotkeys", "Export all to JLDR2", "LeftControl+RightControl+X", "Exports everything from the base game that you can do with JSONLoader when the keybind is pressed."); MigrateConfigs(); ModdedSaveManager.SaveData.SetValue("MADH.inscryption.JSONLoader", "LastLoadedVersion", (object)currentVersion.ToString()); } private static Version GetOldConfigVersion() { string value = ModdedSaveManager.SaveData.GetValue("MADH.inscryption.JSONLoader", "LastLoadedVersion"); if (string.IsNullOrEmpty(value)) { return new Version("2.5.2"); } return new Version(value); } private static void MigrateConfigs() { if (!(oldConfigVersion == currentVersion) && oldConfigVersion <= new Version("2.5.3")) { Plugin.Log.LogInfo((object)$"Migrating from {oldConfigVersion} to {currentVersion}!"); if (ReloadHotkey == (string)((ConfigEntryBase)exportHotkey).DefaultValue && ExportHotkey == (string)((ConfigEntryBase)reloadHotkey).DefaultValue) { Plugin.Log.LogInfo((object)"\tMigrating hotkeys to new defaults!"); exportHotkey.Value = (string)((ConfigEntryBase)exportHotkey).DefaultValue; reloadHotkey.Value = (string)((ConfigEntryBase)reloadHotkey).DefaultValue; configFile.Save(); } } } } [BepInPlugin("MADH.inscryption.JSONLoader", "JSONLoader", "2.7.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] public class Plugin : BaseUnityPlugin { public static Plugin Instance; public const string PluginGuid = "MADH.inscryption.JSONLoader"; public const string PluginName = "JSONLoader"; public const string PluginVersion = "2.7.0"; public static string JSONLoaderDirectory = ""; public static string BepInExDirectory = ""; internal static ManualLogSource Log; private HotkeyController hotkeyController; public static string ExportDirectory => Path.Combine(JSONLoaderDirectory, "Examples", "Exported"); private static List GetAllJLDRFiles() { return (from a in Directory.GetFiles(Paths.PluginPath, "*.jldr*", SearchOption.AllDirectories) where (a.EndsWith(".jldr") || a.EndsWith(".jldr2")) && !a.Contains(Path.Combine(JSONLoaderDirectory, "Examples")) select a).ToList(); } private void Awake() { //IL_0092: Unknown result type (might be due to invalid IL or missing references) ((BaseUnityPlugin)this).Logger.LogInfo((object)"Loading JSONLoader!"); Instance = this; Log = ((BaseUnityPlugin)this).Logger; JSONLoaderDirectory = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location); int num = ((BaseUnityPlugin)this).Info.Location.LastIndexOf("BepInEx"); if (num > 0) { BepInExDirectory = ((BaseUnityPlugin)this).Info.Location.Substring(0, num); } else { BepInExDirectory = Directory.GetParent(JSONLoaderDirectory)?.FullName ?? ""; } new Harmony("MADH.inscryption.JSONLoader").PatchAll(); Configs.InitializeConfigs(((BaseUnityPlugin)this).Config); hotkeyController = new HotkeyController(); hotkeyController.AddHotkey(Configs.ReloadHotkey, ReloadGame); hotkeyController.AddHotkey(Configs.ExportHotkey, ExportAllToJLDR2); Log.LogWarning((object)"Note: JSONLoader now uses .jldr2 files, not .json files."); List allJLDRFiles = GetAllJLDRFiles(); if (Configs.BetaCompatibility) { Log.LogWarning((object)"Note: Backwards compatibility has been enabled. Old *.jldr files will be converted to *.jldr2 automatically. This will slow down your game loading!"); JLUtils.LoadCardsFromFiles(allJLDRFiles); } try { LoadAll(allJLDRFiles); } catch (Exception) { } ((BaseUnityPlugin)this).Logger.LogInfo((object)"Loaded JSONLoader!"); } public void LoadAll(List files) { TribeList.LoadAllTribes(files); TraitList.LoadAllTraits(files); SigilData.LoadAllSigils(files); CardSerializeInfo.LoadAllJLDR2(files); EncounterData.LoadAllEncounters(files); StarterDeckList.LoadAllStarterDecks(files); GramophoneData.LoadAllGramophone(files); LanguageData.LoadAllLanguages(files); MaskData.LoadAllMasks(files); ItemData.LoadAllConsumableItems(files); RegionSerializeInfo.LoadAllRegions(files); LoadTalkingCards.InitAndLoad(files); } public void Update() { hotkeyController.Update(); } private void ReloadGame() { List allJLDRFiles = GetAllJLDRFiles(); LoadAll(allJLDRFiles); CachedCardData.Flush(); if (SaveFile.IsAscension) { ReloadKaycees(); } if (SaveManager.SaveFile.IsPart1) { ReloadVanilla(); } } public void ExportAllToJLDR2() { //IL_0028: 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) if (Configs.ExportAllLanguages) { foreach (CustomLanguage allLanguage in LocalizationManager.AllLanguages) { VerboseLog($"Loading Language {allLanguage.LanguageName} {allLanguage.Language}"); Localization.TryLoadLanguage(allLanguage.Language); } } TribeList.ExportAllTribes(); ItemData.ExportAllItems(); EncounterData.ExportAllEncounters(); StarterDeckList.ExportAllStarterDecks(); LanguageData.ExportAllLanguages(); RegionSerializeInfo.ExportAllRegions(); CardSerializeInfo.ExportAllCards(); } public static void ReloadVanilla() { FrameLoopManager.Instance.SetIterationDisabled(false); MenuController.ReturnToStartScreen(); MenuController.LoadGameFromMenu(false); } public static void ReloadKaycees() { FrameLoopManager.Instance.SetIterationDisabled(false); SceneLoader.Load("Ascension_Configure"); FrameLoopManager.Instance.SetIterationDisabled(false); SaveManager.savingDisabled = false; MenuController.LoadGameFromMenu(false); } internal static void VerboseLog(string s) { if (Configs.VerboseLogging) { Log.LogInfo((object)s); } } internal static void VerboseWarning(string s) { if (Configs.VerboseLogging) { Log.LogWarning((object)s); } } internal static void VerboseError(string s) { if (Configs.VerboseLogging) { Log.LogError((object)s); } } public static void LogFields() { string text = "\n"; foreach (Type item in new List { typeof(PlayableCard), typeof(CardInfo), typeof(CardSlot) }) { FieldInfo[] fields = item.GetFields(); if (fields.Length != 0) { string text2 = item.Name + " fields:\n"; text += text2; text = text + new string('-', text2.Length - 1) + "\n"; FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { text = text + fieldInfo.Name + " (" + fieldInfo.FieldType.Name + ")\n"; } text = text + new string('-', text2.Length - 1) + "\n\n"; } PropertyInfo[] properties = item.GetProperties(); if (properties.Length != 0) { string text3 = item.Name + " properties:\n"; text += text3; text = text + new string('-', text3.Length - 1) + "\n"; PropertyInfo[] array2 = properties; foreach (PropertyInfo propertyInfo in array2) { text = text + propertyInfo.Name + " (" + propertyInfo.PropertyType.Name + ")\n"; } text = text + new string('-', text3.Length - 1) + "\n\n"; } } Log.LogInfo((object)text); } } public static class MyPluginInfo { public const string PLUGIN_GUID = "JSONLoader"; public const string PLUGIN_NAME = "JSONLoader"; public const string PLUGIN_VERSION = "2.7.0"; } } namespace JLPlugin.Hotkeys { internal class HotkeyController { public class Hotkey { public KeyCode[] KeyCodes; public Action Function; } private static Action, KeyCode> OnHotkeyPressed = delegate { }; private static KeyCode[] AllCodes = Enum.GetValues(typeof(KeyCode)).Cast().ToArray(); private List Hotkeys = new List(); private List m_pressedKeys = new List(); private bool m_hotkeyActivated; private static KeyCode[] DeserializeKeyCodes(string hotkey) { return hotkey.Trim().Split(new char[1] { '+' }).Select(delegate(string a) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) if (!Enum.TryParse(a, out KeyCode result)) { Plugin.Log.LogError((object)("Unknown hotkey: '" + a + "'. See possible hotkeys here separated by +. https://docs.unity3d.com/ScriptReference/KeyCode.html")); } return result; }) .ToArray(); } public void Update() { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) KeyCode[] allCodes = AllCodes; foreach (KeyCode val in allCodes) { if (Input.GetKeyDown(val) && !m_pressedKeys.Contains(val)) { m_pressedKeys.Add(val); HotkeysChanged(val, triggerHotkey: true); } } for (int j = 0; j < m_pressedKeys.Count; j++) { KeyCode val2 = m_pressedKeys[j]; if (!Input.GetKey(val2)) { m_pressedKeys.Remove(val2); HotkeysChanged((KeyCode)0, triggerHotkey: false); m_hotkeyActivated = false; } } } private void HotkeysChanged(KeyCode pressedButton, bool triggerHotkey) { //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) if (triggerHotkey) { Hotkey hotkey = null; foreach (Hotkey hotkey2 in Hotkeys) { if (!m_hotkeyActivated && hotkey2.KeyCodes.Length != 0 && m_pressedKeys.Intersect(hotkey2.KeyCodes).Count() == hotkey2.KeyCodes.Length && (hotkey == null || hotkey.KeyCodes.Length < hotkey2.KeyCodes.Length)) { hotkey = hotkey2; } } hotkey?.Function?.Invoke(); } if ((int)pressedButton != 0) { OnHotkeyPressed?.Invoke(m_pressedKeys, pressedButton); } } public void AddHotkey(string hotkeys, Action callback) { Hotkeys.Add(new Hotkey { KeyCodes = DeserializeKeyCodes(hotkeys), Function = callback }); } } } namespace JLPlugin.V2.Data { public class CardSerializeInfo : IInitializable { public const string DEFAULT_MOD_PREFIX = "JSON"; public string name; public string modPrefix; public string[] decals; public LocalizableField displayedName; public LocalizableField description; public int? baseAttack; public int? baseHealth; public int? bloodCost; public int? bonesCost; public int? energyCost; public string[] gemsCost; public string[] abilities; public string[] specialAbilities; public string specialStatIcon; public string[] metaCategories; public string cardComplexity; public bool? onePerDeck; public string temple; public string titleGraphic; public bool? hideAttackAndHealth; public string[] appearanceBehaviour; public string texture; public string emissionTexture; public string holoPortraitPrefab; public string animatedPortrait; public string altTexture; public string altEmissionTexture; public string pixelTexture; public string[] tribes; public string[] traits; public string evolveIntoName; public int? evolveTurns; public string defaultEvolutionName; public string tailName; public string tailLostPortrait; public string iceCubeName; public bool? flipPortraitForStrafe; public Dictionary extensionProperties; public string filePath; public static List fileExtensionExceptions = new List { "_encounter", "_tribe", "_tribes", "_sigil", "_deck", "_gram", "_language", "_mask", "_region", "_trait", "_item", "_talk" }; public CardSerializeInfo() { Initialize(); } public void Initialize() { displayedName = new LocalizableField("displayedName"); description = new LocalizableField("description"); } public static void Apply(CardInfo cardInfo, CardSerializeInfo serializeInfo, bool toCardInfo, string cardName) { ImportExportUtils.SetID(cardName); ImportExportUtils.ApplyLocaleField("displayedName", ref serializeInfo.displayedName, ref cardInfo.displayedName, toCardInfo); ImportExportUtils.ApplyLocaleField("description", ref serializeInfo.description, ref cardInfo.description, toCardInfo); ImportExportUtils.ApplyProperty(() => ((Object)cardInfo).name, delegate(string text) { ((Object)cardInfo).name = text; }, ref serializeInfo.name, toCardInfo, "Cards", "name"); ImportExportUtils.ApplyValue(ref cardInfo.baseAttack, ref serializeInfo.baseAttack, toCardInfo, "Cards", "baseAttack"); ImportExportUtils.ApplyValue(ref cardInfo.baseHealth, ref serializeInfo.baseHealth, toCardInfo, "Cards", "baseHealth"); ImportExportUtils.ApplyValue(ref cardInfo.cost, ref serializeInfo.bloodCost, toCardInfo, "Cards", "cost"); ImportExportUtils.ApplyValue(ref cardInfo.bonesCost, ref serializeInfo.bonesCost, toCardInfo, "Cards", "bonesCost"); ImportExportUtils.ApplyValue(ref cardInfo.energyCost, ref serializeInfo.energyCost, toCardInfo, "Cards", "energyCost"); ImportExportUtils.ApplyValue(ref cardInfo.gemsCost, ref serializeInfo.gemsCost, toCardInfo, "Cards", "gemsCost"); ImportExportUtils.ApplyValue(ref cardInfo.abilities, ref serializeInfo.abilities, toCardInfo, "Cards", "abilities"); ImportExportUtils.ApplyValue(ref cardInfo.specialAbilities, ref serializeInfo.specialAbilities, toCardInfo, "Cards", "specialAbilities"); ImportExportUtils.ApplyValue(ref cardInfo.specialStatIcon, ref serializeInfo.specialStatIcon, toCardInfo, "Cards", "specialStatIcon"); ImportExportUtils.ApplyValue(ref cardInfo.metaCategories, ref serializeInfo.metaCategories, toCardInfo, "Cards", "metaCategories"); ImportExportUtils.ApplyValue(ref cardInfo.cardComplexity, ref serializeInfo.cardComplexity, toCardInfo, "Cards", "cardComplexity"); ImportExportUtils.ApplyValue(ref cardInfo.onePerDeck, ref serializeInfo.onePerDeck, toCardInfo, "Cards", "onePerDeck"); ImportExportUtils.ApplyValue(ref cardInfo.temple, ref serializeInfo.temple, toCardInfo, "Cards", "temple"); ImportExportUtils.ApplyValue(ref cardInfo.titleGraphic, ref serializeInfo.titleGraphic, toCardInfo, "Cards", "titleGraphic"); ImportExportUtils.ApplyValue(ref cardInfo.hideAttackAndHealth, ref serializeInfo.hideAttackAndHealth, toCardInfo, "Cards", "hideAttackAndHealth"); ImportExportUtils.ApplyValue(ref cardInfo.appearanceBehaviour, ref serializeInfo.appearanceBehaviour, toCardInfo, "Cards", "appearanceBehaviour"); ImportExportUtils.ApplyValue(ref cardInfo.tribes, ref serializeInfo.tribes, toCardInfo, "Cards", "tribes"); ImportExportUtils.ApplyValue(ref cardInfo.traits, ref serializeInfo.traits, toCardInfo, "Cards", "traits"); ImportExportUtils.ApplyValue(ref cardInfo.defaultEvolutionName, ref serializeInfo.defaultEvolutionName, toCardInfo, "Cards", "defaultEvolutionName"); ImportExportUtils.ApplyValue(ref cardInfo.flipPortraitForStrafe, ref serializeInfo.flipPortraitForStrafe, toCardInfo, "Cards", "flipPortraitForStrafe"); ImportExportUtils.ApplyValue(ref cardInfo.decals, ref serializeInfo.decals, toCardInfo, "Cards", "decals"); ImportExportUtils.ApplyValue(ref cardInfo.portraitTex, ref serializeInfo.texture, toCardInfo, "Cards", "texture"); ImportExportUtils.ApplyValue(ref cardInfo.alternatePortrait, ref serializeInfo.altTexture, toCardInfo, "Cards", "altTexture"); ImportExportUtils.ApplyValue(ref cardInfo.pixelPortrait, ref serializeInfo.pixelTexture, toCardInfo, "Cards", "pixelTexture"); Sprite a = CardExtensions.GetEmissivePortrait(cardInfo); Sprite a2 = CardExtensions.GetEmissiveAltPortrait(cardInfo); ImportExportUtils.ApplyValue(ref a, ref serializeInfo.emissionTexture, toCardInfo, "Cards", "emissionTexture"); ImportExportUtils.ApplyValue(ref a2, ref serializeInfo.altEmissionTexture, toCardInfo, "Cards", "altEmissionTexture"); if ((Object)(object)cardInfo.portraitTex != (Object)null && (Object)(object)a != (Object)null) { CardExtensions.SetEmissivePortrait(cardInfo, a); } if ((Object)(object)cardInfo.alternatePortrait != (Object)null && (Object)(object)a2 != (Object)null) { CardExtensions.SetEmissiveAltPortrait(cardInfo, a2); } if (toCardInfo) { if (!string.IsNullOrEmpty(serializeInfo.evolveIntoName)) { CardExtensions.SetEvolve(cardInfo, serializeInfo.evolveIntoName, (!serializeInfo.evolveTurns.HasValue) ? 1 : serializeInfo.evolveTurns.Value, (IEnumerable)null); } } else if (cardInfo.evolveParams != null) { CardInfo evolution = cardInfo.evolveParams.evolution; serializeInfo.evolveIntoName = ((evolution != null) ? ((Object)evolution).name : null); serializeInfo.evolveTurns = cardInfo.evolveParams.turnsToEvolve; } if (toCardInfo) { if (!string.IsNullOrEmpty(serializeInfo.tailName)) { CardExtensions.SetTail(cardInfo, serializeInfo.tailName, serializeInfo.tailLostPortrait, (IEnumerable)null); } } else if (cardInfo.tailParams != null) { CardInfo tail = cardInfo.tailParams.tail; serializeInfo.tailName = ((tail != null) ? ((Object)tail).name : null); ImportExportUtils.ApplyValue(ref cardInfo.tailParams.tailLostPortrait, ref serializeInfo.tailLostPortrait, toCardInfo, "Cards", "tailLostPortrait"); } if (toCardInfo) { if (!string.IsNullOrEmpty(serializeInfo.iceCubeName)) { CardExtensions.SetIceCube(cardInfo, serializeInfo.iceCubeName, (IEnumerable)null); } } else if (cardInfo.iceCubeParams != null) { serializeInfo.iceCubeName = ((Object)cardInfo.iceCubeParams.creatureWithin).name; } if (toCardInfo) { if (serializeInfo.extensionProperties != null) { foreach (KeyValuePair extensionProperty in serializeInfo.extensionProperties) { CardExtensions.SetExtendedProperty(cardInfo, extensionProperty.Key, (object)extensionProperty.Value); } } CardExtensions.SetExtendedProperty(cardInfo, "JSONFilePath", (object)serializeInfo.filePath); } else { Dictionary cardExtensionTable = CardManager.GetCardExtensionTable(cardInfo); if (cardExtensionTable != null && cardExtensionTable.Count > 0) { foreach (KeyValuePair item in cardExtensionTable) { if (item.Key == "ModPrefix") { serializeInfo.modPrefix = item.Value; } } serializeInfo.extensionProperties = cardExtensionTable; } } if (toCardInfo) { if (!string.IsNullOrEmpty(serializeInfo.holoPortraitPrefab)) { cardInfo.holoPortraitPrefab = Resources.Load(serializeInfo.holoPortraitPrefab); } } else if ((Object)(object)cardInfo.holoPortraitPrefab != (Object)null) { serializeInfo.holoPortraitPrefab = ((object)cardInfo.holoPortraitPrefab).ToString(); } if (toCardInfo) { if (!string.IsNullOrEmpty(serializeInfo.animatedPortrait)) { cardInfo.animatedPortrait = Resources.Load(serializeInfo.animatedPortrait); } } else if ((Object)(object)cardInfo.animatedPortrait != (Object)null) { serializeInfo.holoPortraitPrefab = ((object)cardInfo.animatedPortrait).ToString(); } } private void ApplyLocaleField(string field, LocalizableField rows, out string cardInfoEnglishField) { //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Invalid comparison between Unknown and I4 //IL_00d1: Unknown result type (might be due to invalid IL or missing references) if (rows.rows.TryGetValue(rows.englishFieldName, out var value)) { cardInfoEnglishField = value; } else { if (rows.rows.Count <= 0) { cardInfoEnglishField = null; return; } cardInfoEnglishField = rows.rows.First().Value; } foreach (KeyValuePair row in rows.rows) { if (row.Key == rows.englishFieldName) { continue; } int num = row.Key.LastIndexOf("_", StringComparison.Ordinal); if (num >= 0) { int length = row.Key.Length - num - 1; string text = row.Key.Substring(num + 1, length); Language val = LocalizationManager.CodeToLanguage(text); if ((int)val != 12) { LocalizationManager.Translate("MADH.inscryption.JSONLoader", (string)null, cardInfoEnglishField, row.Value, val); } else { Plugin.Log.LogDebug((object)$"Unknown language code {text} for card {displayedName} in field {field}"); } } } } internal void Apply(bool UpdateCard = false) { if (string.IsNullOrEmpty(name)) { throw new InvalidOperationException("Card cannot have an empty name!"); } CardInfo val = (CardInfo)(UpdateCard ? ((object)ScriptableObjectLoader.AllData.Find((CardInfo x) => ((Object)x).name == name)) : ((object)CardExtensions.CardByName((IEnumerable)CardManager.BaseGameCards, name))); if ((Object)(object)val != (Object)null) { Plugin.VerboseLog("Modifying " + name); Apply(val, this, toCardInfo: true, ((Object)val).name); return; } Plugin.VerboseLog("New Card " + name); string text = modPrefix ?? "JSON"; CardInfo val2 = ScriptableObject.CreateInstance(); ((Object)val2).name = (name.StartsWith(text + "_") ? name : (text + "_" + name)); Apply(val2, this, toCardInfo: true, ((Object)val2).name); CardManager.Add(text, val2); } internal void Remove() { if (string.IsNullOrEmpty(name)) { throw new InvalidOperationException("Card cannot have an empty name!"); } if ((Object)(object)CardExtensions.CardByName((IEnumerable)CardManager.BaseGameCards, name) != (Object)null) { throw new InvalidOperationException("Base game cards cannot be removed!"); } CardInfo val = ((IEnumerable)(ObservableCollection)typeof(CardManager).GetField("NewCards", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null)).FirstOrDefault((Func)((CardInfo x) => ((Object)x).name == name)); if ((Object)(object)val != (Object)null) { CardManager.Remove(val); } else { Plugin.Log.LogWarning((object)("Cannot remove " + name)); } } internal CardInfo ToCardInfo() { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Expected O, but got Unknown if (string.IsNullOrEmpty(name)) { throw new InvalidOperationException("Card cannot have an empty name!"); } CardInfo val = (CardInfo)CardExtensions.CardByName((IEnumerable)CardManager.BaseGameCards, name).Clone(); if ((Object)(object)val != (Object)null) { Plugin.Log.LogDebug((object)("Modifying " + name)); Apply(val, this, toCardInfo: true, name); return val; } string text = modPrefix ?? "JSON"; CardInfo obj = ScriptableObject.CreateInstance(); ((Object)obj).name = (name.StartsWith(text + "_") ? name : (text + "_" + name)); Apply(obj, this, toCardInfo: true, name); return obj; } public string WriteToFile(string filename, bool overwrite = true) { Plugin.Log.LogDebug((object)("Writing card " + (name ?? "Unnamed") + " to " + filename)); if (!filename.EndsWith("2")) { filename += "2"; } if (overwrite || !File.Exists(filename)) { File.WriteAllText(filename, JSONParser.ToJSON(this)); } return filename; } public static void LoadAllJLDR2(List files) { for (int i = 0; i < files.Count; i++) { string text = files[i]; string text2 = text.Substring(text.LastIndexOf(Path.DirectorySeparatorChar) + 1); bool flag = true; fileExtensionExceptions.AddRange(JSONLoaderAPI.customFileExtensionExceptions); foreach (string fileExtensionException in fileExtensionExceptions) { if (text2.ToLower().EndsWith(fileExtensionException + ".jldr2")) { flag = false; break; } } if (flag) { files.RemoveAt(i--); ImportExportUtils.SetDebugPath(text); try { Plugin.VerboseLog("Loading JLDR2 Card " + text2); CardSerializeInfo cardSerializeInfo = text.FromFilePath(); cardSerializeInfo.filePath = text; cardSerializeInfo.Apply(); Plugin.VerboseLog("Loaded JSON card from " + text); } catch (Exception ex) { Plugin.Log.LogError((object)("Failed to load card " + text2)); Plugin.Log.LogError((object)ex); } } } } public static void ExportAllCards() { Plugin.Log.LogInfo((object)$"Exporting {CardManager.AllCardsCopy.Count} cards."); foreach (CardInfo item in CardManager.AllCardsCopy) { string text = Path.Combine(Plugin.ExportDirectory, "Cards", ((Object)item).name + ".jldr2"); ImportExportUtils.SetDebugPath(text); CardSerializeInfo cardSerializeInfo = new CardSerializeInfo(); cardSerializeInfo.Initialize(); Apply(item, cardSerializeInfo, toCardInfo: false, ((Object)item).name); string directoryName = Path.GetDirectoryName(text); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } cardSerializeInfo.WriteToFile(text); } } } } namespace JLPlugin.Utils { public static class CDUtils { public static void CheckValidFields(List fields) { foreach (string field in fields) { if (string.IsNullOrEmpty(field)) { Plugin.Log.LogError((object)(ErrorUtil.Card + " - fieldsToEdit cannot contain an empty string")); } else if (!Dicts.CardDataFields.Contains(field)) { Plugin.Log.LogError((object)(ErrorUtil.Card + " - \"" + field + "\" is an invalid field name")); } } } public static T Assign(string data, string field, Dictionary dict) { ErrorUtil.Field = field; if (string.IsNullOrEmpty(data)) { return default(T); } if (!dict.ContainsKey(data)) { ErrorUtil.Log(data); return default(T); } return dict[data]; } public static List Assign(List list, string field, Dictionary dict) { ErrorUtil.Field = field; if (list == null || list.Count == 0) { return null; } List list2 = new List(); foreach (string item in list) { if (!dict.ContainsKey(item)) { ErrorUtil.Log(item); } else { list2.Add(dict[item]); } } if (list2.Count == 0) { return null; } return list2; } public static Texture2D Assign(string image, string field) { ErrorUtil.Field = field; if (string.IsNullOrEmpty(image)) { return null; } if (!image.EndsWith(".png")) { ErrorUtil.Log(image, ", it must be a .png"); return null; } return JLUtils.LoadTexture2D(image); } public static List Assign(List list, string field) { ErrorUtil.Field = field; if (list == null || list.Count == 0) { return null; } List list2 = new List(); foreach (string item in list) { if (!string.IsNullOrEmpty(item)) { if (!item.EndsWith(".png")) { ErrorUtil.Log(item, ", it must be a .png"); } else { list2.Add((Texture)(object)JLUtils.LoadTexture2D(item)); } } } if (list2.Count == 0) { return null; } return list2; } } public static class Dicts { public unsafe static readonly Dictionary MetaCategory = Enum.GetValues(typeof(CardMetaCategory)).Cast().ToDictionary((CardMetaCategory t) => ((object)(*(CardMetaCategory*)(&t))/*cast due to .constrained prefix*/).ToString(), (CardMetaCategory t) => t); public unsafe static readonly Dictionary Complexity = Enum.GetValues(typeof(CardComplexity)).Cast().ToDictionary((CardComplexity t) => ((object)(*(CardComplexity*)(&t))/*cast due to .constrained prefix*/).ToString(), (CardComplexity t) => t); public unsafe static readonly Dictionary Temple = Enum.GetValues(typeof(CardTemple)).Cast().ToDictionary((CardTemple t) => ((object)(*(CardTemple*)(&t))/*cast due to .constrained prefix*/).ToString(), (CardTemple t) => t); public unsafe static readonly Dictionary GemColour = Enum.GetValues(typeof(GemType)).Cast().ToDictionary((GemType t) => ((object)(*(GemType*)(&t))/*cast due to .constrained prefix*/).ToString(), (GemType t) => t); public unsafe static readonly Dictionary StatIcon = Enum.GetValues(typeof(SpecialStatIcon)).Cast().ToDictionary((SpecialStatIcon t) => ((object)(*(SpecialStatIcon*)(&t))/*cast due to .constrained prefix*/).ToString(), (SpecialStatIcon t) => t); public unsafe static readonly Dictionary Tribes = Enum.GetValues(typeof(Tribe)).Cast().ToDictionary((Tribe t) => ((object)(*(Tribe*)(&t))/*cast due to .constrained prefix*/).ToString(), (Tribe t) => t); public unsafe static readonly Dictionary Traits = Enum.GetValues(typeof(Trait)).Cast().ToDictionary((Trait t) => ((object)(*(Trait*)(&t))/*cast due to .constrained prefix*/).ToString(), (Trait t) => t); public unsafe static readonly Dictionary SpecialAbilities = Enum.GetValues(typeof(SpecialTriggeredAbility)).Cast().ToDictionary((SpecialTriggeredAbility t) => ((object)(*(SpecialTriggeredAbility*)(&t))/*cast due to .constrained prefix*/).ToString(), (SpecialTriggeredAbility t) => t); public unsafe static readonly Dictionary Abilities = Enum.GetValues(typeof(Ability)).Cast().ToDictionary((Ability t) => ((object)(*(Ability*)(&t))/*cast due to .constrained prefix*/).ToString(), (Ability t) => t); public unsafe static readonly Dictionary AppearanceBehaviour = Enum.GetValues(typeof(Appearance)).Cast().ToDictionary((Appearance t) => ((object)(*(Appearance*)(&t))/*cast due to .constrained prefix*/).ToString(), (Appearance t) => t); public static readonly List CardDataFields = (from elem in typeof(CardData).GetFields() select elem.Name).ToList(); } [StructLayout(LayoutKind.Sequential, Size = 1)] public struct ErrorUtil { public static string Card { get; set; } public static string Field { get; set; } public static string Message { get; set; } public static void Log(string Data, string addition = "") { Plugin.Log.LogError((object)string.Format(Message + addition, Card, Field, Data)); } public static void Clear() { Card = null; Field = null; Message = null; } } [Obsolete] public static class IDUtils { public static EvolveIdentifier GenerateEvolveIdentifier(CardData card) { //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Expected O, but got Unknown if (card.evolution == null) { return null; } if (string.IsNullOrEmpty(card.evolution.name)) { Plugin.Log.LogError((object)(card.name + " - evolution must have a name")); return null; } return new EvolveIdentifier(card.evolution.name, (card.evolution.turnsToEvolve == 0) ? 1 : card.evolution.turnsToEvolve, (CardModificationInfo)null); } public static TailIdentifier GenerateTailIdentifier(CardData card) { //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Expected O, but got Unknown if (card.tail == null) { return null; } if (string.IsNullOrEmpty(card.tail.name)) { Plugin.Log.LogError((object)(card.name + " - tail must have a name")); return null; } return new TailIdentifier(card.tail.name, CDUtils.Assign(card.tail.tailLostPortrait, "tailLostPortrait"), (CardModificationInfo)null); } public static IceCubeIdentifier GenerateIceCubeIdentifier(CardData card) { //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Expected O, but got Unknown if (card.iceCube == null) { return null; } if (string.IsNullOrEmpty(card.iceCube.creatureWithin)) { Plugin.Log.LogError((object)(card.name + " - iceCube must have a creatureWithin")); return null; } return new IceCubeIdentifier(card.iceCube.creatureWithin, (CardModificationInfo)null); } public static List GenerateAbilityIdentifiers(List list) { return list?.Select((AbilityData elem) => AbilityIdentifier.GetAbilityIdentifier(elem.GUID, elem.name)).ToList(); } public static List GenerateSpecialAbilityIdentifiers(List list) { return list?.Select((SpecialAbilityData elem) => SpecialAbilityIdentifier.GetID(elem.GUID, elem.name)).ToList(); } } [Obsolete] public static class JLUtils { public static void LoadCardsFromFiles(List files) { Dictionary dictionary = new Dictionary(); for (int num = files.Count - 1; num >= 0; num--) { string text = files[num]; string text2 = text.Substring(text.LastIndexOf(Path.DirectorySeparatorChar) + 1); if (text.EndsWith(".jldr")) { files.RemoveAt(num); CardData cardData = text.FromFilePath(); if (cardData == null) { Plugin.Log.LogWarning((object)("Failed to load " + text2)); } else { dictionary.Add(text, cardData); } } } List allKnownCards = dictionary.Values.ToList(); foreach (KeyValuePair item2 in dictionary) { string key = item2.Key; CardSerializeInfo cardSerializeInfo = item2.Value.ConvertToV2(allKnownCards); if (cardSerializeInfo != null) { string item = cardSerializeInfo.WriteToFile(key, overwrite: false); files.Add(item); } else { Plugin.Log.LogError((object)(key + " is a JLDR without a valid name")); } } } public static Texture2D LoadTexture2D(string image) { //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Expected O, but got Unknown string[] files = Directory.GetFiles(Paths.PluginPath, image, SearchOption.AllDirectories); if (files.Length == 0) { Plugin.Log.LogError((object)(ErrorUtil.Card + " - Couldn't find texture \"" + image + "\" to load into " + ErrorUtil.Field)); return null; } if (files.Length > 1) { Plugin.Log.LogError((object)(ErrorUtil.Card + " - Couldn't load \"" + image + "\" into " + ErrorUtil.Field + ", more than one file with that name found in the plugins folder")); return null; } byte[] array = File.ReadAllBytes(files[0]); Texture2D val = new Texture2D(2, 2); if (!ImageConversion.LoadImage(val, array)) { Plugin.Log.LogError((object)(ErrorUtil.Card + " - Couldn't load \"" + image + "\" into " + ErrorUtil.Field)); return null; } return val; } } } namespace JLPlugin.SigilCode { [HarmonyPatch(typeof(CardTriggerHandler), "AddAbility", new Type[] { typeof(Ability) })] public class Add_Ability_patch { [HarmonyPrefix] public static bool Prefix(Ability ability, CardTriggerHandler __instance) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0013: 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_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) if (!SigilDicts.ArgumentList.ContainsKey(ability)) { return true; } Type item = SigilDicts.ArgumentList[ability].Item1; if ((!__instance.triggeredAbilities.Exists((Tuple x) => x.Item1 == ability) || AbilitiesUtil.GetInfo(ability).canStack) && !AbilitiesUtil.GetInfo(ability).passive) { ConfigurableMain configurableMain = ((Component)__instance).gameObject.AddComponent(item) as ConfigurableMain; configurableMain.Initialize(SigilData.GetAbilityArguments(ability), ability); __instance.triggeredAbilities.Add(new Tuple(ability, (AbilityBehaviour)(object)configurableMain)); } return false; } } [HarmonyPatch(typeof(ItemSlot), "CreateItem", new Type[] { typeof(ItemData), typeof(bool) })] internal class Add_Consumable_Item_patch { [HarmonyPostfix] internal static void Initialize_Configil(ItemSlot __instance, ItemData data, bool skipDropAnimation) { Plugin.Log.LogInfo((object)("Initialize_Configil " + ((Object)data).name)); if (SigilDicts.ConsumableItemList.TryGetValue(((Object)data).name, out var value)) { Plugin.Log.LogInfo((object)("\t" + ((Object)data).name + " is a JLDR2 consumable item!")); ((Component)__instance.Item).GetComponent().Initialize(value); } } } [HarmonyPatch(typeof(CardTriggerHandler), "AddAbility", new Type[] { typeof(SpecialTriggeredAbility) })] public class Add__Power_Stat_patch { [HarmonyPrefix] public static bool Prefix(SpecialTriggeredAbility ability, CardTriggerHandler __instance) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0013: 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_006e: Unknown result type (might be due to invalid IL or missing references) if (!SigilDicts.PowerStatArgumentList.TryGetValue(ability, out var value)) { return true; } Type item = value.Item1; if (!__instance.specialAbilities.Exists((Tuple x) => x.Item1 == ability)) { ConfigurablePowerStat configurablePowerStat = ((Component)__instance).gameObject.AddComponent(item) as ConfigurablePowerStat; configurablePowerStat.Initialize(value.Item2, value.Item3); __instance.specialAbilities.Add(new Tuple(ability, (SpecialCardBehaviour)(object)configurablePowerStat)); } return false; } } [HarmonyPatch(typeof(CardTriggerHandler), "AddAbility", new Type[] { typeof(SpecialTriggeredAbility) })] public class Add__Special_Ability_patch { [HarmonyPrefix] public static bool Prefix(SpecialTriggeredAbility ability, CardTriggerHandler __instance) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0013: 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_0064: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) if (!SigilDicts.SpecialArgumentList.ContainsKey(ability)) { return true; } Type item = SigilDicts.SpecialArgumentList[ability].Item1; if (!__instance.specialAbilities.Exists((Tuple x) => x.Item1 == ability)) { ConfigurableSpecial configurableSpecial = ((Component)__instance).gameObject.AddComponent(item) as ConfigurableSpecial; configurableSpecial.Initialize(SigilData.GetAbilityArguments(ability), ability); __instance.specialAbilities.Add(new Tuple(ability, (SpecialCardBehaviour)(object)configurableSpecial)); } return false; } } [HarmonyPatch(/*Could not decode attribute arguments.*/)] public class GetOpposingSlots_patch { [HarmonyPostfix] public static void Postfix(PlayableCard __instance, ref List __result) { //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_006b: 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) if (!__instance.OnBoard) { return; } foreach (CardSlot item in Singleton.Instance.AllSlotsCopy) { if ((Object)(object)item.Card == (Object)null) { continue; } foreach (Ability triggeredAbility in item.Card.GetTriggeredAbilities()) { if (!SigilDicts.ArgumentList.ContainsKey(triggeredAbility) || !item.Card.HasAbility(triggeredAbility)) { continue; } foreach (AbilityBehaviourData item2 in SigilData.GetAbilityArguments(triggeredAbility).abilityBehaviour.Where((AbilityBehaviourData x) => x?.extraAttacks != null)) { foreach (extraAttacks extraAttack in item2.extraAttacks) { AConfigilData.UpdateVariables(item2, item.Card); item2.generatedVariables["TriggerCard"] = __instance; if (AConfigilData.ConvertArgument(extraAttack.runOnCondition, item2) == "false") { continue; } CardSlot val = slotData.GetSlot(extraAttack.attackingSlot, item2); if (extraAttack.attackingSlot == null) { val = item; } if (!((Object)(object)val == (Object)(object)__instance.slot)) { continue; } __result.Remove(__instance.Slot.opposingSlot); foreach (slotData item3 in extraAttack.slotsToAttack) { CardSlot slot = slotData.GetSlot(item3, item2); if ((Object)(object)slot != (Object)null) { __result.Add(slot); } } } } } } } } [HarmonyPatch] public class OnBoardCleanup_patch { [HarmonyPrefix] [HarmonyPatch(typeof(TurnManager), "CleanupPhase")] public static void CleanupPhase() { //IL_0043: 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_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) foreach (CardSlot item in Singleton.Instance.AllSlotsCopy) { if ((Object)(object)item.Card == (Object)null) { continue; } foreach (Ability triggeredAbility in item.Card.GetTriggeredAbilities()) { if (SigilDicts.ArgumentList.ContainsKey(triggeredAbility)) { ((Card)item.Card).Info.temporaryDecals.Clear(); ((Card)item.Card).RenderCard(); } } foreach (SpecialTriggeredAbility specialAbility in ((Card)item.Card).Info.SpecialAbilities) { if (SigilDicts.SpecialArgumentList.ContainsKey(specialAbility)) { ((Card)item.Card).Info.temporaryDecals.Clear(); ((Card)item.Card).RenderCard(); } } } } } [HarmonyPatch(typeof(PlayableCard), "GetPassiveAttackBuffs")] public class PassiveAttackBuffs_patch { [HarmonyPostfix] public static void Postfix(ref int __result, ref PlayableCard __instance) { //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) if (!__instance.OnBoard) { return; } foreach (CardSlot item in Singleton.Instance.AllSlotsCopy) { if ((Object)(object)item.Card == (Object)null) { continue; } foreach (Ability triggeredAbility in item.Card.GetTriggeredAbilities()) { if (SigilDicts.ArgumentList.ContainsKey(triggeredAbility)) { ApplyBuffs(SigilData.GetAbilityArguments(triggeredAbility).abilityBehaviour, item, ref __result, ref __instance); } } foreach (SpecialTriggeredAbility specialAbility in ((Card)item.Card).Info.SpecialAbilities) { if (SigilDicts.SpecialArgumentList.ContainsKey(specialAbility)) { ApplyBuffs(SigilData.GetAbilityArguments(specialAbility).abilityBehaviour, item, ref __result, ref __instance); } } } } public static void ApplyBuffs(List AbilityBehaviourList, CardSlot slot, ref int __result, ref PlayableCard __instance) { foreach (AbilityBehaviourData item in AbilityBehaviourList.Where((AbilityBehaviourData x) => x.trigger?.triggerType == "Passive")) { if (item.buffCards == null) { continue; } foreach (buffCards buffCard in item.buffCards) { AConfigilData.UpdateVariables(item, slot.Card); if (AConfigilData.ConvertArgument(buffCard.runOnCondition, item, sendDebug: false) == "false") { continue; } CardSlot val = slotData.GetSlot(buffCard.slot, item, sendDebug: false); if (buffCard.slot == null) { val = slot; } if (!((Object)(object)val == (Object)(object)__instance.slot)) { continue; } if (!string.IsNullOrEmpty(buffCard.addStats)) { string text = AConfigilData.ConvertArgument(buffCard.addStats.Split(new char[1] { '/' })[0], item, sendDebug: false); if (text != "?") { __result += int.Parse(text); } } if (!string.IsNullOrEmpty(buffCard.setStats)) { string text2 = AConfigilData.ConvertArgument(buffCard.setStats.Split(new char[1] { '/' })[0], item, sendDebug: false); if (text2 != "?") { __result = int.Parse(text2) - ((Card)slot.Card).Info.Attack; } } } } } } [HarmonyPatch(typeof(PlayableCard), "GetPassiveHealthBuffs")] public class PassiveHealthBuffs_patch { [HarmonyPostfix] public static void Postfix(ref int __result, ref PlayableCard __instance) { //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) if (!__instance.OnBoard) { return; } foreach (CardSlot item in Singleton.Instance.AllSlotsCopy) { if ((Object)(object)item.Card == (Object)null) { continue; } foreach (Ability triggeredAbility in item.Card.GetTriggeredAbilities()) { if (SigilDicts.ArgumentList.ContainsKey(triggeredAbility)) { ApplyBuffs(SigilData.GetAbilityArguments(triggeredAbility).abilityBehaviour, item, ref __result, ref __instance); } } foreach (SpecialTriggeredAbility specialAbility in ((Card)item.Card).Info.SpecialAbilities) { if (SigilDicts.SpecialArgumentList.ContainsKey(specialAbility)) { ApplyBuffs(SigilData.GetAbilityArguments(specialAbility).abilityBehaviour, item, ref __result, ref __instance); } } } } public static void ApplyBuffs(List AbilityBehaviourList, CardSlot slot, ref int __result, ref PlayableCard __instance) { foreach (AbilityBehaviourData item in AbilityBehaviourList.Where((AbilityBehaviourData x) => x.trigger?.triggerType == "Passive")) { if (item.buffCards == null) { continue; } foreach (buffCards buffCard in item.buffCards) { AConfigilData.UpdateVariables(item, slot.Card); if (AConfigilData.ConvertArgument(buffCard.runOnCondition, item, sendDebug: false) == "false") { continue; } CardSlot val = slotData.GetSlot(buffCard.slot, item, sendDebug: false); if (buffCard.slot == null) { val = slot; } if (!((Object)(object)val == (Object)(object)__instance.slot)) { continue; } if (!string.IsNullOrEmpty(buffCard.addStats)) { string text = AConfigilData.ConvertArgument(buffCard.addStats.Split(new char[1] { '/' })[1], item, sendDebug: false); if (text != "?") { __result += int.Parse(text); } } if (!string.IsNullOrEmpty(buffCard.setStats)) { string text2 = AConfigilData.ConvertArgument(buffCard.setStats.Split(new char[1] { '/' })[1], item, sendDebug: false); if (text2 != "?") { __result = int.Parse(text2) - ((Card)slot.Card).Info.Health; } } if (((Card)__instance).Info.Health + __result <= 0) { ((MonoBehaviour)Singleton.Instance).StartCoroutine(__instance.Die(false, (PlayableCard)null, true)); } } } } } public static class CachedCardData { private static Dictionary CardDataCache = new Dictionary(); public static CardSerializeInfo? Get(string filePath) { if (filePath == null) { return null; } if (!CardDataCache.ContainsKey(filePath)) { return null; } return CardDataCache[filePath]; } public static void Add(string filePath, CardSerializeInfo data) { CardDataCache[filePath] = data; } public static bool Contains(string? filePath) { if (filePath != null) { return CardDataCache.ContainsKey(filePath); } return false; } public static void Flush() { CardDataCache.Clear(); } } public class ConfigurableConsumableItem : ConsumableItem { private ABaseConfigilLogic _logic; public void Initialize(ItemData abilityData) { _logic = new ConfigConsumableItemLogic(this, abilityData); } private IEnumerator Start() { yield return _logic.Start(); } public override IEnumerator ActivateSequence() { ((Item)this).PlayExitAnimation(); yield return (object)new WaitForSeconds(0.1f); yield return _logic.Activate(); yield return (object)new WaitForSeconds(0.5f); } public override bool ExtraActivationPrerequisitesMet() { return _logic.CanActivate(); } } public class ConfigurableMain : ActivatedAbilityBehaviour, IOnBellRung, IOnOtherCardAddedToHand, IOnCardAssignedToSlotContext, IOnCardDealtDamageDirectly { private ABaseConfigilLogic _logic; private Ability ability; public override Ability Ability => ability; public void Initialize(SigilData abilityData, Ability ability) { //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) this.ability = ability; _logic = new ConfigilAbilityLogic((ActivatedAbilityBehaviour)(object)this, abilityData); } public IEnumerator Start() { yield return _logic.Start(); } public override IEnumerator Activate() { yield return _logic.Activate(); } public override bool RespondsToOtherCardResolve(PlayableCard otherCard) { return _logic.RespondsToOtherCardResolve(otherCard); } public override IEnumerator OnOtherCardResolve(PlayableCard otherCard) { yield return _logic.OnOtherCardResolve(otherCard); } public override bool RespondsToOtherCardAssignedToSlot(PlayableCard otherCard) { return _logic.RespondsToOtherCardAssignedToSlot(otherCard); } public override IEnumerator OnOtherCardAssignedToSlot(PlayableCard otherCard) { yield return _logic.OnOtherCardAssignedToSlot(otherCard); } public override bool RespondsToTurnEnd(bool playerTurnEnd) { return _logic.RespondsToTurnEnd(playerTurnEnd); } public override IEnumerator OnTurnEnd(bool playerTurnEnd) { yield return _logic.OnTurnEnd(playerTurnEnd); } public override bool RespondsToUpkeep(bool playerUpkeep) { return _logic.RespondsToUpkeep(playerUpkeep); } public override IEnumerator OnUpkeep(bool playerUpkeep) { yield return _logic.OnUpkeep(playerUpkeep); } public override bool RespondsToOtherCardDealtDamage(PlayableCard attacker, int amount, PlayableCard target) { return _logic.RespondsToOtherCardDealtDamage(attacker, amount, target); } public override IEnumerator OnOtherCardDealtDamage(PlayableCard attacker, int amount, PlayableCard target) { yield return _logic.OnOtherCardDealtDamage(attacker, amount, target); } public override bool RespondsToOtherCardDie(PlayableCard card, CardSlot deathSlot, bool fromCombat, PlayableCard killer) { return _logic.RespondsToOtherCardDie(card, deathSlot, fromCombat, killer); } public override IEnumerator OnOtherCardDie(PlayableCard card, CardSlot deathSlot, bool fromCombat, PlayableCard killer) { yield return _logic.OnOtherCardDie(card, deathSlot, fromCombat, killer); } public override bool RespondsToSacrifice() { return _logic.RespondsToSacrifice(); } public override IEnumerator OnSacrifice() { yield return _logic.OnSacrifice(); } public override bool RespondsToOtherCardPreDeath(CardSlot deathSlot, bool fromCombat, PlayableCard killer) { return _logic.RespondsToOtherCardPreDeath(deathSlot, fromCombat, killer); } public override IEnumerator OnOtherCardPreDeath(CardSlot deathSlot, bool fromCombat, PlayableCard killer) { yield return _logic.OnOtherCardPreDeath(deathSlot, fromCombat, killer); } public override bool RespondsToSlotTargetedForAttack(CardSlot slot, PlayableCard attacker) { return _logic.RespondsToSlotTargetedForAttack(slot, attacker); } public override IEnumerator OnSlotTargetedForAttack(CardSlot slot, PlayableCard attacker) { yield return _logic.OnSlotTargetedForAttack(slot, attacker); } public bool RespondsToBellRung(bool playerCombatPhase) { return _logic.RespondsToBellRung(playerCombatPhase); } public IEnumerator OnBellRung(bool playerCombatPhase) { yield return _logic.OnBellRung(playerCombatPhase); } public bool RespondsToOtherCardAddedToHand(PlayableCard card) { return _logic.RespondsToOtherCardAddedToHand(card); } public IEnumerator OnOtherCardAddedToHand(PlayableCard card) { yield return _logic.OnOtherCardAddedToHand(card); } public bool RespondsToCardAssignedToSlotContext(PlayableCard card, CardSlot oldSlot, CardSlot newSlot) { return _logic.RespondsToCardAssignedToSlotContext(card, oldSlot, newSlot); } public IEnumerator OnCardAssignedToSlotContext(PlayableCard card, CardSlot oldSlot, CardSlot newSlot) { yield return _logic.OnCardAssignedToSlotContext(card, oldSlot, newSlot); } public bool RespondsToCardDealtDamageDirectly(PlayableCard attacker, CardSlot opposingSlot, int damage) { return _logic.RespondsToCardDealtDamageDirectly(attacker, opposingSlot, damage); } public IEnumerator OnCardDealtDamageDirectly(PlayableCard attacker, CardSlot opposingSlot, int damage) { yield return _logic.OnCardDealtDamageDirectly(attacker, opposingSlot, damage); } public override bool CanActivate() { return _logic.CanActivate(); } } public class ConfigurablePowerStat : VariableStatBehaviour, IOnBellRung, IOnOtherCardAddedToHand, IOnCardAssignedToSlotContext, IOnCardDealtDamageDirectly { private ConfigPowerStateBehaviour _logic; public override SpecialStatIcon IconType => (SpecialStatIcon)_logic.ability; public virtual void Initialize(SigilData abilityData, SpecialStatIcon icon) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) _logic = new ConfigPowerStateBehaviour((SpecialCardBehaviour)(object)this, abilityData, icon); } public void Start() { ((VariableStatBehaviour)this).Start(); if (_logic != null) { ((MonoBehaviour)this).StartCoroutine(_logic.Start()); } } public override int[] GetStatValues() { return _logic.GetStatValues(); } public override bool RespondsToOtherCardResolve(PlayableCard otherCard) { return _logic.RespondsToOtherCardResolve(otherCard); } public override IEnumerator OnOtherCardResolve(PlayableCard otherCard) { yield return _logic.OnOtherCardResolve(otherCard); } public override bool RespondsToOtherCardAssignedToSlot(PlayableCard otherCard) { return _logic.RespondsToOtherCardAssignedToSlot(otherCard); } public override IEnumerator OnOtherCardAssignedToSlot(PlayableCard otherCard) { yield return _logic.OnOtherCardAssignedToSlot(otherCard); } public override bool RespondsToTurnEnd(bool playerTurnEnd) { return _logic.RespondsToTurnEnd(playerTurnEnd); } public override IEnumerator OnTurnEnd(bool playerTurnEnd) { yield return _logic.OnTurnEnd(playerTurnEnd); } public override bool RespondsToUpkeep(bool playerUpkeep) { return _logic.RespondsToUpkeep(playerUpkeep); } public override IEnumerator OnUpkeep(bool playerUpkeep) { yield return _logic.OnUpkeep(playerUpkeep); } public override bool RespondsToOtherCardDealtDamage(PlayableCard attacker, int amount, PlayableCard target) { return _logic.RespondsToOtherCardDealtDamage(attacker, amount, target); } public override IEnumerator OnOtherCardDealtDamage(PlayableCard attacker, int amount, PlayableCard target) { yield return _logic.OnOtherCardDealtDamage(attacker, amount, target); } public override bool RespondsToOtherCardDie(PlayableCard card, CardSlot deathSlot, bool fromCombat, PlayableCard killer) { return _logic.RespondsToOtherCardDie(card, deathSlot, fromCombat, killer); } public override IEnumerator OnOtherCardDie(PlayableCard card, CardSlot deathSlot, bool fromCombat, PlayableCard killer) { yield return _logic.OnOtherCardDie(card, deathSlot, fromCombat, killer); } public override bool RespondsToSacrifice() { return _logic.RespondsToSacrifice(); } public override IEnumerator OnSacrifice() { yield return _logic.OnSacrifice(); } public override bool RespondsToOtherCardPreDeath(CardSlot deathSlot, bool fromCombat, PlayableCard killer) { return _logic.RespondsToOtherCardPreDeath(deathSlot, fromCombat, killer); } public override IEnumerator OnOtherCardPreDeath(CardSlot deathSlot, bool fromCombat, PlayableCard killer) { yield return _logic.OnOtherCardPreDeath(deathSlot, fromCombat, killer); } public override bool RespondsToSlotTargetedForAttack(CardSlot slot, PlayableCard attacker) { return _logic.RespondsToSlotTargetedForAttack(slot, attacker); } public override IEnumerator OnSlotTargetedForAttack(CardSlot slot, PlayableCard attacker) { yield return _logic.OnSlotTargetedForAttack(slot, attacker); } public bool RespondsToBellRung(bool playerCombatPhase) { return _logic.RespondsToBellRung(playerCombatPhase); } public IEnumerator OnBellRung(bool playerCombatPhase) { yield return _logic.OnBellRung(playerCombatPhase); } public bool RespondsToOtherCardAddedToHand(PlayableCard card) { return _logic.RespondsToOtherCardAddedToHand(card); } public IEnumerator OnOtherCardAddedToHand(PlayableCard card) { yield return _logic.OnOtherCardAddedToHand(card); } public bool RespondsToCardAssignedToSlotContext(PlayableCard card, CardSlot oldSlot, CardSlot newSlot) { return _logic.RespondsToCardAssignedToSlotContext(card, oldSlot, newSlot); } public IEnumerator OnCardAssignedToSlotContext(PlayableCard card, CardSlot oldSlot, CardSlot newSlot) { yield return _logic.OnCardAssignedToSlotContext(card, oldSlot, newSlot); } public bool RespondsToCardDealtDamageDirectly(PlayableCard attacker, CardSlot opposingSlot, int damage) { return _logic.RespondsToCardDealtDamageDirectly(attacker, opposingSlot, damage); } public IEnumerator OnCardDealtDamageDirectly(PlayableCard attacker, CardSlot opposingSlot, int damage) { yield return _logic.OnCardDealtDamageDirectly(attacker, opposingSlot, damage); } } public class ConfigurableSpecial : SpecialCardBehaviour, IOnBellRung, IOnOtherCardAddedToHand, IOnCardAssignedToSlotContext, IOnCardDealtDamageDirectly { private ABaseConfigilLogic _logic; public virtual void Initialize(SigilData abilityData, SpecialTriggeredAbility ability) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) _logic = new ConfigilSpecialAbilityLogic((SpecialCardBehaviour)(object)this, abilityData, ability); } public IEnumerator Start() { yield return _logic.Start(); } public override bool RespondsToOtherCardResolve(PlayableCard otherCard) { return _logic.RespondsToOtherCardResolve(otherCard); } public override IEnumerator OnOtherCardResolve(PlayableCard otherCard) { yield return _logic.OnOtherCardResolve(otherCard); } public override bool RespondsToOtherCardAssignedToSlot(PlayableCard otherCard) { return _logic.RespondsToOtherCardAssignedToSlot(otherCard); } public override IEnumerator OnOtherCardAssignedToSlot(PlayableCard otherCard) { yield return _logic.OnOtherCardAssignedToSlot(otherCard); } public override bool RespondsToTurnEnd(bool playerTurnEnd) { return _logic.RespondsToTurnEnd(playerTurnEnd); } public override IEnumerator OnTurnEnd(bool playerTurnEnd) { yield return _logic.OnTurnEnd(playerTurnEnd); } public override bool RespondsToUpkeep(bool playerUpkeep) { return _logic.RespondsToUpkeep(playerUpkeep); } public override IEnumerator OnUpkeep(bool playerUpkeep) { yield return _logic.OnUpkeep(playerUpkeep); } public override bool RespondsToOtherCardDealtDamage(PlayableCard attacker, int amount, PlayableCard target) { return _logic.RespondsToOtherCardDealtDamage(attacker, amount, target); } public override IEnumerator OnOtherCardDealtDamage(PlayableCard attacker, int amount, PlayableCard target) { yield return _logic.OnOtherCardDealtDamage(attacker, amount, target); } public override bool RespondsToOtherCardDie(PlayableCard card, CardSlot deathSlot, bool fromCombat, PlayableCard killer) { return _logic.RespondsToOtherCardDie(card, deathSlot, fromCombat, killer); } public override IEnumerator OnOtherCardDie(PlayableCard card, CardSlot deathSlot, bool fromCombat, PlayableCard killer) { yield return _logic.OnOtherCardDie(card, deathSlot, fromCombat, killer); } public override bool RespondsToSacrifice() { return _logic.RespondsToSacrifice(); } public override IEnumerator OnSacrifice() { yield return _logic.OnSacrifice(); } public override bool RespondsToOtherCardPreDeath(CardSlot deathSlot, bool fromCombat, PlayableCard killer) { return _logic.RespondsToOtherCardPreDeath(deathSlot, fromCombat, killer); } public override IEnumerator OnOtherCardPreDeath(CardSlot deathSlot, bool fromCombat, PlayableCard killer) { yield return _logic.OnOtherCardPreDeath(deathSlot, fromCombat, killer); } public override bool RespondsToSlotTargetedForAttack(CardSlot slot, PlayableCard attacker) { return _logic.RespondsToSlotTargetedForAttack(slot, attacker); } public override IEnumerator OnSlotTargetedForAttack(CardSlot slot, PlayableCard attacker) { yield return _logic.OnSlotTargetedForAttack(slot, attacker); } public bool RespondsToBellRung(bool playerCombatPhase) { return _logic.RespondsToBellRung(playerCombatPhase); } public IEnumerator OnBellRung(bool playerCombatPhase) { yield return _logic.OnBellRung(playerCombatPhase); } public bool RespondsToOtherCardAddedToHand(PlayableCard card) { return _logic.RespondsToOtherCardAddedToHand(card); } public IEnumerator OnOtherCardAddedToHand(PlayableCard card) { yield return _logic.OnOtherCardAddedToHand(card); } public bool RespondsToCardAssignedToSlotContext(PlayableCard card, CardSlot oldSlot, CardSlot newSlot) { return _logic.RespondsToCardAssignedToSlotContext(card, oldSlot, newSlot); } public IEnumerator OnCardAssignedToSlotContext(PlayableCard card, CardSlot oldSlot, CardSlot newSlot) { yield return _logic.OnCardAssignedToSlotContext(card, oldSlot, newSlot); } public bool RespondsToCardDealtDamageDirectly(PlayableCard attacker, CardSlot opposingSlot, int damage) { return _logic.RespondsToCardDealtDamageDirectly(attacker, opposingSlot, damage); } public IEnumerator OnCardDealtDamageDirectly(PlayableCard attacker, CardSlot opposingSlot, int damage) { yield return _logic.OnCardDealtDamageDirectly(attacker, opposingSlot, damage); } } } namespace JLPlugin.ConfigilFunctions { internal static class AbilityFunction { internal static void Evaluate(FunctionArgs functionArgs) { //IL_0064: Unknown result type (might be due to invalid IL or missing references) List list = functionArgs.Parameters.Select((Expression x) => x.Evaluate()).ToList(); if (list.Count != 1) { throw new FormatException("Ability() requires 1 parameter."); } if (list[0] == null) { functionArgs.Result = null; return; } string value = (string)list[0]; functionArgs.Result = ImportExportUtils.ParseEnum(value); } } internal static class GetSlot { internal static void Evaluate(FunctionArgs functionArgs) { List list = functionArgs.Parameters.Select((Expression x) => x.Evaluate()).ToList(); if (list.Count < 1 || list.Count > 3) { throw new FormatException("GetSlot() requires between 1 and 3 parameters."); } if (list[0] == null) { functionArgs.Result = null; return; } int index = (int)list[0]; if (list.Count == 1) { functionArgs.Result = Singleton.Instance.playerSlots.ElementAtOrDefault(index); return; } CardSlot val = (((bool)list[1]) ? Singleton.Instance.opponentSlots.ElementAtOrDefault(index) : Singleton.Instance.playerSlots.ElementAtOrDefault(index)); if (list.Count == 2) { functionArgs.Result = val; return; } string contents = "slot." + (string)list[2]; if (list.Count == 3) { functionArgs.Result = Interpreter.ProcessGeneratedVariable(contents, null, val); } } } internal static class SpecialAbilityFunction { internal static void Evaluate(FunctionArgs functionArgs) { //IL_0064: Unknown result type (might be due to invalid IL or missing references) List list = functionArgs.Parameters.Select((Expression x) => x.Evaluate()).ToList(); if (list.Count != 1) { throw new FormatException("SpecialAbility() requires 1 parameter."); } if (list[0] == null) { functionArgs.Result = null; return; } string value = (string)list[0]; functionArgs.Result = ImportExportUtils.ParseEnum(value); } } internal static class TraitFunction { internal static void Evaluate(FunctionArgs functionArgs) { //IL_0064: Unknown result type (might be due to invalid IL or missing references) List list = functionArgs.Parameters.Select((Expression x) => x.Evaluate()).ToList(); if (list.Count != 1) { throw new FormatException("Trait() requires 1 parameter."); } if (list[0] == null) { functionArgs.Result = null; return; } string value = (string)list[0]; functionArgs.Result = ImportExportUtils.ParseEnum(value); } } internal static class TribeFunction { internal static void Evaluate(FunctionArgs functionArgs) { //IL_0064: Unknown result type (might be due to invalid IL or missing references) List list = functionArgs.Parameters.Select((Expression x) => x.Evaluate()).ToList(); if (list.Count != 1) { throw new FormatException("Tribe() requires 1 parameter."); } if (list[0] == null) { functionArgs.Result = null; return; } string value = (string)list[0]; functionArgs.Result = ImportExportUtils.ParseEnum(value); } } internal static class HasAbilityFunction { internal static void Evaluate(FunctionArgs functionArgs) { //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Expected O, but got Unknown //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) List list = functionArgs.Parameters.Select((Expression x) => x.Evaluate()).ToList(); if (list.Count != 2) { throw new FormatException("HasAbility() requires 2 parameters."); } if (list[0] == null || list[1] == null) { functionArgs.Result = null; return; } PlayableCard val = (PlayableCard)list[0]; Ability val2 = (Ability)list[1]; functionArgs.Result = val.HasAbility(val2); } } internal static class HasSpecialAbilityFunction { internal static void Evaluate(FunctionArgs functionArgs) { //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Expected O, but got Unknown //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) List list = functionArgs.Parameters.Select((Expression x) => x.Evaluate()).ToList(); if (list.Count != 2) { throw new FormatException("HasSpecialAbility() requires 2 parameters."); } if (list[0] == null || list[1] == null) { functionArgs.Result = null; return; } PlayableCard val = (PlayableCard)list[0]; SpecialTriggeredAbility item = (SpecialTriggeredAbility)list[1]; functionArgs.Result = ((Card)val).Info.SpecialAbilities.Contains(item); } } internal static class HasTraitFunction { internal static void Evaluate(FunctionArgs functionArgs) { //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Expected O, but got Unknown //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) List list = functionArgs.Parameters.Select((Expression x) => x.Evaluate()).ToList(); if (list.Count != 2) { throw new FormatException("HasTrait() requires 2 parameters."); } if (list[0] == null || list[1] == null) { functionArgs.Result = null; return; } PlayableCard val = (PlayableCard)list[0]; Trait val2 = (Trait)list[1]; functionArgs.Result = ((Card)val).Info.HasTrait(val2); } } internal static class HasTribeFunction { internal static void Evaluate(FunctionArgs functionArgs) { //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Expected O, but got Unknown //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) List list = functionArgs.Parameters.Select((Expression x) => x.Evaluate()).ToList(); if (list.Count != 2) { throw new FormatException("HasTribe() requires 2 parameters."); } if (list[0] == null || list[1] == null) { functionArgs.Result = null; return; } PlayableCard val = (PlayableCard)list[0]; Tribe val2 = (Tribe)list[1]; functionArgs.Result = ((Card)val).Info.IsOfTribe(val2); } } internal static class ListContains { internal static void Evaluate(FunctionArgs functionArgs) { List list = functionArgs.Parameters.Select((Expression x) => x.Evaluate()).ToList(); if (list.Count != 2) { throw new FormatException("ListContains() requires 2 parameters."); } if (list[0] == null || list[1] == null) { functionArgs.Result = null; return; } List list2 = ((IList)list[0]).Cast().ToList(); object item = list[1]; functionArgs.Result = list2.Contains(item); } } internal static class RandomParFunction { internal static void Evaluate(FunctionArgs functionArgs) { List list = functionArgs.Parameters.Select((Expression x) => x.Evaluate()).ToList(); functionArgs.Result = list[Interpreter.random.Next(list.Count)]; } } } namespace JLPlugin.Data { public static class SigilDicts { public unsafe static readonly Dictionary AbilityMetaCategory = Enum.GetValues(typeof(AbilityMetaCategory)).Cast().ToDictionary((AbilityMetaCategory t) => ((object)(*(AbilityMetaCategory*)(&t))/*cast due to .constrained prefix*/).ToString(), (AbilityMetaCategory t) => t); public unsafe static readonly Dictionary Emotion = Enum.GetValues(typeof(Emotion)).Cast().ToDictionary((Emotion t) => ((object)(*(Emotion*)(&t))/*cast due to .constrained prefix*/).ToString(), (Emotion t) => t); public unsafe static readonly Dictionary LetterAnimation = Enum.GetValues(typeof(LetterAnimation)).Cast().ToDictionary((LetterAnimation t) => ((object)(*(LetterAnimation*)(&t))/*cast due to .constrained prefix*/).ToString(), (LetterAnimation t) => t); public unsafe static readonly Dictionary Speaker = Enum.GetValues(typeof(Speaker)).Cast().ToDictionary((Speaker t) => ((object)(*(Speaker*)(&t))/*cast due to .constrained prefix*/).ToString(), (Speaker t) => t); public static IDictionary> ArgumentList = new Dictionary>(); public static IDictionary> SpecialArgumentList = new Dictionary>(); public static IDictionary> PowerStatArgumentList = new Dictionary>(); public static IDictionary ConsumableItemList = new Dictionary(); } public class ConfigilUtils { public static CardModificationInfo GetModById(PlayableCard card, string id, bool isPermanent = false) { //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_0088: Expected O, but got Unknown CardModificationInfo val; if ((isPermanent ? ((Card)card).Info.Mods : card.TemporaryMods).Where((CardModificationInfo x) => x.singletonId == id).ToList().Count > 0) { val = (isPermanent ? ((Card)card).Info.Mods : card.TemporaryMods).Where((CardModificationInfo x) => x.singletonId == id).ToList()[0]; } else { val = new CardModificationInfo { singletonId = id }; if (isPermanent) { ((Card)card).Info.Mods.Add(val); } else { card.AddTemporaryMod(val); } } return val; } public static object GetConfigByGuid(string guid, string configSection, string configName) { //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Expected O, but got Unknown KeyValuePair? keyValuePair = Chainloader.PluginInfos.First((KeyValuePair x) => x.Key == guid); if (!keyValuePair.HasValue) { return null; } return keyValuePair.Value.Value.Instance.Config[new ConfigDefinition(configSection, configName)].BoxedValue; } } public class CoroutineWithData { public object result; private IEnumerator target; public Coroutine coroutine { get; private set; } public CoroutineWithData(IEnumerator target) { this.target = target; coroutine = ((MonoBehaviour)Singleton.Instance).StartCoroutine(Run()); } private IEnumerator Run() { while (target.MoveNext()) { result = target.Current; yield return result; } } } public static class SacrificeHelper { public static IEnumerator ChooseSacrificesForCard(this BoardManager self, List validSlots, PlayableCard card, int requiredSacrifices, List sacrificedSlots = null, List sacrificedCards = null, bool killVictims = true) { Singleton.Instance.Controller.LockState = (ViewLockState)0; Singleton.Instance.SwitchToView(self.BoardView, false, false); Singleton.Instance.ForceCursorType((CursorType)1); self.cancelledPlacementWithInput = false; self.currentValidSlots = validSlots; self.currentSacrificeDemandingCard = card; self.CancelledSacrifice = false; self.LastSacrificesInfo.Clear(); self.SetQueueSlotsEnabled(false); foreach (CardSlot allSlot in self.AllSlots) { if (!allSlot.IsPlayerSlot || (Object)(object)allSlot.Card == (Object)null) { ((InteractableBase)allSlot).SetEnabled(false); ((HighlightedInteractable)allSlot).ShowState((State)1, false, 0.15f); } if (allSlot.IsPlayerSlot && (Object)(object)allSlot.Card != (Object)null && allSlot.Card.CanBeSacrificed && validSlots.Contains(allSlot)) { ((Card)allSlot.Card).Anim.SetShaking(true); } } yield return self.SetSacrificeMarkersShown(requiredSacrifices); while (self.GetValueOfSacrifices(self.currentSacrifices) < requiredSacrifices && !self.cancelledPlacementWithInput) { self.SetSacrificeMarkersValue(self.currentSacrifices.Count); yield return (object)new WaitForEndOfFrame(); } foreach (CardSlot allSlot2 in self.AllSlots) { ((InteractableBase)allSlot2).SetEnabled(false); if (allSlot2.IsPlayerSlot && (Object)(object)allSlot2.Card != (Object)null) { ((Card)allSlot2.Card).Anim.SetShaking(false); } } foreach (CardSlot currentSacrifice in self.currentSacrifices) { self.LastSacrificesInfo.Add(((Card)currentSacrifice.Card).Info); } bool flag = !self.SacrificesCreateRoomForCard(card, self.currentSacrifices) && !card.OnBoard; if (self.cancelledPlacementWithInput || flag) { self.HideSacrificeMarkers(); if (flag) { yield return (object)new WaitForSeconds(0.25f); } foreach (CardSlot slot in self.GetSlots(true)) { if ((Object)(object)slot.Card != (Object)null) { ((Card)slot.Card).Anim.SetSacrificeHoverMarkerShown(false); if (self.currentSacrifices.Contains(slot)) { ((Card)slot.Card).Anim.SetMarkedForSacrifice(false); } } } Singleton.Instance.SwitchToView(self.defaultView, false, false); Singleton.Instance.ClearForcedCursorType(); self.CancelledSacrifice = true; } else { self.SetSacrificeMarkersValue(self.GetValueOfSacrifices(self.currentSacrifices)); yield return (object)new WaitForSeconds(0.2f); self.HideSacrificeMarkers(); foreach (CardSlot currentSacrifice2 in self.currentSacrifices) { if ((Object)(object)currentSacrifice2.Card != (Object)null && !currentSacrifice2.Card.Dead) { if (killVictims) { int sacrificesMadeThisTurn = self.SacrificesMadeThisTurn; self.SacrificesMadeThisTurn = sacrificesMadeThisTurn + 1; yield return currentSacrifice2.Card.Sacrifice(); Singleton.Instance.SwitchToView(self.BoardView, false, false); } else { currentSacrifice2.Card.FakeOutSacrifice(); Singleton.Instance.SwitchToView(self.BoardView, false, false); } } } } self.SetQueueSlotsEnabled(true); foreach (CardSlot allSlot3 in self.AllSlots) { ((InteractableBase)allSlot3).SetEnabled(true); ((HighlightedInteractable)allSlot3).ShowState((State)2, false, 0.15f); } self.currentSacrificeDemandingCard = null; if (sacrificedSlots != null && !self.CancelledSacrifice) { sacrificedSlots.AddRange(self.currentSacrifices); } if (sacrificedCards != null && !self.CancelledSacrifice) { sacrificedCards.AddRange(self.LastSacrificesInfo); } self.currentSacrifices.Clear(); Singleton.Instance.ClearForcedCursorType(); } public static void FakeOutSacrifice(this PlayableCard card) { ((Card)card).Anim.PlaySacrificeSound(); ((Card)card).Anim.SetSacrificeHoverMarkerShown(false); ((Card)card).Anim.SetMarkedForSacrifice(false); ((Card)card).Anim.PlaySacrificeParticles(); } public static int AvailableSacrificeValueInSlots(this BoardManager self, List slots) { return self.GetValueOfSacrifices(slots.FindAll((CardSlot x) => (Object)(object)x.Card != (Object)null && x.Card.CanBeSacrificed)); } } [Serializable] public class AbilityBehaviourData { public trigger trigger; public List actionOrder; public List placeCards; public List buffCards; public List transformCards; public List changeAppearance; public gainCurrency gainCurrency; public dealScaleDamage dealScaleDamage; public getStatValues getStatValues; public List drawCards; public List chooseSlots; public List moveCards; public List damageSlots; public List attackSlots; public List extraAttacks; public messageData showMessage; public Dictionary>> customActions; public Dictionary variables; public Dictionary generatedVariables; public PlayableCard self; public int? TurnsInPlay; public Ability? ability; public SpecialTriggeredAbility? specialAbility; public SpecialStatIcon? specialStatIcon; public string consumableItem; } [Serializable] public class ItemData : AConfigilData { public string GUID; public LocalizableField rulebookName; public LocalizableField rulebookDescription; public LocalizableField description; public string icon; public string bottledCardName = ""; public bool regionSpecific; public bool notRandomlyGiven; public string rulebookCategory = ((object)(AbilityMetaCategory)0/*cast due to .constrained prefix*/).ToString(); public string modelType = ((object)(ModelType)2/*cast due to .constrained prefix*/).ToString(); public string pickupSoundId = "stone_object_up"; public string placedSoundId = "stone_object_hit"; public string examineSoundId = "stone_object_hit"; public int powerLevel = 1; public override string Name => rulebookName.EnglishValue; public sealed override void Initialize() { rulebookName = new LocalizableField("rulebookName"); rulebookDescription = new LocalizableField("rulebookDescription"); description = new LocalizableField("description"); } public static void LoadAllConsumableItems(List files) { //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) for (int i = 0; i < files.Count; i++) { string text = files[i]; string text2 = text.Substring(text.LastIndexOf(Path.DirectorySeparatorChar) + 1); if (!text2.EndsWith("_item.jldr2")) { continue; } ImportExportUtils.SetDebugPath(text); files.RemoveAt(i--); try { Plugin.VerboseLog("Loading JLDR2 (consumableItem) " + text2); ItemData itemData = text.FromFilePath(); ConsumableItemData val = null; string text3 = itemData.GUID ?? "MADH.inscryption.JSONLoader"; Texture2D a = null; ImportExportUtils.ApplyValue(ref a, ref itemData.icon, toA: true, "Items", "icon"); if (!string.IsNullOrEmpty(itemData.bottledCardName)) { val = ConsumableItemManager.NewCardInABottle(text3, itemData.bottledCardName, a); } else { string cardInfoEnglishField = null; string cardInfoEnglishField2 = null; ImportExportUtils.ApplyLocaleField("rulebookName", ref itemData.rulebookName, ref cardInfoEnglishField, toCardInfo: true); ImportExportUtils.ApplyLocaleField("rulebookDescription", ref itemData.rulebookDescription, ref cardInfoEnglishField2, toCardInfo: true); ModelType a2 = (ModelType)2; ImportExportUtils.ApplyValue(ref a2, ref itemData.modelType, toA: true, "Items", "modelType"); val = ConsumableItemManager.New(text3, cardInfoEnglishField, cardInfoEnglishField2, a, typeof(ConfigurableConsumableItem), a2); SigilDicts.ConsumableItemList[((Object)val).name] = itemData; } Process(val, itemData, toInfo: true); Plugin.VerboseLog("Loaded JLDR2 (consumableItem) " + text2); } catch (Exception ex) { Plugin.Log.LogError((object)("Error loading trait from " + text)); Plugin.Log.LogError((object)ex); } } } private unsafe static void Process(ConsumableItemData info, ItemData data, bool toInfo) { ImportExportUtils.ApplyValue(ref info.regionSpecific, ref data.regionSpecific, toInfo, "Items", "regionSpecific"); ImportExportUtils.ApplyValue(ref info.notRandomlyGiven, ref data.notRandomlyGiven, toInfo, "Items", "notRandomlyGiven"); ImportExportUtils.ApplyLocaleField("description", ref data.description, ref info.description, toInfo); ImportExportUtils.ApplyValue(ref ((ItemData)info).pickupSoundId, ref data.pickupSoundId, toInfo, "Items", "pickupSoundId"); ImportExportUtils.ApplyValue(ref ((ItemData)info).placedSoundId, ref data.placedSoundId, toInfo, "Items", "placedSoundId"); ImportExportUtils.ApplyValue(ref ((ItemData)info).examineSoundId, ref data.examineSoundId, toInfo, "Items", "examineSoundId"); ImportExportUtils.ApplyValue(ref info.powerLevel, ref data.powerLevel, toInfo, "Items", "powerLevel"); ImportExportUtils.ApplyValue(ref info.rulebookCategory, ref data.rulebookCategory, toInfo, "Items", "rulebookCategory"); if (!toInfo) { ImportExportUtils.ApplyValue(ref info.rulebookSprite, ref data.icon, toA: false, "Items", "icon"); string a = ConsumableItemDataExtensions.GetCardWithinBottle(info); ImportExportUtils.ApplyValue(ref a, ref data.bottledCardName, toA: false, "Items", "bottledCardName"); ImportExportUtils.ApplyProperty(new Func(info, (nint)(delegate*)(&ConsumableItemDataExtensions.GetPrefabModelType)), delegate { }, ref data.modelType, toCardInfo: false, "Items", "modelType"); ImportExportUtils.ApplyProperty(new Func(info, (nint)(delegate*)(&ConsumableItemDataExtensions.GetModPrefix)), delegate { }, ref data.GUID, toCardInfo: false, "Items", "GUID"); ImportExportUtils.ApplyLocaleField("rulebookName", ref data.rulebookName, ref info.rulebookName, toCardInfo: false); ImportExportUtils.ApplyLocaleField("rulebookDescription", ref data.rulebookDescription, ref info.rulebookDescription, toCardInfo: false); } } public static void ExportAllItems() { List list = new List(ConsumableItemManager.NewConsumableItemDatas); list.AddRange(Resources.LoadAll("")); Plugin.Log.LogInfo((object)$"Exporting {list.Count} ConsumableItems to JSON"); string text = Path.Combine(Plugin.ExportDirectory, "Items"); if (!Directory.Exists(text)) { Directory.CreateDirectory(text); } for (int i = 0; i < list.Count; i++) { ConsumableItemData obj = list[i]; ImportExportUtils.SetID(((Object)obj).name); ItemData itemData = new ItemData(); Process(obj, itemData, toInfo: false); string contents = JSONParser.ToJSON(itemData); File.WriteAllText(Path.Combine(text, itemData.rulebookName.EnglishValue + "_item.jldr2"), contents); } } } [Serializable] public class SigilData : AConfigilData { public string GUID; public LocalizableField name; public LocalizableField description; public List metaCategories; public string texture; public string pixelTexture; public int? powerLevel; public string abilityLearnedDialogue; public int? priority; public bool? opponentUsable; public bool? canStack; public bool? isSpecialAbility; public bool? isPowerStat; public bool? appliesToAttack; public bool? appliesToHealth; private AConfigilData _aConfigilDataImplementation; public override string Name => name.EnglishValue; public sealed override void Initialize() { name = new LocalizableField("name"); description = new LocalizableField("description"); } public void GenerateNew() { //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_0167: Unknown result type (might be due to invalid IL or missing references) //IL_01d9: Unknown result type (might be due to invalid IL or missing references) //IL_02e6: Unknown result type (might be due to invalid IL or missing references) //IL_0339: Unknown result type (might be due to invalid IL or missing references) Type typeFromHandle = typeof(ConfigurableMain); if (isSpecialAbility == true) { typeFromHandle = typeof(ConfigurableSpecial); string cardInfoEnglishField = ""; ImportExportUtils.ApplyLocaleField("name", ref name, ref cardInfoEnglishField, toCardInfo: true); FullSpecialTriggeredAbility val = SpecialTriggeredAbilityManager.Add(GUID ?? "MADH.inscryption.JSONLoader", cardInfoEnglishField, typeFromHandle); SigilDicts.SpecialArgumentList[val.Id] = new Tuple(typeFromHandle, this); return; } if (isPowerStat == true) { typeFromHandle = typeof(ConfigurablePowerStat); StatIconInfo val2 = ScriptableObject.CreateInstance(); ImportExportUtils.ApplyValue(ref val2.metaCategories, ref metaCategories, toA: true, "PowerStat", "metaCategories"); ImportExportUtils.ApplyValue(ref val2.appliesToAttack, ref appliesToAttack, toA: true, "appliesToAttack", "appliesToAttack"); ImportExportUtils.ApplyValue(ref val2.appliesToHealth, ref appliesToHealth, toA: true, "appliesToHealth", "appliesToHealth"); ImportExportUtils.ApplyLocaleField("name", ref name, ref val2.rulebookName, toCardInfo: true); ImportExportUtils.ApplyLocaleField("description", ref description, ref val2.rulebookDescription, toCardInfo: true); ImportExportUtils.ApplyValue(ref val2.iconGraphic, ref texture, toA: true, "PowerStat", "texture"); FullStatIcon val3 = StatIconManager.Add(GUID ?? "MADH.inscryption.JSONLoader", val2, typeof(ConfigurablePowerStat)); SigilDicts.PowerStatArgumentList[val3.AbilityId] = new Tuple(typeFromHandle, this, val3.Id); return; } Texture2D a = null; ImportExportUtils.ApplyValue(ref a, ref texture, toA: true, "Configils", "texture"); AbilityInfo val4 = AbilityManager.New(GUID ?? "MADH.inscryption.JSONLoader", name.EnglishValue ?? "", description.EnglishValue ?? "", typeFromHandle, (Texture)((!((Object)(object)a == (Object)null)) ? ((object)a) : ((object)new Texture2D(49, 49)))); string cardInfoEnglishField2 = "_"; ImportExportUtils.ApplyLocaleField("name", ref name, ref cardInfoEnglishField2, toCardInfo: true); ImportExportUtils.ApplyLocaleField("description", ref description, ref cardInfoEnglishField2, toCardInfo: true); ImportExportUtils.ApplyValue(ref val4.powerLevel, ref powerLevel, toA: true, "Configils", "powerLevel"); ImportExportUtils.ApplyValue(ref val4.canStack, ref canStack, toA: true, "Configils", "canStack"); ImportExportUtils.ApplyValue(ref val4.opponentUsable, ref opponentUsable, toA: true, "Configils", "opponentUsable"); ImportExportUtils.ApplyValue(ref val4.abilityLearnedDialogue, ref abilityLearnedDialogue, toA: true, "Configils", "abilityLearnedDialogue"); ImportExportUtils.ApplyValue(ref val4.metaCategories, ref metaCategories, toA: true, "Configils", "metaCategories"); if (metaCategories == null || metaCategories.Count == 0) { AbilityExtensions.SetDefaultPart1Ability(val4); } Texture2D a2 = null; ImportExportUtils.ApplyValue(ref a2, ref pixelTexture, toA: true, "Configils", "pixelTexture"); AbilityExtensions.SetPixelAbilityIcon(val4, (Texture2D)((!((Object)(object)a2 == (Object)null)) ? ((object)a2) : ((object)new Texture2D(17, 17))), (FilterMode?)null); if (abilityBehaviour != null) { val4.activated = abilityBehaviour.Any((AbilityBehaviourData x) => x.trigger?.triggerType == "OnActivate"); } SigilDicts.ArgumentList[val4.ability] = new Tuple(typeFromHandle, this); } public static SigilData GetAbilityArguments(Ability ability) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) if (!SigilDicts.ArgumentList.TryGetValue(ability, out var value)) { return null; } return value.Item2; } public static SigilData GetAbilityArguments(SpecialTriggeredAbility ability) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) if (!SigilDicts.SpecialArgumentList.TryGetValue(ability, out var value)) { return null; } return value.Item2; } public static void LoadAllSigils(List files) { for (int i = 0; i < files.Count; i++) { string text = files[i]; string text2 = text.Substring(text.LastIndexOf(Path.DirectorySeparatorChar) + 1); if (text2.EndsWith("_sigil.jldr2")) { files.RemoveAt(i--); Plugin.VerboseLog("Loading JLDR2 (sigil) " + text2); ImportExportUtils.SetDebugPath(text); try { SigilData sigilData = text.FromFilePath(); ImportExportUtils.SetID(sigilData.GUID + "_" + sigilData.name.EnglishValue); sigilData.GenerateNew(); Plugin.VerboseLog($"Loaded JSON sigil {sigilData.name}"); } catch (Exception ex) { Plugin.Log.LogError((object)("Failed to load " + text2 + ": " + ex.Message)); Plugin.Log.LogError((object)ex); } } } } } [Serializable] public class activationCost { public int? bonesCost; public int? energyCost; public int? bloodCost; public List gemsCost; } [Serializable] public class addAbilityData { public string name; public string infused; public string list; } [Serializable] public class attackSlots { public string runOnCondition; public slotData attackerSlot; public slotData victimSlot; public static IEnumerator AttackSlots(AbilityBehaviourData abilitydata) { foreach (attackSlots attackslotinfo in abilitydata.attackSlots) { if (!(AConfigilData.ConvertArgument(attackslotinfo.runOnCondition, abilitydata) == "false")) { yield return (object)new WaitForSeconds(0.3f); Singleton.Instance.SwitchToView((View)4, false, false); CardSlot slot = slotData.GetSlot(attackslotinfo.attackerSlot, abilitydata); if ((Object)(object)slot == (Object)null) { slot = abilitydata.self.slot; } CardSlot slot2 = slotData.GetSlot(attackslotinfo.victimSlot, abilitydata); if ((Object)(object)slot != (Object)null && (Object)(object)slot2 != (Object)null) { yield return Singleton.Instance.SlotAttackSlot(slot, slot2, 0f); } } } } } [Serializable] public class buffCards { public string runOnCondition; public string targetCard; public slotData slot; public string addStats; public string setStats; public string heal; public List addAbilities; public List removeAbilities; public string isPermanent; public static IEnumerator BuffCards(AbilityBehaviourData abilitydata) { foreach (buffCards buffcardsinfo in abilitydata.buffCards) { if (AConfigilData.ConvertArgument(buffcardsinfo.runOnCondition, abilitydata) == "false") { continue; } PlayableCard card2 = GetCard(abilitydata, buffcardsinfo); if (!((Object)(object)card2 == (Object)null)) { bool flag = Singleton.Instance.CardsInHand.Contains(card2); Singleton.Instance.SwitchToView((View)((!flag) ? 4 : 0), false, false); bool isPermanent = AConfigilData.ConvertArgument(buffcardsinfo.isPermanent, abilitydata) == "true"; CardModificationInfo mod = ConfigilUtils.GetModById(card2, "ConfigilMod", isPermanent); Heal(abilitydata, buffcardsinfo, card2); AddStats(abilitydata, buffcardsinfo, mod); SetStats(abilitydata, buffcardsinfo, mod, card2); if (buffcardsinfo.addAbilities != null || buffcardsinfo.removeAbilities != null) { yield return PlayTransformAnimation(card2); } RemoveAbilities(abilitydata, buffcardsinfo, card2, mod); AddAbilities(abilitydata, buffcardsinfo, card2, mod, isPermanent); card2.OnStatsChanged(); if (card2.Health <= 0) { yield return card2.Die(false, (PlayableCard)null, true); } } } } private static void AddAbilities(AbilityBehaviourData abilitydata, buffCards buffcardsinfo, PlayableCard card, CardModificationInfo mod, bool isPermanent) { //IL_0051: 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_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) if (buffcardsinfo.addAbilities == null) { return; } List list = new List(); List list2 = new List(); foreach (addAbilityData addAbility in buffcardsinfo.addAbilities) { List list3 = new List(); if (!string.IsNullOrWhiteSpace(addAbility.name)) { list3.Add(ImportExportUtils.ParseEnum(AConfigilData.ConvertArgument(addAbility.name, abilitydata))); } if (!string.IsNullOrWhiteSpace(addAbility.list)) { list3.AddRange((List)AConfigilData.ConvertArgumentToType(addAbility.list, abilitydata, typeof(List))); } foreach (Ability item in list3) { if (mod.negateAbilities.Contains(item)) { mod.negateAbilities.Remove(item); card.Status.hiddenAbilities.Remove(item); } else if (AConfigilData.ConvertArgument(addAbility.infused, abilitydata) == "true") { list2.Add(item); } else { list.Add(item); } } } if (list.Count > 0) { mod.abilities.AddRange(list); } if (list2.Count > 0) { CardModificationInfo modById = ConfigilUtils.GetModById(card, "ConfigilMergedMod", isPermanent); ((Card)card).renderInfo.forceEmissivePortrait = true; modById.abilities.AddRange(list2); } } private static void RemoveAbilities(AbilityBehaviourData abilitydata, buffCards buffcardsinfo, PlayableCard card, CardModificationInfo mod) { //IL_0053: 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_0100: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) if (buffcardsinfo.removeAbilities == null) { return; } foreach (removeAbilityData removeAbility in buffcardsinfo.removeAbilities) { List sigils = new List(); if (!string.IsNullOrWhiteSpace(removeAbility.name)) { sigils.Add(ImportExportUtils.ParseEnum(AConfigilData.ConvertArgument(removeAbility.name, abilitydata))); } if (!string.IsNullOrWhiteSpace(removeAbility.list)) { sigils.AddRange((List)AConfigilData.ConvertArgumentToType(removeAbility.list, abilitydata, typeof(List))); } if (AConfigilData.ConvertArgument(removeAbility.all, abilitydata) == "true") { mod.abilities.RemoveAll((Ability x) => sigils.Contains(x)); card.Status.hiddenAbilities.AddRange(sigils); mod.negateAbilities.AddRange(sigils); continue; } foreach (Ability item in sigils) { if (mod.abilities.Contains(item)) { mod.abilities.Remove(item); continue; } card.Status.hiddenAbilities.AddRange(sigils); mod.negateAbilities.AddRange(sigils); } } } private static IEnumerator PlayTransformAnimation(PlayableCard card) { yield return (object)new WaitForSeconds(0.15f); ((Card)card).Anim.PlayTransformAnimation(); yield return (object)new WaitForSeconds(0.15f); } private static void SetStats(AbilityBehaviourData abilitydata, buffCards buffcardsinfo, CardModificationInfo mod, PlayableCard card) { if (buffcardsinfo.setStats != null) { string text = AConfigilData.ConvertArgument(buffcardsinfo.setStats.Split(new char[1] { '/' })[0], abilitydata); if (text != "?" && text != null) { mod.attackAdjustment += int.Parse(text) - ((Card)card).Info.Attack; } string text2 = AConfigilData.ConvertArgument(buffcardsinfo.setStats.Split(new char[1] { '/' })[1], abilitydata); if (text2 != "?" && text2 != null) { mod.healthAdjustment += int.Parse(text2) - ((Card)card).Info.Health; } } } private static void AddStats(AbilityBehaviourData abilitydata, buffCards buffcardsinfo, CardModificationInfo mod) { if (buffcardsinfo.addStats != null) { string text = AConfigilData.ConvertArgument(buffcardsinfo.addStats.Split(new char[1] { '/' })[0], abilitydata); if (text != "?" && text != null) { mod.attackAdjustment += int.Parse(text); } string text2 = AConfigilData.ConvertArgument(buffcardsinfo.addStats.Split(new char[1] { '/' })[1], abilitydata); if (text2 != "?" && text2 != null) { mod.healthAdjustment += int.Parse(text2); } } } private static void Heal(AbilityBehaviourData abilitydata, buffCards buffcardsinfo, PlayableCard card) { if (!string.IsNullOrWhiteSpace(buffcardsinfo.heal) && card.Status.damageTaken > 0) { card.HealDamage(Math.Min(card.Status.damageTaken, int.Parse(AConfigilData.ConvertArgument(buffcardsinfo.heal, abilitydata)))); } } public static PlayableCard GetCard(AbilityBehaviourData abilitydata, buffCards buffcardsinfo) { //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Expected O, but got Unknown PlayableCard result = null; if (buffcardsinfo.slot == null) { result = (PlayableCard)(string.IsNullOrWhiteSpace(buffcardsinfo.targetCard) ? ((object)abilitydata.self) : ((object)(PlayableCard)AConfigilData.ConvertArgumentToType(buffcardsinfo.targetCard, abilitydata, typeof(PlayableCard)))); } else { CardSlot val = slotData.GetSlot(buffcardsinfo.slot, abilitydata); if ((Object)(object)val != (Object)null && (Object)(object)val.Card != (Object)null) { result = val.Card; } } return result; } } [Serializable] public class card { public string name; public string retainMods; public string randomCardOnCondition; public string targetCard; public static CardInfo getCard(card cardInfo, AbilityBehaviourData abilitydata) { //IL_019c: Unknown result type (might be due to invalid IL or missing references) CardInfo result = null; if (cardInfo == null) { return null; } if (AConfigilData.ConvertArgument(cardInfo.name, abilitydata) == "None") { return null; } if (!string.IsNullOrWhiteSpace(cardInfo.name)) { result = CardLoader.GetCardByName(AConfigilData.ConvertArgument(cardInfo.name, abilitydata)); } else if (cardInfo.randomCardOnCondition != null) { List list = new List(); foreach (CardInfo allDatum in ScriptableObjectLoader.allData) { abilitydata.generatedVariables["RandomCardInfo"] = allDatum; if (SaveManager.SaveFile.IsPart1) { if (AConfigilData.ConvertArgument(cardInfo.randomCardOnCondition, abilitydata) == "true" && allDatum.metaCategories.Contains((CardMetaCategory)1)) { list.Add(allDatum); } } else if (SaveManager.SaveFile.IsPart2) { if (AConfigilData.ConvertArgument(cardInfo.randomCardOnCondition, abilitydata) == "true" && allDatum.metaCategories.Contains((CardMetaCategory)5)) { list.Add(allDatum); } } else if (SaveManager.SaveFile.IsPart3 && AConfigilData.ConvertArgument(cardInfo.randomCardOnCondition, abilitydata) == "true" && allDatum.metaCategories.Contains((CardMetaCategory)2)) { list.Add(allDatum); } } if (list.Count > 0) { Random random = new Random(); result = list[random.Next(list.Count)]; } } else if (!string.IsNullOrEmpty(cardInfo.targetCard)) { result = ((Card)AConfigilData.ConvertArgumentToType(cardInfo.targetCard, abilitydata, typeof(Card))).Info; } if (AConfigilData.ConvertArgument(cardInfo.retainMods, abilitydata) == "true") { ModifyCard(result, abilitydata); } return result; } private static void ModifyCard(CardInfo card, AbilityBehaviourData abilitydata) { //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Expected O, but got Unknown if ((Object)(object)abilitydata.self == (Object)null) { return; } foreach (CardModificationInfo item2 in ((Card)abilitydata.self).Info.Mods.FindAll((CardModificationInfo x) => !x.nonCopyable)) { CardModificationInfo item = (CardModificationInfo)item2.Clone(); card.Mods.Add(item); } } } [Serializable] public class changeAppearance { public string runOnCondition; public slotData slot; public string targetCard; public string changePortrait; public string changeName; public List addDecals; public List removeDecals; public static IEnumerator ChangeAppearance(AbilityBehaviourData abilitydata) { foreach (changeAppearance item in abilitydata.changeAppearance) { if (AConfigilData.ConvertArgument(item.runOnCondition, abilitydata) == "false") { continue; } Singleton.Instance.SwitchToView((View)4, false, false); PlayableCard val = null; if (item.slot == null) { val = (PlayableCard)(string.IsNullOrWhiteSpace(item.targetCard) ? ((object)abilitydata.self) : ((object)(PlayableCard)AConfigilData.ConvertArgumentToType(item.targetCard, abilitydata, typeof(PlayableCard)))); } else { CardSlot val2 = slotData.GetSlot(item.slot, abilitydata); if ((Object)(object)val2 != (Object)null && (Object)(object)val2.Card != (Object)null) { val = val2.Card; } } if (!((Object)(object)val != (Object)null)) { continue; } if (!string.IsNullOrWhiteSpace(item.changePortrait)) { try { Texture2D a = null; ImportExportUtils.ApplyValue(ref a, ref item.changePortrait, toA: true, "Configils", "changePortrait"); Sprite val3 = TextureHelper.ConvertTexture(a, (SpriteType)0, (FilterMode)0); val.SwitchToPortrait(val3); } catch (FileNotFoundException innerException) { throw new ArgumentException("Image file not found for card \"" + ((Object)abilitydata.self).name + "\"!", innerException); } } if (!string.IsNullOrWhiteSpace(item.changeName)) { ((Card)val).RenderInfo.nameOverride = item.changeName; } if (item.removeDecals != null) { foreach (string removeDecal in item.removeDecals) { object arg = (abilitydata.ability.HasValue ? ((object)abilitydata.ability) : ((!abilitydata.specialAbility.HasValue) ? ((object)abilitydata.specialStatIcon) : ((object)abilitydata.specialAbility))); string name = $"{arg}_{removeDecal}"; ((Card)val).Info.temporaryDecals.RemoveAll((Texture x) => ((Object)x).name == name); } } if (item.addDecals != null) { for (int num = 0; num < item.addDecals.Count; num++) { string b = item.addDecals[num]; Texture2D a2 = null; ImportExportUtils.ApplyValue(ref a2, ref b, toA: true, "Configils", "addDecals"); object arg2 = (abilitydata.ability.HasValue ? ((object)abilitydata.ability) : ((!abilitydata.specialAbility.HasValue) ? ((object)abilitydata.specialStatIcon) : ((object)abilitydata.specialAbility))); ((Object)a2).name = $"{arg2}_{b}"; ((Card)val).Info.temporaryDecals.Add((Texture)(object)a2); } } ((Card)val).RenderCard(); } yield break; } } [Serializable] public class chooseSlot { public string slotChooseableOnCondition; public static IEnumerator ChooseSlot(AbilityBehaviourData abilitydata, chooseSlot chooseslot, CardSlot baseSlot) { List allSlotsCopy = Singleton.Instance.AllSlotsCopy; List allSlotsCopy2 = Singleton.Instance.AllSlotsCopy; foreach (CardSlot item in Singleton.Instance.AllSlotsCopy) { abilitydata.generatedVariables["ChooseableSlot"] = item; if (AConfigilData.ConvertArgument(chooseslot.slotChooseableOnCondition, abilitydata, sendDebug: false) == "false") { allSlotsCopy2.Remove(item); } } CardSlot target = null; if (allSlotsCopy2.Count > 0) { _ = baseSlot; new List(); Singleton.Instance.SwitchToView(Singleton.Instance.CombatView, false, false); Singleton.Instance.Controller.LockState = (ViewLockState)1; Singleton.Instance.Controller.SwitchToControlMode(Singleton.Instance.ChoosingSlotViewMode, false); Singleton.Instance.Controller.LockState = (ViewLockState)0; _ = Singleton.Instance.CurrentInteractable; BoardManager instance = Singleton.Instance; yield return instance.ChooseTarget(allSlotsCopy, allSlotsCopy2, (Action)delegate(CardSlot slot) { target = slot; }, (Action)null, (Action)null, (Func)(() => false), (CursorType)16); Singleton.Instance.Controller.SwitchToControlMode(Singleton.Instance.DefaultViewMode, false); Singleton.Instance.Controller.LockState = (ViewLockState)1; Singleton.Instance.SwitchToView(Singleton.Instance.CombatView, false, false); yield return (object)new WaitForSeconds(0.2f); Singleton.Instance.Controller.LockState = (ViewLockState)0; } yield return target; } } public class customActions { public static IEnumerator runCustomActions(AbilityBehaviourData abilitydata) { if (abilitydata.customActions == null) { yield break; } foreach (JSONLoaderAPI.ConfigilAction action in JSONLoaderAPI.customActionList) { KeyValuePair>> keyValuePair = abilitydata.customActions.FirstOrDefault((KeyValuePair>> x) => x.Key == action.actionName); if (keyValuePair.Equals(default(KeyValuePair>>))) { continue; } foreach (Dictionary item in keyValuePair.Value) { if (!action.fields.Contains("runOnCondition") && Enumerable.Contains(item.Keys, "runOnCondition") && AConfigilData.ConvertArgument(item["runOnCondition"], abilitydata) == "false") { continue; } Dictionary dictionary = new Dictionary(); foreach (string field in action.fields) { if (Enumerable.Contains(item.Keys, field)) { dictionary[field] = AConfigilData.ConvertArgument(item[field], abilitydata); } else { dictionary[field] = null; } } action.functionToCall(dictionary); } } } } [Serializable] public class damageSlots { public string runOnCondition; public slotData slot; public string damageSource; public string damage; public static IEnumerator DamageSlots(AbilityBehaviourData abilitydata) { foreach (damageSlots damageSlot in abilitydata.damageSlots) { if (AConfigilData.ConvertArgument(damageSlot.runOnCondition, abilitydata) == "false") { continue; } Singleton.Instance.SwitchToView((View)4, false, false); CardSlot val = slotData.GetSlot(damageSlot.slot, abilitydata); if (damageSlot.slot == null) { val = abilitydata.self.Slot; } if (!((Object)(object)val != (Object)null) || string.IsNullOrWhiteSpace(damageSlot.damage)) { continue; } int num = int.Parse(AConfigilData.ConvertArgument(damageSlot.damage, abilitydata)); if ((Object)(object)val.Card != (Object)null) { PlayableCard val2 = abilitydata.self; if (!string.IsNullOrWhiteSpace(damageSlot.damageSource)) { val2 = ((!(AConfigilData.ConvertArgument(damageSlot.damageSource, abilitydata) == "null")) ? ((PlayableCard)AConfigilData.ConvertArgumentToType(damageSlot.damageSource, abilitydata, typeof(PlayableCard))) : ((PlayableCard)null)); } yield return val.Card.TakeDamage(num, val2); } else { yield return Singleton.Instance.ShowDamageSequence(num, num, val.IsPlayerSlot, 0.125f, (GameObject)null, 0f, true); } } } } [Serializable] public class dealScaleDamage { public string runOnCondition; public string damage; public static IEnumerator DealScaleDamage(AbilityBehaviourData abilitydata) { if (!(AConfigilData.ConvertArgument(abilitydata.dealScaleDamage.runOnCondition, abilitydata) == "false") && !string.IsNullOrWhiteSpace(abilitydata.dealScaleDamage.damage)) { int num = int.Parse(AConfigilData.ConvertArgument(abilitydata.dealScaleDamage.damage, abilitydata)); if (num > 0) { yield return Singleton.Instance.ShowDamageSequence(num, num, false, 0.125f, (GameObject)null, 0f, true); } else if (num < 0) { yield return Singleton.Instance.ShowDamageSequence(-num, -num, true, 0.125f, (GameObject)null, 0f, true); } } } } [Serializable] public class drawCards { public string runOnCondition; public card card; public static IEnumerator DrawCards(AbilityBehaviourData abilitydata) { foreach (drawCards drawCard in abilitydata.drawCards) { if (drawCard.runOnCondition == null || !(AConfigilData.ConvertArgument(drawCard.runOnCondition, abilitydata) == "false")) { Singleton.Instance.SwitchToView((View)1, false, false); CardInfo val = card.getCard(drawCard.card, abilitydata); if ((Object)(object)val != (Object)null) { PlayableCard CardInHand = CardSpawner.SpawnPlayableCard(val); yield return Singleton.Instance.AddCardToHand(CardInHand, new Vector3(0f, 0f, 0f), 0f); abilitydata.generatedVariables["LastDrawnCard"] = CardInHand; yield return (object)new WaitForSeconds(0.45f); } } } } } [Serializable] public class extraAttacks { public string runOnCondition; public slotData attackingSlot; public List slotsToAttack; } [Serializable] public class gainCurrency { public string runOnCondition; public string bones; public string energy; public string maxEnergy; public string foils; public static IEnumerator GainCurrency(AbilityBehaviourData abilitydata) { if (AConfigilData.ConvertArgument(abilitydata.gainCurrency.runOnCondition, abilitydata) == "false") { yield break; } if (!string.IsNullOrWhiteSpace(abilitydata.gainCurrency.bones)) { int num = int.Parse(AConfigilData.ConvertArgument(abilitydata.gainCurrency.bones, abilitydata)); if (num > 0) { yield return Singleton.Instance.AddBones(num, (CardSlot)null); } else if (num < 0) { yield return Singleton.Instance.SpendBones(num * -1); } } if (!string.IsNullOrWhiteSpace(abilitydata.gainCurrency.energy)) { int num2 = int.Parse(AConfigilData.ConvertArgument(abilitydata.gainCurrency.energy, abilitydata)); if (num2 > 0) { yield return Singleton.Instance.AddEnergy(num2); } else if (num2 < 0) { yield return Singleton.Instance.SpendEnergy(num2 * -1); } } if (!string.IsNullOrWhiteSpace(abilitydata.gainCurrency.maxEnergy)) { int num3 = int.Parse(AConfigilData.ConvertArgument(abilitydata.gainCurrency.maxEnergy, abilitydata)); if (num3 > 0) { yield return Singleton.Instance.AddMaxEnergy(num3); } else if (num3 < 0) { ResourcesManager instance = Singleton.Instance; instance.PlayerMaxEnergy -= num3; } } if (!string.IsNullOrWhiteSpace(abilitydata.gainCurrency.foils)) { int num4 = int.Parse(AConfigilData.ConvertArgument(abilitydata.gainCurrency.foils, abilitydata)); if (num4 > 0) { RunState run = RunState.Run; run.currency += num4; yield return Singleton.Instance.DropWeightsIn(num4); } else if (num4 < 0) { RunState run2 = RunState.Run; run2.currency -= num4; yield return Singleton.Instance.TakeWeights(num4 * -1); } } } } [Serializable] public class getStatValues { public string attack; public string health; } [Serializable] public class messageData { public string runOnCondition; public string message; public string length; public string emotion; public string letterAnimation; public string speaker; public static IEnumerator showMessage(AbilityBehaviourData abilitydata) { messageData messageData2 = abilitydata.showMessage; if (!(AConfigilData.ConvertArgument(messageData2.runOnCondition, abilitydata) == "false")) { yield return Singleton.Instance.ShowThenClear(AConfigilData.ConvertArgument(messageData2.message, abilitydata) ?? "", float.Parse(AConfigilData.ConvertArgument(messageData2.length, abilitydata) ?? "2"), 0f, SigilDicts.Emotion[messageData2.emotion ?? "Neutral"], SigilDicts.LetterAnimation[messageData2.letterAnimation ?? "Jitter"], SigilDicts.Speaker[messageData2.speaker ?? "Single"], (string[])null); } } } [Serializable] public class moveCards { public string runOnCondition; public slotData moveFromSlot; public slotData moveToSlot; public string replace; public strafeData strafe; public bool movingLeft; public static IEnumerator MoveCards(AbilityBehaviourData abilitydata) { foreach (moveCards movecardinfo in abilitydata.moveCards) { if (AConfigilData.ConvertArgument(movecardinfo.runOnCondition, abilitydata) == "false") { continue; } Singleton.Instance.SwitchToView((View)4, false, false); CardSlot slotFrom = slotData.GetSlot(movecardinfo.moveFromSlot, abilitydata); if (movecardinfo.moveFromSlot == null) { slotFrom = abilitydata.self.Slot; } CardSlot slot = slotData.GetSlot(movecardinfo.moveToSlot, abilitydata); CardSlot obj = slotFrom; if (!((Object)(object)((obj != null) ? obj.Card : null) != (Object)null)) { continue; } if ((Object)(object)slot != (Object)null) { if ((Object)(object)slot.Card != (Object)null && (AConfigilData.ConvertArgument(movecardinfo.replace, abilitydata) ?? "true") == "true") { ((Card)slot.Card).ExitBoard(0f, new Vector3(0f, 0f, 0f)); } if ((Object)(object)slot.Card == (Object)null) { slotFrom.Card.SetIsOpponentCard(!slot.IsPlayerSlot); yield return Singleton.Instance.AssignCardToSlot(slotFrom.Card, slot, 0.1f, (Action)null, true); } } if (movecardinfo.strafe != null) { yield return movecardinfo.strafe.Strafe(abilitydata, movecardinfo, slotFrom); } } } } [Serializable] public class placeCards { public string runOnCondition; public slotData slot; public card card; public string replace; public static IEnumerator PlaceCards(AbilityBehaviourData abilitydata) { foreach (placeCards placeCard in abilitydata.placeCards) { if (AConfigilData.ConvertArgument(placeCard.runOnCondition, abilitydata) == "false") { continue; } Singleton.Instance.SwitchToView((View)4, false, false); bool flag = AConfigilData.ConvertArgument(placeCard.replace, abilitydata) == "true"; CardSlot val = slotData.GetSlot(placeCard.slot, abilitydata); if ((Object)(object)val != (Object)null) { CardInfo val2 = card.getCard(placeCard.card, abilitydata); if ((Object)(object)val.Card != (Object)null && flag) { ((Card)val.Card).ExitBoard(0f, new Vector3(0f, 0f, 0f)); } if (((Object)(object)val.Card == (Object)null || val.Card.Dead) && (Object)(object)val2 != (Object)null) { yield return Singleton.Instance.CreateCardInSlot(val2, val, 0.15f, true); } } } } } [Serializable] public class removeAbilityData { public string name; public string all; public string list; } [Serializable] public class slotData { public string randomSlotOnCondition; public string index; public string isOpponentSlot; public static CardSlot GetSlot(slotData slotdata, AbilityBehaviourData abilitydata, bool sendDebug = true) { if (slotdata == null) { return null; } if (string.IsNullOrWhiteSpace(slotdata.index)) { return null; } if (!string.IsNullOrWhiteSpace(slotdata.randomSlotOnCondition)) { Random random = new Random(); List list = new List(); foreach (CardSlot allSlot in Singleton.Instance.AllSlots) { abilitydata.generatedVariables["RandomSlot"] = allSlot; if (AConfigilData.ConvertArgument(slotdata.randomSlotOnCondition, abilitydata, sendDebug) == "true") { list.Add(allSlot); } } if (list.Count == 0) { return null; } return list[random.Next(list.Count)]; } return ConvertIntToSlot(slotdata, abilitydata, int.Parse(AConfigilData.ConvertArgument(slotdata.index, abilitydata, sendDebug)), sendDebug); } public static CardSlot ConvertIntToSlot(slotData slotdata, AbilityBehaviourData abilitydata, int index, bool sendDebug = true) { if (index < 0 || index >= Singleton.Instance.PlayerSlotsCopy.Count) { return null; } CardSlot result = Singleton.Instance.playerSlots[index]; if (!string.IsNullOrWhiteSpace(slotdata.isOpponentSlot) && AConfigilData.ConvertArgument(slotdata.isOpponentSlot, abilitydata, sendDebug) == "true") { result = Singleton.Instance.opponentSlots[index]; } return result; } } [Serializable] public class strafeData { public enum StrafeType { normal, left, right } public string direction; public string flipSigil; public bool movingLeft; public IEnumerator Strafe(AbilityBehaviourData abilityData, moveCards movecardinfo, CardSlot SlotToMove) { switch ((!string.IsNullOrWhiteSpace(movecardinfo.strafe.direction)) ? ImportExportUtils.ParseEnum(AConfigilData.ConvertArgument(movecardinfo.strafe.direction, abilityData)) : StrafeType.right) { default: yield break; case StrafeType.left: movingLeft = true; break; case StrafeType.right: movingLeft = false; break; case StrafeType.normal: break; } CardSlot adjacent = Singleton.Instance.GetAdjacent(SlotToMove, true); CardSlot adjacent2 = Singleton.Instance.GetAdjacent(SlotToMove, false); bool flag = (Object)(object)adjacent != (Object)null && (Object)(object)adjacent.Card == (Object)null; bool flag2 = (Object)(object)adjacent2 != (Object)null && (Object)(object)adjacent2.Card == (Object)null; if (movingLeft && !flag) { movingLeft = false; } if (!movingLeft && !flag2) { movingLeft = true; } CardSlot destination = (movingLeft ? adjacent : adjacent2); bool destinationValid = (movingLeft ? flag : flag2); yield return MoveToSlot(abilityData, movecardinfo, destination, destinationValid, SlotToMove); } public IEnumerator MoveToSlot(AbilityBehaviourData abilityData, moveCards movecardinfo, CardSlot destination, bool destinationValid, CardSlot SlotToMove) { if ((AConfigilData.ConvertArgument(movecardinfo.strafe.flipSigil, abilityData) ?? "true") == "true" && abilityData.ability.HasValue) { ((Card)SlotToMove.Card).RenderInfo.SetAbilityFlipped(abilityData.ability.Value, movingLeft); } ((Card)SlotToMove.Card).RenderInfo.flippedPortrait = movingLeft && ((Card)SlotToMove.Card).Info.flipPortraitForStrafe; ((Card)SlotToMove.Card).RenderCard(); if ((Object)(object)destination != (Object)null && destinationValid) { yield return Singleton.Instance.AssignCardToSlot(SlotToMove.Card, destination, 0.1f, (Action)null, true); yield return (object)new WaitForSeconds(0.25f); } else { ((Card)SlotToMove.Card).Anim.StrongNegationEffect(); yield return (object)new WaitForSeconds(0.15f); } } } [Serializable] public class transformCards { public string runOnCondition; public slotData slot; public string targetCard; public card card; public string noRetainDamage; public static IEnumerator TransformCards(AbilityBehaviourData abilitydata) { foreach (transformCards transformCardsInfo in abilitydata.transformCards) { if (AConfigilData.ConvertArgument(transformCardsInfo.runOnCondition, abilitydata) == "false") { continue; } PlayableCard CardToReplace = null; if (transformCardsInfo.slot == null) { CardToReplace = (PlayableCard)(string.IsNullOrWhiteSpace(transformCardsInfo.targetCard) ? ((object)abilitydata.self) : ((object)(PlayableCard)AConfigilData.ConvertArgumentToType(transformCardsInfo.targetCard, abilitydata, typeof(PlayableCard)))); } else { CardSlot val = slotData.GetSlot(transformCardsInfo.slot, abilitydata); if ((Object)(object)val != (Object)null && (Object)(object)val.Card != (Object)null) { CardToReplace = val.Card; } } if ((Object)(object)CardToReplace != (Object)null) { bool flag = Singleton.Instance.CardsInHand.Contains(CardToReplace); Singleton.Instance.SwitchToView((View)((!flag) ? 4 : 0), false, false); CardInfo val2 = card.getCard(transformCardsInfo.card, abilitydata); yield return CardToReplace.TransformIntoCard(val2, (Action)null, (Action)null); if (AConfigilData.ConvertArgument(transformCardsInfo.noRetainDamage, abilitydata) == "true") { CardToReplace.HealDamage(CardToReplace.Status.damageTaken); } } } } } public enum TriggerType { OnDie, OnResolveOnBoard, OnStruck, OnKill, OnAttack, OnEndOfTurn, OnStartOfTurn, OnDamage, OnHealthLevel, OnCombatStart, OnEnemyCombatStart, OnDetect, OnDraw, OnActivate, OnPreDeath, OnPreKill, OnMove, Passive } [Serializable] public class trigger { public string triggerType; public string activatesForCardsWithCondition; } public static class ConfigilExtensions { public static void Extend(string functionName, FunctionArgs functionArgs, AbilityBehaviourData abilitydata) { if (functionArgs == null) { throw new ArgumentNullException("functionArgs"); } if (functionName == null) { return; } switch (functionName.Length) { case 6: switch (functionName[0]) { case 'R': if (functionName == "Random") { RandomParFunction.Evaluate(functionArgs); } break; case 'S': if (functionName == "SetVar") { SetVarFunction.Evaluate(functionArgs, abilitydata); } break; } break; case 7: switch (functionName[0]) { case 'G': if (functionName == "GetSlot") { GetSlot.Evaluate(functionArgs); } break; case 'A': if (functionName == "Ability") { AbilityFunction.Evaluate(functionArgs); } break; } break; case 5: switch (functionName[2]) { case 'i': if (functionName == "Tribe") { TribeFunction.Evaluate(functionArgs); } break; case 'a': if (functionName == "Trait") { TraitFunction.Evaluate(functionArgs); } break; } break; case 8: switch (functionName[5]) { case 'i': if (functionName == "HasTribe") { HasTribeFunction.Evaluate(functionArgs); } break; case 'a': if (functionName == "HasTrait") { HasTraitFunction.Evaluate(functionArgs); } break; } break; case 12: if (functionName == "ListContains") { ListContains.Evaluate(functionArgs); } break; case 14: if (functionName == "SpecialAbility") { SpecialAbilityFunction.Evaluate(functionArgs); } break; case 10: if (functionName == "HasAbility") { HasAbilityFunction.Evaluate(functionArgs); } break; case 17: if (functionName == "HasSpecialAbility") { HasSpecialAbilityFunction.Evaluate(functionArgs); } break; case 9: case 11: case 13: case 15: case 16: break; } } } internal static class SetVarFunction { internal static void Evaluate(FunctionArgs functionArgs, AbilityBehaviourData abilitydata) { List list = functionArgs.Parameters.Select((Expression x) => x.Evaluate()).ToList(); if (list.Count != 2) { throw new FormatException("SetVar() requires 2 parameters."); } abilitydata.generatedVariables[(string)list[0]] = list[1]; functionArgs.Result = true; } } [Serializable] public class AbilityData { public string name; public string GUID; } [Serializable] [Obsolete] public class CardData { public List fieldsToEdit; public string name; public string displayedName; public string description; public List metaCategories; public string cardComplexity; public string temple; public List tribes; public int baseAttack; public int baseHealth; public bool hideAttackAndHealth; public int bloodCost; public int bonesCost; public int energyCost; public List gemsColour; public List abilities; public List traits; public List specialAbilities; public string specialStatIcon; public List customAbilities; public List customSpecialAbilities; public EvolveData evolution; public string defaultEvolutionName; public TailData tail; public IceCubeData iceCube; public bool flipPortraitForStrafe; public bool onePerDeck; public List appearanceBehaviour; public string texture; public string altTexture; public string titleGraphic; public string pixelTexture; public string animatedPortrait; public string emissionTexture; public List decals; public void GenerateNew() { //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Unknown result type (might be due to invalid IL or missing references) //IL_0196: Unknown result type (might be due to invalid IL or missing references) ErrorUtil.Card = name; ErrorUtil.Message = "{0} - {2} is an invalid value for {1}"; if (baseHealth == 0) { baseHealth = 1; } List list = CDUtils.Assign(metaCategories, "metaCategories", Dicts.MetaCategory); if (abilities != null && (abilities.Count == 0 || abilities[0] == "None")) { abilities = null; } string text = name; string obj = displayedName ?? ""; string text2 = description ?? ""; int num = baseAttack; int num2 = baseHealth; bool flag = hideAttackAndHealth; List obj2 = list ?? new List(); bool flag2 = onePerDeck; bool flag3 = flipPortraitForStrafe; string text3 = defaultEvolutionName; int num3 = bloodCost; int num4 = bonesCost; int num5 = energyCost; List list2 = CDUtils.Assign(gemsColour, "gemsColour", Dicts.GemColour); CardComplexity val = CDUtils.Assign(cardComplexity, "cardComplexity", Dicts.Complexity); CardTemple val2 = CDUtils.Assign(temple, "temple", Dicts.Temple); List list3 = CDUtils.Assign(tribes, "tribes", Dicts.Tribes); List list4 = CDUtils.Assign(abilities, "abilities", Dicts.Abilities); List list5 = CDUtils.Assign(traits, "traits", Dicts.Traits); List list6 = CDUtils.Assign(specialAbilities, "specialAbilities", Dicts.SpecialAbilities); SpecialStatIcon val3 = CDUtils.Assign(specialStatIcon, "specialStatIcon", Dicts.StatIcon); List list7 = CDUtils.Assign(appearanceBehaviour, "appearanceBehaviour", Dicts.AppearanceBehaviour); Texture2D val4 = CDUtils.Assign(texture, "texture"); Texture2D val5 = CDUtils.Assign(altTexture, "altTexture"); Texture2D val6 = CDUtils.Assign(emissionTexture, "emissionTexture"); Texture val7 = (Texture)(object)CDUtils.Assign(titleGraphic, "titleGraphic"); Texture2D val8 = CDUtils.Assign(pixelTexture, "pixelTexture"); List list8 = CDUtils.Assign(decals, "decals"); EvolveIdentifier val9 = IDUtils.GenerateEvolveIdentifier(this); TailIdentifier val10 = IDUtils.GenerateTailIdentifier(this); IceCubeIdentifier val11 = IDUtils.GenerateIceCubeIdentifier(this); NewCard.Add(text, obj, num, num2, obj2, val, val2, text2, flag, num3, num4, num5, list2, val3, list3, list5, list6, list4, IDUtils.GenerateAbilityIdentifiers(customAbilities), IDUtils.GenerateSpecialAbilityIdentifiers(customSpecialAbilities), (EvolveParams)null, text3, (TailParams)null, (IceCubeParams)null, flag3, flag2, list7, val4, val5, val7, val8, val6, (GameObject)null, list8, val9, val11, val10); ErrorUtil.Clear(); } public void Edit() { //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_0115: 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_0169: Unknown result type (might be due to invalid IL or missing references) //IL_0193: Unknown result type (might be due to invalid IL or missing references) //IL_01bd: Unknown result type (might be due to invalid IL or missing references) //IL_01d9: Unknown result type (might be due to invalid IL or missing references) //IL_0203: Unknown result type (might be due to invalid IL or missing references) //IL_022d: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Unknown result type (might be due to invalid IL or missing references) //IL_0282: Unknown result type (might be due to invalid IL or missing references) //IL_02ad: Unknown result type (might be due to invalid IL or missing references) //IL_02d7: Unknown result type (might be due to invalid IL or missing references) //IL_02e6: Unknown result type (might be due to invalid IL or missing references) //IL_0310: Unknown result type (might be due to invalid IL or missing references) //IL_031f: Unknown result type (might be due to invalid IL or missing references) //IL_034a: Unknown result type (might be due to invalid IL or missing references) //IL_0375: Unknown result type (might be due to invalid IL or missing references) //IL_03a0: Unknown result type (might be due to invalid IL or missing references) //IL_03cb: Unknown result type (might be due to invalid IL or missing references) //IL_03f5: Unknown result type (might be due to invalid IL or missing references) //IL_0404: Unknown result type (might be due to invalid IL or missing references) //IL_042f: Unknown result type (might be due to invalid IL or missing references) //IL_0455: Unknown result type (might be due to invalid IL or missing references) //IL_047b: Unknown result type (might be due to invalid IL or missing references) //IL_04a1: Unknown result type (might be due to invalid IL or missing references) //IL_04c7: Unknown result type (might be due to invalid IL or missing references) //IL_04ed: Unknown result type (might be due to invalid IL or missing references) //IL_04f4: Unknown result type (might be due to invalid IL or missing references) ErrorUtil.Card = name; ErrorUtil.Message = "{0} - Can't change {1} to {2}"; CDUtils.CheckValidFields(fieldsToEdit); bool flag = check("customAbilities"); bool flag2 = check("customSpecialAbilities"); bool flag3 = check("evolution"); bool flag4 = check("tail"); bool flag5 = check("iceCube"); string text = name; List obj = (flag ? IDUtils.GenerateAbilityIdentifiers(customAbilities) : null); List obj2 = (flag2 ? IDUtils.GenerateSpecialAbilityIdentifiers(customSpecialAbilities) : null); EvolveIdentifier obj3 = (flag3 ? IDUtils.GenerateEvolveIdentifier(this) : null); TailIdentifier val = (flag4 ? IDUtils.GenerateTailIdentifier(this) : null); new CustomCard(text, obj, obj2, obj3, flag5 ? IDUtils.GenerateIceCubeIdentifier(this) : null, val) { displayedName = (check("displayedName") ? displayedName : null), description = (check("description") ? description : null), baseAttack = (check("baseAttack") ? new int?(baseAttack) : ((int?)null)), baseHealth = (check("baseHealth") ? new int?(baseHealth) : ((int?)null)), hideAttackAndHealth = (check("hideAttackAndHealth") ? new bool?(hideAttackAndHealth) : ((bool?)null)), onePerDeck = (check("onePerDeck") ? new bool?(onePerDeck) : ((bool?)null)), flipPortraitForStrafe = (check("flipPortraitForStrafe") ? new bool?(flipPortraitForStrafe) : ((bool?)null)), defaultEvolutionName = (check("defaultEvolutionName") ? defaultEvolutionName : null), cost = (check("bloodCost") ? new int?(bloodCost) : ((int?)null)), bonesCost = (check("bonesCost") ? new int?(bonesCost) : ((int?)null)), energyCost = (check("energyCost") ? new int?(energyCost) : ((int?)null)), gemsCost = (check("gemsColour") ? CDUtils.Assign(gemsColour, "gemsColour", Dicts.GemColour) : null), metaCategories = (check("metaCategories") ? CDUtils.Assign(metaCategories, "metaCategories", Dicts.MetaCategory) : null), cardComplexity = (check("cardComplexity") ? new CardComplexity?(CDUtils.Assign(cardComplexity, "cardComplexity", Dicts.Complexity)) : ((CardComplexity?)null)), temple = (check("temple") ? new CardTemple?(CDUtils.Assign(temple, "temple", Dicts.Temple)) : ((CardTemple?)null)), tribes = (check("tribes") ? CDUtils.Assign(tribes, "tribes", Dicts.Tribes) : null), abilities = (check("abilities") ? CDUtils.Assign(abilities, "abilities", Dicts.Abilities) : null), traits = (check("traits") ? CDUtils.Assign(traits, "traits", Dicts.Traits) : null), specialAbilities = (check("specialAbilities") ? CDUtils.Assign(specialAbilities, "specialAbilities", Dicts.SpecialAbilities) : null), specialStatIcon = (check("specialStatIcon") ? new SpecialStatIcon?(CDUtils.Assign(specialStatIcon, "specialStatIcon", Dicts.StatIcon)) : ((SpecialStatIcon?)null)), appearanceBehaviour = (check("appearanceBehaviour") ? CDUtils.Assign(appearanceBehaviour, "appearanceBehaviour", Dicts.AppearanceBehaviour) : null), tex = (check("texture") ? CDUtils.Assign(texture, "texture") : null), altTex = (check("altTexture") ? CDUtils.Assign(altTexture, "altTexture") : null), emissionTex = (check("emissionTexture") ? CDUtils.Assign(emissionTexture, "emissionTexture") : null), pixelTex = (check("pixelTexture") ? CDUtils.Assign(pixelTexture, "pixelTexture") : null), titleGraphic = (Texture)(object)(check("titleGraphic") ? CDUtils.Assign(titleGraphic, "titleGraphic") : null), animatedPortrait = null, decals = (check("decals") ? CDUtils.Assign(decals, "decals") : null) }; ErrorUtil.Clear(); bool check(string fieldName) { return fieldsToEdit.Contains(fieldName); } } private static string[] Combine(List normal, List custom) { List list = new List(); if (normal != null) { list.AddRange(normal); } if (custom != null) { list.AddRange(custom.Select((AbilityData x) => x.GUID + "." + x.name)); } return list.ToArray(); } private static string[] Combine(List normal, List custom) { List list = new List(); if (normal != null) { list.AddRange(normal); } if (custom != null) { list.AddRange(custom.Select((SpecialAbilityData x) => x.GUID + "." + x.name)); } return list.ToArray(); } private string GetUpdatedName(string name, List allKnownCards) { if (string.IsNullOrEmpty(name)) { return name; } if (name.Split(new char[1] { '_' }).Length > 1) { return name; } if ((Object)(object)CardExtensions.CardByName((IEnumerable)CardManager.BaseGameCards, name) != (Object)null) { return name; } if (allKnownCards.Exists((CardData c) => c != null && !string.IsNullOrEmpty(c.name) && c.name.Equals(name))) { return "JSON_" + name; } return name; } public CardSerializeInfo ConvertToV2(List allKnownCards) { if (string.IsNullOrEmpty(name)) { Plugin.Log.LogError((object)"I found a JLDR without a name!!"); return null; } Plugin.Log.LogDebug((object)("Converting " + name + " to JLDR2")); CardSerializeInfo cardSerializeInfo = new CardSerializeInfo(); string[] array = name.Split(new char[1] { '_' }); if ((Object)(object)CardExtensions.CardByName((IEnumerable)CardManager.BaseGameCards, name) != (Object)null) { cardSerializeInfo.name = name; } else if (array.Length > 1) { cardSerializeInfo.modPrefix = array[0]; cardSerializeInfo.name = name; } else { cardSerializeInfo.modPrefix = "JSON"; cardSerializeInfo.name = cardSerializeInfo.modPrefix + "_" + name; } cardSerializeInfo.displayedName.Initialize(displayedName); cardSerializeInfo.description.Initialize(description); cardSerializeInfo.metaCategories = metaCategories?.ToArray(); cardSerializeInfo.cardComplexity = cardComplexity; cardSerializeInfo.temple = temple; cardSerializeInfo.tribes = tribes?.ToArray(); List list = fieldsToEdit ?? new List(); if (baseAttack > 0 || list.Exists((string f) => f.Equals("baseAttack", StringComparison.OrdinalIgnoreCase))) { cardSerializeInfo.baseAttack = baseAttack; } if (baseHealth > 0 || list.Exists((string f) => f.Equals("baseHealth", StringComparison.OrdinalIgnoreCase))) { cardSerializeInfo.baseHealth = baseHealth; } if (hideAttackAndHealth || list.Exists((string f) => f.Equals("hideAttackAndHealth", StringComparison.OrdinalIgnoreCase))) { cardSerializeInfo.hideAttackAndHealth = hideAttackAndHealth; } if (bloodCost > 0 || list.Exists((string f) => f.Equals("bloodcost", StringComparison.OrdinalIgnoreCase))) { cardSerializeInfo.bloodCost = bloodCost; } if (bonesCost > 0 || list.Exists((string f) => f.Equals("bonesCost", StringComparison.OrdinalIgnoreCase))) { cardSerializeInfo.bonesCost = bonesCost; } if (bonesCost > 0 || list.Exists((string f) => f.Equals("energyCost", StringComparison.OrdinalIgnoreCase))) { cardSerializeInfo.energyCost = energyCost; } cardSerializeInfo.gemsCost = gemsColour?.ToArray(); cardSerializeInfo.abilities = Combine(abilities, customAbilities); cardSerializeInfo.traits = traits?.ToArray(); cardSerializeInfo.specialAbilities = Combine(specialAbilities, customSpecialAbilities); cardSerializeInfo.specialStatIcon = specialStatIcon; cardSerializeInfo.defaultEvolutionName = GetUpdatedName(defaultEvolutionName, allKnownCards); if (evolution != null) { cardSerializeInfo.evolveIntoName = GetUpdatedName(evolution.name, allKnownCards); cardSerializeInfo.evolveTurns = evolution.turnsToEvolve; } if (tail != null) { cardSerializeInfo.tailName = GetUpdatedName(tail.name, allKnownCards); cardSerializeInfo.tailLostPortrait = tail.tailLostPortrait; } if (iceCube != null) { cardSerializeInfo.iceCubeName = GetUpdatedName(iceCube.creatureWithin, allKnownCards); } if (flipPortraitForStrafe || list.Exists((string f) => f.Equals("flipPortraitForStrafe", StringComparison.OrdinalIgnoreCase))) { cardSerializeInfo.flipPortraitForStrafe = flipPortraitForStrafe; } if (onePerDeck || list.Exists((string f) => f.Equals("onePerDeck", StringComparison.OrdinalIgnoreCase))) { cardSerializeInfo.onePerDeck = onePerDeck; } cardSerializeInfo.appearanceBehaviour = appearanceBehaviour?.ToArray(); cardSerializeInfo.texture = texture; cardSerializeInfo.altTexture = altTexture; cardSerializeInfo.titleGraphic = titleGraphic; cardSerializeInfo.pixelTexture = pixelTexture; cardSerializeInfo.animatedPortrait = animatedPortrait; cardSerializeInfo.emissionTexture = emissionTexture; cardSerializeInfo.decals = decals?.ToArray(); return cardSerializeInfo; } } public class EvolveData { public string name; public int turnsToEvolve; } public class IceCubeData { public string creatureWithin; } [Serializable] public class SpecialAbilityData { public string name; public string GUID; } public class TailData { public string name; public string tailLostPortrait; } [Serializable] public class EncounterData { public class EncounterInfo { public string name; public int? minDifficulty; public int? maxDifficulty; public List regions; public List dominantTribes; public List randomReplacementCards; public List redundantAbilities; public List turns; } public class TurnInfo { public List cardInfo; } public class TurnCardInfo { public string card; public int? randomReplaceChance; public int? difficultyReq; public string difficultyReplacement; } public static void Process(EncounterBlueprintData encounter, EncounterInfo encounterInfo, bool toEncounter, string path) { //IL_017c: Unknown result type (might be due to invalid IL or missing references) //IL_0183: Expected O, but got Unknown ImportExportUtils.SetDebugPath(path); ImportExportUtils.SetID(toEncounter ? encounterInfo.name : ((Object)encounter).name); ImportExportUtils.ApplyProperty(() => ((Object)encounter).name, delegate(string a) { ((Object)encounter).name = a; }, ref encounterInfo.name, toEncounter, "Encounters", "name"); ImportExportUtils.ApplyValue(ref encounter.minDifficulty, ref encounterInfo.minDifficulty, toEncounter, "Encounters", "minDifficulty"); ImportExportUtils.ApplyValue(ref encounter.maxDifficulty, ref encounterInfo.maxDifficulty, toEncounter, "Encounters", "maxDifficulty"); ImportExportUtils.ApplyValue(ref encounter.dominantTribes, ref encounterInfo.dominantTribes, toEncounter, "Encounters", "dominantTribes"); ImportExportUtils.ApplyValue(ref encounter.randomReplacementCards, ref encounterInfo.randomReplacementCards, toEncounter, "Encounters", "randomReplacementCards"); ImportExportUtils.ApplyValue(ref encounter.redundantAbilities, ref encounterInfo.redundantAbilities, toEncounter, "Encounters", "redundantAbilities"); if (toEncounter) { encounter.turns.Clear(); foreach (TurnInfo turn in encounterInfo.turns) { List list = new List(); for (int num = 0; num < turn.cardInfo.Count; num++) { TurnCardInfo turnCardInfo = turn.cardInfo[num]; CardBlueprint val = new CardBlueprint(); ImportExportUtils.ApplyValue(ref val.card, ref turnCardInfo.card, toA: true, "Encounters", $"turn_{num + 1}_card"); if (turnCardInfo.randomReplaceChance.HasValue) { val.randomReplaceChance = turnCardInfo.randomReplaceChance.Value; } if (turnCardInfo.difficultyReplacement != null) { val.difficultyReplace = true; ImportExportUtils.ApplyValue(ref val.replacement, ref turnCardInfo.difficultyReplacement, toA: true, "Encounters", $"turn_{num + 1}_difficultyReplacement"); } if (turnCardInfo.difficultyReq.HasValue) { val.difficultyReq = turnCardInfo.difficultyReq.Value; } list.Add(val); } EncounterExtensions.AddTurn(encounter, list.ToArray()); } } else if (encounter.turns != null) { encounterInfo.turns = new List(); for (int num2 = 0; num2 < encounter.turns.Count; num2++) { List list2 = encounter.turns[num2]; if (list2 == null) { continue; } TurnInfo turnInfo = new TurnInfo(); turnInfo.cardInfo = new List(); for (int num3 = 0; num3 < list2.Count; num3++) { CardBlueprint val2 = list2[num3]; TurnCardInfo turnCardInfo2 = new TurnCardInfo(); turnCardInfo2.randomReplaceChance = val2.randomReplaceChance; turnCardInfo2.difficultyReq = val2.difficultyReq; if ((Object)(object)val2.card != (Object)null) { turnCardInfo2.card = ((Object)val2.card).name; } if ((Object)(object)val2.replacement != (Object)null) { turnCardInfo2.difficultyReplacement = ((Object)val2.replacement).name; } turnInfo.cardInfo.Add(turnCardInfo2); } encounterInfo.turns.Add(turnInfo); } } if (toEncounter) { if (encounterInfo.regions == null) { return; } { foreach (RegionData item in RegionManager.AllRegionsCopy.Where((RegionData x) => encounterInfo.regions.Contains(((Object)x).name)).ToList()) { RegionExtensions.AddEncounters(item, (EncounterBlueprintData[])(object)new EncounterBlueprintData[1] { encounter }); } return; } } RegionData[] source = RegionManager.AllRegionsCopy.FindAll((RegionData a) => (Object)(object)((IEnumerable)a.encounters).FirstOrDefault((Func)((EncounterBlueprintData val3) => ((Object)val3).name == ((Object)encounter).name)) != (Object)null).ToArray(); encounterInfo.regions = source.Select((RegionData a) => ((Object)a).name).ToList(); } public static void LoadAllEncounters(List files) { for (int i = 0; i < files.Count; i++) { string text = files[i]; string text2 = text.Substring(text.LastIndexOf(Path.DirectorySeparatorChar) + 1); if (!text2.ToLower().EndsWith("_encounter.jldr2")) { continue; } files.RemoveAt(i--); ImportExportUtils.SetDebugPath(text); try { EncounterInfo encounterInfo = text.FromFilePath(); EncounterBlueprintData val = GetBluePrint(encounterInfo.name); if ((Object)(object)val == (Object)null) { val = EncounterManager.New(encounterInfo.name, true); Plugin.VerboseLog("Loading new JLDR2 (encounters) " + text2); } else { Plugin.VerboseLog("Loading replacement JLDR2 (encounters) " + text2); } Process(val, encounterInfo, toEncounter: true, text); Plugin.VerboseLog("Loaded JSON encounters from " + text2 + "!"); } catch (Exception ex) { Plugin.Log.LogError((object)("Error loading JLDR2 (encounters) " + text2)); Plugin.Log.LogError((object)ex); } } EncounterManager.SyncEncounterList(); } private static EncounterBlueprintData GetBluePrint(string name) { foreach (EncounterBlueprintData baseGameEncounter in EncounterManager.BaseGameEncounters) { if (((Object)baseGameEncounter).name == name) { return baseGameEncounter; } } foreach (EncounterBlueprintData newEncounter in EncounterManager.NewEncounters) { if (((Object)newEncounter).name == name) { return newEncounter; } } return null; } public static void ExportAllEncounters() { Plugin.Log.LogInfo((object)$"Exporting {EncounterManager.AllEncountersCopy.Count} Encounters to JSON"); foreach (EncounterBlueprintData item in EncounterManager.AllEncountersCopy) { ExportEncounter(item); } } public static void ExportEncounter(EncounterBlueprintData info) { string text = Path.Combine(Plugin.ExportDirectory, "Encounters"); if (!Directory.Exists(text)) { Directory.CreateDirectory(text); } EncounterInfo encounterInfo = new EncounterInfo(); Process(info, encounterInfo, toEncounter: false, text); string contents = JSONParser.ToJSON(encounterInfo); File.WriteAllText(Path.Combine(text, encounterInfo.name + "_encounter.jldr2"), contents); } } [Serializable] public class StarterDeckList { public class StarterDeckInfo { public string name; public string[] cards; public string iconTexture; public int unlockLevel; } public StarterDeckInfo[] decks; public static void LoadAllStarterDecks(List files) { for (int i = 0; i < files.Count; i++) { string text = files[i]; string text2 = text.Substring(text.LastIndexOf(Path.DirectorySeparatorChar) + 1); if (!text2.ToLower().EndsWith("_deck.jldr2")) { continue; } files.RemoveAt(i--); ImportExportUtils.SetDebugPath(text); try { Plugin.VerboseLog("Loading JLDR2 (starter decks) " + text2); StarterDeckList starterDeckList = text.FromFilePath(); StarterDeckInfo[] array = starterDeckList.decks; foreach (StarterDeckInfo starterDeckInfo in array) { StarterDeckManager.New("MADH.inscryption.JSONLoader", starterDeckInfo.name, starterDeckInfo.iconTexture, starterDeckInfo.cards, starterDeckInfo.unlockLevel); } Plugin.VerboseLog("Loaded JSON starter decks " + string.Join(",", starterDeckList.decks.Select((StarterDeckInfo s) => s.name).ToList())); } catch (Exception ex) { Plugin.Log.LogError((object)("Error loading JLDR2 (starter decks) " + text2)); Plugin.Log.LogError((object)ex); } } } public static void Process(FullStarterDeck deckInfo, StarterDeckInfo serializeInfo, bool toDeckInfo, string path) { ImportExportUtils.SetDebugPath(path); ImportExportUtils.SetID(toDeckInfo ? serializeInfo.name : ((Object)deckInfo.Info).name); ImportExportUtils.ApplyProperty(() => ((Object)deckInfo.Info).name, delegate(string a) { ((Object)deckInfo.Info).name = a; }, ref serializeInfo.name, toDeckInfo, "StarterDecks", "name"); ImportExportUtils.ApplyProperty(() => deckInfo.CardNames, delegate(List a) { deckInfo.CardNames = a; }, ref serializeInfo.cards, toDeckInfo, "StarterDecks", "cards"); ImportExportUtils.ApplyValue(ref deckInfo.Info.iconSprite, ref serializeInfo.iconTexture, toDeckInfo, "StarterDecks", "iconTexture"); ImportExportUtils.ApplyProperty(() => deckInfo.UnlockLevel, delegate(int a) { deckInfo.UnlockLevel = a; }, ref serializeInfo.unlockLevel, toDeckInfo, "StarterDecks", "unlockLevel"); } public static void ExportAllStarterDecks() { Plugin.Log.LogInfo((object)$"Exporting {StarterDeckManager.AllDecks.Count} Starter decks"); foreach (FullStarterDeck allDeck in StarterDeckManager.AllDecks) { StarterDeckInfo starterDeckInfo = new StarterDeckInfo(); string path = Path.Combine(Plugin.ExportDirectory, "StarterDecks", ((Object)allDeck.Info).name + "_deck.jldr2"); Process(allDeck, starterDeckInfo, toDeckInfo: false, path); string directoryName = Path.GetDirectoryName(path); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } File.WriteAllText(path, JSONParser.ToJSON(starterDeckInfo)); } } } [Serializable] public class TraitList { public class TraitInfo { public string name; public string guid; } public TraitInfo[] traits; public static void LoadAllTraits(List files) { //IL_0094: Unknown result type (might be due to invalid IL or missing references) for (int i = 0; i < files.Count; i++) { string text = files[i]; string text2 = text.Substring(text.LastIndexOf(Path.DirectorySeparatorChar) + 1); if (!text2.ToLower().EndsWith("_traits.jldr2") && !text2.EndsWith("_trait.jldr2")) { continue; } ImportExportUtils.SetDebugPath(text); files.RemoveAt(i--); try { Plugin.VerboseLog("Loading JLDR2 (traits) " + text2); TraitInfo[] array = text.FromFilePath().traits; foreach (TraitInfo traitInfo in array) { GuidManager.GetEnumValue(traitInfo.guid ?? "MADH.inscryption.JSONLoader", traitInfo.name); } } catch (Exception ex) { Plugin.Log.LogError((object)("Error loading trait from " + text)); Plugin.Log.LogError((object)ex); } } } } [Serializable] public class TribeList { public class TribeInfo { public string name; public string guid; public string tribeIcon; public bool appearInTribeChoices; public string choiceCardBackTexture; } public TribeInfo[] tribes; public static void LoadAllTribes(List files) { //IL_0192: Unknown result type (might be due to invalid IL or missing references) //IL_0154: Unknown result type (might be due to invalid IL or missing references) //IL_0159: Unknown result type (might be due to invalid IL or missing references) for (int i = 0; i < files.Count; i++) { string text = files[i]; string text2 = text.Substring(text.LastIndexOf(Path.DirectorySeparatorChar) + 1); if (!text2.ToLower().EndsWith("_tribe.jldr2") && !text2.EndsWith("_tribes.jldr2")) { continue; } ImportExportUtils.SetDebugPath(text); files.RemoveAt(i--); try { Plugin.VerboseLog("Loading JLDR2 (tribes) " + text2); TribeInfo[] array = text.FromFilePath().tribes; foreach (TribeInfo tribeInfo in array) { Texture2D a = null; Texture2D a2 = null; ImportExportUtils.SetID(tribeInfo.name); ImportExportUtils.ApplyValue(ref a2, ref tribeInfo.tribeIcon, toA: true, "Tribes", "tribeIcon"); if (!string.IsNullOrEmpty(tribeInfo.choiceCardBackTexture)) { Plugin.VerboseLog("Loading " + tribeInfo.name + " back " + tribeInfo.choiceCardBackTexture); ImportExportUtils.ApplyValue(ref a, ref tribeInfo.choiceCardBackTexture, toA: true, "Tribes", "choiceCardBackTexture"); } if ((Object)(object)a == (Object)null) { a = TextureHelper.GetImageAsTexture("default_card_rewardback_blank.png", (FilterMode)0); if ((Object)(object)a2 != (Object)null) { Color32[] pixels = a2.GetPixels32(); for (int k = 0; k < pixels.Length; k++) { if (pixels[k].a >= 1) { a.SetPixel(k % ((Texture)a2).width + 12, k / ((Texture)a2).width + 12, Color32.op_Implicit(pixels[k])); } } a.Apply(false); } } TribeManager.Add(tribeInfo.guid, tribeInfo.name, a2, tribeInfo.appearInTribeChoices, a); } } catch (Exception ex) { Plugin.Log.LogError((object)("Error loading tribe from " + text)); Plugin.Log.LogError((object)ex); } } } public static void ExportAllTribes() { //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004b: 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_0050: Invalid comparison between Unknown and I4 //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Expected O, but got Unknown Plugin.Log.LogInfo((object)$"Exporting {6 + TribeManager.NewTribes.Count} Tribes to JSON"); foreach (Tribe value in Enum.GetValues(typeof(Tribe))) { if (((int)value != 0 && (int)value != 7) || 1 == 0) { TribeInfo val2 = new TribeInfo { name = ((object)value/*cast due to .constrained prefix*/).ToString() }; val2.guid = val2.guid; val2.tribeChoice = true; val2.cardback = ResourceBank.Get("Art/Cards/RewardBacks/card_rewardback_" + ((object)value/*cast due to .constrained prefix*/).ToString().ToLowerInvariant()); val2.icon = ResourceBank.Get("Art/Cards/TribeIcons/tribeicon_" + ((object)value/*cast due to .constrained prefix*/).ToString().ToLowerInvariant()); ExportTribe(val2); } } foreach (TribeInfo newTribe in TribeManager.NewTribes) { ExportTribe(newTribe); } } public static void ExportTribe(TribeInfo info) { string text = Path.Combine(Plugin.ExportDirectory, "Tribes"); if (!Directory.Exists(text)) { Directory.CreateDirectory(text); } TribeInfo tribeInfo = new TribeInfo(); tribeInfo.name = info.name; tribeInfo.guid = info.guid; tribeInfo.appearInTribeChoices = info.tribeChoice; ImportExportUtils.SetID(info.name); ImportExportUtils.ApplyValue(ref info.icon, ref tribeInfo.tribeIcon, toA: false, "Tribes", "tribeIcon"); ImportExportUtils.ApplyValue(ref info.cardback, ref tribeInfo.choiceCardBackTexture, toA: false, "Tribes", "choiceCardBackTexture"); string contents = JSONParser.ToJSON(tribeInfo); File.WriteAllText(Path.Combine(text, tribeInfo.name + "_tribe.jldr2"), contents); } } } namespace JSONLoader.V2Code { [Serializable] public class LanguageData { [Serializable] public class Fonts { public FontReplacementType Type; public string AssetBundlePath; public string FontAssetName; public string TMPFontAssetName; } public string languageName; public string languageCode; public string resetButtonText; public string stringTablePath; public List fontReplacementPaths; private static Dictionary pathToLoadedAssetBundles = new Dictionary(); private static AssetBundle LoadAssetBundle(string path) { if (pathToLoadedAssetBundles.TryGetValue(path, out var value)) { return value; } AssetBundle val = AssetBundle.LoadFromFile(path); if ((Object)(object)val != (Object)null) { pathToLoadedAssetBundles.Add(path, val); } return val; } public static void LoadAllLanguages(List files) { //IL_01f5: Unknown result type (might be due to invalid IL or missing references) //IL_01ab: Unknown result type (might be due to invalid IL or missing references) for (int i = 0; i < files.Count; i++) { string text = files[i]; string text2 = text.Substring(text.LastIndexOf(Path.DirectorySeparatorChar) + 1); if (!text2.ToLower().EndsWith("_language.jldr2")) { continue; } files.RemoveAt(i--); ImportExportUtils.SetDebugPath(text); try { Plugin.VerboseLog("Loading JLDR2 (language) " + text2); LanguageData languageData = text.FromFilePath(); string fullFilePath = languageData.stringTablePath; if (!TryGetFullPath(fullFilePath, out fullFilePath)) { Plugin.Log.LogError((object)("Could not load language. Could not find string table with name " + languageData.stringTablePath + "!")); break; } List list = null; if (languageData.fontReplacementPaths != null) { list = new List(); foreach (Fonts fontReplacementPath in languageData.fontReplacementPaths) { if (!TryGetFullPath(fontReplacementPath.AssetBundlePath, out var fullFilePath2)) { Plugin.Log.LogWarning((object)("Could not load font replacement. Could not find file with name " + fontReplacementPath.AssetBundlePath + "!")); continue; } AssetBundle val = LoadAssetBundle(fullFilePath2); if ((Object)(object)val == (Object)null) { Plugin.Log.LogWarning((object)("Could not load asset bundle at path '" + fullFilePath2 + "'. Skipping font replacement!")); continue; } Font val2 = val.LoadAsset(fontReplacementPath.FontAssetName); if ((Object)(object)val2 == (Object)null) { Plugin.Log.LogWarning((object)("Could not load FontAssetName asset from bundle with name '" + fontReplacementPath.FontAssetName + "'. Skipping font replacement!")); continue; } TMP_FontAsset val3 = val.LoadAsset(fontReplacementPath.TMPFontAssetName); if ((Object)(object)val3 == (Object)null) { Plugin.Log.LogWarning((object)("Could not load TMPFontAssetName asset from bundle with name '" + fontReplacementPath.TMPFontAssetName + "'. Skipping font replacement!")); } else { list.Add(LocalizationManager.GetFontReplacementForFont(fontReplacementPath.Type, val2, val3)); } } } LocalizationManager.NewLanguage("MADH.inscryption.JSONLoader", languageData.languageName, languageData.languageCode, languageData.resetButtonText, fullFilePath, list); Plugin.VerboseLog("Loaded JSON language " + languageData.languageName + " from " + text2 + "!"); } catch (Exception ex) { Plugin.Log.LogError((object)("Error loading language " + text2)); Plugin.Log.LogError((object)ex); } } } private static bool TryGetFullPath(string fileName, out string fullFilePath) { FileInfo[] files = new DirectoryInfo(Paths.PluginPath).GetFiles(fileName, SearchOption.AllDirectories); if (files.Length == 0) { fullFilePath = null; return false; } if (files.Length > 1) { Plugin.Log.LogWarning((object)("More than 1 file with the filename " + fileName + "! Using first one!")); } fullFilePath = files[0].FullName; return true; } public static void ExportAllLanguages() { //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) Plugin.Log.LogInfo((object)$"Exporting {LocalizationManager.AllLanguages.Count} languages."); StringBuilder stringBuilder = new StringBuilder("id"); for (int i = 0; i < LocalizationManager.AllLanguages.Count; i++) { stringBuilder.Append("," + (object)LocalizationManager.AllLanguages[i]); } int count = Localization.Translations.Count; for (int j = 0; j < count; j++) { Translation val = Localization.Translations[j]; stringBuilder.Append("\n" + val.id); for (int k = 0; k < LocalizationManager.AllLanguages.Count; k++) { Language language = LocalizationManager.AllLanguages[k].Language; stringBuilder.Append(","); string value; if ((int)language == 0) { stringBuilder.Append(val.englishString); } else if (val.values.TryGetValue(language, out value)) { stringBuilder.Append(value); } } } string text = Path.Combine(Plugin.ExportDirectory, "Languages"); if (!Directory.Exists(text)) { Directory.CreateDirectory(text); } File.WriteAllText(Path.Combine(text, "localisation_table.csv"), stringBuilder.ToString()); } } [Serializable] public class MaskData { public enum AdditionType { Override, Add, Random } public string maskName; public string texturePath; public string maskType; public string modelType; public string type; public static void LoadAllMasks(List files) { //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_0130: Unknown result type (might be due to invalid IL or missing references) for (int i = 0; i < files.Count; i++) { string text = files[i]; string text2 = text.Substring(text.LastIndexOf(Path.DirectorySeparatorChar) + 1); if (!text2.ToLower().EndsWith("_mask.jldr2")) { continue; } files.RemoveAt(i--); ImportExportUtils.SetDebugPath(text); try { Plugin.VerboseLog("Loading JLDR2 (mask) " + text2); MaskData maskData = text.FromFilePath(); Mask? mask = GetMask(maskData.maskType); if (!mask.HasValue) { continue; } if (!Enum.TryParse(maskData.type, out var result)) { Plugin.Log.LogError((object)$"Could not parse mask {maskData.maskName} type '{result}'!"); continue; } CustomMask val = null; val = (CustomMask)(result switch { AdditionType.Override => MaskManager.Override("MADH.inscryption.JSONLoader", maskData.maskName, mask.Value, maskData.texturePath), AdditionType.Random => MaskManager.AddRandom("MADH.inscryption.JSONLoader", maskData.maskName, mask.Value, maskData.texturePath), _ => MaskManager.Add("MADH.inscryption.JSONLoader", maskData.maskName, maskData.texturePath), }); ModelType? val2 = GetModelType(maskData.modelType); if (val2.HasValue) { val.SetModelType(val2.Value); } Plugin.VerboseLog("Loaded JSON mask from " + text2 + "!"); } catch (Exception ex) { Plugin.Log.LogError((object)("Error loading JSON mask from " + text2 + "!")); Plugin.Log.LogError((object)ex); } } } private static ModelType? GetModelType(string modelType) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) if (string.IsNullOrEmpty(modelType)) { return (ModelType)101; } if (Enum.TryParse(modelType, out ModelType result)) { return result; } Plugin.Log.LogWarning((object)("Could not parse mask model type '" + modelType + "'!")); return null; } private static Mask? GetMask(string maskOverrideMask) { //IL_000a: 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) if (Enum.TryParse(maskOverrideMask, out Mask result)) { return result; } foreach (CustomMask customMask in MaskManager.CustomMasks) { if (maskOverrideMask.StartsWith(customMask.GUID) && maskOverrideMask.EndsWith(customMask.Name)) { return customMask.ID; } } Plugin.Log.LogError((object)("Could not parse mask type '" + maskOverrideMask + "'!")); return (Mask)0; } private static bool TryGetFullPath(string fileName, out string fullFilePath) { FileInfo[] files = new DirectoryInfo(Paths.PluginPath).GetFiles(fileName, SearchOption.AllDirectories); if (files.Length == 0) { fullFilePath = null; return false; } if (files.Length > 1) { Plugin.Log.LogWarning((object)("More than 1 file with the filename " + fileName + "! Using first one!")); } fullFilePath = files[0].FullName; return true; } } } namespace JSONLoader.Data { [Serializable] public class GramophoneData { public class GramophoneInfo { public string Prefix; public TrackData[] Tracks; } public class TrackData { public string Track; public float? Volume; } public static void LoadAllGramophone(List files) { for (int i = 0; i < files.Count; i++) { string text = files[i]; string text2 = text.Substring(text.LastIndexOf(Path.DirectorySeparatorChar) + 1); if (!text2.ToLower().EndsWith("_gram.jldr2")) { continue; } files.RemoveAt(i--); ImportExportUtils.SetDebugPath(text); try { Plugin.VerboseLog("Loading JLDR2 (gramophone) " + text2); GramophoneInfo gramophoneInfo = text.FromFilePath(); string text3 = "MADH.inscryption.JSONLoader_" + (gramophoneInfo.Prefix ?? string.Empty); TrackData[] tracks = gramophoneInfo.Tracks; foreach (TrackData trackData in tracks) { if (trackData != null) { GramophoneManager.AddTrack(text3, trackData.Track, trackData.Volume ?? 1f); } } Plugin.VerboseLog("Loaded JSON gramophone tracks from " + text2 + "!"); } catch (Exception ex) { Plugin.Log.LogError((object)("Error loading JLDR2 (graphaphone) " + text2)); Plugin.Log.LogError((object)ex); } } } } } namespace JSONLoader.Data.TalkingCards { internal static class LoadTalkingCards { public static void InitAndLoad(List files) { if (Configs.BetaCompatibility) { string[] array = RenameFiles.RenameAll(); if (array != null) { files.AddRange(array); } } for (int i = 0; i < files.Count; i++) { string text = files[i]; if (text.ToLower().EndsWith("_talk.jldr2")) { files.RemoveAt(i--); LoadTalkJSON(text); } } } private static void LoadTalkJSON(string file) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) LogHelpers.LogInfo("Loading file: " + Path.GetFileName(file)); try { TalkingJSONData talkingJSONData = file.FromFilePath(); if (talkingJSONData != null) { TalkingCardManager.Create(talkingJSONData.GetFaceData(), GeneratePortrait.DialogueDummy); talkingJSONData.MakeDialogueEvents().ForEach(delegate(DialogueEvent? x) { TalkingCardCreator.AddToDialogueCache(x?.id); }); LogHelpers.LogInfo("Loaded talking card data for card: " + talkingJSONData.cardName + "!"); } } catch (Exception ex) { LogHelpers.LogError("Error loading JSON data from file " + Path.GetFileName(file) + "!"); LogHelpers.LogError(ex.ToString()); } } } internal static class LogHelpers { internal static void LogInfo(string message) { Plugin.VerboseLog(message); } internal static void LogError(string message) { Plugin.VerboseLog(message); } internal static void DebugLog(string message) { Plugin.VerboseLog(message); } } internal static class RenameFiles { private static string[] FindJSON() { return Directory.GetFiles(Paths.PluginPath, "*_talk.json", SearchOption.AllDirectories); } internal static string[] RenameAll() { string[] array = FindJSON(); if (array.Length == 0) { return null; } LogHelpers.LogInfo($"TalkingCards: Found {array.Length} '_talk.json' files."); LogHelpers.LogInfo("Renaming each to end in '_talk.jldr2' instead for compatibility!"); for (int i = 0; i < array.Length; i++) { string text = Rename(array[i]); array[i] = text; } return array; } internal static string Rename(string filePath) { if (!filePath.ToLower().EndsWith("_talk.json")) { return null; } string text = filePath.Substring(0, filePath.Length - ".json".Length) + ".jldr2"; string fileName = Path.GetFileName(filePath); string fileName2 = Path.GetFileName(text); if (!File.Exists(text)) { File.Move(filePath, text); LogHelpers.DebugLog("Renamed file '" + fileName + "' to '" + fileName2 + "' for compatibility."); } else { string directoryName = Path.GetDirectoryName(filePath); LogHelpers.LogError("Couldn't rename file '" + fileName + "' to '" + fileName2 + "' as there's already a file named '" + fileName2 + "' in the '" + directoryName + "' directory."); } return text; } } [Serializable] public class TalkingJSONData { public string cardName { get; set; } public string faceSprite { get; set; } public FaceImages? eyeSprites { get; set; } public FaceImages? mouthSprites { get; set; } public string? emissionSprite { get; set; } public FaceImages? emissionSprites { get; set; } public EmotionImages[]? emotions { get; set; } public FaceInfo? faceInfo { get; set; } public DialogueEventStrings[] dialogueEvents { get; set; } public TalkingJSONData(string cardName, string faceSprite, FaceImages? eyeSprites = null, FaceImages? mouthSprites = null, string? emissionSprite = null, FaceImages? emissionSprites = null, EmotionImages[]? emotions = null, FaceInfo? faceInfo = null, DialogueEventStrings[]? dialogueEvents = null) { this.cardName = cardName; this.faceSprite = faceSprite; this.eyeSprites = eyeSprites; this.mouthSprites = mouthSprites; this.emissionSprite = emissionSprite; this.emissionSprites = emissionSprites; this.emotions = emotions; this.faceInfo = faceInfo; this.dialogueEvents = (DialogueEventStrings[])(((object)dialogueEvents) ?? ((object)new DialogueEventStrings[0])); } public List GetEmotions() { //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Expected O, but got Unknown List list = new List(); EmotionData neutral = new EmotionData("Neutral", faceSprite, eyeSprites?.AsTuple(), mouthSprites?.AsTuple(), (ValueTuple?)((emissionSprite != null) ? ((ValueType)new(string, string)?((emissionSprite, "_"))) : ((ValueType)(emissionSprites?.AsTuple())))); list.Add(neutral); IEnumerable enumerable = emotions?.Select((EmotionImages x) => x.MakeEmotion(neutral)); if (enumerable == null) { return list; } foreach (EmotionData item in enumerable) { if (item != null) { list.Add(item); } } return list; } public FaceData GetFaceData() { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Expected O, but got Unknown return new FaceData(cardName, GetEmotions(), faceInfo); } public List MakeDialogueEvents() { return dialogueEvents.Select((DialogueEventStrings x) => (x == null) ? null : x.CreateEvent(cardName)).ToList(); } } [Serializable] public class FaceImages { public string? open { get; set; } public string? closed { get; set; } public FaceImages(string open, string? closed) { this.open = open; this.closed = closed; } public (string? open, string? closed) AsTuple() { return (open: open, closed: closed); } public FaceAnim GetSprites() { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Expected O, but got Unknown return new FaceAnim(open, closed); } public static implicit operator FaceImages((string open, string closed) x) { return new FaceImages(x.open, x.closed); } } [Serializable] public class EmotionImages { public string emotion { get; set; } public string? faceSprite { get; set; } public FaceImages? eyeSprites { get; set; } public FaceImages? mouthSprites { get; set; } public string? emissionSprite { get; set; } public FaceImages? emissionSprites { get; set; } public EmotionImages(string emotion, string? faceSprite = null, FaceImages? eyeSprites = null, FaceImages? mouthSprites = null, string? emissionSprite = null, FaceImages? emissionSprites = null) { this.emotion = emotion; this.faceSprite = faceSprite; this.eyeSprites = eyeSprites; this.mouthSprites = mouthSprites; this.emissionSprite = emissionSprite; this.emissionSprites = emissionSprites; } public EmotionData? MakeEmotion(EmotionData neutralEmotion) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000c: 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_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Expected O, but got Unknown Emotion val = AssetHelpers.ParseAsEnumValue(emotion); if ((int)val == 0) { return null; } Sprite val2 = AssetHelpers.MakeSprite(faceSprite) ?? neutralEmotion.Face; FaceAnim val3 = (FaceAnim)((eyeSprites != null) ? ((object)eyeSprites.GetSprites()) : ((object)neutralEmotion.Eyes)); FaceAnim val4 = (FaceAnim)((mouthSprites != null) ? ((object)mouthSprites.GetSprites()) : ((object)neutralEmotion.Mouth)); FaceAnim val5 = (FaceAnim)((emissionSprite != null) ? FaceAnim.op_Implicit((AssetHelpers.MakeSprite(emissionSprite), GeneratePortrait.EmptyPortrait)) : ((emissionSprites != null) ? ((object)emissionSprites.GetSprites()) : ((object)neutralEmotion.Emission))); return new EmotionData(val, val2, val3, val4, val5); } } } namespace JSONLoader.API { public static class JSONLoaderAPI { public class ConfigilAction { public string actionName { get; set; } public List fields { get; set; } public Action> functionToCall { get; set; } } public static List customFileExtensionExceptions = new List(); public static List customActionList = new List(); public static event Func, Dictionary> ModifyVariableList; public static void AddAction(ConfigilAction action) { customActionList.Add(action); } public static void AddActions(List actions) { customActionList.AddRange(actions); } public static Dictionary GetModifiedVariableList(Dictionary variables) { if (JSONLoaderAPI.ModifyVariableList == null) { return variables; } return JSONLoaderAPI.ModifyVariableList(variables); } public static void AddCard(string json) { AddCards(json); } public static void AddCards(params string[] json) { foreach (string json2 in json) { try { CardSerializeInfo cardSerializeInfo = json2.FromJson(); ImportExportUtils.SetDebugPath(Environment.StackTrace); cardSerializeInfo.Apply(); Plugin.Log.LogDebug((object)("Added card " + cardSerializeInfo.name + " using JSONLoader API")); } catch (Exception ex) { Plugin.Log.LogError((object)("Failed to add card using JSONLoader API: " + ex.Message)); Plugin.Log.LogError((object)ex); } } } public static void RemoveCard(string json) { RemoveCards(json); } public static void RemoveCards(params string[] json) { foreach (string json2 in json) { try { CardSerializeInfo cardSerializeInfo = json2.FromJson(); cardSerializeInfo.Remove(); Plugin.Log.LogDebug((object)("Removed card " + cardSerializeInfo.name + " using JSONLoader API")); } catch (Exception ex) { Plugin.Log.LogError((object)("Failed to remove card using JSONLoader API: " + ex.Message)); Plugin.Log.LogError((object)ex); } } } public static CardInfo ParseCard(string json) { try { ImportExportUtils.SetDebugPath(Environment.StackTrace); return json.FromJson().ToCardInfo(); } catch (Exception ex) { Plugin.Log.LogError((object)("Failed to parse card using JSONLoader API: " + ex.Message)); Plugin.Log.LogError((object)ex); } return null; } public static List ParseCards(params string[] json) { List list = new List(); foreach (string json2 in json) { list.Add(ParseCard(json2)); } return list; } } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class IgnoresAccessChecksToAttribute : Attribute { public IgnoresAccessChecksToAttribute(string assemblyName) { } } }