using System; using System.Buffers; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Cryptography; using System.Security.Permissions; using System.Text; using System.Threading; using System.Threading.Tasks; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using JetBrains.Annotations; using Jotunn.Managers; using Jotunn.Utils; using Microsoft.CodeAnalysis; using ServerSync; using TMPro; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.Events; using UnityEngine.UI; using YAVSOS.Catalog; using YAVSOS.Classification; using YAVSOS.Cleanup; using YAVSOS.Configuration; using YAVSOS.Core.Catalog; using YAVSOS.Core.Classification; using YAVSOS.Core.Interface; using YAVSOS.Core.Policy; using YAVSOS.Core.Transfers; using YAVSOS.Integrations; using YAVSOS.Interface; using YAVSOS.Networking; using YAVSOS.Sources; using YAVSOS.Transfers; using YAVSOS.Vendor.MultiUserChest; using YAVSOS.Vendor.MultiUserChest.Patches; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("BastionNtB")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright (C) 2026 BastionNtB")] [assembly: AssemblyDescription("Valheim plugin entry point and game adapters for YAVSOS.")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+d5aaa1b9ccbb9dd00e376b293e718c38397c8336")] [assembly: AssemblyProduct("Yet Another Valheim Storage Organization System")] [assembly: AssemblyTitle("YAVSOS")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace YAVSOS { [BepInPlugin("com.bastionntb.yavsos", "Yet Another Valheim Storage Organization System", "1.0.0")] [NetworkCompatibility(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] public sealed class Plugin : BaseUnityPlugin { private ConfigSync sync; private PluginSettings settings; private PolicyHost policy; private Harmony harmony; private ZNet? activeNet; private ZNetPeer? activeServerPeer; private readonly PeerIdentityGate peerGate = new PeerIdentityGate(); private readonly ServerSyncSettingsBridge settingsBridge = new ServerSyncSettingsBridge(); private Action broadcastSettings; private Action publishSettings; private ConfigEntryBase[] sharedEntries; private LoadedCatalogHost catalog; private ClassificationHost classification; private LoadedSourceHost sources; private AssignmentHost assignments; private OptionalEpicLootRegistrationHost? epicLootRegistration; private readonly ClassificationTaxonomy defaultTaxonomy = DefaultClassificationTaxonomy.Create(); private CategoryPolicy? taxonomyPolicy; private ClassificationTaxonomy? policyTaxonomy; private RuleControls? ruleControls; internal static Plugin? Instance { get; private set; } internal ChestRuleStore ChestRules { get; private set; } internal ChestRuleEvaluator RuleEvaluator { get; } = new ChestRuleEvaluator(256, 65536); internal RuleControls? RuleEditor => ruleControls; internal CleanupRunner Cleanup { get; private set; } internal StashRunner Stash { get; private set; } internal RunResults Results { get; } = new RunResults(); internal ChestHighlight Highlight { get; private set; } internal PluginSettings Settings => settings; internal bool IsManagedServer { get { if ((Object)(object)activeNet != (Object)null) { return activeNet.IsServer(); } return false; } } internal bool ServerWithoutYavsos => (int)policy.State.Mode == 2; internal CatalogSnapshot? LoadedCatalog => catalog?.Current; internal ICategoryAnswers? CategoryAnswers => assignments?.Answers; internal bool EpicLootRarityOffered => sources?.EpicLootRarityOffered ?? false; internal OptionalCapabilityState EpicLootState => (OptionalCapabilityState)(((??)sources?.EpicLootState) ?? 0); internal EpicLootRegistrationState EpicLootRegistration => epicLootRegistration?.State ?? EpicLootRegistrationState.Absent; internal string? CategoriesGaveUp { get { object obj = catalog?.GaveUp; if (obj == null) { obj = sources?.GaveUp; if (obj == null) { if (!PolicyFromServer) { return classification?.GaveUp; } obj = null; } } return (string?)obj; } } internal bool PolicyFromServer => (int)policy.State.Mode == 5; internal bool CategoriesRebuilding => assignments?.CategoriesRebuilding ?? false; internal ClassificationTaxonomy RuleTaxonomy { get { CategoryPolicy val = (policy.State.PolicyReady ? policy.State.Effective : null); if (val == null) { return defaultTaxonomy; } if (val != taxonomyPolicy) { taxonomyPolicy = val; policyTaxonomy = defaultTaxonomy.WithPolicy(val); } return policyTaxonomy; } } internal bool ClassificationEvidenceReady { get { AssignmentHost assignmentHost = assignments; if (assignmentHost == null) { return false; } return assignmentHost.Answers.CategoriesReady; } } private void Awake() { //IL_02af: Unknown result type (might be due to invalid IL or missing references) //IL_02b9: Expected O, but got Unknown sync = new ConfigSync("com.bastionntb.yavsos") { DisplayName = "Yet Another Valheim Storage Organization System", CurrentVersion = "1.0.0", MinimumRequiredVersion = "1.0.0", ModRequired = false }; policy = new PolicyHost(sync, Paths.ConfigPath, ((BaseUnityPlugin)this).Logger); catalog = new LoadedCatalogHost(((BaseUnityPlugin)this).Logger); sources = new LoadedSourceHost(((BaseUnityPlugin)this).Logger); classification = new ClassificationHost((Action)((BaseUnityPlugin)this).Logger.LogInfo, (Action)((BaseUnityPlugin)this).Logger.LogWarning, policy.State, (Func)(() => catalog.Current), (ClassificationCache?)null, (Func?)(() => sources.Current), requireSources: true); assignments = new AssignmentHost(sync, policy.State, ((BaseUnityPlugin)this).Logger, () => catalog.Current, () => classification.Current, () => sources.Current); ChestRules = new ChestRuleStore(() => RuleTaxonomy, () => policy.State.PolicyReady); settings = new PluginSettings(((BaseUnityPlugin)this).Config, sync, (Action)policy.State.SharedSettingsChanged); sharedEntries = settings.SharedEntries; Cleanup = new CleanupRunner(settings, ((BaseUnityPlugin)this).Logger, Results); Stash = new StashRunner(settings, ((BaseUnityPlugin)this).Logger, Results); Highlight = new ChestHighlight(((BaseUnityPlugin)this).Logger); ruleControls = new RuleControls(settings.ShowRuleControls, settings.ShowResultPanel, settings.RulePanelOffsetX, settings.RulePanelOffsetY, Cleanup, Stash, Results, Highlight, ((BaseUnityPlugin)this).Logger); MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ConfigSync), "Broadcast", new Type[2] { typeof(long), typeof(ConfigEntryBase[]) }, (Type[])null); if (methodInfo == null || methodInfo.ReturnType != typeof(void)) { throw new NotSupportedException("Pinned ServerSync settings-publication contract is unavailable."); } broadcastSettings = (Action)Delegate.CreateDelegate(typeof(Action), sync, methodInfo); publishSettings = delegate { broadcastSettings(0L, sharedEntries); }; Instance = this; harmony = new Harmony("com.bastionntb.yavsos.policy-lifecycle"); harmony.PatchAll(typeof(NetPolicyPatches)); harmony.PatchAll(typeof(ServerPolicyRpcGuard)); harmony.PatchAll(typeof(ServerPolicyRoutedGuard)); harmony.PatchAll(typeof(ServerSettingsAcceptedPatch)); harmony.PatchAll(typeof(LocalSharedSettingsSavePatch)); PatchView(typeof(CatalogRegistryPatches), "Catalog refresh on ObjectDB.UpdateRegisters"); PatchView(typeof(CleanupConsoleCommand), "The \"yavsos cleanup\" console command"); ContainerRegistry.Initialize(harmony, ((BaseUnityPlugin)this).Logger); ChestLabels.Log = ((BaseUnityPlugin)this).Logger; PatchView(typeof(ChestLabels), "Chest labels"); ItemTooltips.Log = ((BaseUnityPlugin)this).Logger; PatchView(typeof(ItemTooltips), "Item category tooltips"); PatchView(typeof(WhereTooltip), "\"Where would it go?\" in item tooltips"); PatchView(typeof(ItemOrigins), "Base-game item origin"); PatchView(typeof(BaseGameCopy), "Base-game item origin (menu copy)"); epicLootRegistration = new OptionalEpicLootRegistrationHost(InvalidateLoadedCatalog, ((BaseUnityPlugin)this).Logger); AzuAutoStoreIntegration.Initialize(((BaseUnityPlugin)this).Logger); RossItemDrawersIntegration.Initialize(((BaseUnityPlugin)this).Logger); ((BaseUnityPlugin)this).Logger.LogInfo((object)("Yet Another Valheim Storage Organization System 1.0.0 loaded. Policy synchronization enabled; chest rules: " + AzuAutoStoreIntegration.Status)); } private void Start() { MucRoute.Initialize(((BaseUnityPlugin)this).Logger); if (!ServerYavsosProbe.Supported) { ((BaseUnityPlugin)this).Logger.LogWarning((object)"Server detection turned off: the bundled ServerSync changed. On a server without YAVSOS chest rules stay off."); } ruleControls?.Probe(); _ = Highlight.Supported; } private void Update() { long started = UiCost.Start(); UpdateCore(); UiCost.Stop("plugin update", started); } private void UpdateCore() { policy?.Update(Time.unscaledTime); epicLootRegistration?.Update(); OptionalEpicLootRegistrationHost? optionalEpicLootRegistrationHost = epicLootRegistration; if (optionalEpicLootRegistrationHost == null || !optionalEpicLootRegistrationHost.Pending) { catalog?.Update(); } sources?.Update(catalog?.Current); classification?.Update(); assignments?.Update(); if ((Object)(object)activeNet != (Object)null) { NativeInventoryProbe.Update((Action)((BaseUnityPlugin)this).Logger.LogInfo, (Action)((BaseUnityPlugin)this).Logger.LogWarning); } MucRoute.Update(); Cleanup?.Update(); Stash?.Update(); if (Cleanup != null && !Cleanup.Running && CleanupTriggers.Pressed(settings.CleanupShortcut)) { Cleanup.Start(); } else if (Stash != null && !Stash.Running) { StashTriggers.Poll(settings, Stash); } settingsBridge.Publish(IsManagedServer, ConfigSync.ProcessingServerUpdate, publishSettings); } private void PatchView(Type patch, string name) { try { harmony.PatchAll(patch); } catch (Exception ex) when (OptionalFailure.Recoverable(ex)) { ((BaseUnityPlugin)this).Logger.LogWarning((object)(name + " turned off: " + ex.GetType().Name + ": " + ex.Message)); } } private void LateUpdate() { UiCost.Frame(); long started = UiCost.Start(); ruleControls?.LateUpdate(); UiCost.Stop("panel frame", started); } internal void StartWorld(ZNet net) { //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) if (activeNet != net) { activeNet = net; catalog.BeginSession(isActive: true); classification.BeginSession(active: true); sources.BeginSession(isActive: true); assignments.BeginSession(active: true); settingsBridge.BeginSession(); NativeInventoryProbe.BeginSession(); sync.ModRequired = net.IsServer() && !ZNet.IsSinglePlayer; PolicyMode mode = (PolicyMode)((!net.IsServer()) ? 3 : (ZNet.IsSinglePlayer ? 1 : 4)); policy.BeginSession(mode); } } internal void EndWorld(ZNet net) { if (activeNet == net) { activeNet = null; Cleanup?.EndWorld(); Stash?.EndWorld(); Results.Dismiss(); Highlight?.Clear(); catalog.BeginSession(isActive: false); classification.BeginSession(active: false); sources.BeginSession(isActive: false); assignments.BeginSession(active: false); settingsBridge.BeginSession(); activeServerPeer = null; peerGate.Clear(); policy.BeginSession((PolicyMode)0); sync.ModRequired = false; } } internal void StartConnection(ZNet net, ZNetPeer peer) { StartWorld(net); if (!net.IsServer() && activeServerPeer != peer) { activeServerPeer = peer; catalog.BeginSession(isActive: true); classification.BeginSession(active: true); sources.BeginSession(isActive: true); assignments.BeginSession(active: true); peerGate.Replace(peer.m_rpc); policy.BeginSession((PolicyMode)3); } } internal void ServerPeerInfo(ZNet net, ZRpc rpc) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Invalid comparison between Unknown and I4 //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Invalid comparison between Unknown and I4 //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_007c: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Invalid comparison between Unknown and I4 //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Invalid comparison between Unknown and I4 //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) if (activeNet != net || net.IsServer() || activeServerPeer == null || !peerGate.Accepts(rpc)) { return; } if ((int)policy.State.Mode == 5) { ((BaseUnityPlugin)this).Logger.LogInfo((object)"Server has YAVSOS: its category settings already arrived."); } else { if ((int)policy.State.Mode != 3) { return; } bool received; ServerYavsos val = ServerDetection.AtHandshake(ServerYavsosProbe.TryVersionReceived(out received), received, !sync.IsSourceOfTruth); if ((int)val != 1) { if ((int)val == 2) { PolicyLifecycle state = policy.State; PolicyStamp stamp = policy.State.Stamp; if (state.ServerLacksYavsos(((PolicyStamp)(ref stamp)).Session)) { ((BaseUnityPlugin)this).Logger.LogInfo((object)"Server without YAVSOS: this game's own categories and settings apply (D044)."); } } else { ((BaseUnityPlugin)this).Logger.LogWarning((object)"Cannot tell whether the server has YAVSOS (ServerSync changed); chest rules wait for server settings."); } } else { ((BaseUnityPlugin)this).Logger.LogInfo((object)"Server has YAVSOS: waiting for its category settings."); } } } internal void AdvertiseClientVersion(ZNet net, ZNetPeer peer) { if (activeNet == net && activeServerPeer == peer && peerGate.Accepts(peer.m_rpc) && ServerSyncVersionAdvertisement.TrySend(net.IsServer(), sync.ModRequired, "1.0.0", "1.0.0", delegate(string rpcName, byte[] payload) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown peer.m_rpc.Invoke(rpcName, new object[1] { (object)new ZPackage(payload) }); })) { ((BaseUnityPlugin)this).Logger.LogInfo((object)"Advertising YAVSOS version 1.0.0, minimum 1.0.0 to the server; unmanaged-server use remains optional."); } } internal bool IsServerConnection(ZRpc rpc) { if ((Object)(object)activeNet != (Object)null && !activeNet.IsServer()) { return peerGate.Accepts(rpc); } return false; } internal bool IsServerSender(long sender) { if ((Object)(object)activeNet != (Object)null && !activeNet.IsServer() && activeServerPeer != null && activeServerPeer.m_uid != 0L && activeServerPeer.m_uid == sender && policy.IncomingRpc != null) { return peerGate.Accepts(policy.IncomingRpc); } return false; } internal bool IsActiveServerPeer(ZNetPeer peer) { return activeServerPeer == peer; } internal void InvalidateLoadedCatalog() { catalog?.Invalidate(); sources?.Invalidate(); classification?.InvalidateCatalog(); assignments?.Invalidate(); } internal IReadOnlyList InstanceFacets(ItemData? item, ICategoryAnswers answers) { GameObject val = item?.m_dropPrefab; if (item == null || !Object.op_Implicit((Object)(object)val) || answers == null) { return Array.Empty(); } ClassificationResult val2 = null; try { val2 = answers.Resolve(((Object)val).name); if (val2 == null) { return Array.Empty(); } List list = new List(4); if (val2.InstanceRarity) { IReadOnlyList collection; if (sources == null) { IReadOnlyList readOnlyList = (IReadOnlyList)(object)new FacetEvidence[1] { ClassificationFilters.UnreadableRow("rarity") }; collection = readOnlyList; } else { collection = sources.FilterEquipmentRarity(val2, item); } list.AddRange(collection); } SharedData shared = item.m_shared; list.AddRange(ClassificationFilters.Condition(Math.Max(1, item.m_quality), shared?.m_useDurability ?? false, item.m_durability, (shared != null) ? item.GetMaxDurability() : 0f, UpgradeRecipes.Can(((Object)val).name))); FacetEvidence val3 = ClassificationFilters.Crafter(item.m_crafterID); if (val3 != null) { list.Add(val3); } return list; } catch (Exception ex) when (!(ex is OutOfMemoryException)) { IReadOnlyList result; if (val2 != null) { result = ClassificationFilters.UnreadableInstance(val2); } else { IReadOnlyList readOnlyList = Array.Empty(); result = readOnlyList; } return result; } } internal static IReadOnlyList UnreadableFacets(string prefab, ICategoryAnswers answers) { ClassificationResult val = ((answers != null) ? answers.Resolve(prefab) : null); if (val != null) { return ClassificationFilters.UnreadableInstance(val); } return Array.Empty(); } internal IReadOnlyList? InstanceFacetsFor(string payload, string prefab, ItemData? item, ICategoryAnswers answers) { if (RuleEvaluator.UsesInstanceFilters(payload, RuleTaxonomy)) { if (item == null) { return UnreadableFacets(prefab, answers); } return InstanceFacets(item, answers); } return null; } internal ClassificationResult? ResolveCategories(string prefab) { AssignmentHost assignmentHost = assignments; if (assignmentHost == null) { return null; } return assignmentHost.Answers.Resolve(prefab); } internal int CategoryMemberCount(string category) { return assignments?.CategoryMemberCount(category) ?? 0; } internal long? CaptureSettingsUpdate(long sender, ZPackage package) { ZRpc incoming = policy.IncomingRpc; bool currentPeer = (Object)(object)activeNet != (Object)null && incoming != null && activeNet.GetPeers().Any((ZNetPeer peer) => peer.m_uid != 0L && peer.m_uid == sender && peer.m_rpc == incoming); long? result = settingsBridge.CaptureUpdate(IsManagedServer, clientUpdate: true, currentPeer); if (!result.HasValue) { return null; } if (!ServerSyncSettingsBridge.ValidateRequest(package.GetArray(), sharedEntries.Length, settings.SharedType, out string diagnostic)) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Client settings request rejected: " + diagnostic)); return null; } return result; } internal void CompleteSettingsUpdate(long? captured, bool accepted) { settingsBridge.CompleteUpdate(captured, accepted); } internal bool TrySerializeLocalShared(ConfigEntryBase entry, out string serialized) { serialized = ""; if (entry.ConfigFile != ((BaseUnityPlugin)this).Config) { return false; } OwnConfigEntryBase ownConfigEntryBase = entry.Description.Tags.OfType().FirstOrDefault(); if (ownConfigEntryBase != null) { return ServerSyncSettingsBridge.TrySerializeLocal(!sync.IsSourceOfTruth, ownConfigEntryBase.SynchronizedConfig, ownConfigEntryBase.LocalBaseValue, entry.SettingType, (Func)TomlTypeConverter.ConvertToString, out serialized); } return false; } private void OnDestroy() { Instance = null; epicLootRegistration?.Dispose(); policy?.Dispose(); catalog?.Dispose(); classification?.Dispose(); sources?.Dispose(); assignments?.Dispose(); Harmony obj = harmony; if (obj != null) { obj.UnpatchSelf(); } BundledCopy.Deactivate(); } } internal static class NetPolicyPatches { [HarmonyPatch(typeof(ZNet), "Awake")] [HarmonyPostfix] [HarmonyPriority(800)] private static void WorldStarted(ZNet __instance) { Plugin.Instance?.StartWorld(__instance); } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] [HarmonyPrefix] [HarmonyPriority(800)] private static void Reconnecting(ZNet __instance, ZNetPeer peer) { Plugin.Instance?.StartConnection(__instance, peer); } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] [HarmonyPrefix] [HarmonyPriority(0)] private static void AdvertiseVersion(ZNet __instance, ZNetPeer peer) { Plugin.Instance?.AdvertiseClientVersion(__instance, peer); } [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] [HarmonyPostfix] private static void PeerInfo(ZNet __instance, ZRpc rpc) { Plugin.Instance?.ServerPeerInfo(__instance, rpc); } [HarmonyPatch(typeof(ZNet), "Shutdown")] [HarmonyPrefix] private static void WorldStopping(ZNet __instance) { Plugin.Instance?.EndWorld(__instance); } [HarmonyPatch(typeof(ZNet), "OnDestroy")] [HarmonyPrefix] private static void WorldDestroyed(ZNet __instance) { Plugin.Instance?.EndWorld(__instance); } [HarmonyPatch(typeof(ZNet), "Disconnect")] [HarmonyPrefix] private static void PeerDisconnected(ZNet __instance, ZNetPeer peer) { if (!__instance.IsServer()) { Plugin? instance = Plugin.Instance; if (instance != null && instance.IsActiveServerPeer(peer)) { Plugin.Instance.EndWorld(__instance); } } } } [HarmonyPatch(typeof(ConfigSync), "RPC_FromServerConfigSync")] internal static class ServerPolicyRpcGuard { [HarmonyPrefix] private static bool FromCurrentServer(ConfigSync __instance, ZRpc rpc) { if (!(__instance.Name != "com.bastionntb.yavsos")) { return Plugin.Instance?.IsServerConnection(rpc) ?? false; } return true; } } [HarmonyPatch(typeof(ConfigSync), "RPC_FromOtherClientConfigSync")] internal static class ServerPolicyRoutedGuard { [HarmonyPrefix] private static bool FromCurrentSession(ConfigSync __instance, long sender) { if (!(__instance.Name != "com.bastionntb.yavsos")) { Plugin? instance = Plugin.Instance; if (instance == null || !instance.IsManagedServer) { return Plugin.Instance?.IsServerSender(sender) ?? false; } } return true; } } [HarmonyPatch(typeof(ConfigSync), "HandleConfigSyncRPC")] internal static class ServerSettingsAcceptedPatch { [HarmonyPrefix] private static bool Before(ConfigSync __instance, long sender, ZPackage package, bool clientUpdate, out long? __state) { __state = null; if (!(__instance.Name != "com.bastionntb.yavsos") && clientUpdate) { Plugin? instance = Plugin.Instance; if (instance != null && instance.IsManagedServer) { __state = Plugin.Instance.CaptureSettingsUpdate(sender, package); return __state.HasValue; } } return true; } [HarmonyPostfix] private static void After(ConfigSync __instance, bool __result, long? __state) { if (__instance.Name == "com.bastionntb.yavsos") { Plugin.Instance?.CompleteSettingsUpdate(__state, __result); } } } [HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")] internal static class LocalSharedSettingsSavePatch { [HarmonyPrefix] [HarmonyPriority(800)] private static bool PreserveLocal(ConfigEntryBase __instance, ref string __result) { Plugin instance = Plugin.Instance; if ((Object)(object)instance == (Object)null || !instance.TrySerializeLocalShared(__instance, out string serialized)) { return true; } __result = serialized; return false; } } } namespace YAVSOS.Transfers { internal enum RuleEligibility { Eligible, Missing, Tombstone, ItemDrawer, NotPlayerBuilt, OnCharacter } internal sealed class ChestRuleResult { internal TransferRefusal Reason { get; } internal string Message { get; } internal ContainerPolicyRead? Policy { get; } internal bool Succeeded => (int)Reason == 0; internal ChestRuleResult(TransferRefusal reason, string message, ContainerPolicyRead? policy = null) { //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) Reason = reason; Message = message; Policy = policy; } } internal sealed class ChestRuleStore { private const string RossDrawerType = "DrawerComponent"; private static readonly FieldRef? ViewField; private static readonly Func? CheckAccess; private readonly Func taxonomy; private readonly Func policyReady; internal const string CleanupOptOutKey = "com.bastionntb.yavsos.cleanup-optout"; internal static string BindingFailure { get; } static ChestRuleStore() { BindingFailure = ""; try { ViewField = AccessTools.FieldRefAccess("m_nview"); CheckAccess = AccessTools.MethodDelegate>(AccessTools.DeclaredMethod(typeof(Container), "CheckAccess", new Type[1] { typeof(long) }, (Type[])null) ?? throw new MissingMethodException("Container", "CheckAccess"), (object)null, true); } catch (Exception ex) { ViewField = null; CheckAccess = null; BindingFailure = "Chest rules unavailable: " + ex.GetType().Name; } } internal static ZNetView? View(Container container) { if (!Object.op_Implicit((Object)(object)container) || ViewField == null) { return null; } return ViewField.Invoke(container); } internal ChestRuleStore(Func taxonomy, Func policyReady) { this.taxonomy = taxonomy ?? throw new ArgumentNullException("taxonomy"); this.policyReady = policyReady ?? throw new ArgumentNullException("policyReady"); } internal static RuleEligibility Eligibility(Container? container) { if (Object.op_Implicit((Object)(object)container) && IsRossDrawer(container)) { return RuleEligibility.ItemDrawer; } ZNetView val = View(container); if (!Object.op_Implicit((Object)(object)val) || !val.IsValid() || val.GetZDO() == null || container.GetInventory() == null) { return RuleEligibility.Missing; } if (Object.op_Implicit((Object)(object)((Component)container).GetComponentInParent())) { return RuleEligibility.Tombstone; } Character componentInParent = ((Component)container).GetComponentInParent(); if (Object.op_Implicit((Object)(object)componentInParent) && (Object)(object)componentInParent != (Object)(object)Player.m_localPlayer) { return RuleEligibility.OnCharacter; } if (val.GetZDO().GetLong(ZDOVars.s_creator, 0L) == 0L) { return RuleEligibility.NotPlayerBuilt; } return RuleEligibility.Eligible; } internal static bool IsRossDrawer(Container container) { Type type = ((object)container).GetType(); while (type != null && type != typeof(Container)) { if (type.Name == "DrawerComponent") { return true; } type = type.BaseType; } return false; } internal static string Describe(RuleEligibility eligibility) { return eligibility switch { RuleEligibility.Eligible => "", RuleEligibility.Tombstone => "Tombstones cannot have YAVSOS rules.", RuleEligibility.ItemDrawer => "Item drawers use their own item assignment instead of a YAVSOS rule.", RuleEligibility.NotPlayerBuilt => "Only player-built containers can have YAVSOS rules.", RuleEligibility.OnCharacter => "Containers carried by a creature cannot have YAVSOS rules.", _ => "This container is not available.", }; } internal ChestRuleResult Read(Container container) { RuleEligibility ruleEligibility = Eligibility(container); if (ruleEligibility != RuleEligibility.Eligible) { return new ChestRuleResult((TransferRefusal)4, Describe(ruleEligibility)); } string text = Payload(container); return new ChestRuleResult((TransferRefusal)0, "", ContainerPolicyEnvelope.Read(text, taxonomy())); } internal static string Payload(Container container) { ZNetView? obj = View(container); object obj2; if (obj == null) { obj2 = null; } else { ZDO zDO = obj.GetZDO(); obj2 = ((zDO != null) ? zDO.GetString("com.bastionntb.yavsos.container-policy", "") : null); } if (obj2 == null) { obj2 = ""; } return (string)obj2; } internal static bool CleanupOptOut(Container container) { ZNetView? obj = View(container); if (obj == null) { return false; } ZDO zDO = obj.GetZDO(); return ((zDO != null) ? new bool?(zDO.GetBool("com.bastionntb.yavsos.cleanup-optout", false)) : ((bool?)null)) == true; } internal static bool HasAccess(Container container, Player player) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) if (CheckAccess != null && CheckAccess(container, player.GetPlayerID())) { if (container.m_checkGuardStone) { return PrivateArea.CheckAccess(((Component)container).transform.position, 0f, false, false); } return true; } return false; } internal ChestRuleResult TrySetCleanupOptOut(Container container, bool optOut) { RuleEligibility ruleEligibility = Eligibility(container); if (ruleEligibility != RuleEligibility.Eligible) { return new ChestRuleResult((TransferRefusal)4, Describe(ruleEligibility)); } Player localPlayer = Player.m_localPlayer; if (!Object.op_Implicit((Object)(object)localPlayer) || ((Character)localPlayer).IsDead()) { return new ChestRuleResult((TransferRefusal)11, "No local player."); } ZNetView val = View(container); if (!val.IsOwner()) { return new ChestRuleResult((TransferRefusal)3, "Another player is using this chest. Change it after they close it."); } if (!HasAccess(container, localPlayer)) { return new ChestRuleResult((TransferRefusal)1, "You do not have access to this chest."); } val.GetZDO().Set("com.bastionntb.yavsos.cleanup-optout", optOut); if (CleanupOptOut(container) != optOut) { return new ChestRuleResult((TransferRefusal)14, "The setting could not be confirmed. Reopen the chest to check it."); } return new ChestRuleResult((TransferRefusal)0, optOut ? "Cleanup leaves this container alone." : "Cleanup may take misplaced items out of this container."); } internal ChestRuleResult TryEdit(Container container, string expectedPayload, ChestRuleEdit? edit) { //IL_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Invalid comparison between Unknown and I4 //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_0111: 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_0115: Unknown result type (might be due to invalid IL or missing references) if (expectedPayload == null) { throw new ArgumentNullException("expectedPayload"); } RuleEligibility ruleEligibility = Eligibility(container); if (ruleEligibility != RuleEligibility.Eligible) { return new ChestRuleResult((TransferRefusal)4, Describe(ruleEligibility)); } if (!policyReady()) { return new ChestRuleResult((TransferRefusal)4, "YAVSOS is still loading its settings. Try again shortly."); } Player localPlayer = Player.m_localPlayer; if (!Object.op_Implicit((Object)(object)localPlayer) || ((Character)localPlayer).IsDead()) { return new ChestRuleResult((TransferRefusal)11, "No local player."); } ZNetView val = View(container); ZDO zDO = val.GetZDO(); if (!val.IsOwner()) { return new ChestRuleResult((TransferRefusal)3, "Another player is using this chest. Edit its rule after they close it."); } if (!CheckAccess(container, localPlayer.GetPlayerID()) || (container.m_checkGuardStone && !PrivateArea.CheckAccess(((Component)container).transform.position, 0f, true, false))) { return new ChestRuleResult((TransferRefusal)1, "You do not have access to this chest."); } string text = zDO.GetString("com.bastionntb.yavsos.container-policy", ""); ClassificationTaxonomy val2 = taxonomy(); string text2 = default(string); TransferRefusal val3 = ContainerPolicyEnvelope.TryEdit(text, expectedPayload, val2, edit, ref text2); if ((int)val3 == 6) { return new ChestRuleResult(val3, "The rule changed since you opened it. Reopen it and try again.", ContainerPolicyEnvelope.Read(text, val2)); } if ((int)val3 != 0) { return new ChestRuleResult(val3, "This chest has a rule from a different YAVSOS version or category set; it was left unchanged.", ContainerPolicyEnvelope.Read(text, val2)); } zDO.Set("com.bastionntb.yavsos.container-policy", text2); string text3 = zDO.GetString("com.bastionntb.yavsos.container-policy", ""); if (!val.IsOwner() || !StringComparer.Ordinal.Equals(text3, text2)) { return new ChestRuleResult((TransferRefusal)14, "The rule could not be confirmed. Reopen the chest to check it.", ContainerPolicyEnvelope.Read(text3, val2)); } return new ChestRuleResult((TransferRefusal)0, (text2.Length == 0) ? "Rule cleared." : "Rule saved.", ContainerPolicyEnvelope.Read(text3, val2)); } } internal sealed class GameInventorySnapshotAdapter : IDisposable { private sealed class InventoryBinding { internal readonly Guid Generation = Guid.NewGuid(); internal readonly Dictionary Handles = new Dictionary(); internal ulong Epoch; internal string LastPayload = ""; } internal const string NativeAdapter = "valheim-item-110-exact-1"; private readonly Dictionary bindings = new Dictionary(); private readonly List mergeClasses = new List(); private readonly int threadId = Environment.CurrentManagedThreadId; private bool disposed; private static readonly UTF8Encoding StrictUtf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); private const float DurabilitySaveStep = 0.011f; internal GameInventoryCapture Capture(Inventory inventory, string inventoryId, long owner, ushort ownerRevision, Func registration, Func protectedItem, IEnumerable protectedCells, Func capabilityCurrent, bool keepUncapturable = false) { //IL_0429: Unknown result type (might be due to invalid IL or missing references) //IL_0430: Expected O, but got Unknown //IL_04b0: Unknown result type (might be due to invalid IL or missing references) //IL_04c0: Expected O, but got Unknown //IL_04bb: Unknown result type (might be due to invalid IL or missing references) //IL_04db: Expected O, but got Unknown //IL_03a1: Unknown result type (might be due to invalid IL or missing references) //IL_03ab: Expected O, but got Unknown CheckThread(); if (!capabilityCurrent() || !NativeInventoryProbe.Supported || inventory == null || ((object)inventory).GetType() != typeof(Inventory)) { throw new NotSupportedException("The native inventory capability is unavailable."); } int width = inventory.GetWidth(); int height = inventory.GetHeight(); if (width < 1 || height < 1 || width > 256 || height > 256) { throw new NotSupportedException("Inventory layout cannot round-trip through the native format."); } List allItems = inventory.GetAllItems(); if (allItems.Count > 65535 || allItems.Count > width * height) { throw new InvalidDataException("Inventory occupancy is unsupported."); } HashSet hashSet = new HashSet(); foreach (int protectedCell in protectedCells) { if (protectedCell < 0 || protectedCell >= width * height || (hashSet.Count >= width * height && !hashSet.Contains(protectedCell))) { throw new InvalidDataException("Protected cell is outside the native grid."); } hashSet.Add(protectedCell); } if (!bindings.TryGetValue(inventory, out InventoryBinding value)) { if (bindings.Count >= 257) { throw new InvalidOperationException("Run inventory binding limit reached."); } value = new InventoryBinding(); bindings.Add(inventory, value); } HashSet seen = new HashSet(); List list = new List(allItems.Count); List list2 = new List(); long num = 6L; bool flag = default(bool); foreach (ItemData item in allItems) { if (item == null || !seen.Add(item)) { throw new InvalidDataException("Duplicate live item reference."); } if (!value.Handles.TryGetValue(item, out var value2)) { value.Handles.Add(item, value2 = Guid.NewGuid()); } TransferItemIdentity val; try { num += PreflightBytes(item); if (num > 1048576) { throw new InvalidDataException("Native inventory preimage exceeds its bound."); } val = Preflighted(item, registration(item)); VerifyNativeRoundtrip(item, val); } catch (Exception ex) when (((Func)delegate { // Could not convert BlockContainer to single expression flag = keepUncapturable; if (flag) { flag = ((ex is NotSupportedException || ex is InvalidDataException || ex is ArgumentException) ? true : false); } return flag && num <= 1048576; }).Invoke()) { Guid handle = value2; int isProtected; if (!item.m_equipped) { SharedData shared = item.m_shared; if (shared == null || !shared.m_questItem) { isProtected = (protectedItem(item) ? 1 : 0); goto IL_0292; } } isProtected = 1; goto IL_0292; IL_0292: list.Add(Uncapturable(item, handle, width, height, (byte)isProtected != 0)); list2.Add((Object.op_Implicit((Object)(object)item.m_dropPrefab) ? ((Object)item.m_dropPrefab).name : (item.m_shared?.m_name ?? "unknown item")) + " at (" + item.m_gridPos.x + "," + item.m_gridPos.y + ") (" + ex.Message.TrimEnd('.') + ")"); continue; } list.Add(new TransferStack(value2, item.m_gridPos.x, item.m_gridPos.y, item.m_stack, item.m_shared.m_maxStackSize, val, item.m_equipped || item.m_shared.m_questItem || protectedItem(item), true, MergeClass(item))); } ItemData[] array = value.Handles.Keys.Where((ItemData item) => !seen.Contains(item)).ToArray(); foreach (ItemData key in array) { value.Handles.Remove(key); } ZPackage val2 = new ZPackage(); inventory.Save(val2); byte[] array2 = val2.GetArray(); if (array2.Length > 1048576) { throw new InvalidDataException("Native inventory preimage exceeds its bound."); } string text = Hash(array2); if (value.LastPayload != text) { if (value.Epoch == ulong.MaxValue) { throw new InvalidOperationException("Inventory epoch exhausted."); } value.Epoch++; value.LastPayload = text; } TransferInventorySnapshot val3 = new TransferInventorySnapshot(new TransferInventoryStamp(inventoryId, value.Generation, value.Epoch, 0uL, owner, ownerRevision, text), width, height, (IEnumerable)list, (IEnumerable)hashSet); if (!capabilityCurrent()) { throw new NotSupportedException("Inventory capability changed during capture."); } return new GameInventoryCapture(val3, list2); } private static TransferStack Uncapturable(ItemData item, Guid handle, int width, int height, bool isProtected) { //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Expected O, but got Unknown //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_00fc: Expected O, but got Unknown int x = item.m_gridPos.x; int y = item.m_gridPos.y; if (x < 0 || y < 0 || x >= width || y >= height) { throw new NotSupportedException("An unreadable item is outside the inventory grid."); } int num = Math.Max(1, Math.Min(item.m_stack, 65535)); int num2 = Math.Max(num, Math.Min(item.m_shared?.m_maxStackSize ?? 1, 65535)); string text = (Object.op_Implicit((Object)(object)item.m_dropPrefab) ? ((Object)item.m_dropPrefab).name : "unknown"); int length = text.Length; TransferItemIdentity val = new TransferItemIdentity((length > 0 && length <= 256) ? text : "unknown", "uncapturable:" + handle.ToString("N"), 1, 0, 0, 0f, 0L, "", false, false, (IEnumerable>)Array.Empty>(), "valheim-item-110-exact-1", Array.Empty()); return new TransferStack(handle, x, y, num, num2, val, isProtected, false, (string)null); } private string? MergeClass(ItemData item) { if (item.m_shared.m_maxStackSize <= 1) { return null; } for (int i = 0; i < mergeClasses.Count; i++) { if (mergeClasses[i].IsSameType(item) && item.IsSameType(mergeClasses[i])) { return "c" + i; } } if (mergeClasses.Count >= 4096) { return null; } mergeClasses.Add(item.Clone()); return "c" + (mergeClasses.Count - 1); } internal bool TryResolve(Inventory inventory, Guid instanceGeneration, Guid handle, out ItemData? item) { CheckThread(); item = null; if (!bindings.TryGetValue(inventory, out InventoryBinding value) || value.Generation != instanceGeneration) { return false; } foreach (KeyValuePair handle2 in value.Handles) { if (handle2.Value == handle && inventory.ContainsItem(handle2.Key)) { item = handle2.Key; return true; } } return false; } internal bool TryItem(Inventory inventory, Guid handle, out ItemData? item) { CheckThread(); item = null; if (bindings.TryGetValue(inventory, out InventoryBinding value)) { return TryResolve(inventory, value.Generation, handle, out item); } return false; } internal bool TryHandle(Inventory inventory, ItemData item, out Guid handle) { CheckThread(); handle = Guid.Empty; if (item != null && bindings.TryGetValue(inventory, out InventoryBinding value)) { return value.Handles.TryGetValue(item, out handle); } return false; } internal static TransferItemIdentity Identity(ItemData item, string? registration) { PreflightBytes(item); return Preflighted(item, registration); } private static TransferItemIdentity Preflighted(ItemData item, string? registration) { //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Expected O, but got Unknown if (string.IsNullOrEmpty(registration) || !Object.op_Implicit((Object)(object)item.m_dropPrefab)) { throw new NotSupportedException("Item registration is not currently verified."); } return new TransferItemIdentity(((Object)item.m_dropPrefab).name, registration, item.m_quality, item.m_variant, item.m_worldLevel, item.m_durability, item.m_crafterID, item.m_crafterName, item.m_pickedUp, item.m_cheated, (IEnumerable>)item.m_customData, "valheim-item-110-exact-1", Array.Empty()); } private static long PreflightBytes(ItemData item) { if (item == null || ((object)item).GetType() != typeof(ItemData) || item.m_shared == null || item.m_stack < 1 || item.m_stack > 65535 || item.m_stack > item.m_shared.m_maxStackSize || item.m_shared.m_maxStackSize < 1 || item.m_shared.m_maxStackSize > 65535 || item.m_quality < 1 || item.m_quality > 65535 || item.m_variant < 0 || item.m_worldLevel < 0 || item.m_worldLevel > 255 || item.m_gridPos.x < 0 || item.m_gridPos.x > 255 || item.m_gridPos.y < 0 || item.m_gridPos.y > 255 || float.IsNaN(item.m_durability) || float.IsInfinity(item.m_durability) || item.m_durability < 0f || (double)item.m_durability * 100.0 > 2147483647.0 || item.m_customData == null || item.m_customData.Count > 2048) { throw new NotSupportedException("Item state cannot be represented by the native adapter."); } long num = 128 + TextBytes(item.m_crafterName, 16384); foreach (KeyValuePair customDatum in item.m_customData) { num += 10 + TextBytes(customDatum.Key, 16384) + TextBytes(customDatum.Value, 65536); } if (num > 1048576) { throw new InvalidDataException("Item metadata exceeds its bound."); } return num; } private static int TextBytes(string value, int maximum) { if (value == null || value.Length > maximum) { throw new InvalidDataException("Invalid native item text."); } int byteCount = StrictUtf8.GetByteCount(value); if (byteCount > maximum) { throw new InvalidDataException("Native item text exceeds its bound."); } return byteCount; } internal static void VerifyItem(ItemData item, string registration) { VerifyNativeRoundtrip(item, Identity(item, registration)); } private static void VerifyNativeRoundtrip(ItemData item, TransferItemIdentity identity) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Expected O, but got Unknown //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) ZPackage val = new ZPackage(); item.Save(val); byte[] array = val.GetArray(); if (array.Length > 1048576) { throw new InvalidDataException("Item payload exceeds its bound."); } ZPackage val2 = new ZPackage(array); var (num, val3) = ItemData.Load(val2, (Item)110); if (val2.GetPos() != array.Length || num != StringExtensionMethods.GetStableHashCode(((Object)item.m_dropPrefab).name)) { throw new InvalidDataException("Native item identity did not round-trip."); } val3.m_dropPrefab = item.m_dropPrefab; val3.m_shared = item.m_shared; if (Math.Abs(val3.m_durability - item.m_durability) > 0.011f) { throw new NotSupportedException("Native save changes item durability; this exact-state adapter refuses it."); } val3.m_durability = item.m_durability; if (val3.m_stack != item.m_stack || val3.m_gridPos != item.m_gridPos || val3.m_equipped != item.m_equipped || !identity.Equals(Preflighted(val3, identity.Registration))) { throw new NotSupportedException("Native save normalizes item state; this exact-state adapter refuses it."); } } private static string Hash(byte[] bytes) { using SHA256 sHA = SHA256.Create(); return BitConverter.ToString(sHA.ComputeHash(bytes)).Replace("-", "").ToLowerInvariant(); } private void CheckThread() { if (disposed) { throw new ObjectDisposedException("GameInventorySnapshotAdapter"); } if (Environment.CurrentManagedThreadId != threadId) { throw new InvalidOperationException("Game-thread capture required."); } } public void Dispose() { CheckThread(); bindings.Clear(); mergeClasses.Clear(); disposed = true; } } internal sealed class GameInventoryCapture { internal TransferInventorySnapshot Snapshot { get; } internal IReadOnlyList Uncapturable { get; } internal GameInventoryCapture(TransferInventorySnapshot snapshot, IReadOnlyList? uncapturable = null) { Snapshot = snapshot; Uncapturable = uncapturable ?? Array.Empty(); } } internal static class NativeInventoryProbe { internal const string Registration = "yavsos-native-probe"; private const string ProbeKey = "com.bastionntb.yavsos.native-probe"; private static bool ran; internal static bool Supported { get; private set; } internal static bool Checked => ran; internal static string Status { get; private set; } = "inventory reader not checked yet"; internal static void BeginSession() { ran = false; Supported = false; Status = "inventory reader not checked yet"; } internal static bool Update(Action info, Action warning) { if (ran || !Object.op_Implicit((Object)(object)ObjectDB.instance) || ObjectDB.instance.m_items == null || ObjectDB.instance.m_items.Count == 0 || !Object.op_Implicit((Object)(object)ZNetScene.instance)) { return false; } ran = true; try { string text = Check(); Supported = true; Status = "inventory reader verified: " + text; info(Status); } catch (Exception ex) when ((!(ex is OutOfMemoryException) && !(ex is StackOverflowException)) || 1 == 0) { Supported = false; Status = "inventory reader unavailable (" + ex.GetType().Name + ": " + ex.Message + "); cleanup is disabled, everything else works"; warning(Status); } return true; } private static string Check() { //IL_00f8: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Expected O, but got Unknown //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Expected O, but got Unknown //IL_012f: Unknown result type (might be due to invalid IL or missing references) //IL_0135: Expected O, but got Unknown //IL_0135: Unknown result type (might be due to invalid IL or missing references) List source = ObjectDB.instance.m_items.Where((GameObject x) => Object.op_Implicit((Object)(object)x) && Object.op_Implicit((Object)(object)x.GetComponent())).OrderBy((GameObject x) => ((Object)x).name, StringComparer.Ordinal).ToList(); GameObject val = ((IEnumerable)source).FirstOrDefault((Func)((GameObject x) => Shared(x).m_maxStackSize > 2)) ?? throw new InvalidOperationException("no stackable sample item"); GameObject val2 = ((IEnumerable)source).FirstOrDefault((Func)((GameObject x) => Shared(x).m_maxStackSize == 1 && Shared(x).m_useDurability && Shared(x).m_maxQuality > 1)) ?? ((IEnumerable)source).FirstOrDefault((Func)((GameObject x) => Shared(x).m_maxStackSize == 1)) ?? throw new InvalidOperationException("no single-stack sample item"); Inventory val3 = new Inventory("YAVSOS probe", (Sprite)null, 4, 2); Place(val3, Sample(val, Math.Min(Shared(val).m_maxStackSize - 1, 7), rich: false), 0, 0); Place(val3, Sample(val2, 1, rich: true), 2, 1); ZPackage val4 = new ZPackage(); val3.Save(val4); byte[] array = val4.GetArray(); NativeTransferInventoryCodec.Validate(array, 4, 2, (Func)Limits); byte[] resaved; Inventory val5 = RoundTrip(array, 4, 2, out resaved); List allItems = val3.GetAllItems(); SortedSet sortedSet = new SortedSet(StringComparer.Ordinal); foreach (ItemData item in allItems) { GameInventorySnapshotAdapter.VerifyItem(item, "yavsos-native-probe"); ItemData val6 = Copy(val5, item); foreach (string item2 in val6.m_customData.Keys.Where((string x) => !item.m_customData.ContainsKey(x))) { sortedSet.Add(item2); } ItemData obj = val6.Clone(); obj.m_customData = val6.m_customData.Where((KeyValuePair x) => item.m_customData.ContainsKey(x.Key)).ToDictionary((KeyValuePair x) => x.Key, (KeyValuePair x) => x.Value); if (!GameInventorySnapshotAdapter.Identity(obj, "yavsos-native-probe").Equals(GameInventorySnapshotAdapter.Identity(item, "yavsos-native-probe"))) { throw new InvalidOperationException(((Object)item.m_dropPrefab).name + " did not round-trip exactly"); } } if (sortedSet.Count == 0 && !resaved.SequenceEqual(array)) { throw new InvalidOperationException("re-saved bytes differ"); } NativeTransferInventoryCodec.Validate(resaved, 4, 2, (Func)Limits); byte[] resaved2; Inventory loaded = RoundTrip(resaved, 4, 2, out resaved2); if (!resaved2.SequenceEqual(resaved)) { throw new InvalidOperationException("re-saved bytes keep changing"); } foreach (ItemData allItem in val5.GetAllItems()) { if (!GameInventorySnapshotAdapter.Identity(Copy(loaded, allItem), "yavsos-native-probe").Equals(GameInventorySnapshotAdapter.Identity(allItem, "yavsos-native-probe"))) { throw new InvalidOperationException(((Object)allItem.m_dropPrefab).name + " keeps changing on load"); } } string text = ((sortedSet.Count == 0) ? "" : ("; another mod adds on load: " + string.Join(", ", sortedSet))); return $"{((Object)val).name} x{allItems[0].m_stack} and {((Object)val2).name} q{allItems[1].m_quality} round-trip exactly ({array.Length} bytes){text}"; } private static Inventory RoundTrip(byte[] bytes, int width, int height, out byte[] resaved) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Expected O, but got Unknown //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Expected O, but got Unknown //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected O, but got Unknown Inventory val = new Inventory("YAVSOS probe copy", (Sprite)null, width, height); val.Load(new ZPackage(bytes)); ZPackage val2 = new ZPackage(); val.Save(val2); resaved = val2.GetArray(); return val; } private static ItemData Copy(Inventory loaded, ItemData item) { ItemData val = loaded.GetItemAt(item.m_gridPos.x, item.m_gridPos.y) ?? throw new InvalidOperationException("item cell changed"); if (val.m_stack != item.m_stack || val.m_equipped != item.m_equipped || !Object.op_Implicit((Object)(object)val.m_dropPrefab) || loaded.GetAllItems().Count != 2) { throw new InvalidOperationException(((Object)item.m_dropPrefab).name + " did not round-trip exactly"); } return val; } private static SharedData Shared(GameObject prefab) { return prefab.GetComponent().m_itemData.m_shared; } private static ItemData Sample(GameObject prefab, int stack, bool rich) { ItemData val = prefab.GetComponent().m_itemData.Clone(); val.m_dropPrefab = prefab; val.m_stack = stack; val.m_equipped = false; val.m_quality = ((!rich) ? 1 : Math.Min(2, val.m_shared.m_maxQuality)); val.m_variant = ((rich && val.m_shared.m_variants > 1) ? 1 : 0); val.m_durability = (val.m_shared.m_useDurability ? Mathf.Floor(val.GetMaxDurability() / 2f) : val.m_durability); val.m_worldLevel = (rich ? 1 : 0); val.m_pickedUp = rich; val.m_crafterID = (rich ? 4242424242u : 0); val.m_crafterName = (rich ? "YAVSOS probe ✓" : ""); val.m_customData = (rich ? new Dictionary { ["com.bastionntb.yavsos.native-probe"] = "{\"text\":\"ü\\n\",\"n\":3}", ["com.bastionntb.yavsos.native-probe.empty"] = "" } : new Dictionary()); return val; } private static void Place(Inventory inventory, ItemData item, int x, int y) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) if (!inventory.AddItem(item, new Vector2i(x, y)) || inventory.GetItemAt(x, y) != item) { throw new InvalidOperationException("could not place " + ((Object)item.m_dropPrefab).name); } } private static NativeTransferPrefabLimits? Limits(int hash) { //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Expected O, but got Unknown GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(hash); ItemData val = ((!Object.op_Implicit((Object)(object)itemPrefab)) ? null : itemPrefab.GetComponent()?.m_itemData); if (val?.m_shared != null) { return new NativeTransferPrefabLimits(val.m_shared.m_maxStackSize, val.m_shared.m_maxQuality, val.m_shared.m_variants); } return null; } } } namespace YAVSOS.Sources { internal static class LoadedProducerReaders { private const int MaxNestedEntries = 256; internal static IEnumerable Read(GameObject prefab, string id, bool active, Action check) { check(); if (!Object.op_Implicit((Object)(object)prefab)) { throw new InvalidDataException("Null/destroyed loaded producer definition."); } Trader component = prefab.GetComponent(); Incinerator incinerator = prefab.GetComponent(); WispSpawner lure = prefab.GetComponent(); SapCollector collector = prefab.GetComponent(); Procreation breeding = prefab.GetComponent(); if (Object.op_Implicit((Object)(object)component)) { foreach (LoadedSourceFact item in Purchases(component, id, active, check)) { yield return item; } } if (Object.op_Implicit((Object)(object)incinerator)) { foreach (LoadedSourceFact item2 in Exchanges(incinerator, id, active, check)) { yield return item2; } } if (Object.op_Implicit((Object)(object)lure)) { foreach (LoadedSourceFact item3 in Wisps(lure, id, active, check)) { yield return item3; } } if (Object.op_Implicit((Object)(object)collector)) { foreach (LoadedSourceFact item4 in Sap(collector, id, active, check)) { yield return item4; } } if (Object.op_Implicit((Object)(object)breeding)) { foreach (LoadedSourceFact item5 in Breeding(breeding, id, active, check)) { yield return item5; } } check(); } private static IEnumerable Purchases(Trader trader, string id, bool active, Action check) { Alive((Component)(object)trader, check); List entries = trader.m_items; if (entries == null) { yield return Coverage(id + ":trade", "gap: missing trader stock list; store faults"); yield break; } if (entries.Count > 256) { throw new MalformedDefinitionException("Trader stock bound exceeded."); } int count = entries.Count; for (int i = 0; i < count; i++) { CheckStock(); TradeItem val = entries[i]; string id2 = id + ":trade:" + i; if (val == null) { throw new MalformedDefinitionException("Null trader stock entry."); } string text = "price=" + val.m_price + "; currency=StoreGui.m_coinPrefab (client store UI; not read, no currency biome); worldKey=" + Clean(val.m_requiredGlobalKey) + " (recorded, ignored for origin); playerBuyKey=" + Clean(val.m_buyKey) + "; playerIncrementKey=" + Clean(val.m_incrementKey); if (!Object.op_Implicit((Object)(object)val.m_prefab)) { yield return Coverage(id2, (string.IsNullOrEmpty(val.m_buyKey) ? "gap: missing purchase item; " : "player-key purchase without inventory output; ") + text); continue; } SharedData val2 = val.m_prefab.m_itemData?.m_shared; int num = ((val2 != null) ? LoadedProducerSemantics.PurchaseAmount(val.m_stack, val2.m_maxStackSize, val.m_price) : 0); ObjectDB instance = ObjectDB.instance; GameObject val3 = (Object.op_Implicit((Object)(object)instance) ? instance.GetItemPrefab(((Object)val.m_prefab).name) : null); string name = ((Object.op_Implicit((Object)(object)val3) && Object.op_Implicit((Object)(object)val3.GetComponent())) ? ((Object)val3).name : ""); yield return Acquisition(id2, name, id, "purchase", text + "; stack=" + val.m_stack + " capped by maxStack=" + (val2?.m_maxStackSize ?? 0), num, active && ((Behaviour)trader).enabled && num > 0); } CheckStock(); void CheckStock() { check(); if (!Object.op_Implicit((Object)(object)trader) || trader.m_items != entries || entries.Count != count) { throw new InvalidDataException("Trader stock changed during capture."); } } } private static IEnumerable Exchanges(Incinerator machine, string id, bool active, Action check) { Alive((Component)(object)machine, check); string root = id + ":incinerate"; List conversions = machine.m_conversions; bool flag = Object.op_Implicit((Object)(object)machine.m_incinerateSwitch) && Object.op_Implicit((Object)(object)machine.m_container) && Object.op_Implicit((Object)(object)machine.m_lightingAOEs) && Object.op_Implicit((Object)(object)machine.m_leverAnim) && Object.op_Implicit((Object)(object)((Component)machine).GetComponent()); bool usable = active && ((Behaviour)machine).enabled && flag && conversions != null; if (!flag) { yield return Coverage(root + ":wiring", "gap: missing switch/container/effect/lever/view reference; incineration faults"); } if (conversions == null) { yield return Coverage(root, "gap: missing conversion list; Awake sort faults"); } else if (conversions.Count > 256) { throw new MalformedDefinitionException("Incinerator conversion bound exceeded."); } int count = conversions?.Count ?? 0; (IncineratorConversion? Entry, List? Inputs, int Count)[] tracked = new(IncineratorConversion, List, int)[count]; IncineratorConversionShape?[] shapes = (IncineratorConversionShape?[])(object)new IncineratorConversionShape[count]; bool safe = usable; long total = 0L; for (int c = 0; c < count; c++) { CheckMachine(c); IncineratorConversion val = conversions[c]; if (val == null) { tracked[c] = (Entry: null, Inputs: null, Count: 0); safe = false; yield return Coverage(root + ":" + c, "gap: null conversion; Awake sort faults"); continue; } List requirements = val.m_requirements; tracked[c] = (Entry: val, Inputs: requirements, Count: requirements?.Count ?? 0); total += tracked[c].Count; if (requirements == null || total > 256) { safe = false; yield return null; continue; } bool flag2 = Object.op_Implicit((Object)(object)val.m_result); List> list = new List>(requirements.Count); foreach (Requirement item in requirements) { SharedData val2 = ((item == null || !Object.op_Implicit((Object)(object)item.m_resItem)) ? null : item.m_resItem.m_itemData?.m_shared); if (val2 == null || string.IsNullOrEmpty(val2.m_name) || item.m_amount <= 0) { flag2 = false; } else { list.Add(new KeyValuePair(val2.m_name, item.m_amount)); } } shapes[c] = ((!flag2) ? ((IncineratorConversionShape)null) : new IncineratorConversionShape(val.m_priority, val.m_requireOnlyOneIngredient, (IEnumerable>)list)); safe &= flag2 && shapes[c].Safe; yield return null; } if (total > 256) { yield return Coverage(root + ":bound", "gap: more than " + 256 + " total requirements; reachability unsupported"); } else if (usable && !safe) { yield return Coverage(root + ":unsafe", "gap: a conversion can fault or discard items (null/non-positive/empty AND); every conversion unsupported"); } IncineratorConversionShape[] ready = (safe ? Array.ConvertAll(shapes, (IncineratorConversionShape x) => x) : null); for (int c = 0; c < count; c++) { CheckMachine(count); IncineratorConversion entry; List inputs; int n; (entry, inputs, n) = tracked[c]; if (entry == null) { continue; } string route = root + ":" + c; string output = Name(Object.op_Implicit((Object)(object)entry.m_result) ? ((Component)entry.m_result).gameObject : null); if (output.Length == 0) { yield return Coverage(route, "gap: missing/unresolved incinerator result"); continue; } bool basis = ready != null && entry.m_resultAmount > 0; string detail = "priority=" + entry.m_priority + " (descending; equal order unspecified); mode=" + (entry.m_requireOnlyOneIngredient ? "one-of" : "all") + "; resultAmount=" + entry.m_resultAmount + "; inputs match shared item names; aggregate default result separate"; bool any = false; if (n > 256) { yield return Coverage(route + ":inputs", "gap: single conversion exceeds requirement bound; no input scan"); yield return Acquisition(route + ":acquire", output, id, "exchange", detail, entry.m_resultAmount, eligible: false); continue; } if (inputs == null || n == 0) { yield return Coverage(route + ":inputs", "gap: no requirement inputs"); } else if (!entry.m_requireOnlyOneIngredient) { bool reachable = basis && LoadedProducerSemantics.IncineratorAlternativeReachable((IReadOnlyList)ready, c, -1); for (int r = 0; r < n; r++) { CheckMachine(count); yield return Exchange(route + ":" + r, output, inputs[r], route, detail, reachable); } if (basis && !reachable) { yield return Coverage(route + ":shadow", "gap: an equal/higher-priority conversion may consume the minimal inputs"); } any = reachable; } else { for (int r = 0; r < n; r++) { CheckMachine(count); string alternative = route + ":alt:" + r; bool reachable = basis && LoadedProducerSemantics.IncineratorAlternativeReachable((IReadOnlyList)ready, c, r); yield return Exchange(alternative, output, inputs[r], alternative, detail, reachable); if (basis && !reachable) { yield return Coverage(alternative + ":shadow", "gap: an equal/higher-priority conversion may consume the minimal input"); } any = any || reachable; } } CheckMachine(count); yield return Acquisition(route + ":acquire", output, id, "exchange", detail, entry.m_resultAmount, any); yield return null; } CheckMachine(count); if (Object.op_Implicit((Object)(object)machine.m_defaultResult)) { yield return Acquisition(root + ":default", Name(((Component)machine.m_defaultResult).gameObject), id, "exchange", "aggregate residue: one result per " + machine.m_defaultCost + " remaining units after conversions; no input recipe", 1, usable && safe && machine.m_defaultCost > 0); yield return Coverage(root + ":default-domain", "gap: aggregate residue input domain is not a material route"); } void CheckMachine(int read) { check(); if (!Object.op_Implicit((Object)(object)machine) || machine.m_conversions != conversions || (conversions?.Count ?? 0) != count) { throw new InvalidDataException("Incinerator conversions changed during capture."); } for (int i = 0; i < read; i++) { (IncineratorConversion, List, int) tuple2 = tracked[i]; if (conversions[i] != tuple2.Item1 || (tuple2.Item1 != null && (tuple2.Item1.m_requirements != tuple2.Item2 || (tuple2.Item2?.Count ?? 0) != tuple2.Item3))) { throw new InvalidDataException("Incinerator requirements changed during capture."); } } } } private static LoadedSourceFact Exchange(string id, string output, Requirement? input, string route, string detail, bool eligible) { //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Expected O, but got Unknown string text = ((input != null && Object.op_Implicit((Object)(object)input.m_resItem)) ? Item(((Component)input.m_resItem).gameObject) : ""); return new LoadedSourceFact((LoadedSourceFactKind)0, id, output, (text.Length == 0) ? Missing(id) : text, route, "exchange", detail, input?.m_amount ?? 1, eligible); } private static IEnumerable Wisps(WispSpawner lure, string id, bool active, Action check) { Alive((Component)(object)lure, check); string row = id + ":wisp"; GameObject wispPrefab = lure.m_wispPrefab; string text = "night=" + lure.m_onlySpawnAtNight + "; maxCover=" + F(lure.m_maxCover) + "; chance=" + F(lure.m_spawnChance) + "; maxSpawned=" + lure.m_maxSpawned + "; interval=" + F(lure.m_spawnInterval) + "; lured wisp must be picked; no biome gate in definition"; GameObject val = null; int num = 0; bool flag = false; if (Object.op_Implicit((Object)(object)wispPrefab)) { Pickable component = wispPrefab.GetComponent(); ItemDrop component2 = wispPrefab.GetComponent(); if (Object.op_Implicit((Object)(object)component) && Object.op_Implicit((Object)(object)component.m_itemPrefab)) { val = component.m_itemPrefab; num = component.m_amount; flag = !component.m_defaultPicked || (((Behaviour)component).enabled && component.m_respawnTimeMinutes > 0f && component.m_spawnCheck == null); } else if (Object.op_Implicit((Object)(object)component2) && !Object.op_Implicit((Object)(object)wispPrefab.GetComponent())) { val = wispPrefab; num = component2.m_itemData?.m_stack ?? 0; flag = true; } } if (!Object.op_Implicit((Object)(object)val)) { yield return Coverage(row, "gap: lure output is not a root Pickable/ItemDrop; " + text); yield break; } yield return Acquisition(row, Name(val), id, "production", text, num, active && ((Behaviour)lure).enabled && flag && num > 0 && FinitePositive(lure.m_spawnChance) && lure.m_maxSpawned > 0 && Object.op_Implicit((Object)(object)lure.m_spawnPoint) && Object.op_Implicit((Object)(object)lure.m_coverPoint)); yield return Coverage(row + ":origin", "gap: no environment source; lure site, build cost and night are conditions, not natural origin"); } private static IEnumerable Sap(SapCollector collector, string id, bool active, Action check) { Alive((Component)(object)collector, check); string row = id + ":sap"; string text = "overlapping ResourceRoot with level>1 (any root; mustConnectTo=" + Clean(Object.op_Implicit((Object)(object)collector.m_mustConnectTo) ? ((Object)collector.m_mustConnectTo).name : null) + " is a non-null gate); secPerUnit=" + F(collector.m_secPerUnit) + "; maxLevel=" + collector.m_maxLevel + "; one scaled item per stored level"; if (!Object.op_Implicit((Object)(object)collector.m_spawnItem)) { yield return Coverage(row, "gap: missing sap output; " + text); yield break; } yield return Acquisition(row, Name(((Component)collector.m_spawnItem).gameObject), id, "production", text, 1, active && ((Behaviour)collector).enabled && Object.op_Implicit((Object)(object)collector.m_mustConnectTo) && Object.op_Implicit((Object)(object)collector.m_spawnPoint) && collector.m_maxLevel > 0 && FinitePositive(collector.m_secPerUnit)); yield return Coverage(row + ":origin", "natural ResourceRoot origin must be established independently by rooted world traversal; any overlapping root, not mustConnectTo identity; collector site/cost is not origin"); } private static IEnumerable Breeding(Procreation breeding, string id, bool active, Action check) { Alive((Component)(object)breeding, check); GameObject gameObject = ((Component)breeding).gameObject; string text = id + ":breed"; Tameable component = gameObject.GetComponent(); Character component2 = gameObject.GetComponent(); MonsterAI component3 = gameObject.GetComponent(); int num = ((Object.op_Implicit((Object)(object)component3) && component3.m_consumeItems != null) ? component3.m_consumeItems.Count : 0); bool flag = !Object.op_Implicit((Object)(object)component2) || num > 0; bool flag2 = Object.op_Implicit((Object)(object)component) && (component.m_startsTamed || (Object.op_Implicit((Object)(object)component3) && Object.op_Implicit((Object)(object)component2) && num > 0)); ZNetScene instance = ZNetScene.instance; GameObject val = ((Object.op_Implicit((Object)(object)breeding.m_offspring) && Object.op_Implicit((Object)(object)instance)) ? instance.GetPrefab(Utils.GetPrefabName(((Object)breeding.m_offspring).name)) : null); GameObject seperatePartner = breeding.m_seperatePartner; GameObject noPartnerOffspring = breeding.m_noPartnerOffspring; bool flag3 = Object.op_Implicit((Object)(object)seperatePartner); GameObject val2 = ((Object.op_Implicit((Object)(object)seperatePartner) && Object.op_Implicit((Object)(object)instance)) ? instance.GetPrefab(Utils.GetPrefabName(((Object)seperatePartner).name)) : null); bool flag4 = !flag3 || (Object.op_Implicit((Object)(object)val2) && ((Object)val2).name == ((Object)seperatePartner).name && CanBeReadyPartner(val2)); bool flag5 = Object.op_Implicit((Object)(object)val) && ((Object)val).name == ((Object)gameObject).name; bool flag6 = Object.op_Implicit((Object)(object)val) && flag3 && ((Object)val).name == ((Object)seperatePartner).name; bool flag7 = active && ((Behaviour)breeding).enabled && flag2 && flag && Object.op_Implicit((Object)(object)val) && LoadedProducerSemantics.ProcreationInitiates(breeding.m_pregnancyChance) && LoadedProducerSemantics.ProcreationCompletes(breeding.m_pregnancyDuration); string text2 = "parent=" + Clean(((Object)gameObject).name) + "; tamed (startsTamed=" + (Object.op_Implicit((Object)(object)component) && component.m_startsTamed) + "); fed by " + num + " MonsterAI foods; not alerted; initiation needs Random.value>" + F(breeding.m_pregnancyChance) + "; population<" + breeding.m_maxCreatures + " within " + F(breeding.m_totalCheckRange) + "; partner=" + (flag3 ? (Clean(((Object)seperatePartner).name) + " x1") : "same prefab x2 including parent") + " ready within " + F(breeding.m_partnerCheckRange) + "; lovePoints=" + breeding.m_requiredLovePoints + "; duration=" + F(breeding.m_pregnancyDuration) + "s; no biome/environment gate; origin anchor is the parent's natural source"; List list = new List(4); if (!Object.op_Implicit((Object)(object)breeding.m_offspring)) { list.Add(Coverage(text + ":registration", "gap: missing offspring; Procreate faults")); } else { if (!Object.op_Implicit((Object)(object)val)) { list.Add(Coverage(text + ":registration", "gap: offspring is not a registered prefab; Procreate faults")); } list.Add(Offspring(text, Object.op_Implicit((Object)(object)val) ? val : breeding.m_offspring, id, text2 + (Object.op_Implicit((Object)(object)noPartnerOffspring) ? "; partner present at birth" : "; partner present at initiation"), flag7 && flag4 && LoadedProducerSemantics.ProcreationCapacity(breeding.m_maxCreatures, !Object.op_Implicit((Object)(object)noPartnerOffspring), flag3, flag5, flag6))); } if (Object.op_Implicit((Object)(object)noPartnerOffspring)) { list.Add(Offspring(text + ":alone", noPartnerOffspring, id, text2 + "; no partner present at birth", flag7 && LoadedProducerSemantics.ProcreationCapacity(breeding.m_maxCreatures, false, flag3, flag5, flag6))); } list.Add(Coverage(text + ":origin", "gap: breeding needs an external parent anchor; parent natural-source join unsupported; no biome")); foreach (LoadedSourceFact item in list) { yield return item; } } private static bool CanBeReadyPartner(GameObject partner) { Procreation component = partner.GetComponent(); Tameable component2 = partner.GetComponent(); Character component3 = partner.GetComponent(); MonsterAI component4 = partner.GetComponent(); bool flag = Object.op_Implicit((Object)(object)component4) && component4.m_consumeItems != null && component4.m_consumeItems.Count > 0; if (Object.op_Implicit((Object)(object)component) && ((Behaviour)component).enabled && Object.op_Implicit((Object)(object)component2) && (!Object.op_Implicit((Object)(object)component3) || flag)) { if (!component2.m_startsTamed) { return Object.op_Implicit((Object)(object)component4) && Object.op_Implicit((Object)(object)component3) && flag; } return true; } return false; } private static LoadedSourceFact Offspring(string id, GameObject output, string producer, string conditions, bool eligible) { if (!Object.op_Implicit((Object)(object)output.GetComponent())) { return Acquisition(id, Name(output), producer, "breeding", conditions, 1, eligible); } return Coverage(id, "creature offspring " + Clean(((Object)output).name) + " is not an inventory item; growth/drops unsupported here; " + conditions); } private static LoadedSourceFact Acquisition(string id, string name, string producer, string method, string detail, int amount, bool eligible) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Expected O, but got Unknown if (name.Length != 0) { return new LoadedSourceFact((LoadedSourceFactKind)4, id, name, "", producer, method, detail, amount, eligible && amount > 0); } return Coverage(id, "gap: unresolved " + method + " inventory output; " + detail); } private static string Name(GameObject? output) { if (!Object.op_Implicit((Object)(object)output)) { return ""; } return Item(output); } private static string Item(GameObject prefab) { ItemDrop component = prefab.GetComponent(); if (!Object.op_Implicit((Object)(object)component)) { return ""; } GameObject val = component.m_itemData?.m_dropPrefab; ObjectDB instance = ObjectDB.instance; if (!Object.op_Implicit((Object)(object)instance)) { return ""; } GameObject val2 = (Object.op_Implicit((Object)(object)val) ? instance.GetItemPrefab(((Object)val).name) : null); if (!Object.op_Implicit((Object)(object)val2)) { val2 = instance.GetItemPrefab(((Object)prefab).name); } if (!Object.op_Implicit((Object)(object)val2)) { string text = LoadedSourceSemantics.CloneBaseName(((Object)prefab).name); if (text != null) { val2 = instance.GetItemPrefab(text); } } if (!Object.op_Implicit((Object)(object)val2) || !Object.op_Implicit((Object)(object)val2.GetComponent())) { return ""; } return ((Object)val2).name; } private static string Clean(string? value) { if (string.IsNullOrEmpty(value)) { return "none"; } StringBuilder stringBuilder = new StringBuilder(Math.Min(value.Length, 128)); foreach (char c in value) { if (stringBuilder.Length == 128) { break; } stringBuilder.Append((char.IsControl(c) || char.IsSurrogate(c)) ? '?' : c); } return stringBuilder.ToString(); } private static void Alive(Component component, Action check) { check(); if (!Object.op_Implicit((Object)(object)component)) { throw new InvalidDataException("Loaded producer destroyed during capture."); } } private static LoadedSourceFact Coverage(string id, string detail) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Expected O, but got Unknown return new LoadedSourceFact((LoadedSourceFactKind)1, id, "", "", "", "", detail, 1, true); } private static string Missing(string id) { return "yavsos:missing-source:" + id; } private static string F(float value) { return value.ToString("R", CultureInfo.InvariantCulture); } private static bool FinitePositive(float value) { if (value > 0f && !float.IsNaN(value)) { return !float.IsInfinity(value); } return false; } } internal sealed class LoadedSourceHost : IDisposable { private const int MaxRoots = 32768; private const int MaxNestedEntries = 256; private readonly LoadedSourceCache cache; private ObjectDB? ordinaryDb; private readonly OptionalDefinitionWork optionalWork = new OptionalDefinitionWork(); private readonly ManualLogSource log; private readonly Func?> open; private ZNetScene? scene; private List? prefabs; private StoreGui? store; private ItemDrop? currency; private int prefabCount; private CatalogSnapshot? catalog; private OptionalIntegrations? optional; private bool active; private LoadedSourceState reported; private int reportedRetries; private string reportedOff = ""; private readonly HashSet malformedReported = new HashSet(StringComparer.Ordinal); internal ClassificationSourceSnapshot? Current { get { LoadedSourceReceipt current = cache.Current; if (current == null) { return null; } return current.Snapshot; } } internal LoadedSourceReceipt? Receipt => cache.Current; internal long Revision => cache.Revision; internal bool EpicLootRarityOffered { get { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Invalid comparison between Unknown and I4 if (optional != null) { return (int)optional.EpicLoot.State == 1; } return false; } } internal OptionalCapabilityState EpicLootState { get { //IL_0011: Unknown result type (might be due to invalid IL or missing references) OptionalIntegrations? optionalIntegrations = optional; if (optionalIntegrations == null) { return (OptionalCapabilityState)0; } return optionalIntegrations.EpicLoot.State; } } internal string? GaveUp { get { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Invalid comparison between Unknown and I4 if (!active || (int)cache.State != 5) { return null; } return cache.Diagnostic; } } internal LoadedSourceHost(ManualLogSource log) { //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Expected O, but got Unknown //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Expected O, but got Unknown this.log = log; LoadedSourceLimits limits = new LoadedSourceLimits(65536, 8388608, 32, 1.0, 30.0); cache = new LoadedSourceCache(limits, (Func, CancellationToken, Task>)((CatalogSnapshot loaded, IReadOnlyList facts, CancellationToken token) => Task.Run(() => LoadedSourceReceipt.Build(loaded, (IEnumerable)facts, limits, token), token)), (Func)null, 3, 3.0); open = OpenOrdinaryCapture; } internal void BeginSession(bool isActive) { //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) active = isActive; ordinaryDb = null; catalog = null; scene = null; prefabs = null; optional = null; store = null; currency = null; cache.BeginSession(isActive); reported = cache.State; } internal void Invalidate() { cache.Invalidate(); } internal IReadOnlyList FilterEquipmentRarity(ClassificationResult item, ItemData data) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) if (!item.InstanceRarity) { return Array.Empty(); } if (optional != null && (int)optional.EpicLoot.State == 0) { return Array.Empty(); } if (cache.Current != null && optional != null) { return optional.FilterEquipmentRarity(item, data); } return (IReadOnlyList)(object)new FacetEvidence[1] { ClassificationFilters.UnreadableRow("rarity") }; } internal void Update(CatalogSnapshot? loaded) { //IL_0139: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Unknown result type (might be due to invalid IL or missing references) //IL_0153: Unknown result type (might be due to invalid IL or missing references) //IL_0158: 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_0164: Invalid comparison between Unknown and I4 //IL_0273: Unknown result type (might be due to invalid IL or missing references) //IL_0279: Invalid comparison between Unknown and I4 optionalWork.ReapRetired(); catalog = loaded; cache.SetCatalog(loaded); if (active) { ObjectDB instance = ObjectDB.instance; ZNetScene instance2 = ZNetScene.instance; List list = (Object.op_Implicit((Object)(object)instance2) ? instance2.m_prefabs : null); StoreGui instance3 = StoreGui.instance; ItemDrop val = (Object.op_Implicit((Object)(object)instance3) ? instance3.m_coinPrefab : null); if (ordinaryDb != instance || scene != instance2 || prefabs != list || prefabCount != (list?.Count ?? 0) || store != instance3 || currency != val) { ordinaryDb = instance; scene = instance2; prefabs = list; prefabCount = list?.Count ?? 0; store = instance3; currency = val; cache.Invalidate(); } } cache.Tick(open); if (cache.Retries > reportedRetries) { log.LogWarning((object)("Fresh loaded sources rejected: " + cache.Diagnostic)); } reportedRetries = cache.Retries; if (reported == cache.State) { return; } reported = cache.State; if ((int)reported == 4) { LoadedSourceReceipt current = cache.Current; log.LogInfo((object)($"Fresh loaded sources: {current.Facts.Count} detached facts, " + $"{current.Snapshot.Routes.Count} routes, {current.ScalarBytes} UTF-8 scalar bytes, maximum capture step {cache.MaximumStepMilliseconds:F3} ms, " + "SHA-256 " + current.Snapshot.Fingerprint + ".")); { foreach (string item in current.Coverage) { if (item.EndsWith("; skipped", StringComparison.Ordinal) && malformedReported.Add(item)) { log.LogWarning((object)("Loaded sources: " + item + ". Only this evidence is missing; report it to the mod that adds the item.")); } } return; } } if ((int)reported == 5) { log.LogWarning((object)("Fresh loaded sources rejected: " + cache.Diagnostic)); } } private IEnumerable? OpenOrdinaryCapture() { if (catalog == null || !Object.op_Implicit((Object)(object)ordinaryDb) || !Object.op_Implicit((Object)(object)scene) || prefabs == null) { return null; } return CaptureOrdinary(catalog, ordinaryDb, scene, prefabs); } private IEnumerable CaptureOrdinary(CatalogSnapshot loaded, ObjectDB db, ZNetScene net, List definitions) { int count = definitions.Count; StoreGui expectedStore = store; ItemDrop expectedCurrency = currency; if (count > 32768) { throw new InvalidDataException("Ordinary definition root limit exceeded."); } Check(); yield return Coverage("ordinary:capability", "game=" + Version.GetVersionString(false) + "; ordinary-loaded-consumers"); GameObject val = (Object.op_Implicit((Object)(object)expectedCurrency) ? ((Component)expectedCurrency).gameObject : null); GameObject val2 = (Object.op_Implicit((Object)(object)val) ? db.GetItemPrefab(((Object)val).name) : null); if (Object.op_Implicit((Object)(object)expectedStore) && Object.op_Implicit((Object)(object)val2) && (Object)(object)val2 == (Object)(object)val && expectedCurrency.m_itemData?.m_shared != null) { yield return new LoadedSourceFact((LoadedSourceFactKind)2, "payment:store", ((Object)val2).name, "", "payment:store", "payment-currency", "", 1, true); } else { yield return Coverage("payment:store", "gap: current registered payment definition unavailable"); } for (int i = 0; i < count; i++) { Check(); GameObject val3 = definitions[i]; if (!Object.op_Implicit((Object)(object)val3)) { throw new InvalidDataException("Null/destroyed loaded prefab registration."); } string id = "prefab:" + i + ":" + ((Object)val3).name; foreach (LoadedSourceFact item in Definition(val3, id, Check)) { yield return item; } yield return null; } optional = OptionalIntegrations.Probe(); Report(optional); foreach (LoadedSourceFact item2 in optional.Capture(loaded, db, definitions, Check, optionalWork)) { yield return item2; } Check(); void Check() { if (!active || catalog != loaded || !Object.op_Implicit((Object)(object)db) || !Object.op_Implicit((Object)(object)net) || ObjectDB.instance != db || ZNetScene.instance != net || net.m_prefabs != definitions || definitions.Count != count || StoreGui.instance != expectedStore || (Object.op_Implicit((Object)(object)expectedStore) ? expectedStore.m_coinPrefab : null) != expectedCurrency) { throw new InvalidDataException("Ordinary category registrations changed during capture."); } } } private void Report(OptionalIntegrations found) { List list = ((IEnumerable)(object)new OptionalCapability[3] { found.Jotunn, found.EpicLoot, found.EpicLootSemantics }).Where((OptionalCapability x) => (int)x.State == 2).ToList(); string text = string.Join("|", list.Select((OptionalCapability x) => x.Witness)); if (text == reportedOff) { return; } reportedOff = text; foreach (OptionalCapability item in list) { log.LogWarning((object)(item.Adapter + " turned off for version " + item.ObservedVersion + ": its code differs from what YAVSOS checked (" + item.Diagnostic + "). The rest of YAVSOS keeps working.")); } } private IReadOnlyList Definition(GameObject prefab, string id, Action check) { List list = new List(); try { list.AddRange(ItemUses(prefab, id, check)); list.AddRange(Machine(prefab, id, check)); Piece component = prefab.GetComponent(); list.AddRange(LoadedProducerReaders.Read(prefab, id, !Object.op_Implicit((Object)(object)component) || component.m_enabled, check)); } catch (MalformedDefinitionException ex) { list.Clear(); list.Add(Coverage(id + ":malformed", "gap: " + ex.Message + " Its recipes, uses and products give no evidence.")); if (malformedReported.Add(((Object)prefab).name)) { log.LogWarning((object)("Loaded sources: " + ((Object)prefab).name + " has a malformed definition (" + ex.Message + "); only its own evidence is skipped. Report it to the mod that adds it.")); } } return list; } private static IEnumerable ItemUses(GameObject prefab, string id, Action check) { check(); Piece piece = prefab.GetComponent(); bool active = !Object.op_Implicit((Object)(object)piece) || piece.m_enabled; Plant plant = prefab.GetComponent(); Feast feast = prefab.GetComponent(); ItemDrop val = ((!Object.op_Implicit((Object)(object)feast)) ? null : (Object.op_Implicit((Object)(object)feast.m_foodItem) ? feast.m_foodItem : prefab.GetComponent())); SharedData val2 = ((!Object.op_Implicit((Object)(object)val)) ? null : val.m_itemData?.m_shared); bool feastAvailable = active && Object.op_Implicit((Object)(object)feast) && ((Behaviour)feast).enabled && feast.m_eatStacks > 0 && val2 != null && FinitePositive(val2.m_foodBurnTime) && FinitePositive(val2.m_food); if (Object.op_Implicit((Object)(object)piece)) { Requirement[] resources = piece.m_resources; if (resources == null || resources.Length > 256) { throw new MalformedDefinitionException("Piece resource bound exceeded."); } for (int i = 0; i < resources.Length; i++) { check(); if (!Object.op_Implicit((Object)(object)piece) || piece.m_resources != resources) { throw new InvalidDataException("Piece resources changed during capture."); } Requirement resource = resources[i]; if (resource == null) { throw new MalformedDefinitionException("Null piece resource."); } bool eligible = active && !resource.m_upgraderResource; yield return Use(id + ":build:" + i, resource.m_resItem, id, "building", eligible, resource.m_amount); if (Object.op_Implicit((Object)(object)plant)) { yield return Use(id + ":plant-use:" + i, resource.m_resItem, id, "planting", eligible && ((Behaviour)plant).enabled, resource.m_amount); } if (Object.op_Implicit((Object)(object)feast)) { yield return Use(id + ":feast-use:" + i, resource.m_resItem, id, "feast-ingredient", eligible && feastAvailable, resource.m_amount); } } check(); if (!Object.op_Implicit((Object)(object)piece) || piece.m_resources != resources) { throw new InvalidDataException("Piece resources changed during capture."); } } Smelter component = prefab.GetComponent(); if (Object.op_Implicit((Object)(object)component) && Object.op_Implicit((Object)(object)component.m_fuelItem)) { yield return Use(id + ":smelter-fuel", component.m_fuelItem, id, "fuel", active && ((Behaviour)component).enabled && component.m_maxFuel > 0 && component.m_fuelPerProduct > 0); } CookingStation component2 = prefab.GetComponent(); if (Object.op_Implicit((Object)(object)component2) && Object.op_Implicit((Object)(object)component2.m_fuelItem)) { yield return Use(id + ":cooking-fuel", component2.m_fuelItem, id, "fuel", active && ((Behaviour)component2).enabled && component2.m_useFuel && component2.m_maxFuel > 0); } Fireplace fire = prefab.GetComponent(); if (Object.op_Implicit((Object)(object)fire) && Object.op_Implicit((Object)(object)fire.m_fuelItem)) { yield return Use(id + ":fire-fuel", fire.m_fuelItem, id, "fuel", active && ((Behaviour)fire).enabled && !fire.m_infiniteFuel && fire.m_canRefill && fire.m_maxFuel > 0f); } if (Object.op_Implicit((Object)(object)fire) && fire.m_fireworkItemList != null) { FireworkItem[] entries = fire.m_fireworkItemList; if (entries.Length > 256) { throw new MalformedDefinitionException("Fireworks consumer bound exceeded."); } SharedData fuel = ((!Object.op_Implicit((Object)(object)fire.m_fuelItem)) ? null : fire.m_fuelItem.m_itemData?.m_shared); HashSet names = new HashSet(StringComparer.Ordinal); for (int i = 0; i < entries.Length; i++) { check(); if (!Object.op_Implicit((Object)(object)fire) || fire.m_fireworkItemList != entries) { throw new InvalidDataException("Fireworks consumers changed during capture."); } FireworkItem val3 = entries[i]; SharedData val4 = ((!Object.op_Implicit((Object)(object)val3.m_fireworkItem)) ? null : val3.m_fireworkItem.m_itemData?.m_shared); if (val4 == null || string.IsNullOrEmpty(val4.m_name)) { yield return Coverage(id + ":fireworks:gap", "gap: malformed entry prevents later fireworks consumers"); break; } bool flag = names.Add(val4.m_name) && (fire.m_infiniteFuel || fuel?.m_name != val4.m_name); yield return Use(id + ":fireworks:" + i, val3.m_fireworkItem, id, "fireworks", active && ((Behaviour)fire).enabled && fire.m_canRefill && fuel != null && flag, val3.m_fireworkItemCount); } check(); if (!Object.op_Implicit((Object)(object)fire) || fire.m_fireworkItemList != entries) { throw new InvalidDataException("Fireworks consumers changed during capture."); } } Door component3 = prefab.GetComponent(); if (Object.op_Implicit((Object)(object)component3) && Object.op_Implicit((Object)(object)component3.m_keyItem)) { yield return Use(id + ":key", component3.m_keyItem, id, "door-key", active && ((Behaviour)component3).enabled); } Tameable tameable = prefab.GetComponent(); if (Object.op_Implicit((Object)(object)tameable) && Object.op_Implicit((Object)(object)tameable.m_saddleItem)) { yield return Use(id + ":saddle", tameable.m_saddleItem, id, "saddle", active && ((Behaviour)tameable).enabled); } MonsterAI ai = prefab.GetComponent(); if (Object.op_Implicit((Object)(object)ai) && ai.m_consumeItems != null) { Character component4 = prefab.GetComponent(); string tame = ((Object.op_Implicit((Object)(object)tameable) && !tameable.m_startsTamed) ? ((Object.op_Implicit((Object)(object)component4) && !string.IsNullOrEmpty(component4.m_name)) ? component4.m_name : id) : ""); List foods = ai.m_consumeItems; int i = foods.Count; if (i > 256) { throw new MalformedDefinitionException("Creature food bound exceeded."); } for (int j = 0; j < i; j++) { check(); if (!Object.op_Implicit((Object)(object)ai) || ai.m_consumeItems != foods || foods.Count != i) { throw new InvalidDataException("Creature foods changed during capture."); } yield return Use(id + ":feed:" + j, foods[j], id, "creature-food", active && ((Behaviour)ai).enabled); if (tame.Length != 0 && Object.op_Implicit((Object)(object)foods[j])) { string text = Item(((Component)foods[j]).gameObject); if (text != null && text.Length > 0) { yield return new LoadedSourceFact((LoadedSourceFactKind)3, id + ":tame-food:" + j, text, "", id, "eaten-by", tame, 1, active && ((Behaviour)ai).enabled && ((Behaviour)tameable).enabled); } } } check(); if (!Object.op_Implicit((Object)(object)ai) || ai.m_consumeItems != foods || foods.Count != i) { throw new InvalidDataException("Creature foods changed during capture."); } } Trader trader = prefab.GetComponent(); if (Object.op_Implicit((Object)(object)trader)) { List entries2 = trader.m_useItems; if (entries2 == null || entries2.Count > 256) { throw new MalformedDefinitionException("Trader handover bound exceeded."); } int i = entries2.Count; for (int j = 0; j < i; j++) { check(); if (!Object.op_Implicit((Object)(object)trader) || trader.m_useItems != entries2 || entries2.Count != i) { throw new InvalidDataException("Trader handovers changed during capture."); } TraderUseItem val5 = entries2[j]; if (val5 == null) { throw new MalformedDefinitionException("Null trader handover."); } yield return Use(id + ":handover:" + j, val5.m_prefab, id, "trader-handover", active && ((Behaviour)trader).enabled); } check(); if (!Object.op_Implicit((Object)(object)trader) || trader.m_useItems != entries2 || entries2.Count != i) { throw new InvalidDataException("Trader handovers changed during capture."); } } OfferingBowl component5 = prefab.GetComponent(); if (Object.op_Implicit((Object)(object)component5) && Object.op_Implicit((Object)(object)component5.m_bossItem)) { yield return Use(id + ":offering", component5.m_bossItem, id, "offering", active && ((Behaviour)component5).enabled && !component5.m_useItemStands, component5.m_bossItems); } Catapult launcher = prefab.GetComponent(); if (Object.op_Implicit((Object)(object)launcher)) { List foods = launcher.m_includeItemsOverride; if (foods == null || foods.Count > 256) { throw new MalformedDefinitionException("Catapult include bound exceeded."); } int i = foods.Count; for (int j = 0; j < i; j++) { check(); if (!Object.op_Implicit((Object)(object)launcher) || launcher.m_includeItemsOverride != foods || foods.Count != i) { throw new InvalidDataException("Catapult includes changed during capture."); } if (!Object.op_Implicit((Object)(object)foods[j]) || foods[j].m_itemData?.m_shared == null) { yield return new LoadedSourceFact((LoadedSourceFactKind)1, id + ":siege:gap", "", "", "", "", "gap: malformed include faults Any before later entries", 1, true); break; } yield return Use(id + ":siege:" + j, foods[j], id, "siege-ammunition", active && ((Behaviour)launcher).enabled); } check(); if (!Object.op_Implicit((Object)(object)launcher) || launcher.m_includeItemsOverride != foods || foods.Count != i) { throw new InvalidDataException("Catapult includes changed during capture."); } } check(); } private static LoadedSourceFact Use(string id, ItemDrop? target, string consumer, string method, bool eligible, int amount = 1) { //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Expected O, but got Unknown string text = (Object.op_Implicit((Object)(object)target) ? Item(((Component)target).gameObject) : ""); if (text.Length != 0) { return new LoadedSourceFact((LoadedSourceFactKind)2, id, text, "", consumer, method, "", amount, eligible); } return Coverage(id, "gap: unresolved " + method + " inventory identity"); } private static IEnumerable Machine(GameObject prefab, string id, Action check) { check(); Piece piece = prefab.GetComponent(); bool active = !Object.op_Implicit((Object)(object)piece) || piece.m_enabled; Smelter smelter = prefab.GetComponent(); if (Object.op_Implicit((Object)(object)smelter)) { if (smelter.m_conversion == null || smelter.m_conversion.Count > 256) { throw new MalformedDefinitionException("Smelter conversion bound exceeded."); } List conversions = smelter.m_conversion; int count = conversions.Count; for (int i = 0; i < count; i++) { check(); if (!Object.op_Implicit((Object)(object)smelter) || smelter.m_conversion != conversions || conversions.Count != count) { throw new InvalidDataException("Smelter registrations changed during capture."); } ItemConversion val = conversions[i]; if (val == null) { throw new MalformedDefinitionException("Null smelter conversion."); } yield return Conversion(id + ":smelt:" + i, val.m_from, val.m_to, "smelt", active && ((Behaviour)smelter).enabled); } check(); if (!Object.op_Implicit((Object)(object)smelter) || smelter.m_conversion != conversions || conversions.Count != count) { throw new InvalidDataException("Smelter registrations changed during capture."); } } CookingStation cooking = prefab.GetComponent(); if (Object.op_Implicit((Object)(object)cooking)) { if (cooking.m_conversion == null || cooking.m_conversion.Count > 256) { throw new MalformedDefinitionException("Cooking conversion bound exceeded."); } List conversions2 = cooking.m_conversion; int count = conversions2.Count; for (int i = 0; i < count; i++) { check(); if (!Object.op_Implicit((Object)(object)cooking) || cooking.m_conversion != conversions2 || conversions2.Count != count) { throw new InvalidDataException("Cooking registrations changed during capture."); } ItemConversion val2 = conversions2[i]; if (val2 == null) { throw new MalformedDefinitionException("Null cooking conversion."); } yield return Conversion(id + ":cook:" + i, val2.m_from, val2.m_to, "cook", active && ((Behaviour)cooking).enabled); } check(); if (!Object.op_Implicit((Object)(object)cooking) || cooking.m_conversion != conversions2 || conversions2.Count != count) { throw new InvalidDataException("Cooking registrations changed during capture."); } } Fermenter fermenter = prefab.GetComponent(); if (Object.op_Implicit((Object)(object)fermenter)) { if (fermenter.m_conversion == null || fermenter.m_conversion.Count > 256) { throw new MalformedDefinitionException("Fermenter conversion bound exceeded."); } List conversions3 = fermenter.m_conversion; int count = conversions3.Count; for (int i = 0; i < count; i++) { check(); if (!Object.op_Implicit((Object)(object)fermenter) || fermenter.m_conversion != conversions3 || conversions3.Count != count) { throw new InvalidDataException("Fermentation registrations changed during capture."); } ItemConversion val3 = conversions3[i]; if (val3 == null) { throw new MalformedDefinitionException("Null fermentation conversion."); } yield return Conversion(id + ":ferment:" + i, val3.m_from, val3.m_to, "ferment", active && ((Behaviour)fermenter).enabled && val3.m_producedItems > 0); } check(); if (!Object.op_Implicit((Object)(object)fermenter) || fermenter.m_conversion != conversions3 || conversions3.Count != count) { throw new InvalidDataException("Fermentation registrations changed during capture."); } } Plant plant = prefab.GetComponent(); if (!Object.op_Implicit((Object)(object)plant)) { yield break; } if (!Object.op_Implicit((Object)(object)piece) || piece.m_resources == null || piece.m_resources.Length == 0) { yield return Coverage(id + ":plant", "gap: missing planting materials"); yield break; } if (piece.m_resources.Length > 256 || plant.m_grownPrefabs == null || plant.m_grownPrefabs.Length > 64) { throw new MalformedDefinitionException("Cultivation input/output bound exceeded."); } GameObject[] grownPrefabs = plant.m_grownPrefabs; Requirement[] resources = piece.m_resources; for (int count = 0; count < grownPrefabs.Length; count++) { CheckPlant(); GameObject val4 = grownPrefabs[count]; Pickable val5 = (Object.op_Implicit((Object)(object)val4) ? val4.GetComponent() : null); string route = id + ":cultivate:" + count; if (!Object.op_Implicit((Object)(object)val5) || !Object.op_Implicit((Object)(object)val5.m_itemPrefab)) { yield return Coverage(route, "gap: grown root is not a direct output Pickable"); continue; } bool possible = active && ((Behaviour)plant).enabled && val5.m_amount > 0 && (!val5.m_defaultPicked || (((Behaviour)val5).enabled && val5.m_respawnTimeMinutes > 0f && val5.m_spawnCheck == null)); string output = Item(val5.m_itemPrefab); if (output.Length == 0) { yield return Coverage(route, "gap: unresolved cultivation output inventory identity"); continue; } for (int i = 0; i < resources.Length; i++) { CheckPlant(); Requirement val6 = resources[i]; if (val6 != null && (val6.m_upgraderResource || val6.m_amount <= 0)) { yield return null; continue; } string text = (Object.op_Implicit((Object)(object)val6?.m_resItem) ? Item(((Component)val6.m_resItem).gameObject) : ""); if (text.Length == 0) { text = Missing(route + ":" + i); } yield return new LoadedSourceFact((LoadedSourceFactKind)0, route + ":" + i, output, text, route, "cultivate", "natural-material-origin; planting/growth biome is not an output source", val6?.m_amount ?? 1, possible); } } CheckPlant(); void CheckPlant() { check(); if (!Object.op_Implicit((Object)(object)plant) || !Object.op_Implicit((Object)(object)piece) || plant.m_grownPrefabs != grownPrefabs || piece.m_resources != resources) { throw new InvalidDataException("Cultivation registrations changed during capture."); } } } private static LoadedSourceFact Conversion(string id, ItemDrop? from, ItemDrop? to, string kind, bool eligible) { //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Expected O, but got Unknown string text = (Object.op_Implicit((Object)(object)to) ? Item(((Component)to).gameObject) : ""); if (text.Length == 0) { return Coverage(id, "gap: missing/unresolved conversion output"); } string text2 = (Object.op_Implicit((Object)(object)from) ? Item(((Component)from).gameObject) : ""); return new LoadedSourceFact((LoadedSourceFactKind)0, id, text, (text2.Length == 0) ? Missing(id) : text2, id, kind, "machine/fuel equipment never relabels material origin", 1, eligible); } private static string Item(GameObject prefab) { ItemDrop component = prefab.GetComponent(); if (!Object.op_Implicit((Object)(object)component)) { return ""; } GameObject val = component.m_itemData?.m_dropPrefab; ObjectDB instance = ObjectDB.instance; if (!Object.op_Implicit((Object)(object)instance)) { return ""; } GameObject val2 = (Object.op_Implicit((Object)(object)val) ? instance.GetItemPrefab(((Object)val).name) : null); if (!Object.op_Implicit((Object)(object)val2)) { val2 = instance.GetItemPrefab(((Object)prefab).name); } if (!Object.op_Implicit((Object)(object)val2)) { string text = LoadedSourceSemantics.CloneBaseName(((Object)prefab).name); if (text != null) { val2 = instance.GetItemPrefab(text); } } if (!Object.op_Implicit((Object)(object)val2) || !Object.op_Implicit((Object)(object)val2.GetComponent())) { return ""; } return ((Object)val2).name; } private static LoadedSourceFact Coverage(string id, string detail) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Expected O, but got Unknown return new LoadedSourceFact((LoadedSourceFactKind)1, id, "", "", "", "", detail, 1, true); } private static string Missing(string id) { return "yavsos:missing-source:" + id; } private static bool FinitePositive(float value) { if (value > 0f && !float.IsNaN(value)) { return !float.IsInfinity(value); } return false; } public void Dispose() { active = false; cache.Dispose(); optionalWork.Dispose(); } } internal sealed class MalformedDefinitionException : Exception { internal MalformedDefinitionException(string message) : base(message) { } } } namespace YAVSOS.Networking { internal sealed class AssignmentHost : IDisposable { internal const string SyncIdentifier = "authoritative-assignments-v1"; private readonly ConfigSync sync; private readonly CustomSyncedValue value; private readonly PolicyLifecycle policy; private readonly ManualLogSource log; private readonly Func getCatalog; private readonly Func getClassification; private readonly Func getSources; private readonly AssignmentExchange exchange = new AssignmentExchange((Func, CancellationToken, Task>)null, (Func)null, 30.0); private readonly AssignmentEnvelopeReceiver receiver = new AssignmentEnvelopeReceiver(); private readonly RetainedCategoryAnswers answers = new RetainedCategoryAnswers(); private long session; private CatalogSnapshot? lastCatalog; private CategoryPolicy? lastPolicy; private ClassifiedCatalog? lastClassification; private ClassificationSourceSnapshot? lastSources; private AuthoritativeAssignmentSnapshot? identity; private CatalogSnapshot? identityCatalog; private CategoryPolicy? identityPolicy; private string incoming = ""; private string published = ""; private string reported = ""; private bool disposed; private bool hasPublished; private string serverSession = ""; private long publicationSequence; private double categoriesMissingSince = -1.0; private bool categoriesMissingInRebuild; internal bool IdentityReady { get { if (!disposed && policy.PolicyReady) { AuthoritativeAssignmentSnapshot? obj = identity; if (obj != null && obj.IdentityReady && identityCatalog == getCatalog()) { return identityPolicy == policy.Effective; } } return false; } } internal AuthoritativeAssignmentSnapshot? Current { get { //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Invalid comparison between Unknown and I4 //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Invalid comparison between Unknown and I4 //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Invalid comparison between Unknown and I4 if (!policy.PolicyReady || lastCatalog != getCatalog() || lastPolicy != policy.Effective || (((int)policy.Mode == 4 || (int)policy.Mode == 1 || (int)policy.Mode == 2) && (lastClassification != getClassification() || lastSources != getSources()))) { return null; } AssignmentPublication current = exchange.Current; if (current == null) { return null; } return current.Snapshot; } } internal ICategoryAnswers Answers => (ICategoryAnswers)(object)answers; internal bool CategoriesRebuilding => answers.Rebuilding; internal int CategoryMemberCount(string category) { return answers.MemberCount(category); } internal AssignmentHost(ConfigSync sync, PolicyLifecycle policy, ManualLogSource log, Func getCatalog, Func getClassification, Func getSources) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Expected O, but got Unknown this.sync = sync; this.policy = policy; this.log = log; this.getCatalog = getCatalog; this.getClassification = getClassification; this.getSources = getSources; value = new CustomSyncedValue(sync, "authoritative-assignments-v1", ""); value.ValueChanged += OnRemoteChanged; } internal void BeginSession(bool active) { identity = null; identityCatalog = null; identityPolicy = null; exchange.BeginSession(active); incoming = (published = (reported = "")); receiver.Reset(); serverSession = Guid.NewGuid().ToString("N"); publicationSequence = 0L; hasPublished = false; lastCatalog = null; lastPolicy = null; lastClassification = null; lastSources = null; session++; answers.SetScope(session, ""); categoriesMissingSince = -1.0; value.AssignLocalValue(""); policy.SetAssignmentEvidence((string)null, false); } internal void Invalidate() { identity = null; InvalidateCategories(); } internal void InvalidateCategories() { exchange.Invalidate(); policy.SetAssignmentEvidence((string)null, false); answers.BeginRebuild(); lastCatalog = null; lastPolicy = null; } private void OnRemoteChanged() { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Invalid comparison between Unknown and I4 //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Invalid comparison between Unknown and I4 bool flag = disposed || sync.IsSourceOfTruth; if (!flag) { PolicyMode mode = policy.Mode; bool flag2 = (((int)mode <= 1 || (int)mode == 4) ? true : false); flag = flag2; } if (!flag && receiver.Receive(value.Value)) { identity = null; incoming = receiver.Payload; exchange.Invalidate(); policy.SetAssignmentEvidence((string)null, false); answers.Withdraw(); } } internal void Update() { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Invalid comparison between Unknown and I4 //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Invalid comparison between Unknown and I4 //IL_016c: Unknown result type (might be due to invalid IL or missing references) //IL_0174: Unknown result type (might be due to invalid IL or missing references) //IL_01d6: Unknown result type (might be due to invalid IL or missing references) //IL_026f: Unknown result type (might be due to invalid IL or missing references) //IL_0275: Invalid comparison between Unknown and I4 //IL_0380: Unknown result type (might be due to invalid IL or missing references) //IL_0385: Unknown result type (might be due to invalid IL or missing references) if (disposed) { return; } PolicyMode mode = policy.Mode; bool flag = ((mode - 1 <= 1 || (int)mode == 4) ? true : false); bool flag2 = flag; lastCatalog = getCatalog(); lastPolicy = (policy.PolicyReady ? policy.Effective : null); lastClassification = (flag2 ? getClassification() : null); lastSources = (flag2 ? getSources() : null); exchange.SetInputs(flag2, lastCatalog, lastPolicy, flag2 ? lastClassification : null, flag2 ? "" : incoming); exchange.Tick(); AuthoritativeAssignmentSnapshot current = Current; RetainedCategoryAnswers obj = answers; long num = session; CategoryPolicy? obj2 = lastPolicy; obj.SetScope(num, ((obj2 != null) ? obj2.Fingerprint : null) ?? ""); bool flag3 = current != null && !current.CategoriesReady && answers.Rebuilding && answers.CategoriesReady; if (current != null && lastCatalog != null) { identity = current; identityCatalog = lastCatalog; identityPolicy = lastPolicy; CategoryAnswerUpdate val = (CategoryAnswerUpdate)(flag3 ? 1 : ((int)answers.Accept(current, lastCatalog, session))); if (current.CategoriesReady && categoriesMissingSince >= 0.0) { log.LogInfo((object)($"Categories ready {(Time.realtimeSinceStartupAsDouble - categoriesMissingSince) * 1000.0:F0} ms after " + (categoriesMissingInRebuild ? "the rebuild started" : "they were withdrawn or the session started") + $" ({val}).")); categoriesMissingSince = -1.0; } } else { answers.BeginRebuild(); } if ((current == null || !current.CategoriesReady) && categoriesMissingSince < 0.0) { categoriesMissingSince = Time.realtimeSinceStartupAsDouble; categoriesMissingInRebuild = answers.Rebuilding; } policy.SetAssignmentEvidence((current != null) ? current.Fingerprint : null, current != null && current.CategoriesReady); if ((int)policy.Mode == 4 && sync.IsSourceOfTruth && !ConfigSync.ProcessingServerUpdate) { string text = ((current != null && !flag3) ? exchange.Current.Wire : (answers.Rebuilding ? published : "")); if (!hasPublished || published != text) { published = text; hasPublished = true; value.Value = AssignmentEnvelope.Encode(serverSession, checked(++publicationSequence), text); } } string text2 = ((current != null) ? current.Fingerprint : null) ?? exchange.Diagnostic; if (!(text2 == reported)) { reported = text2; string text3 = ((current != null) ? ("Assignment evidence ready: " + current.Fingerprint) : exchange.Diagnostic); if (current != null) { log.LogInfo((object)(text3 + ". Capabilities=" + ((object)current.Capabilities/*cast due to .constrained prefix*/).ToString() + ".")); } else if (text3.Contains("rejected") || text3.Contains("deadline")) { log.LogWarning((object)text3); } } } public void Dispose() { if (!disposed) { disposed = true; identity = null; answers.Withdraw(); value.ValueChanged -= OnRemoteChanged; exchange.Dispose(); policy.SetAssignmentEvidence((string)null, false); } } } internal static class CategoryPolicyFileReader { private static readonly UTF8Encoding StrictUtf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); public static bool TryRead(Stream stream, out string payload, out string diagnostic) { payload = ""; diagnostic = ""; try { if (stream.Length > 262144) { throw new InvalidDataException("Category file exceeds 256 KiB."); } int num = 262145; byte[] array = ArrayPool.Shared.Rent(num); try { int i; int num2; for (i = 0; i < num; i += num2) { if ((num2 = stream.Read(array, i, num - i)) <= 0) { break; } } if (i > 262144) { throw new InvalidDataException("Category file exceeds 256 KiB."); } payload = StrictUtf8.GetString(array, 0, i).TrimStart('\ufeff'); } finally { ArrayPool.Shared.Return(array); } return true; } catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException || ex is DecoderFallbackException || ex is InvalidDataException) { diagnostic = ex.Message; return false; } } } internal sealed class PeerIdentityGate { private object? current; public void Replace(object rpc) { current = rpc ?? throw new ArgumentNullException("rpc"); } public void Clear() { current = null; } public bool Accepts(object rpc) { if (current != null) { return current == rpc; } return false; } } internal sealed class PolicyHost : IDisposable { private readonly ConfigSync sync; private readonly CustomSyncedValue wirePolicy; private readonly ManualLogSource log; private readonly string path; private readonly PolicyMailbox mailbox = new PolicyMailbox(); private readonly ServerSyncSessionCache sessionCache; private FileSystemWatcher? watcher; private int watcherFailed; private bool reloadPending; private float reloadAt; private float pollAt; private DateTime lastWrite; private long lastLength = -1L; private bool disposed; public PolicyLifecycle State { get; } = new PolicyLifecycle(); public ZRpc? IncomingRpc => sessionCache.IncomingRpc; public PolicyHost(ConfigSync sync, string configDirectory, ManualLogSource log) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown this.sync = sync; this.log = log; sessionCache = new ServerSyncSessionCache(sync); path = Path.Combine(configDirectory, "com.bastionntb.yavsos.categories.xml"); wirePolicy = new CustomSyncedValue(sync, "category-policy-v1", ""); sync.SourceOfTruthChanged += OnSourceChanged; wirePolicy.ValueChanged += OnRemoteChanged; Directory.CreateDirectory(configDirectory); try { using FileStream fileStream = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.Read); byte[] bytes = Encoding.UTF8.GetBytes(CategoryPolicyCodec.EmptyDocument); fileStream.Write(bytes, 0, bytes.Length); } catch (IOException) when (File.Exists(path)) { } ReloadLocal(); try { watcher = new FileSystemWatcher(configDirectory, "com.bastionntb.yavsos.categories.xml") { NotifyFilter = (NotifyFilters.FileName | NotifyFilters.Size | NotifyFilters.LastWrite), IncludeSubdirectories = false }; watcher.Changed += OnFileChanged; watcher.Created += OnFileChanged; watcher.Deleted += OnFileChanged; watcher.Renamed += OnFileChanged; watcher.Error += OnWatcherError; watcher.EnableRaisingEvents = true; } catch (Exception ex2) when (ex2 is IOException || ex2 is UnauthorizedAccessException || ex2 is PlatformNotSupportedException) { log.LogWarning((object)("Category watcher unavailable; using five-second file-stat polling: " + ex2.Message)); } } public void BeginSession(PolicyMode mode) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) State.BeginSession(mode); sessionCache.Clear(); PolicyMailbox policyMailbox = mailbox; PolicyStamp stamp = State.Stamp; policyMailbox.Reset(((PolicyStamp)(ref stamp)).Session); ReloadLocal(); log.LogInfo((object)$"Policy mode: {mode}. {State.Diagnostic}"); } public void Update(float now) { //IL_0162: 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_0187: Unknown result type (might be due to invalid IL or missing references) //IL_018c: Unknown result type (might be due to invalid IL or missing references) //IL_0197: Unknown result type (might be due to invalid IL or missing references) //IL_019c: Unknown result type (might be due to invalid IL or missing references) //IL_019f: Unknown result type (might be due to invalid IL or missing references) if (disposed) { return; } if (Interlocked.Exchange(ref watcherFailed, 0) != 0) { log.LogWarning((object)"Category watcher lost events; rescanning and retaining five-second polling."); mailbox.MarkFileDirty(); } if (now >= pollAt) { pollAt = now + 5f; try { FileInfo fileInfo = new FileInfo(path); DateTime dateTime = (fileInfo.Exists ? fileInfo.LastWriteTimeUtc : DateTime.MinValue); long num = (fileInfo.Exists ? fileInfo.Length : (-1)); if (dateTime != lastWrite || num != lastLength) { lastWrite = dateTime; lastLength = num; mailbox.MarkFileDirty(); } } catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException) { log.LogWarning((object)("Cannot inspect category file: " + ex.Message)); } } if (mailbox.TakeFileDirty()) { reloadPending = true; reloadAt = now + 0.35f; } if (reloadPending && now >= reloadAt) { reloadPending = false; ReloadLocal(); } if (!sync.IsSourceOfTruth && sync.InitialSyncDone && !ConfigSync.ProcessingServerUpdate) { PolicyMailbox policyMailbox = mailbox; PolicyStamp stamp = State.Stamp; string text = policyMailbox.TakeRemote(((PolicyStamp)(ref stamp)).Session); if (text != null) { PolicyLifecycle state = State; stamp = State.Stamp; PolicyUpdate result = state.ApplyRemote(((PolicyStamp)(ref stamp)).Session, text); Report(result, "Server"); } } } private void OnSourceChanged(bool local) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) if (!disposed && !local) { State.AwaitServer(); PolicyMailbox policyMailbox = mailbox; PolicyStamp stamp = State.Stamp; policyMailbox.Reset(((PolicyStamp)(ref stamp)).Session); } } private void OnRemoteChanged() { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Invalid comparison between Unknown and I4 //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) if (disposed || sync.IsSourceOfTruth || (int)State.Mode == 0) { return; } if ((int)State.Mode == 5 && State.PolicyReady) { CategoryPolicy effective = State.Effective; if (((effective != null) ? effective.CanonicalXml : null) == wirePolicy.Value) { return; } } State.AwaitServer(); PolicyMailbox policyMailbox = mailbox; PolicyStamp stamp = State.Stamp; policyMailbox.PostRemote(((PolicyStamp)(ref stamp)).Session, wirePolicy.Value); } private void ReloadLocal() { //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) try { using FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); if (!CategoryPolicyFileReader.TryRead(stream, out string payload, out string diagnostic)) { log.LogWarning((object)("Cannot reload " + path + "; last accepted policy retained: " + diagnostic)); return; } PolicyUpdate val = State.ApplyLocal(payload); if ((int)val == 0 && sync.IsSourceOfTruth && !ConfigSync.ProcessingServerUpdate) { wirePolicy.Value = State.Local.CanonicalXml; } else if ((int)val == 0 && !sync.IsSourceOfTruth) { wirePolicy.AssignLocalValue(State.Local.CanonicalXml); } Report(val, "Local"); } catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException || ex is DecoderFallbackException) { log.LogWarning((object)("Cannot reload " + path + "; last accepted policy retained: " + ex.Message)); } } private void Report(PolicyUpdate result, string source) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Invalid comparison between Unknown and I4 //IL_001b: Unknown result type (might be due to invalid IL or missing references) if ((int)result == 2) { log.LogWarning((object)State.Diagnostic); } else if ((int)result == 0) { CategoryPolicy val = ((source == "Local") ? State.Local : State.Effective); log.LogInfo((object)$"{source} category policy accepted: revision {val.Revision}, SHA-256 {val.Fingerprint}. Classification remains pending."); } } private void OnFileChanged(object sender, FileSystemEventArgs args) { mailbox.MarkFileDirty(); } private void OnWatcherError(object sender, ErrorEventArgs args) { Interlocked.Exchange(ref watcherFailed, 1); } public void Dispose() { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) if (!disposed) { disposed = true; State.BeginSession((PolicyMode)0); sessionCache.Clear(); PolicyMailbox policyMailbox = mailbox; PolicyStamp stamp = State.Stamp; policyMailbox.Reset(((PolicyStamp)(ref stamp)).Session); sync.SourceOfTruthChanged -= OnSourceChanged; wirePolicy.ValueChanged -= OnRemoteChanged; watcher?.Dispose(); } } } internal sealed class PolicyMailbox { private readonly object gate = new object(); private long activeSession; private string? remote; private int fileDirty; public void Reset(long session) { lock (gate) { activeSession = session; remote = null; } } public void MarkFileDirty() { Interlocked.Exchange(ref fileDirty, 1); } public bool TakeFileDirty() { return Interlocked.Exchange(ref fileDirty, 0) != 0; } public void PostRemote(long session, string? value) { lock (gate) { if (session == activeSession) { remote = ((value == null || value.Length > 262144) ? "" : value); } } } public string? TakeRemote(long session) { lock (gate) { if (session != activeSession) { return null; } string? result = remote; remote = null; return result; } } } internal sealed class ServerSyncSessionCache { private readonly IDictionary fragments; private readonly IList expirations; private readonly FieldInfo incomingRpc; public ZRpc? IncomingRpc { get { object? value = incomingRpc.GetValue(null); return (ZRpc?)((value is ZRpc) ? value : null); } } public ServerSyncSessionCache(ConfigSync sync) { fragments = (AccessTools.Field(typeof(ConfigSync), "configValueCache")?.GetValue(sync) as IDictionary) ?? throw new NotSupportedException("Pinned ServerSync fragment-cache contract is unavailable."); expirations = (AccessTools.Field(typeof(ConfigSync), "cacheExpirations")?.GetValue(sync) as IList) ?? throw new NotSupportedException("Pinned ServerSync cache-expiration contract is unavailable."); incomingRpc = AccessTools.Field(AccessTools.Inner(typeof(ConfigSync), "SnatchCurrentlyHandlingRPC"), "currentRpc") ?? throw new NotSupportedException("Pinned ServerSync routed-message ingress contract is unavailable."); if (incomingRpc.FieldType != typeof(ZRpc) || !incomingRpc.IsStatic) { throw new NotSupportedException("Pinned ServerSync routed-message ingress type is incompatible."); } } public void Clear() { fragments.Clear(); expirations.Clear(); } } internal sealed class ServerSyncSettingsBridge { internal const int MaxRequestBytes = 262144; private static readonly Encoding StrictUtf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); private long session; private bool publishPending; public void BeginSession() { session++; publishPending = false; } public long? CaptureUpdate(bool managedServer, bool clientUpdate, bool currentPeer) { if (!(managedServer && clientUpdate && currentPeer)) { return null; } return session; } public void CompleteUpdate(long? capturedSession, bool accepted) { if (accepted && capturedSession == session) { publishPending = true; } } public bool Publish(bool managedServer, bool processingUpdate, Action publishCurrentSettings) { if (!managedServer) { publishPending = false; return false; } if (!publishPending || processingUpdate) { return false; } publishPending = false; publishCurrentSettings(); return true; } public static bool TrySerializeLocal(bool managedOverlay, bool synchronized, object? localValue, Type valueType, Func serialize, out string serialized) { serialized = ""; if (!managedOverlay || !synchronized || localValue == null) { return false; } serialized = serialize(localValue, valueType); return true; } public static bool ValidateRequest(byte[] payload, int maxEntries, Func settingType, out string diagnostic) { diagnostic = ""; try { if (payload.Length > 262144) { throw new InvalidDataException("Settings request exceeds 256 KiB."); } using MemoryStream memoryStream = new MemoryStream(payload, writable: false); using BinaryReader binaryReader = new BinaryReader(memoryStream, StrictUtf8); if (binaryReader.ReadByte() == 4) { int num = binaryReader.ReadInt32(); if (num < 0 || num != memoryStream.Length - memoryStream.Position) { throw new InvalidDataException("Invalid compressed settings envelope."); } using MemoryStream stream = new MemoryStream(binaryReader.ReadBytes(num), writable: false); using DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress); using MemoryStream memoryStream2 = new MemoryStream(); byte[] array = new byte[4096]; int count; while ((count = deflateStream.Read(array, 0, Math.Min(array.Length, 262145 - (int)memoryStream2.Length))) != 0) { memoryStream2.Write(array, 0, count); if (memoryStream2.Length > 262144) { throw new InvalidDataException("Expanded settings request exceeds 256 KiB."); } } using BinaryReader reader = new BinaryReader(new MemoryStream(memoryStream2.ToArray(), writable: false), StrictUtf8); ValidateEntries(reader, maxEntries, settingType); } else { memoryStream.Position = 0L; ValidateEntries(binaryReader, maxEntries, settingType); } return true; } catch (Exception ex) when (ex is IOException || ex is InvalidDataException || ex is DecoderFallbackException) { diagnostic = ex.Message; return false; } } private static void ValidateEntries(BinaryReader reader, int maxEntries, Func settingType) { if (reader.ReadByte() != 1) { throw new InvalidDataException("Only complete partial-settings requests are supported."); } int num = reader.ReadInt32(); if (num < 1 || num > maxEntries) { throw new InvalidDataException("Invalid settings entry count."); } for (int i = 0; i < num; i++) { string text = ReadString(reader, 128); string arg = ReadString(reader, 128); string text2 = ReadString(reader, 1024); Type type = ((text == "Internal") ? null : settingType(text, arg)); if (type == null) { throw new InvalidDataException("Unknown or server-owned settings entry."); } Type type2 = (type.IsEnum ? Enum.GetUnderlyingType(type) : type); if (text2 != type2.AssemblyQualifiedName) { throw new InvalidDataException("Settings entry type mismatch."); } if (type2 == typeof(bool)) { if (reader.ReadByte() > 1) { throw new InvalidDataException("Invalid Boolean settings value."); } } else if (type2 == typeof(int)) { int num2 = reader.ReadInt32(); if (type.IsEnum && !Enum.IsDefined(type, num2)) { throw new InvalidDataException("Unknown settings enumeration value."); } } else if (type2 == typeof(float)) { float f = reader.ReadSingle(); if (float.IsNaN(f) || float.IsInfinity(f)) { throw new InvalidDataException("Nonfinite settings value."); } } else { if (!(type2 == typeof(string))) { throw new InvalidDataException("Unsupported settings value type."); } ReadString(reader, 262144); } } if (reader.BaseStream.Position != reader.BaseStream.Length) { throw new InvalidDataException("Trailing settings request data."); } } private static string ReadString(BinaryReader reader, int limit) { uint num = 0u; for (int i = 0; i < 35; i += 7) { byte b = reader.ReadByte(); if (i == 28 && b > 7) { throw new InvalidDataException("Invalid settings string length."); } num |= (uint)((b & 0x7F) << i); if ((b & 0x80) == 0) { if (num > limit || num > reader.BaseStream.Length - reader.BaseStream.Position) { throw new InvalidDataException("Settings string exceeds its bound or is truncated."); } byte[] bytes = reader.ReadBytes((int)num); return StrictUtf8.GetString(bytes); } } throw new InvalidDataException("Invalid settings string length."); } } internal static class ServerSyncVersionAdvertisement { public static bool TrySend(bool isServer, bool modRequired, string currentVersion, string minimumVersion, Action send) { if (isServer || modRequired) { return false; } using MemoryStream memoryStream = new MemoryStream(); using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream, Encoding.UTF8, leaveOpen: true)) { binaryWriter.Write("com.bastionntb.yavsos"); binaryWriter.Write(minimumVersion); binaryWriter.Write(currentVersion); } send("ServerSync VersionCheck", memoryStream.ToArray()); return true; } } internal static class ServerYavsosProbe { private static readonly FieldInfo? Checks = typeof(VersionCheck).GetField("versionChecks", BindingFlags.Static | BindingFlags.NonPublic); private static readonly FieldInfo? Received = typeof(VersionCheck).GetField("ReceivedCurrentVersion", BindingFlags.Instance | BindingFlags.NonPublic); internal static bool Supported { get { if (Checks != null && typeof(IEnumerable).IsAssignableFrom(Checks.FieldType) && Received != null) { return Received.FieldType == typeof(string); } return false; } } internal static bool TryVersionReceived(out bool received) { received = false; if (!Supported) { return false; } try { if (!(Checks.GetValue(null) is IEnumerable enumerable)) { return false; } foreach (object item in enumerable) { if (item is VersionCheck { Name: "com.bastionntb.yavsos" } versionCheck) { received = Received.GetValue(versionCheck) != null; return true; } } } catch (Exception ex) when (ex is TargetException || ex is FieldAccessException || ex is InvalidOperationException) { } return false; } } } namespace YAVSOS.Interface { internal sealed class ChestHighlight { internal const float Refresh = 0.5f; internal const int MaximumLit = 32; internal const int ChecksPerFrame = 16; internal const int MaximumItems = 64; private static readonly Color Gold = new Color(1f, 0.78f, 0.25f); private readonly ManualLogSource log; private bool probed; private bool supported; private readonly List queue = new List(); private readonly List<(Container Chest, GameObject Target)> lit = new List<(Container, GameObject)>(); private string category = ""; private string key = ""; private readonly List items = new List(); private readonly HighlightLinger linger = new HighlightLinger(); private float nextRefresh; internal readonly List Found = new List(); internal bool Scanning => queue.Count != 0; internal int Revision { get; private set; } internal string Category => category; internal bool Active => key.Length != 0; internal bool Supported { get { if (probed) { return supported; } probed = true; OptionalCapability val = ChestHighlightCapability.Probe(delegate(string name) { Type? type; if (!(name == "UnityEngine.GameObject")) { type = typeof(WearNTear).Assembly.GetType(name, throwOnError: false); if ((object)type == null) { return AccessTools.TypeByName(name); } } else { type = typeof(GameObject); } return type; }); supported = val.Supported; if (!supported) { log.LogWarning((object)("Chest highlight turned off; the rule panel still lists matching chests. " + val.Witness)); } return supported; } } internal bool Lit => lit.Count != 0; internal ChestHighlight(ManualLogSource log) { //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Expected O, but got Unknown this.log = log; } internal void Request(string focus, IReadOnlyList wanted, bool rescan = false) { if (focus == null) { focus = ""; } if (wanted == null) { wanted = Array.Empty(); } string text = focus + "\n" + string.Join("\n", wanted.Take(64)); if (!rescan && text == key && (Scanning || linger.On(Time.unscaledTime))) { linger.Hold(); return; } Clear(); Player localPlayer = Player.m_localPlayer; PluginSettings pluginSettings = Plugin.Instance?.Settings; if (Object.op_Implicit((Object)(object)localPlayer) && pluginSettings != null && (focus.Length != 0 || wanted.Count != 0)) { category = focus; key = text; items.AddRange(wanted.Take(64)); long started = UiCost.Start(); queue.AddRange(CleanupRunner.Nearby(localPlayer, pluginSettings.EffectiveCleanupRange).Take(256)); UiCost.Stop("highlight scene query", started); queue.Reverse(); linger.Hold(); Revision++; } } internal void Release(float seconds) { linger.Release(Time.unscaledTime, seconds); } internal void Clear() { Expire(); queue.Clear(); Found.Clear(); items.Clear(); category = (key = ""); linger.End(); Revision++; } private void Expire() { for (int i = 0; i < lit.Count; i++) { Reset(lit[i].Target); } lit.Clear(); } internal void Update() { if (lit.Count == 0 && queue.Count == 0) { return; } float unscaledTime = Time.unscaledTime; Plugin instance = Plugin.Instance; if (!linger.On(unscaledTime) || !Object.op_Implicit((Object)(object)Player.m_localPlayer) || (Object)(object)instance == (Object)null) { queue.Clear(); Expire(); Revision++; return; } for (int i = 0; i < 16; i++) { if (queue.Count == 0) { break; } Container val = queue[queue.Count - 1]; queue.RemoveAt(queue.Count - 1); if (queue.Count == 0) { Revision++; } if (Object.op_Implicit((Object)(object)val) && Takes(instance, val)) { Found.Add(val); if (lit.Count < 32 && Supported) { GameObject val2 = Target(val); lit.Add((val, val2)); Paint(val2); } Revision++; } } if (unscaledTime < nextRefresh || !supported) { return; } nextRefresh = unscaledTime + 0.5f; int num = lit.Count - 1; while (num >= 0 && supported) { if (!Object.op_Implicit((Object)(object)lit[num].Chest) || !Object.op_Implicit((Object)(object)lit[num].Target)) { lit.RemoveAt(num); } else { Paint(lit[num].Target); } num--; } } private bool Takes(Plugin plugin, Container chest) { string text = ChestRuleStore.Payload(chest); if (text.Length == 0) { return false; } ClassificationTaxonomy ruleTaxonomy = plugin.RuleTaxonomy; ICategoryAnswers categoryAnswers = plugin.CategoryAnswers; if (items.Count != 0 && categoryAnswers != null) { foreach (string item in items) { if (plugin.RuleEvaluator.CouldAccept(text, item, ruleTaxonomy, categoryAnswers)) { return true; } } return false; } return RuleText.TakesCategory(plugin.RuleEvaluator.Read(text, ruleTaxonomy).Rules, ruleTaxonomy, category); } private static GameObject Target(Container chest) { WearNTear componentInParent = ((Component)chest).GetComponentInParent(); if (!Object.op_Implicit((Object)(object)componentInParent)) { return ((Component)chest).gameObject; } return ((Component)componentInParent).gameObject; } private void Paint(GameObject target) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) try { MaterialMan.instance.SetValue(target, ShaderProps._EmissionColor, Gold * 0.4f, false); MaterialMan.instance.SetValue(target, ShaderProps._Color, Gold, false); } catch (Exception error) when (OptionalFailure.Recoverable(error)) { Fail(error); } } private void Reset(GameObject target) { if (!Object.op_Implicit((Object)(object)target) || !Object.op_Implicit((Object)(object)MaterialMan.instance)) { return; } try { MaterialMan.instance.ResetValue(target, ShaderProps._Color); MaterialMan.instance.ResetValue(target, ShaderProps._EmissionColor); } catch (Exception error) when (OptionalFailure.Recoverable(error)) { Fail(error); } } private void Fail(Exception error) { if (supported) { supported = false; log.LogWarning((object)("Chest highlight turned off after " + error.GetType().Name + ": " + error.Message + "; the rule panel still lists matching chests.")); Expire(); } } internal string Status() { return HighlightText.Status(Active, Found.Count, Lit, Scanning, Plugin.Instance?.Settings.EffectiveCleanupRange ?? 0f, category.Length == 0 && items.Count > 1); } internal IReadOnlyList Chests(Func name) { return Found.Where((Container x) => Object.op_Implicit((Object)(object)x)).Select(name).ToList(); } } internal static class ChestHighlightCapability { internal const string Adapter = "chest-highlight"; internal const string MaterialMan = "MaterialMan"; internal const string ShaderProps = "ShaderProps"; internal const string GameObject = "UnityEngine.GameObject"; internal static OptionalCapability Probe(OptionalTypeResolver? resolve) { //IL_0197: Unknown result type (might be due to invalid IL or missing references) //IL_019e: Expected O, but got Unknown if (resolve == null) { return OptionalCapability.Incompatible("chest-highlight", "", "no type resolver"); } try { Type type = OptionalJotunnApi.Require(resolve, "MaterialMan"); Type type2 = OptionalJotunnApi.Require(resolve, "ShaderProps"); Type gameObject = OptionalJotunnApi.Require(resolve, "UnityEngine.GameObject"); PropertyInfo property = type.GetProperty("instance", BindingFlags.Static | BindingFlags.Public); if (property == null || property.PropertyType != type || property.GetGetMethod() == null || property.GetIndexParameters().Length != 0) { throw new MissingMemberException("MaterialMan.instance"); } if (type.GetMethods(BindingFlags.Instance | BindingFlags.Public).FirstOrDefault((MethodInfo x) => x.Name == "SetValue" && x.IsGenericMethodDefinition && x.GetGenericArguments().Length == 1 && x.ReturnType == typeof(void) && (from p in x.GetParameters() select p.ParameterType).SequenceEqual(new Type[4] { gameObject, typeof(int), x.GetGenericArguments()[0], typeof(bool) })) == null) { throw new MissingMemberException("MaterialMan.SetValue"); } MethodInfo method = type.GetMethod("ResetValue", BindingFlags.Instance | BindingFlags.Public, null, new Type[2] { gameObject, typeof(int) }, null); if (method == null || method.ReturnType != typeof(void)) { throw new MissingMemberException("MaterialMan.ResetValue"); } string[] array = new string[2] { "_Color", "_EmissionColor" }; foreach (string text in array) { FieldInfo field = type2.GetField(text, BindingFlags.Static | BindingFlags.Public); if (field == null || field.FieldType != typeof(int)) { throw new MissingMemberException("ShaderProps." + text); } } return new OptionalCapability("chest-highlight", (OptionalCapabilityState)1, "", "MaterialMan property blocks and ShaderProps colour IDs"); } catch (Exception ex) when (OptionalFailure.Recoverable(ex)) { return OptionalCapability.Incompatible("chest-highlight", "", "game shape: " + ex.Message); } } } [HarmonyPatch(typeof(Container), "GetHoverText")] internal static class ChestLabels { private sealed class Cached { internal string Payload = "\0"; internal object? Taxonomy; internal string Line = ""; } internal const string BetterUi = "MK_BetterUI"; private static readonly ConditionalWeakTable Cache = new ConditionalWeakTable(); private static bool failed; internal static ManualLogSource? Log; private static readonly Func? CheckAccess = Bind(); private static Func? Bind() { try { MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(Container), "CheckAccess", new Type[1] { typeof(long) }, (Type[])null); return (methodInfo?.ReturnType == typeof(bool)) ? AccessTools.MethodDelegate>(methodInfo, (object)null, true) : null; } catch (Exception error) when (OptionalFailure.Recoverable(error)) { return null; } } private static bool Accessible(Container chest, long player) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) if (!chest.m_checkGuardStone || PrivateArea.CheckAccess(((Component)chest).transform.position, 0f, false, false)) { if (CheckAccess != null) { return CheckAccess(chest, player); } return true; } return false; } [HarmonyPostfix] [HarmonyAfter(new string[] { "MK_BetterUI" })] [HarmonyPriority(200)] private static void Append(Container __instance, ref string __result) { if (failed || string.IsNullOrEmpty(__result)) { return; } Plugin instance = Plugin.Instance; if ((Object)(object)instance == (Object)null || !instance.Settings.ShowChestLabels.Value) { return; } try { string text = ChestRuleStore.Payload(__instance); if (text.Length == 0) { return; } Player localPlayer = Player.m_localPlayer; if (Object.op_Implicit((Object)(object)localPlayer) && Accessible(__instance, localPlayer.GetPlayerID())) { ClassificationTaxonomy ruleTaxonomy = instance.RuleTaxonomy; Cached orCreateValue = Cache.GetOrCreateValue(__instance); if (((object)orCreateValue.Payload != text && !StringComparer.Ordinal.Equals(orCreateValue.Payload, text)) || orCreateValue.Taxonomy != ruleTaxonomy) { orCreateValue.Payload = text; orCreateValue.Taxonomy = ruleTaxonomy; ContainerPolicyRead val = instance.RuleEvaluator.Read(text, ruleTaxonomy); string text2 = (val.HasRule ? RuleText.Label(val.Rules, ruleTaxonomy, (Func)RuleControls.ItemName, (Func)RuleControls.OpenValueName) : null); orCreateValue.Line = ((text2 == null) ? "" : ("\n" + Plain(text2) + "")); } if (orCreateValue.Line.Length != 0) { __result += orCreateValue.Line; } } } catch (Exception ex) when (OptionalFailure.Recoverable(ex)) { failed = true; ManualLogSource? log = Log; if (log != null) { log.LogWarning((object)("Chest labels turned off: " + ex.GetType().Name + ": " + ex.Message)); } } } private static string Plain(string text) { return text.Replace("<", "‹").Replace(">", "›"); } } internal sealed class ItemGridView { private sealed class CellView { private readonly RectTransform root; private readonly Image slot; private readonly Image image; private readonly Image mark; private readonly UITooltip? tip; private readonly TipFill fill; private GridEntry? entry; private readonly ItemGridView owner; internal GridEntry? Hovered { get { if (!fill.Hovered || !((Component)root).gameObject.activeSelf) { return null; } return entry; } } internal CellView(ItemGridView owner, RectTransform parent) { //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Expected O, but got Unknown //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Expected O, but got Unknown //IL_00a0: 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_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_01d0: Unknown result type (might be due to invalid IL or missing references) //IL_01da: Expected O, but got Unknown CellView cellView = this; GameObject val = new GameObject("Item", new Type[4] { typeof(RectTransform), typeof(Image), typeof(Button), typeof(TipFill) }); root = (RectTransform)val.transform; ((Transform)root).SetParent((Transform)(object)parent, false); RectTransform obj = root; RectTransform obj2 = root; RectTransform obj3 = root; Vector2 val2 = default(Vector2); ((Vector2)(ref val2))..ctor(0f, 1f); obj3.pivot = val2; obj.anchorMin = (obj2.anchorMax = val2); root.sizeDelta = new Vector2(42f, 42f); slot = val.GetComponent(); ((Graphic)slot).color = Slot; image = Child("Icon", 38f); image.preserveAspect = true; mark = Child("Mark", 30f); fill = val.GetComponent(); GameObject val4 = ((!Object.op_Implicit((Object)(object)InventoryGui.instance) || !Object.op_Implicit((Object)(object)InventoryGui.instance.m_playerGrid) || !Object.op_Implicit((Object)(object)InventoryGui.instance.m_playerGrid.m_elementPrefab)) ? null : InventoryGui.instance.m_playerGrid.m_elementPrefab.GetComponent()?.m_tooltipPrefab); if (Object.op_Implicit((Object)(object)val4)) { tip = val.AddComponent(); tip.m_tooltipPrefab = val4; } fill.Fill = delegate { //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) if (cellView.entry != null && Object.op_Implicit((Object)(object)cellView.tip)) { var (text, text2) = owner.tooltip(cellView.entry); cellView.tip.Set(text, text2, (RectTransform)null, default(Vector2)); } }; ((UnityEvent)val.GetComponent