Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of CraftFrom v1.0.0
CraftFrom.dll
Decompiled 3 days ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Linq.Expressions; using System.Numerics; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using JetBrains.Annotations; using Microsoft.CodeAnalysis; using ServerSync; using TMPro; using UnityEngine; using UnityEngine.UI; using YamlDotNet.Core; using YamlDotNet.Core.Events; using YamlDotNet.Core.ObjectPool; using YamlDotNet.Core.Tokens; using YamlDotNet.Helpers; using YamlDotNet.Serialization; using YamlDotNet.Serialization.BufferedDeserialization; using YamlDotNet.Serialization.BufferedDeserialization.TypeDiscriminators; using YamlDotNet.Serialization.Callbacks; using YamlDotNet.Serialization.Converters; using YamlDotNet.Serialization.EventEmitters; using YamlDotNet.Serialization.NamingConventions; using YamlDotNet.Serialization.NodeDeserializers; using YamlDotNet.Serialization.NodeTypeResolvers; using YamlDotNet.Serialization.ObjectFactories; using YamlDotNet.Serialization.ObjectGraphTraversalStrategies; using YamlDotNet.Serialization.ObjectGraphVisitors; using YamlDotNet.Serialization.Schemas; using YamlDotNet.Serialization.TypeInspectors; using YamlDotNet.Serialization.TypeResolvers; using YamlDotNet.Serialization.Utilities; using YamlDotNet.Serialization.ValueDeserializers; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("CraftFrom.Tests")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyCompany("sighsorry")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+748196bfd3dae292b2d9187d115e65bee4766991")] [assembly: AssemblyProduct("CraftFrom")] [assembly: AssemblyTitle("CraftFrom")] [assembly: AssemblyVersion("1.0.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace CraftFrom { internal static class BuildingContracts { private enum Kind { Prefix, Postfix, Transpiler, Finalizer, ILManipulator } private readonly struct Required { internal readonly MethodInfo Target; internal readonly MethodInfo Method; internal readonly Kind Kind; internal Required(MethodInfo target, Type type, string name, Kind kind) { Target = target; Method = ((type == null) ? null : AccessTools.DeclaredMethod(type, name, (Type[])null, (Type[])null)); Kind = kind; } } private readonly struct Entry { internal readonly MethodInfo Target; internal readonly MethodInfo Method; internal readonly string Owner; internal readonly string Before; internal readonly string After; internal readonly int Priority; internal readonly int Index; internal readonly Kind Kind; internal Entry(MethodInfo target, Patch patch, Kind kind) { Target = target; Method = patch.PatchMethod; Owner = patch.owner; Kind = kind; Priority = patch.priority; Index = patch.index; Before = string.Join("|", patch.before ?? Array.Empty<string>()); After = string.Join("|", patch.after ?? Array.Empty<string>()); } internal bool Same(Entry other) { if (Target == other.Target && Method == other.Method && Owner == other.Owner && Kind == other.Kind && Priority == other.Priority && Index == other.Index && Before == other.Before) { return After == other.After; } return false; } } private const string Owner = "sighsorry.CraftFrom.Building"; private const string FineDining = "sighsorry.FineDining"; private static readonly MethodInfo Update = AccessTools.DeclaredMethod(typeof(Player), "UpdatePlacement", (Type[])null, (Type[])null); private static readonly MethodInfo TryPlace = AccessTools.DeclaredMethod(typeof(Player), "TryPlacePiece", (Type[])null, (Type[])null); private static readonly MethodInfo Place = AccessTools.DeclaredMethod(typeof(Player), "PlacePiece", (Type[])null, (Type[])null); private static readonly MethodInfo AvailablePieces = AccessTools.DeclaredMethod(typeof(Player), "UpdateAvailablePiecesList", (Type[])null, (Type[])null); private static readonly MethodInfo Requirements = AccessTools.DeclaredMethod(typeof(Player), "HaveRequirements", new Type[2] { typeof(Piece), typeof(RequirementMode) }, (Type[])null); private static readonly MethodInfo[] Targets = new MethodInfo[5] { Update, TryPlace, Place, Requirements, AvailablePieces }; private static readonly Required[] RequiredPatches = new Required[11] { new Required(Update, typeof(BuildingExecution), "EnterPlacement", Kind.Prefix), new Required(Update, typeof(BuildingExecution), "LeavePlacement", Kind.Finalizer), new Required(Update, typeof(BuildingExecution), "PlacementCalls", Kind.Transpiler), new Required(TryPlace, typeof(BuildingExecution), "Provenance", Kind.Transpiler), new Required(Place, typeof(BuildingExecution), "GuardPlacement", Kind.Prefix), new Required(Place, typeof(BuildingExecution), "Receipt", Kind.Transpiler), new Required(Place, typeof(BuildingExecution), "InfinitySelectionGuard", Kind.Transpiler), new Required(AvailablePieces, typeof(BuildingExecution), "InventoryPreview", Kind.Transpiler), new Required(Requirements, typeof(BuildingDisplay).GetNestedType("Requirements", BindingFlags.NonPublic), "Prefix", Kind.Prefix), new Required(Requirements, typeof(BuildingDisplay).GetNestedType("Requirements", BindingFlags.NonPublic), "Finalizer", Kind.Finalizer), new Required(Requirements, typeof(BuildingDisplay).GetNestedType("Requirements", BindingFlags.NonPublic), "Transpiler", Kind.Transpiler) }; private static List<Entry> verifiedGraph; private static bool result; private static float expires = float.NegativeInfinity; private static string warned; internal static string Failure { get; private set; } internal static bool Verify(bool recheck = false) { if (!recheck && Time.unscaledTime < expires) { return result; } expires = Time.unscaledTime + 1f; try { List<Entry> list = Collect(); Required[] requiredPatches = RequiredPatches; for (int i = 0; i < requiredPatches.Length; i++) { Required required = requiredPatches[i]; if (required.Target == null || required.Method == null || list.Count((Entry p) => p.Target == required.Target && p.Method == required.Method && p.Kind == required.Kind && p.Owner == "sighsorry.CraftFrom.Building") != 1) { throw new NotSupportedException("Required building hook is missing: " + (required.Method?.Name ?? "unknown") + "."); } } if (verifiedGraph == null || list.Count != verifiedGraph.Count || list.Where((Entry entry, int index) => !entry.Same(verifiedGraph[index])).Any()) { CheckInstructions(); MethodInfo method = RequiredPatches.Single((Required p) => p.Target == Requirements && p.Kind == Kind.Prefix).Method; if (PatchProcessor.GetSortedPatchMethods((MethodBase)Requirements, Harmony.GetPatchInfo((MethodBase)Requirements).Prefixes.ToArray()).FirstOrDefault() != method) { throw new NotSupportedException("The material-query depth guard must run before other requirements prefixes."); } verifiedGraph = list; } Failure = null; warned = null; return result = true; } catch (Exception ex) { Failure = ex.GetBaseException().Message; if (warned != Failure) { warned = Failure; ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)("Nearby-chest building suspended: " + Failure + " Existing crafting and native building remain available.")); } } return result = false; } } private static List<Entry> Collect() { List<Entry> list = new List<Entry>(); MethodInfo[] targets = Targets; foreach (MethodInfo target in targets) { if (target == null) { throw new MissingMethodException("A native building method is unavailable."); } Patches patchInfo = Harmony.GetPatchInfo((MethodBase)target); if (patchInfo != null) { list.AddRange(patchInfo.Prefixes.Select((Patch p) => new Entry(target, p, Kind.Prefix))); list.AddRange(patchInfo.Postfixes.Select((Patch p) => new Entry(target, p, Kind.Postfix))); list.AddRange(patchInfo.Transpilers.Select((Patch p) => new Entry(target, p, Kind.Transpiler))); list.AddRange(patchInfo.Finalizers.Select((Patch p) => new Entry(target, p, Kind.Finalizer))); list.AddRange(patchInfo.ILManipulators.Select((Patch p) => new Entry(target, p, Kind.ILManipulator))); } } return list; } private static void CheckInstructions() { List<CodeInstruction> currentInstructions = PatchProcessor.GetCurrentInstructions((MethodBase)Update, int.MaxValue, (ILGenerator)null); MethodInfo query = Helper(typeof(BuildingDisplay), "CheckForPlacement"); MethodInfo build = Helper(typeof(BuildingExecution), "TryBuild"); MethodInfo consume = Helper(typeof(BuildingExecution), "Consume"); Exactly(currentInstructions, query, 1); Exactly(currentInstructions, build, 1); Exactly(currentInstructions, consume, 1); Exactly(currentInstructions, TryPlace, 0); Exactly(currentInstructions, Helper(typeof(Player), "ConsumeResources"), 0); int index = currentInstructions.FindIndex((CodeInstruction i) => CodeInstructionExtensions.Calls(i, query)); if (!BuildingExecution.IsPlacementQuery(currentInstructions, index, build) || currentInstructions.FindIndex((CodeInstruction i) => CodeInstructionExtensions.Calls(i, consume)) <= currentInstructions.FindIndex((CodeInstruction i) => CodeInstructionExtensions.Calls(i, build))) { throw new NotSupportedException("The scoped material query no longer directly guards its paid placement."); } List<CodeInstruction> currentInstructions2 = PatchProcessor.GetCurrentInstructions((MethodBase)AvailablePieces, int.MaxValue, (ILGenerator)null); Exactly(currentInstructions2, Helper(typeof(BuildingExecution), "RefreshAfterInventoryChange"), 1); Exactly(currentInstructions2, Helper(typeof(Player), "SetupPlacementGhost"), 0); List<CodeInstruction> currentInstructions3 = PatchProcessor.GetCurrentInstructions((MethodBase)Place, int.MaxValue, (ILGenerator)null); if (BuildingInfinityHammer.HasUnwrappedPrefabCallback(currentInstructions3)) { throw new NotSupportedException("The active Infinity Hammer prefab callback is unavailable to CraftFrom's initialization cleanup adapter."); } MethodInfo receipt = Helper(typeof(BuildingExecution), "RecordCreation"); Exactly(currentInstructions3, receipt, 1); int num = currentInstructions3.FindIndex(BuildingExecution.IsPieceInstantiation); int num2 = currentInstructions3.FindIndex((CodeInstruction i) => CodeInstructionExtensions.Calls(i, receipt)); int num3 = currentInstructions3.FindIndex((CodeInstruction i) => i.operand is MethodInfo methodInfo && methodInfo.DeclaringType == typeof(Piece) && methodInfo.Name == "SetCreator"); if (num < 0 || currentInstructions3.FindIndex(num + 1, BuildingExecution.IsPieceInstantiation) >= 0 || num2 <= num || num3 <= num2) { throw new NotSupportedException("The creation receipt no longer precedes native creator/effect callbacks."); } List<CodeInstruction> currentInstructions4 = PatchProcessor.GetCurrentInstructions((MethodBase)TryPlace, int.MaxValue, (ILGenerator)null); Exactly(currentInstructions4, Helper(typeof(BuildingExecution), "IncludeCheated"), 1); Exactly(currentInstructions4, Place, 1); List<CodeInstruction> currentInstructions5 = PatchProcessor.GetCurrentInstructions((MethodBase)Requirements, int.MaxValue, (ILGenerator)null); MethodInfo method = Helper(typeof(BuildingDisplay), "CountForBuilding"); Exactly(currentInstructions5, method, 1); static void Exactly(List<CodeInstruction> code, MethodInfo methodInfo, int count) { if (methodInfo == null || code.Count((CodeInstruction i) => CodeInstructionExtensions.Calls(i, methodInfo)) != count) { throw new NotSupportedException("Active building call shape changed: " + methodInfo?.Name + "."); } } static MethodInfo Helper(Type type, string name) { return AccessTools.DeclaredMethod(type, name, (Type[])null, (Type[])null); } } internal static bool AllowsPiece(Piece piece) { if (Object.op_Implicit((Object)(object)piece) && Object.op_Implicit((Object)(object)((Component)piece).GetComponent<ItemDrop>())) { return !Chainloader.PluginInfos.ContainsKey("sighsorry.FineDining"); } return true; } internal static void Reset() { verifiedGraph = null; result = false; expires = float.NegativeInfinity; warned = (Failure = null); BuildingInfinityHammer.Reset(); } } internal static class BuildingDisplay { private readonly struct Query { internal readonly Player Player; internal readonly Piece Piece; internal readonly int Depth; internal Query(Player player, Piece piece, int depth) { Player = player; Piece = piece; Depth = depth; } } private readonly struct RequirementScope { internal readonly int Previous; internal readonly bool Entered; internal RequirementScope(int previous) { Previous = previous; Entered = true; } } [HarmonyPatch] private static class HudScope { private static IEnumerable<MethodBase> TargetMethods() { yield return AccessTools.DeclaredMethod(typeof(Hud), "UpdatePieceBuildStatus", (Type[])null, (Type[])null); yield return AccessTools.DeclaredMethod(typeof(Hud), "UpdatePieceBuildStatusAll", (Type[])null, (Type[])null); yield return AccessTools.DeclaredMethod(typeof(BuildUiPieceButton), "UpdateRequirements", (Type[])null, (Type[])null); } private static void Prefix(out int __state) { __state = hudDepth; hudDepth++; } private static void Finalizer(int __state) { hudDepth = __state; } } [HarmonyPatch(typeof(BuildUi), "Update")] private static class RefreshButtons { private static void Postfix(BuildUi __instance) { Player localPlayer = Player.m_localPlayer; if (!Object.op_Implicit((Object)(object)localPlayer) || !((Behaviour)__instance).isActiveAndEnabled || !((Character)localPlayer).InPlaceMode()) { return; } try { bool buildingReady = Plugin.BuildingReady; bool flag = buttonUi != __instance || buttonPlayer != localPlayer || buttonsEnabled != buildingReady; if (!buildingReady && !buttonsEnabled) { return; } if (buildingReady) { using (ChestAuthority.ReadOnlyQuery()) { ChestCatalog.Nearby(localPlayer, (Component)(object)localPlayer); } } if (!flag && (buttonRevision == ChestCatalog.Revision || Time.unscaledTime < nextButtonRefresh)) { return; } buttonUi = __instance; buttonPlayer = localPlayer; buttonsEnabled = buildingReady; buttonRevision = ChestCatalog.Revision; nextButtonRefresh = Time.unscaledTime + 0.25f; foreach (BuildUiPieceButton item in PieceButtons.Invoke(__instance)) { if (Object.op_Implicit((Object)(object)item) && ((Component)item).gameObject.activeInHierarchy) { item.UpdateRequirements(); } } } catch (Exception error) { Failed(error); } } } [HarmonyPatch(typeof(Hud), "SetupPieceInfo")] private static class SelectionScope { private static void Prefix(Piece piece, out Piece __state) { __state = selected; selected = piece; } private static void Finalizer(Piece __state) { selected = __state; } } [HarmonyPatch(typeof(Hud), "UpdatePieceList")] private static class RefreshList { private static void Prefix(Player player, ref bool updateAllBuildStatuses) { if (!Plugin.BuildingReady || (Object)(object)player != (Object)(object)Player.m_localPlayer || !Object.op_Implicit((Object)(object)player)) { return; } try { using (ChestAuthority.ReadOnlyQuery()) { ChestCatalog.Nearby(player, (Component)(object)player); } if (listedRevision != ChestCatalog.Revision && !(Time.unscaledTime < nextRefresh)) { listedRevision = ChestCatalog.Revision; nextRefresh = Time.unscaledTime + 0.25f; updateAllBuildStatuses = true; } } catch (Exception error) { Failed(error); } } } [HarmonyPatch(typeof(Player), "HaveRequirements", new Type[] { typeof(Piece), typeof(RequirementMode) })] private static class Requirements { [HarmonyPrefix] [HarmonyPriority(int.MaxValue)] private static void Prefix(out RequirementScope __state) { __state = new RequirementScope(requirementsDepth); requirementsDepth++; } [HarmonyFinalizer] [HarmonyPriority(int.MinValue)] private static void Finalizer(RequirementScope __state) { if (__state.Entered) { if (query.Depth == __state.Previous + 1) { query = default(Query); } requirementsDepth = __state.Previous; } } [HarmonyBefore(new string[] { "sighsorry.Groundwork" })] private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> list = instructions.ToList(); MethodInfo count = AccessTools.DeclaredMethod(typeof(Inventory), "CountItems", new Type[3] { typeof(string), typeof(int), typeof(bool) }, (Type[])null); if (list.Count((CodeInstruction i) => CodeInstructionExtensions.Calls(i, count)) != 1) { throw new NotSupportedException("Vanilla building material-count call changed."); } foreach (CodeInstruction instruction in list) { yield return instruction; if (CodeInstructionExtensions.Calls(instruction, count)) { yield return new CodeInstruction(OpCodes.Ldarg_0, (object)null); yield return new CodeInstruction(OpCodes.Ldarg_1, (object)null); yield return new CodeInstruction(OpCodes.Ldarg_2, (object)null); yield return new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(BuildingDisplay), "CountForBuilding", (Type[])null, (Type[])null)); } } } } [HarmonyPatch(typeof(InventoryGui), "SetupRequirement")] private static class RequirementRow { private static void Postfix(bool __result, Transform elementRoot, Requirement req, Player player, int quality, int craftMultiplier) { //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) if (!__result || !Object.op_Implicit((Object)(object)selected) || quality != 0 || req == null || !Object.op_Implicit((Object)(object)req.m_resItem) || !BuildingExecution.Handles(player, selected) || Array.IndexOf(selected.m_resources, req) < 0) { return; } try { int num = req.GetAmount(quality) * craftMultiplier; if (num > 0) { int num2 = BuildingPlanner.Count(player, req, selected); TMP_Text value = Labels.GetValue(elementRoot, FindLabel); value.SetText("{0}/{1}", (float)num2, (float)num); long num3 = BuildingPlanner.Required(selected, req) * craftMultiplier; ((Graphic)value).color = ((num2 < num3 && Mathf.Sin(Time.time * 10f) > 0f) ? Color.red : Color.white); } } catch (Exception error) { Failed(error); } } } [ThreadStatic] private static int hudDepth; [ThreadStatic] private static Piece selected; [ThreadStatic] private static int requirementsDepth; [ThreadStatic] private static int nativeOnlyDepth; [ThreadStatic] private static Query query; private static long listedRevision = -1L; private static float nextRefresh; private static bool loggedFailure; private static BuildUi buttonUi; private static Player buttonPlayer; private static bool buttonsEnabled; private static long buttonRevision = -1L; private static float nextButtonRefresh; private static readonly FieldRef<BuildUi, List<BuildUiPieceButton>> PieceButtons = AccessTools.FieldRefAccess<BuildUi, List<BuildUiPieceButton>>("m_pieceButtons"); private static readonly ConditionalWeakTable<Transform, TMP_Text> Labels = new ConditionalWeakTable<Transform, TMP_Text>(); private static readonly ConditionalWeakTable<Transform, TMP_Text>.CreateValueCallback FindLabel = (Transform root) => ((Component)root.Find("res_amount")).GetComponent<TMP_Text>(); internal static void Reset() { hudDepth = 0; selected = null; requirementsDepth = (nativeOnlyDepth = 0); query = default(Query); listedRevision = -1L; nextRefresh = 0f; loggedFailure = false; buttonUi = null; buttonPlayer = null; buttonsEnabled = false; buttonRevision = -1L; nextButtonRefresh = 0f; BuildingPlanner.Reset(); } private static void Failed(Exception error) { if (!loggedFailure) { loggedFailure = true; ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)("Building material display could not be updated: " + error.GetBaseException().Message)); } } } internal static bool OwnsRow(Player p, Requirement row) { if (Object.op_Implicit((Object)(object)selected) && BuildingExecution.Handles(p, selected)) { return Array.IndexOf(selected.m_resources, row) >= 0; } return false; } internal static bool TryQuote(Player player, Piece piece, int index, out int available, out int needed, out bool affordable) { available = (needed = 0); affordable = false; if (!BuildingExecution.Handles(player, piece) || (uint)index >= piece.m_resources.Length) { return false; } Requirement[] array = (((Object)(object)selected == (Object)(object)piece) ? piece.m_resources : PathOfValheiman.BuildCosts(player, piece)); if (array == null || (uint)index >= array.Length || (Object)(object)array[index]?.m_resItem == (Object)null) { return false; } needed = array[index].GetAmount(0); available = BuildingPlanner.Count(player, array[index], piece); affordable = available >= BuildingPlanner.Required(piece, array[index], array); return needed > 0; } internal static bool UsesShared(Player player, Piece piece, RequirementMode mode) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) if ((int)mode == 0 && nativeOnlyDepth == 0 && (hudDepth > 0 || ((Object)(object)query.Player == (Object)(object)player && (Object)(object)query.Piece == (Object)(object)piece && query.Depth == requirementsDepth && query.Depth > 0))) { return BuildingExecution.Handles(player, piece); } return false; } internal static int CountForBuilding(int original, Player player, Piece piece, RequirementMode mode) { //IL_004d: Unknown result type (might be due to invalid IL or missing references) bool flag = (Object)(object)query.Player == (Object)(object)player && (Object)(object)query.Piece == (Object)(object)piece && query.Depth == requirementsDepth && query.Depth > 0; if (nativeOnlyDepth != 0 || (int)mode != 0 || (hudDepth == 0 && !flag) || !BuildingExecution.Handles(player, piece)) { return original; } try { return ((flag && BuildingExecution.HasPaidRequirements(player, piece)) || BuildingPlanner.CanBuild(player, piece)) ? int.MaxValue : 0; } catch (Exception error) { Failed(error); return 0; } } internal static bool CheckForPlacement(Player player, Piece piece, RequirementMode mode) { //IL_0000: 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_0031: Unknown result type (might be due to invalid IL or missing references) if ((int)mode != 0 || !BuildingExecution.Handles(player, piece, recheck: true)) { return CheckNative(player, piece, mode); } Query query = BuildingDisplay.query; BuildingDisplay.query = new Query(player, piece, requirementsDepth + 1); try { return player.HaveRequirements(piece, mode); } finally { BuildingDisplay.query = query; } } internal static bool CheckNative(Player player, Piece piece, RequirementMode mode) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) nativeOnlyDepth++; try { return player.HaveRequirements(piece, mode); } finally { nativeOnlyDepth--; } } } public static class API { public static int MaterialContractVersion => 1; public static bool RequirePoVChestNodes => Plugin.PoVChestNodesRequired; public static int ContractVersion => 1; public static int HoverContractVersion => 1; public static bool TryGetBuildingRequirement(Player player, Piece piece, int requirementIndex, out int available, out int needed, out bool affordable) { return BuildingDisplay.TryQuote(player, piece, requirementIndex, out available, out needed, out affordable); } public static IDisposable RegisterCarriedMaterialSource(string providerId, Func<Player, ItemData> select, Func<Player, ItemData, Inventory> read, Func<Player, ItemData, Inventory, bool> isCurrent, Action<Player, ItemData, Inventory> save) { return CarriedMaterialProviders.Register(providerId, select, read, isCurrent, save); } public static bool TryGetQueuedCraftOutput(Player player, Recipe recipe, out int outputAmount, out bool awaitingPayment) { return CraftingDisplay.QueueOutput(player, recipe, out outputAmount, out awaitingPayment); } public static bool TryGetRecipeRequirement(Player player, Recipe recipe, ItemData upgrade, int quality, int multiplier, int requirementIndex, out int available, out int needed, out bool unselectedAlternative) { available = (needed = 0); unselectedAlternative = false; if (!MaterialOperations.Usable(player) || !Object.op_Implicit((Object)(object)ZoneSystem.instance) || !Object.op_Implicit((Object)(object)recipe) || recipe.m_resources == null || quality < 1 || multiplier < 1 || (uint)requirementIndex >= recipe.m_resources.Length || (Object)(object)recipe.m_resources[requirementIndex]?.m_resItem == (Object)null || player.NoCostCheat() || ZoneSystem.instance.GetGlobalKey((GlobalKeys)25) || !PathOfValheiman.CanManage || !PathOfValheiman.NormalCraft(recipe, upgrade)) { return false; } using (ChestAuthority.ReadOnlyQuery()) { RecipePlanner.RowAvailability rowAvailability = CraftingDisplay.DisplayRows(player, recipe, upgrade, quality, ref multiplier)[requirementIndex]; needed = (int)Math.Min(2147483647L, (long)recipe.m_resources[requirementIndex].GetAmount(quality) * (long)multiplier); available = rowAvailability.Available; unselectedAlternative = rowAvailability.UnselectedAlternative; return true; } } public static bool IsMaterialServiceAvailable(Player player) { return MaterialOperations.Usable(player); } public static int GetAvailableMaterialCount(Player player, string prefabName, Func<ItemData, bool> inventoryFilter) { return MaterialOperations.CountItems(player, prefabName, inventoryFilter); } public static bool IsMaterialTargetBlocked(Container target) { return ChestAuthority.RequiresProof((Component)(object)target); } public static bool GetCurrentMaterialCheated() { return MaterialOperations.CurrentCheated; } public static bool IsPlainDepositItem(ItemData item) { return MaterialOperations.Plain(item); } public static bool AcceptMaterialDestinationHandoff(string providerId, ZDO state, ZNetPeer previousOwner, ushort previousGeneration, byte[] authoritativePayload) { return ChestAuthority.AcceptDestinationHandoff(providerId, state, previousOwner, previousGeneration, authoritativePayload); } public static IDisposable RegisterContainerPolicy(string providerId, string[] excludedPrefabs, Func<Container, long, bool> destinationAccess) { return MaterialPolicies.Register(providerId, excludedPrefabs, destinationAccess); } public static int GetAvailableMaterialUnits(Player player, string[] prefabNames, int[] unitAmounts, int maxUnits, Func<ItemData, bool> inventoryFilter) { return MaterialOperations.Count(player, prefabNames, unitAmounts, maxUnits, inventoryFilter); } public static IDisposable RequestMaterialUse(Player player, string[] prefabNames, int[] unitAmounts, int maxUnits, Func<ItemData, bool> inventoryFilter, Func<bool> validate, Action<int, Action> applyUnit, Action<int> rollbackUnit, Action<int, string> completed) { return MaterialOperations.Use(player, prefabNames, unitAmounts, maxUnits, inventoryFilter, validate, applyUnit, rollbackUnit, completed); } public static IDisposable RequestMaterialDeposit(Player player, Container destination, Func<KeyValuePair<string, int>[]> getMissing, Func<ItemData, bool> inventoryFilter, Func<bool> validate, Func<KeyValuePair<string, int>[], bool> deposit, Action rollback, Action<int, string> completed) { return MaterialOperations.Deposit(player, destination, getMissing, inventoryFilter, validate, deposit, rollback, completed); } public static bool TryRequestPovUniqueRepair(Player player, ItemData item, Func<bool> validate, Action<bool> completed) { return PovRepair.Selected(player, item, validate, completed); } public static ItemDrop[] GetStationInputs(Component station) { using (ChestAuthority.ReadOnlyQuery()) { if (!ProductionPlanner.Supports(station, fuel: false) || !Object.op_Implicit((Object)(object)Player.m_localPlayer) || !ProductionExecution.Available(station) || !ChestAuthority.CanQuery(station)) { return null; } return (from d in ProductionPlanner.PlanStation(Player.m_localPlayer, station, fuel: false, ChestCatalog.Nearby(Player.m_localPlayer, station), int.MaxValue) select d.Input).Distinct().ToArray(); } } public static int CountStationFuel(Component station) { using (ChestAuthority.ReadOnlyQuery()) { if (!ProductionPlanner.Supports(station, fuel: true) || !Object.op_Implicit((Object)(object)Player.m_localPlayer) || !ProductionExecution.Available(station) || !ChestAuthority.CanQuery(station)) { return -1; } return ProductionPlanner.PlanStation(Player.m_localPlayer, station, fuel: true, ChestCatalog.Nearby(Player.m_localPlayer, station), int.MaxValue).Sum((ProductionDebit d) => d.Amount); } } public static bool IsStationFillAllRequested() { return ProductionExecution.FillAllRequested(); } public static StationHoverPreview GetStationHoverPreview(Component station, bool fuel, bool fillAll) { return StationHoverQueries.Get(station, fuel, fillAll); } } [HarmonyPatch] internal static class BuildingExecution { private sealed class Request { internal Player Player; internal ZDOID Character; internal Piece Piece; internal ItemData Tool; internal GameObject Ghost; internal Vector3 Position; internal Quaternion Rotation; internal string[] Costs; internal Container[] Sources; internal SourceChoice[] Choices; internal Inventory[] Inventories; internal float Deadline; internal bool Waiting; internal bool Ready; } private sealed class Execution { internal Request Request; internal bool Created; internal bool Cheated; internal bool PlacementEntered; internal bool Paid; internal bool MutatingSources; internal bool RefreshGhost; internal ZDO PreparedZdo; internal ZDOID PreparedId; internal int? UndoDepth; } private static readonly FieldRef<Player, GameObject> Ghost = AccessTools.FieldRefAccess<Player, GameObject>("m_placementGhost"); private static readonly FieldRef<Player, float> Pressed = AccessTools.FieldRefAccess<Player, float>("m_placePressedTime"); private static readonly Action<Player, bool> UpdateGhost = AccessTools.MethodDelegate<Action<Player, bool>>(AccessTools.DeclaredMethod(typeof(Player), "UpdatePlacementGhost", (Type[])null, (Type[])null), (object)null, true); private static readonly Action<Player> SetupGhost = AccessTools.MethodDelegate<Action<Player>>(AccessTools.DeclaredMethod(typeof(Player), "SetupPlacementGhost", (Type[])null, (Type[])null), (object)null, true); private static readonly Func<Humanoid, ItemData> RightItem = AccessTools.MethodDelegate<Func<Humanoid, ItemData>>(AccessTools.DeclaredMethod(typeof(Humanoid), "GetRightItem", (Type[])null, (Type[])null), (object)null, true); private static readonly Action<ZDO, bool> SetCheated = AccessTools.MethodDelegate<Action<ZDO, bool>>(AccessTools.DeclaredMethod(typeof(Player).Assembly.GetType("CheatUtils", throwOnError: true), "SetCheated", new Type[2] { typeof(ZDO), typeof(bool) }, (Type[])null), (object)null, true); private static readonly FieldInfo InitZdo = AccessTools.DeclaredField(typeof(ZNetView), "m_initZDO"); private static readonly Action<ZDOMan, ZDOID> DestroyLocalZdo = AccessTools.MethodDelegate<Action<ZDOMan, ZDOID>>(AccessTools.DeclaredMethod(typeof(ZDOMan), "HandleDestroyedZDO", new Type[1] { typeof(ZDOID) }, (Type[])null), (object)null, true); private static Request pending; private static Execution executing; [ThreadStatic] private static Player context; [ThreadStatic] private static Piece paidPiece; [ThreadStatic] private static Requirement[] paidCosts; internal static bool IsBusy { get { if (pending == null) { return executing != null; } return true; } } internal static bool HasPaidRequirements(Player player, Piece piece) { Execution execution = executing; if (execution != null && execution.Paid && (Object)(object)executing.Request.Player == (Object)(object)player) { return (Object)(object)executing.Request.Piece == (Object)(object)piece; } return false; } internal static bool Handles(Player player, Piece piece, bool recheck = false) { //IL_0083: Unknown result type (might be due to invalid IL or missing references) if (PathOfValheiman.CanManage && Plugin.BuildingReady && Plugin.PatchesReady && Object.op_Implicit((Object)(object)ZNet.instance) && Object.op_Implicit((Object)(object)player) && (Object)(object)player == (Object)(object)Player.m_localPlayer && Object.op_Implicit((Object)(object)piece) && !piece.m_repairPiece && !piece.m_removePiece && !player.NoCostCheat() && Object.op_Implicit((Object)(object)ZoneSystem.instance) && !ZoneSystem.instance.GetGlobalKey(piece.FreeBuildKey()) && !PathOfValheiman.Packed(player, piece) && BuildingContracts.AllowsPiece(piece) && !BuildingRouting.Delegated(player, piece, recheck) && !BuildingInfinityHammer.Delegated(recheck) && BuildingContracts.Verify(recheck) && piece.m_resources != null) { return piece.m_resources.Any((Requirement r) => Object.op_Implicit((Object)(object)r?.m_resItem) && r.m_amount > 0); } return false; } private static string[] Costs(Piece piece) { return piece.m_resources.Select((Requirement r) => (r != null) ? ((Object.op_Implicit((Object)(object)r.m_resItem) ? (((Object)r.m_resItem).GetInstanceID() + ":" + r.m_resItem.m_itemData.m_shared.m_name) : "none") + ":" + r.m_amount + ":" + r.m_upgraderResource) : "null").ToArray(); } private static bool Valid(Request request, bool requireVisible = true) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Unknown result type (might be due to invalid IL or missing references) //IL_0135: Unknown result type (might be due to invalid IL or missing references) //IL_013a: Unknown result type (might be due to invalid IL or missing references) //IL_013f: Unknown result type (might be due to invalid IL or missing references) //IL_0159: Unknown result type (might be due to invalid IL or missing references) //IL_015f: Unknown result type (might be due to invalid IL or missing references) if (Object.op_Implicit((Object)(object)request.Player) && (Object)(object)request.Player == (Object)(object)Player.m_localPlayer && request.Character == ((Character)request.Player).GetZDOID() && !((Character)request.Player).IsDead() && !((Character)request.Player).IsTeleporting() && ((Character)request.Player).InPlaceMode() && Handles(request.Player, request.Piece) && (Object)(object)request.Player.GetSelectedPiece() == (Object)(object)request.Piece && RightItem((Humanoid)(object)request.Player) == request.Tool && request.Tool != null && ((Humanoid)request.Player).GetInventory().ContainsItem(request.Tool) && (Object)(object)Ghost.Invoke(request.Player) == (Object)(object)request.Ghost && Object.op_Implicit((Object)(object)request.Ghost) && (!requireVisible || request.Ghost.activeSelf)) { Vector3 val = request.Ghost.transform.position - request.Position; if (((Vector3)(ref val)).sqrMagnitude < 0.0001f && Quaternion.Angle(request.Ghost.transform.rotation, request.Rotation) < 0.1f && Time.realtimeSinceStartup <= request.Deadline) { return Costs(request.Piece).SequenceEqual(request.Costs); } } return false; } internal static void Cancel() { Request request = pending; pending = null; if (request != null && request.Waiting) { ChestAuthority.Cancel(); } } internal static void Reset() { Cancel(); context = null; paidPiece = null; paidCosts = null; } [HarmonyPatch(typeof(Player), "UpdatePlacement")] [HarmonyPrefix] internal static bool EnterPlacement(Player __instance, bool takeInput, out Player __state) { __state = context; if ((Object)(object)context == (Object)(object)__instance) { return false; } context = (((Object)(object)__instance == (Object)(object)Player.m_localPlayer) ? __instance : null); if ((Object)(object)__state == (Object)null) { paidPiece = null; } Request request = pending; if (request == null || (Object)(object)request.Player != (Object)(object)__instance) { return true; } if (!takeInput || Hud.IsPieceSelectionVisible() || !Valid(request, requireVisible: false)) { Cancel(); return true; } if (!request.Ready) { return true; } UpdateGhost(__instance, arg2: false); if (!Valid(request)) { Cancel(); return true; } Pressed.Invoke(__instance) = Time.time; return true; } [HarmonyPatch(typeof(Player), "UpdatePlacement")] [HarmonyFinalizer] private static void LeavePlacement(Player __state) { context = __state; if ((Object)(object)__state == (Object)null) { paidPiece = null; } } [HarmonyPatch(typeof(Player), "UpdatePlacement")] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> PlacementCalls(IEnumerable<CodeInstruction> instructions) { MethodInfo tryPlace = AccessTools.DeclaredMethod(typeof(Player), "TryPlacePiece", (Type[])null, (Type[])null); MethodInfo consume = AccessTools.DeclaredMethod(typeof(Player), "ConsumeResources", (Type[])null, (Type[])null); MethodInfo requirements = AccessTools.DeclaredMethod(typeof(Player), "HaveRequirements", new Type[2] { typeof(Piece), typeof(RequirementMode) }, (Type[])null); List<CodeInstruction> code = instructions.ToList(); HashSet<Label> exitLabels = new HashSet<Label>(code.Where((CodeInstruction val) => val.opcode == OpCodes.Ret).SelectMany((CodeInstruction val) => val.labels)); int queries = 0; int placements = 0; int payments = 0; int exits = 0; int i = 0; while (i < code.Count) { CodeInstruction instruction = code[i]; int num; if (CodeInstructionExtensions.Calls(instruction, requirements) && IsPlacementQuery(code, i, tryPlace)) { num = queries + 1; queries = num; instruction.opcode = OpCodes.Call; instruction.operand = AccessTools.DeclaredMethod(typeof(BuildingDisplay), "CheckForPlacement", (Type[])null, (Type[])null); } else if (CodeInstructionExtensions.Calls(instruction, tryPlace)) { num = placements + 1; placements = num; instruction.opcode = OpCodes.Call; instruction.operand = AccessTools.DeclaredMethod(typeof(BuildingExecution), "TryBuild", (Type[])null, (Type[])null); } else if (CodeInstructionExtensions.Calls(instruction, consume)) { num = payments + 1; payments = num; instruction.opcode = OpCodes.Call; instruction.operand = AccessTools.DeclaredMethod(typeof(BuildingExecution), "Consume", (Type[])null, (Type[])null); } yield return instruction; if ((instruction.opcode == OpCodes.Leave || instruction.opcode == OpCodes.Leave_S) && instruction.operand is Label item && exitLabels.Contains(item) && i + 1 < code.Count && code[i + 1].blocks.Any((ExceptionBlock b) => (int)b.blockType == 4)) { num = exits + 1; exits = num; yield return new CodeInstruction(OpCodes.Nop, (object)null); } num = i + 1; i = num; } if (queries != 1 || placements != 1 || payments != 1 || exits != 1) { throw new NotSupportedException("Native building query/payment/exit calls changed."); } } internal static bool IsPlacementQuery(IReadOnlyList<CodeInstruction> code, int index, MethodInfo placement) { if (index >= 3 && index + 4 < code.Count && code[index - 3].opcode == OpCodes.Ldarg_0 && code[index - 1].opcode == OpCodes.Ldc_I4_0 && (code[index + 1].opcode == OpCodes.Brfalse || code[index + 1].opcode == OpCodes.Brfalse_S) && code[index + 2].opcode == OpCodes.Ldarg_0 && CodeInstructionExtensions.Calls(code[index + 4], placement) && code[index - 2].opcode == code[index + 3].opcode) { return object.Equals(code[index - 2].operand, code[index + 3].operand); } return false; } internal static bool TryBuild(Player player, Piece piece) { //IL_012f: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Unknown result type (might be due to invalid IL or missing references) //IL_015f: Unknown result type (might be due to invalid IL or missing references) //IL_0164: Unknown result type (might be due to invalid IL or missing references) //IL_0170: Unknown result type (might be due to invalid IL or missing references) //IL_0175: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)context != (Object)(object)player) { return player.TryPlacePiece(piece); } if (executing != null) { return false; } if (!Handles(player, piece, recheck: true)) { bool num = pending != null; Cancel(); if (num) { return false; } if (player.NoCostCheat() || BuildingDisplay.CheckNative(player, piece, (RequirementMode)0)) { return player.TryPlacePiece(piece); } return false; } Request request = pending; if (request != null && ((Object)(object)request.Player != (Object)(object)player || (Object)(object)request.Piece != (Object)(object)piece || !Valid(request))) { Cancel(); return false; } Request request2 = request; if ((request2 != null && request2.Waiting) || ChestAuthority.IsBusy) { return false; } if (request == null) { UpdateGhost(player, arg2: false); GameObject val = Ghost.Invoke(player); if (!Object.op_Implicit((Object)(object)val)) { return false; } Container[] array = BuildingPlanner.Sources(player); CraftPlan plan = BuildingPlanner.Plan(player, piece, array); if (plan == null) { Missing(player); return false; } request = new Request { Player = player, Character = ((Character)player).GetZDOID(), Piece = piece, Tool = RightItem((Humanoid)(object)player), Ghost = val, Position = val.transform.position, Rotation = val.transform.rotation, Costs = Costs(piece), Choices = plan.CaptureChoices(), Inventories = plan.Debits.Select((Debit d) => d.Inventory).Distinct().ToArray(), Sources = array.Where((Container c) => plan.Debits.Any((Debit d) => (Object)(object)d.Chest == (Object)(object)c)).ToArray(), Deadline = Time.realtimeSinceStartup + 8f }; pending = request; } bool inCall = true; bool result = false; request.Waiting = true; request.Ready = false; try { ChestAuthority.Acquire(player, request.Sources, delegate(bool granted) { request.Waiting = false; if (pending == request) { if (!granted || !Valid(request, inCall)) { pending = null; } else if (!inCall) { request.Ready = true; } else { pending = null; result = Run(request); } } }, null, cookingCollection: false, request.Inventories); } catch (Exception ex) { if (pending == request) { Cancel(); } Plugin.Log.LogWarning((object)("Building request failed: " + ex.GetBaseException().Message)); } finally { inCall = false; } return result; } private static bool Run(Request request) { if (!BuildingContracts.Verify(recheck: true) || !Valid(request) || request.Sources.Any((Container c) => !ChestAuthority.Ready(c))) { return false; } Requirement[] bill = PathOfValheiman.BuildCosts(request.Player, request.Piece); CraftPlan craftPlan = BuildingPlanner.Plan(request.Player, request.Piece, request.Sources, bill); if (craftPlan == null || !craftPlan.MatchesChoices(request.Choices)) { Missing(request.Player); return false; } InventorySnapshot[] snapshots = MaterialSources.Snapshots(craftPlan.Debits.Select((Debit d) => d.Inventory), request.Player); Execution execution = (executing = new Execution { Request = request, Cheated = craftPlan.Debits.Any((Debit d) => d.Item.m_cheated) }); try { execution.MutatingSources = true; foreach (Debit debit in craftPlan.Debits) { int num = debit.Item.m_stack - debit.Amount; if (request.Sources.Any((Container c) => !ChestAuthority.Ready(c)) || debit.Amount <= 0 || debit.Item.m_stack < debit.Amount || !debit.Inventory.ContainsItem(debit.Item) || !MaterialSources.Ready(debit.Inventory, debit.Chest) || !MaterialSources.Remove(debit.Inventory, debit.Item, debit.Amount)) { throw new InvalidOperationException("Building ingredients changed before payment."); } bool num2; if (num != 0) { if (!debit.Inventory.ContainsItem(debit.Item)) { goto IL_021b; } num2 = debit.Item.m_stack != num; } else { num2 = debit.Inventory.ContainsItem(debit.Item); } if (!num2) { if (Object.op_Implicit((Object)(object)debit.Chest)) { ChestAuthority.Persist(debit.Chest); } continue; } goto IL_021b; IL_021b: throw new InvalidOperationException("Building payment did not preserve the expected stack delta."); } execution.MutatingSources = false; execution.Paid = true; if (!BuildingContracts.Verify(recheck: true) || !Valid(request) || request.Sources.Any((Container c) => !ChestAuthority.Ready(c)) || !BuildingDisplay.CheckForPlacement(request.Player, request.Piece, (RequirementMode)0)) { throw new InvalidOperationException("Building context changed during payment."); } if (request.Player.TryPlacePiece(request.Piece) && !execution.Created) { throw new InvalidOperationException("Building returned success without a native creation receipt."); } } catch (Exception ex) { Plugin.Log.LogWarning((object)$"Building interrupted (output created: {execution.Created}). {ex.GetBaseException().Message}"); } finally { try { if (!execution.Created) { try { RemovePreparedObject(execution); } finally { CloseInfinityUndo(execution); } if (request.Sources.Any((Container c) => !ChestAuthority.HasTransactionAuthority(c))) { throw new InvalidOperationException("Building rollback lost material authority; refusing an unsafe refund."); } execution.MutatingSources = true; InventorySnapshot.RestoreAll(snapshots); Container[] sources = request.Sources; for (int num3 = 0; num3 < sources.Length; num3++) { ChestAuthority.Persist(sources[num3]); } } else { paidPiece = request.Piece; paidCosts = bill; CloseInfinityUndo(execution); } } finally { TerrainModifier.SetTriggerOnPlaced(false); executing = null; if (execution.RefreshGhost && Object.op_Implicit((Object)(object)request.Player)) { FlushGhost(request.Player); } } } return execution.Created; } private static void Consume(Player player, Requirement[] requirements, int quality, int itemQuality, int multiplier) { if ((Object)(object)context == (Object)(object)player && Object.op_Implicit((Object)(object)paidPiece) && requirements == paidPiece.m_resources) { paidPiece = null; Requirement[] costs = paidCosts; paidCosts = null; PathOfValheiman.AfterBuild(player, costs, quality, multiplier); } else { player.ConsumeResources(requirements, quality, itemQuality, multiplier); } } [HarmonyPatch(typeof(Player), "PlacePiece")] [HarmonyTranspiler] [HarmonyAfter(new string[] { "infinity_hammer" })] private static IEnumerable<CodeInstruction> InfinitySelectionGuard(IEnumerable<CodeInstruction> instructions) { bool rawSeen = false; bool wrappedSeen = false; bool failed = false; MethodInfo wrapper = AccessTools.DeclaredMethod(typeof(BuildingExecution), "InfinityPrefab", (Type[])null, (Type[])null); foreach (CodeInstruction instruction in instructions) { bool flag = false; bool prefab = false; if (instruction.operand is MethodInfo methodInfo && CodeInstructionExtensions.Calls(instruction, methodInfo)) { wrappedSeen |= methodInfo == wrapper; if (methodInfo.DeclaringType?.FullName == "InfinityHammer.Placing" && methodInfo.Name == "GetPrefab") { rawSeen = true; prefab = true; flag = BuildingInfinityHammer.IsPrefabCallback(methodInfo) && BuildingInfinityHammer.TryBindPrefabCallback(methodInfo); failed = failed || !flag; } else if (methodInfo.DeclaringType?.FullName == "InfinityHammer.Placing" && methodInfo.Name == "Postprocess" && methodInfo.IsStatic && methodInfo.ReturnType == typeof(void) && (from p in methodInfo.GetParameters() select p.ParameterType).SequenceEqual(new Type[1] { typeof(GameObject) })) { flag = true; } } if (flag) { CodeInstruction val = new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(BuildingExecution), "RequireOrdinarySelection", (Type[])null, (Type[])null)); CodeInstructionExtensions.MoveLabelsFrom(val, instruction); CodeInstructionExtensions.MoveBlocksFrom(val, instruction); yield return val; if (prefab) { instruction.operand = wrapper; } } yield return instruction; } BuildingInfinityHammer.ObservePrefabAdapter(rawSeen, wrappedSeen, failed); } private static void RequireOrdinarySelection() { if (executing != null && BuildingInfinityHammer.Delegated(recheck: true)) { throw new InvalidOperationException("Infinity Hammer selection changed during placement."); } } private static GameObject InfinityPrefab(GameObject prefab, Vector3 position, Quaternion rotation) { //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Expected O, but got Unknown //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0081: 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) Execution execution = executing; if (execution == null) { return BuildingInfinityHammer.TransformPrefab(prefab, position, rotation); } RequireOrdinarySelection(); if (execution.UndoDepth.HasValue || InitZdo.GetValue(null) != null) { throw new InvalidOperationException("Another placement already owns initialization state."); } execution.UndoDepth = BuildingInfinityHammerObject.UndoDepth; try { return BuildingInfinityHammer.TransformPrefab(prefab, position, rotation); } finally { execution.PreparedZdo = (ZDO)InitZdo.GetValue(null); if (execution.PreparedZdo != null) { execution.PreparedId = execution.PreparedZdo.m_uid; } } } private static void RemovePreparedObject(Execution execution) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0017: 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_0033: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) ZDO preparedZdo = execution.PreparedZdo; if (preparedZdo == null) { return; } ZDOID preparedId = execution.PreparedId; ZDO zDO = ZDOMan.instance.GetZDO(preparedId); if (zDO == null) { execution.PreparedZdo = null; return; } if (zDO != preparedZdo || preparedZdo.m_uid != preparedId || !preparedZdo.IsOwner()) { throw new InvalidOperationException("Uncommitted placement lost its network-object identity or ownership; refusing an unsafe refund."); } if (InitZdo.GetValue(null) == preparedZdo) { InitZdo.SetValue(null, null); } ZDOMan.instance.DestroyZDO(preparedZdo); DestroyLocalZdo(ZDOMan.instance, preparedId); if (ZDOMan.instance.GetZDO(preparedId) != null) { throw new InvalidOperationException("Uncommitted placement cleanup did not complete; refusing an unsafe refund."); } execution.PreparedZdo = null; } private static void CloseInfinityUndo(Execution execution) { if (execution.UndoDepth.HasValue) { int value = execution.UndoDepth.Value; int undoDepth = BuildingInfinityHammerObject.UndoDepth; if (undoDepth == value + 1) { BuildingInfinityHammerObject.EndUndo(); } else if (undoDepth != value) { throw new InvalidOperationException("Infinity Hammer undo scope changed during placement."); } execution.UndoDepth = null; } } [HarmonyPatch(typeof(Player), "UpdateAvailablePiecesList")] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> InventoryPreview(IEnumerable<CodeInstruction> instructions) { MethodInfo setup = AccessTools.DeclaredMethod(typeof(Player), "SetupPlacementGhost", (Type[])null, (Type[])null); int found = 0; foreach (CodeInstruction instruction in instructions) { if (CodeInstructionExtensions.Calls(instruction, setup)) { int num = found + 1; found = num; instruction.opcode = OpCodes.Call; instruction.operand = AccessTools.DeclaredMethod(typeof(BuildingExecution), "RefreshAfterInventoryChange", (Type[])null, (Type[])null); } yield return instruction; } if (found != 1) { throw new NotSupportedException("Native inventory placement-preview refresh changed."); } } private static void RefreshAfterInventoryChange(Player player) { Execution execution = executing; if (execution != null && execution.MutatingSources && (Object)(object)execution.Request.Player == (Object)(object)player && (Object)(object)player.GetSelectedPiece() == (Object)(object)execution.Request.Piece && RightItem((Humanoid)(object)player) == execution.Request.Tool && (Object)(object)Ghost.Invoke(player) == (Object)(object)execution.Request.Ghost && Object.op_Implicit((Object)(object)execution.Request.Ghost)) { execution.RefreshGhost = true; } else { SetupGhost(player); } } private static void FlushGhost(Player player) { bool forceDisableInit = ZNetView.m_forceDisableInit; bool forceDisableTerrainOps = TerrainOp.m_forceDisableTerrainOps; Piece selectedPiece = player.GetSelectedPiece(); TerrainModifier val = (Object.op_Implicit((Object)(object)selectedPiece) ? ((Component)selectedPiece).GetComponentInChildren<TerrainModifier>() : null); bool enabled = Object.op_Implicit((Object)(object)val) && ((Behaviour)val).enabled; try { SetupGhost(player); } catch (Exception ex) { if (Object.op_Implicit((Object)(object)Ghost.Invoke(player))) { Object.Destroy((Object)(object)Ghost.Invoke(player)); } Ghost.Invoke(player) = null; Plugin.Log.LogWarning((object)("Building preview refresh failed: " + ex.GetBaseException().Message)); } finally { ZNetView.m_forceDisableInit = forceDisableInit; TerrainOp.m_forceDisableTerrainOps = forceDisableTerrainOps; if (Object.op_Implicit((Object)(object)val)) { ((Behaviour)val).enabled = enabled; } } } [HarmonyPatch(typeof(Player), "PlacePiece")] [HarmonyPrefix] private static void GuardPlacement(Player __instance, Piece piece, Vector3 pos, Quaternion rot) { //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) Request request = executing?.Request; if (request == null || (Object)(object)request.Player != (Object)(object)__instance) { return; } if (!executing.PlacementEntered && !((Object)(object)request.Piece != (Object)(object)piece) && Valid(request)) { Vector3 val = pos - request.Position; if (!(((Vector3)(ref val)).sqrMagnitude >= 0.0001f) && !(Quaternion.Angle(rot, request.Rotation) >= 0.1f)) { executing.PlacementEntered = true; return; } } throw new InvalidOperationException("The pending construction target changed before creation."); } internal static bool IsPieceInstantiation(CodeInstruction instruction) { if (instruction.operand is MethodInfo methodInfo && methodInfo.DeclaringType == typeof(Object) && methodInfo.Name == "Instantiate" && methodInfo.IsGenericMethod && methodInfo.GetGenericArguments().SequenceEqual(new Type[1] { typeof(GameObject) })) { return (from p in methodInfo.GetParameters() select p.ParameterType).SequenceEqual(new Type[3] { typeof(GameObject), typeof(Vector3), typeof(Quaternion) }); } return false; } [HarmonyPatch(typeof(Player), "PlacePiece")] [HarmonyTranspiler] [HarmonyBefore(new string[] { "sighsorry.Groundwork" })] private static IEnumerable<CodeInstruction> Receipt(IEnumerable<CodeInstruction> instructions) { int found = 0; foreach (CodeInstruction instruction in instructions) { yield return instruction; if (IsPieceInstantiation(instruction)) { int num = found + 1; found = num; yield return new CodeInstruction(OpCodes.Ldarg_0, (object)null); yield return new CodeInstruction(OpCodes.Ldarg_1, (object)null); yield return new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(BuildingExecution), "RecordCreation", (Type[])null, (Type[])null)); } } if (found != 1) { throw new NotSupportedException("Native building creation contract changed."); } } private static GameObject RecordCreation(GameObject created, Player player, Piece piece) { if (Object.op_Implicit((Object)(object)created)) { Execution execution = executing; if (execution != null && (Object)(object)execution.Request.Player == (Object)(object)player && (Object)(object)execution.Request.Piece == (Object)(object)piece) { execution.Created = true; ZNetView component = created.GetComponent<ZNetView>(); ZDO val = ((component != null) ? component.GetZDO() : null); if (val != null && execution.Cheated && !PlayerProfile.s_bypassCheatChecks) { SetCheated(val, arg2: true); } } } return created; } [HarmonyPatch(typeof(Player), "TryPlacePiece")] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> Provenance(IEnumerable<CodeInstruction> instructions) { MethodInfo lookup = AccessTools.DeclaredMethod(typeof(Inventory), "ItemCheated", new Type[3] { typeof(Requirement[]), typeof(int), typeof(bool) }, (Type[])null); int found = 0; foreach (CodeInstruction instruction in instructions) { yield return instruction; if (CodeInstructionExtensions.Calls(instruction, lookup)) { int num = found + 1; found = num; yield return new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(BuildingExecution), "IncludeCheated", (Type[])null, (Type[])null)); } } if (found != 1) { throw new NotSupportedException("Native building provenance contract changed."); } } private static bool IncludeCheated(bool original) { if (!original) { return executing?.Cheated ?? false; } return true; } private static void Missing(Player player) { ((Character)player).Message((MessageType)2, "$msg_missingrequirement", 0, (Sprite)null, false); } } internal static class BuildingInfinityHammer { private const string Id = "infinity_hammer"; private static Assembly routed; private static Type baseSelection; private static Func<object> selection; private static Func<bool> noCost; private static FieldInfo singleUse; private static MethodInfo prefabCallback; private static Func<GameObject, Vector3, Quaternion, GameObject> transformPrefab; private static bool prefabAdapterPresent; private static bool prefabAdapterUnavailable; private static Assembly Source() { if (!Chainloader.PluginInfos.TryGetValue("infinity_hammer", out var value) || !Object.op_Implicit((Object)(object)value.Instance)) { return null; } return ((object)value.Instance).GetType().Assembly; } private static bool Signature(MethodInfo method, Type result, params Type[] arguments) { if (method != null && method.IsStatic && !method.IsGenericMethod && method.ReturnType == result) { return (from p in method.GetParameters() select p.ParameterType).SequenceEqual(arguments); } return false; } private static void BindRouting(Assembly source) { if (!(routed == source)) { routed = null; baseSelection = source.GetType("InfinityHammer.BaseSelection", throwOnError: true); MethodInfo methodInfo = AccessTools.DeclaredMethod(source.GetType("InfinityHammer.Selection", throwOnError: true), "Get", (Type[])null, (Type[])null); MethodInfo methodInfo2 = AccessTools.DeclaredMethod(source.GetType("InfinityHammer.Configuration", throwOnError: true), "get_NoResourceCost", (Type[])null, (Type[])null); if (!Signature(methodInfo, baseSelection) || !Signature(methodInfo2, typeof(bool))) { throw Changed("selection/cost query is unavailable"); } singleUse = AccessTools.DeclaredField(baseSelection, "SingleUse"); if (singleUse == null || singleUse.IsStatic || singleUse.FieldType != typeof(bool)) { throw Changed("selection state is unavailable"); } selection = AccessTools.MethodDelegate<Func<object>>(methodInfo, (object)null, true); noCost = AccessTools.MethodDelegate<Func<bool>>(methodInfo2, (object)null, true); routed = source; } } internal static bool Delegated(bool recheck = false) { Assembly assembly = Source(); if (assembly == null) { return false; } try { BindRouting(assembly); if (noCost()) { return true; } object obj = selection(); if (obj == null || (bool)singleUse.GetValue(obj)) { return true; } if (obj.GetType() != baseSelection) { BuildingInfinityHammerObject.Bind(assembly); if (!BuildingInfinityHammerObject.IsOrdinary(obj)) { return true; } } if (prefabAdapterUnavailable) { return true; } if (prefabAdapterPresent) { BuildingInfinityHammerObject.BindCleanup(); } return false; } catch { return true; } } internal static bool IsPrefabCallback(MethodInfo method) { if (method?.DeclaringType?.FullName == "InfinityHammer.Placing" && method.Name == "GetPrefab") { return Signature(method, typeof(GameObject), typeof(GameObject), typeof(Vector3), typeof(Quaternion)); } return false; } internal static bool TryBindPrefabCallback(MethodInfo method) { if (!IsPrefabCallback(method)) { return false; } if (prefabCallback == method && transformPrefab != null) { return true; } try { Func<GameObject, Vector3, Quaternion, GameObject> func = AccessTools.MethodDelegate<Func<GameObject, Vector3, Quaternion, GameObject>>(method, (object)null, true); prefabCallback = method; transformPrefab = func; return true; } catch { return false; } } internal static void ObservePrefabAdapter(bool rawSeen, bool wrappedSeen, bool failed) { if (rawSeen) { prefabAdapterPresent = true; prefabAdapterUnavailable = failed; } else if (wrappedSeen) { prefabAdapterPresent = true; prefabAdapterUnavailable |= transformPrefab == null; } else { prefabAdapterPresent = false; prefabAdapterUnavailable = false; } } internal static bool HasUnwrappedPrefabCallback(IEnumerable<CodeInstruction> code) { Assembly source = Source(); if (source != null) { return code.Any((CodeInstruction instruction) => instruction.operand is MethodInfo methodInfo && methodInfo.DeclaringType?.Assembly == source && methodInfo.DeclaringType.FullName == "InfinityHammer.Placing" && methodInfo.Name == "GetPrefab" && CodeInstructionExtensions.Calls(instruction, methodInfo)); } return false; } internal static GameObject TransformPrefab(GameObject prefab, Vector3 position, Quaternion rotation) { //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) if (transformPrefab == null && !TryBindPrefabCallback(AccessTools.DeclaredMethod(Source()?.GetType("InfinityHammer.Placing"), "GetPrefab", (Type[])null, (Type[])null))) { throw Changed("original prefab callback is unavailable"); } return transformPrefab(prefab, position, rotation); } private static NotSupportedException Changed(string reason) { return new NotSupportedException("Infinity Hammer " + reason + "."); } internal static void Reset() { routed = null; baseSelection = null; selection = null; noCost = null; singleUse = null; BuildingInfinityHammerObject.Reset(); } } internal static class BuildingInfinityHammerObject { private static Assembly bound; private static Assembly undoSource; private static Type selectionType; private static FieldInfo objects; private static FieldInfo selectedPrefab; private static FieldInfo singleUse; private static FieldInfo usesRoot; private static FieldInfo height; private static FieldInfo paint; private static FieldInfo zoops; private static FieldInfo zoopsX; private static FieldInfo zoopsY; private static FieldInfo zoopsZ; private static FieldInfo objectPrefab; private static FieldInfo objectData; private static FieldInfo undoDepth; private static Action endUndo; internal static int UndoDepth { get { BindCleanup(); return (int)undoDepth.GetValue(null); } } internal static void EndUndo() { BindCleanup(); endUndo(); } internal static void Bind(Assembly source) { if (!(bound == source)) { bound = null; selectionType = source.GetType("InfinityHammer.ObjectSelection", throwOnError: true); Type type = source.GetType("InfinityHammer.BaseSelection", throwOnError: true); Type type2 = source.GetType("InfinityHammer.SelectedObject", throwOnError: true); if (!type.IsAssignableFrom(selectionType)) { throw Changed("selection type is unavailable"); } objects = Field(selectionType, "Objects", typeof(List<>).MakeGenericType(type2)); selectedPrefab = Field(type, "SelectedPrefab", typeof(GameObject)); singleUse = Field(type, "SingleUse", typeof(bool)); usesRoot = Field(selectionType, "<UsesSelectionRoot>k__BackingField", typeof(bool)); height = Field(selectionType, "TerrainHeightInfo"); paint = Field(selectionType, "TerrainPaintInfo"); zoops = Field(selectionType, "Zoops", typeof(Dictionary<Vector3Int, GameObject>)); zoopsX = Field(selectionType, "ZoopsX", typeof(int)); zoopsY = Field(selectionType, "ZoopsY", typeof(int)); zoopsZ = Field(selectionType, "ZoopsZ", typeof(int)); objectPrefab = Field(type2, "Prefab", typeof(int)); objectData = Field(type2, "Data"); if (height.FieldType.IsValueType || paint.FieldType.IsValueType || objectData.FieldType.IsValueType) { throw Changed("optional selection data is unavailable"); } bound = source; } } internal static void BindCleanup() { Assembly assembly = null; if (Chainloader.PluginInfos.TryGetValue("world_edit_commands", out var value) && Object.op_Implicit((Object)(object)value.Instance)) { assembly = ((object)value.Instance).GetType().Assembly; } if ((object)assembly == null) { assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault((Assembly a) => a.GetName().Name == "WorldEditCommands"); } if (assembly == null) { throw Changed("undo provider is unavailable"); } if (!(undoSource == assembly) || !(undoDepth != null) || endUndo == null) { Type? type = assembly.GetType("WorldEditCommands.UndoHelper", throwOnError: true); FieldInfo fieldInfo = AccessTools.DeclaredField(type, "SubStack"); MethodInfo methodInfo = AccessTools.DeclaredMethod(type, "EndSubAction", Type.EmptyTypes, (Type[])null); if (fieldInfo == null || !fieldInfo.IsStatic || fieldInfo.FieldType != typeof(int) || methodInfo == null || !methodInfo.IsStatic || methodInfo.IsGenericMethod || methodInfo.ReturnType != typeof(void) || methodInfo.GetParameters().Length != 0) { throw Changed("undo cleanup API is unavailable"); } Action action = AccessTools.MethodDelegate<Action>(methodInfo, (object)null, true); undoDepth = fieldInfo; endUndo = action; undoSource = assembly; } } internal static bool IsOrdinary(object current) { if (current == null || current.GetType() != selectionType || !Object.op_Implicit((Object)(object)ZNetScene.instance)) { return false; } if ((bool)singleUse.GetValue(current) || (bool)usesRoot.GetValue(current) || height.GetValue(current) != null || paint.GetValue(current) != null || (int)zoopsX.GetValue(current) != 0 || (int)zoopsY.GetValue(current) != 0 || (int)zoopsZ.GetValue(current) != 0 || !(zoops.GetValue(current) is IDictionary { Count: 0 }) || !(objects.GetValue(current) is IList { Count: 1 } list)) { return false; } object obj = list[0]; if (obj == null || objectData.GetValue(obj) != null) { return false; } int num = (int)objectPrefab.GetValue(obj); GameObject prefab = ZNetScene.instance.GetPrefab(num); object? value = selectedPrefab.GetValue(current); GameObject val = (GameObject)((value is GameObject) ? value : null); if (!Object.op_Implicit((Object)(object)prefab) || !Object.op_Implicit((Object)(object)val) || !Object.op_Implicit((Object)(object)prefab.GetComponent<ZNetView>()) || Object.op_Implicit((Object)(object)prefab.GetComponent<DungeonGenerator>()) || Object.op_Implicit((Object)(object)val.GetComponent<DungeonGenerator>()) || Utils.GetPrefabName(val) != Utils.GetPrefabName(prefab)) { return false; } Piece component = prefab.GetComponent<Piece>(); Piece component2 = val.GetComponent<Piece>(); if (Object.op_Implicit((Object)(object)component) && Object.op_Implicit((Object)(object)component2)) { return SameCosts(component.m_resources, component2.m_resources); } return false; } private static bool SameCosts(Requirement[] first, Requirement[] second) { if (first == null || second == null || first.Length != second.Length) { return false; } for (int i = 0; i < first.Length; i++) { Requirement val = first[i]; Requirement val2 = second[i]; if (val == null || val2 == null) { if (val != val2) { return false; } } else if ((Object)(object)val.m_resItem != (Object)(object)val2.m_resItem || val.m_amount != val2.m_amount || val.m_upgraderResource != val2.m_upgraderResource) { return false; } } return true; } private static FieldInfo Field(Type type, string name, Type expected = null) { FieldInfo fieldInfo = AccessTools.Field(type, name); if (fieldInfo == null || fieldInfo.IsStatic || (expected != null && fieldInfo.FieldType != expected)) { throw Changed("selection field is unavailable: " + name); } return fieldInfo; } private static NotSupportedException Changed(string reason) { return new NotSupportedException("Infinity Hammer " + reason + "."); } internal static void Reset() { bound = (undoSource = null); selectionType = null; objects = (selectedPrefab = (singleUse = (usesRoot = (height = (paint = (zoops = (zoopsX = (zoopsY = (zoopsZ = (objectPrefab = (objectData = (undoDepth = null)))))))))))); endUndo = null; } } internal static class BuildingPlanner { private readonly struct Stock { internal readonly long Backpack; internal readonly long Chests; internal Stock(long backpack, long chests) { Backpack = backpack; Chests = chests; } } private sealed class Costs { internal readonly (string Name, int Amount)[] Rows; internal readonly Dictionary<string, int> Totals = new Dictionary<string, int>(StringComparer.Ordinal); internal bool Valid = true; internal Costs(int rows) { Rows = new(string, int)[rows]; } } private static readonly Dictionary<Piece, Costs> Quotes = new Dictionary<Piece, Costs>(); private static readonly Dictionary<string, Stock> DisplayStock = new Dictionary<string, Stock>(StringComparer.Ordinal); private static Player displayPlayer; private static Inventory displayInventory; private static long displayRevision = -1L; private static int displayWorld; private static float refreshAt; internal static Container[] Sources(Player player) { if (!Object.op_Implicit((Object)(object)player)) { return Array.Empty<Container>(); } return (from c in ChestCatalog.Nearby(player, (Component)(object)player) where Object.op_Implicit((Object)(object)c) && MaterialPolicies.SourceAllowed(c) select c).ToArray(); } private static (string Name, int Amount) Row(Requirement requirement) { if (requirement == null || !Object.op_Implicit((Object)(object)requirement.m_resItem) || requirement.m_amount <= 0) { return default((string, int)); } return (Name: requirement.m_resItem.m_itemData?.m_shared?.m_name, Amount: requirement.m_amount); } private static Costs GetCosts(Piece piece, Requirement[] effective = null) { if (!Object.op_Implicit((Object)(object)piece) || piece.m_resources == null) { return null; } Requirement[] array = effective ?? piece.m_resources; Costs value; bool flag = !Quotes.TryGetValue(piece, out value) || value.Rows.Length != array.Length; int num = 0; while (!flag && num < array.Length) { (string, int) tuple = value.Rows[num]; (string, int) tuple2 = Row(array[num]); flag = tuple.Item1 != tuple2.Item1 || tuple.Item2 != tuple2.Item2; num++; } if (!flag) { return value; } value = new Costs(array.Length); for (int i = 0; i < array.Length; i++) { (string, int) tuple3 = (value.Rows[i] = Row(array[i])); if (tuple3.Item2 <= 0) { continue; } if (tuple3.Item1 == null) { value.Valid = false; continue; } value.Totals.TryGetValue(tuple3.Item1, out var value2); long num2 = (long)value2 + (long)tuple3.Item2; if (num2 > int.MaxValue) { value.Valid = false; } else { value.Totals[tuple3.Item1] = (int)num2; } } Quotes[piece] = value; return value; } internal static CraftPlan Plan(Player player, Piece piece, IReadOnlyList<Container> chests, Requirement[] bill = null) { //IL_006d: Unknown result type (might be due to invalid IL or missing references) Costs costs = GetCosts(piece, bill ?? PathOfValheiman.BuildCosts(player, piece)); if (!Object.op_Implicit((Object)(object)player) || ((Humanoid)player).GetInventory() == null || chests == null || costs == null || !costs.Valid) { return null; } Dictionary<string, int> dictionary = new Dictionary<string, int>(costs.Totals, StringComparer.Ordinal); CraftPlan craftPlan = new CraftPlan { Player = player, Quality = 0, Multiplier = 1 }; HashSet<ItemData> hashSet = new HashSet<ItemData>(); foreach (var (val, chest) in MaterialSources.Read(player, chests, ((Component)player).transform.position, byDistance: true, PathOfValheiman.ChestsFor(piece))) { if (val == null) { continue; } foreach (ItemData item in val.GetAllItemsInGridOrder()) { string text = item?.m_shared?.m_name; if (text != null && item.m_stack > 0 && item.m_worldLevel >= Game.m_worldLevel && dictionary.TryGetValue(text, out var value) && value > 0 && hashSet.Add(item) && MaterialSources.Allows(val, item) && (!MaterialSources.IsWorld(val, chest) || player.IsKnownMaterial(text))) { int num = Math.Min(value, item.m_stack); craftPlan.Debits.Add(new Debit(val, chest, item, num)); dictionary[text] = value - num; } } } if (!dictionary.Values.Any((int amount) => amount > 0)) { return craftPlan; } return null; } private static void RefreshDisplay(Player player) { //IL_005c: Unknown result type (might be due to invalid IL or missing references) IReadOnlyList<Container> chests = ChestCatalog.Nearby(player, (Component)(object)player); Inventory inventory = ((Humanoid)player).GetInventory(); if (displayPlayer == player && displayInventory == inventory && displayRevision == ChestCatalog.Revision && displayWorld == Game.m_worldLevel && Time.unscaledTime < refreshAt) { return; } DisplayStock.Clear(); HashSet<ItemData> hashSet = new HashSet<ItemData>(); foreach (var item3 in MaterialSources.Read(player, chests, ((Component)player).transform.position)) { Inventory item = item3.Inventory; Container item2 = item3.Chest; bool flag = MaterialSources.IsWorld(item, item2); if (item == null) { continue; } foreach (ItemData allItem in item.GetAllItems()) { string text = allItem?.m_shared?.m_name; if (text != null && allItem.m_stack > 0 && allItem.m_worldLevel >= Game.m_worldLevel && hashSet.Add(allItem) && MaterialSources.Allows(item, allItem)) { DisplayStock.TryGetValue(text, out var value); DisplayStock[text] = (flag ? new Stock(value.Backpack, value.Chests + allItem.m_stack) : new Stock(value.Backpack + allItem.m_stack, value.Chests)); } } } displayPlayer = player; displayInventory = inventory; displayRevision = ChestCatalog.Revision; displayWorld = Game.m_worldLevel; refreshAt = Time.unscaledTime + 0.2f; } private static long Available(Player player, string name, bool world) { if (name == null || !DisplayStock.TryGetValue(name, out var value)) { return 0L; } return value.Backpack + ((world && player.IsKnownMaterial(name)) ? value.Chests : 0); } internal static bool CanBuild(Player player, Piece piece) { if (!Object.op_Implicit((Object)(object)player)) { return false; } Costs costs = GetCosts(piece); if (costs == null || !costs.Valid) { return false; } using (ChestAuthority.ReadOnlyQuery()) { RefreshDisplay(player); bool world = PathOfValheiman.ChestsFor(piece); foreach (KeyValuePair<string, int> total in costs.Totals) { if (Available(player, total.Key, world) < total.Value) { return false; } } return true; } } internal static int Count(Player player, Requirement requirement, Piece piece = null) { if (!Object.op_Implicit((Object)(object)player)) { return 0; } string item = Row(requirement).Name; if (item == null) { return 0; } using (ChestAuthority.ReadOnlyQuery()) { RefreshDisplay(player); return (int)Math.Min(2147483647L, Available(player, item, PathOfValheiman.ChestsFor(piece ?? player.GetSelectedPiece()))); } } internal static long Required(Piece piece, Requirement requirement, Requirement[] effective = null) { Costs costs = GetCosts(piece, effective); if (costs == null || !costs.Valid) { return 2147483648L; } string item = Row(requirement).Name; int value; return (item != null && costs.Totals.TryGetValue(item, out value)) ? value : 0; } internal static void Reset() { Quotes.Clear(); DisplayStock.Clear(); displayPlayer = null; displayInventory = null; displayRevision = -1L; refreshAt = 0f; } } internal static class BuildingRouting { private delegate bool TryPlanting(Piece piece, out float spacing); private const string GroundworkId = "sighsorry.Groundwork"; private const float PatchCacheSeconds = 1f; private static object provider; private static Assembly assembly; private static Func<Player, Piece, bool> shared; private static Func<Player, Piece, bool> povOwns; private static Func<bool> validate; private static Func<Piece, bool> blocked; private static TryPlanting planting; private static FieldInfo pending; private static FieldInfo pendingPlayer; private static FieldInfo placing; private static MethodInfo requirementsPatch; private static MethodInfo creationPatch; private static MethodInfo interceptPatch; private static bool bound; private static bool patchesReady; private static bool warned; private static float patchExpires; private static readonly MethodInfo Requirements = AccessTools.DeclaredMethod(typeof(Player), "HaveRequirements", new Type[2] { typeof(Piece), typeof(RequirementMode) }, (Type[])null); private static readonly MethodInfo Place = AccessTools.DeclaredMethod(typeof(Player), "PlacePiece", (Type[])null, (Type[])null); private static readonly MethodInfo TryPlace = AccessTools.DeclaredMethod(typeof(Player), "TryPlacePiece", (Type[])null, (Type[])null); internal static bool Delegated(Player player, Piece piece, bool recheck = false) { if (!Object.op_Implicit((Object)(object)player) || !Object.op_Implicit((Object)(object)piece) || (Object)(object)player != (Object)(object)Player.m_localPlayer) { return false; } if (!Chainloader.PluginInfos.TryGetValue("sighsorry.Groundwork", out var value)) { Reset(); return false; } BaseUnityPlugin instance = value.Instance; if (provider != instance) { Reset(); provider = instance; if (Object.op_Implicit((Object)(object)instance)) { try { Bind(((object)instance).GetType().Assembly); } catch (Exception ex) { Warn(ex.GetBaseException().Message); } } } bool flag = Object.op_Implicit((Object)(object)((Component)piece).GetComponentInChildren<Plant>(true)) || Object.op_Implicit((Object)(object)((Component)piece).GetComponentInChildren<Pickable>(true)); if (!Object.op_Implicit((Object)(object)instance) || !bound) { return flag; } try { object value2 = pending.GetValue(null); if (value2 != null && pendingPlayer.GetValue(value2) == player) { return true; } flag |= planting(piece, out var _); if (blocked(piece) || povOwns(player, piece)) { return true; } if (flag && (bool)placing.GetValue(null)) { return true; } if (!flag) { return false; } if (recheck || Time.unscaledTime >= patchExpires) { patchesReady = HasPatch(Requirements, requirementsPatch, transpiler: true) && HasPatch(Place, creationPatch, transpiler: true) && HasPatch(TryPlace, interceptPatch, transpiler: false); patchExpires = Time.unscaledTime + 1f; } if (!validate() || !patchesReady) { Warn("the material adapter or its required planting patches are unavailable"); return true; } return shared(player, piece); } catch (Exception ex2) { Warn(ex2.GetBaseException().Message); return flag; } } private static void Bind(Assembly source) { Type type = source.GetType("Groundwork.MassPlantingSystem", throwOnError: true); shared = (Func<Player, Piece, bool>)Method(type.FullName, "UsesSharedMaterials", typeof(bool), new Type[2] { typeof(Player), typeof(Piece) }).CreateDelegate(typeof(Func<Player, Piece, bool>)); validate = (Func<bool>)Method("Groundwork.CraftFromCompatSystem", "ValidateContract", typeof(bool), Array.Empty<Type>()).CreateDelegate(typeof(Func<bool>)); planting = (TryPlanting)Method("Groundwork.CultivationSystem", "TryGetPlanting", typeof(bool), new Type[2] { typeof(Piece), typeof(float).MakeByRefType() }).CreateDelegate(typeof(TryPlanting)); blocked = (Func<Piece, bool>)Method("Groundwork.CultivationSystem", "BlocksPlacement", typeof(bool), new Type[1] { typeof(Piece) }).CreateDelegate(typeof(Func<Piece, bool>)); povOwns = (Func<Player, Piece, bool>)Method("Groundwork.PathOfValheimanCompatSystem", "OwnsPlanting", typeof(bool), new Type[2] { typeof(Player), typeof(Piece) }).CreateDelegate(typeof(Func<Player, Piece, bool>)); pending = type.GetField("_sharedPlantingBatch", BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); placing = type.GetField("_placingBatch", BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); pendingPlayer = pending?.FieldType.GetField("Player", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (pending == null || placing?.FieldType != typeof(bool) || pendingPlayer?.FieldType != typeof(Player)) { throw new MissingFieldException("Groundwork planting operation context changed."); } Type? type2 = source.GetType("Groundwork.CraftFromCompatSystem", throwOnError: true); requirementsPatch = type2.GetMethod("RequirementsTranspiler", BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); creationPatch = type2.GetMethod("PlacePieceTranspiler", BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); interceptPatch = Method("Groundwork.PlayerTryPlacePieceGroundworkPatch", "Prefix", typeof(bool), new Type[3] { typeof(Player), typeof(Piece), typeof(bool).MakeByRefType() }); if (requirementsPatch == null || creationPatch == null) { throw new MissingMethodException("Groundwork planting payment hooks changed."); } assembly = source; patchExpires = float.NegativeInfinity; bound = true; MethodInfo Method(string text, string name, Type result, params Type[] arguments) { MethodInfo method = source.GetType(text, throwOnError: true).GetMethod(name, BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, arguments, null); if (method == null || method.IsGenericMethod || method.ReturnType != result) { throw new MissingMethodException(text, name); } return method; } } private static bool HasPatch(MethodInfo target, MethodInfo expected, bool transpiler) { Patches patchInfo = Harmony.GetPatchInfo((MethodBase)target); return ((!transpiler) ? patchInfo?.Prefixes : patchInfo?.Transpilers)?.Any((Patch p) => p.owner == "sighsorry.Groundwork" && p.PatchMethod == expected && p.PatchMethod.DeclaringType?.Assembly == assembly) ?? false; } private static void Warn(string reason) { if (!warned) { warned = true; ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)("Generic chest-funded planting deferred to Groundwork: " + reason + ". Ordinary building remains available.")); } } } internal static void Reset() { provider = null; assembly = null; shared = null; povOwns = null; validate = null; blocked = null; planting = null; pending = (pendingPlayer = (placing = null)); requirementsPatch = (creationPatch = (interceptPatch = null)); bound = (patchesReady = (warned = false)); patchExpires = float.NegativeInfinity; } } internal static class CarriedContainers { private sealed class Binding { internal string Id; internal MethodInfo Data; internal MethodInfo Get; internal MethodInfo Read; internal MethodInfo Save; internal MethodInfo CanRemove; internal MethodInfo Removing; internal MethodInfo SaveItems; internal MethodInfo SaveInfo; internal FieldInfo InventoryField; internal FieldInfo OpenInfo; internal FieldInfo OpenInventory; internal FieldInfo Sealed; internal PropertyInfo Key; internal PropertyInfo InfoIndexer; internal Type Bag; internal Type Forbidden; internal bool Quiver; } private sealed class Carried : ExtraInventory { internal Binding Binding; internal Player Player; internal ItemData Item; internal object Data; internal object Container; private Dictionary<string, string> savedData; internal bool Retired; internal override ItemData Parent => Item; internal void Remember() { savedData = new Dictionary<string, string>(Item.m_customData); } internal bool Bound() { if (!Retired && Object.op_Implicit((Object)(object)Player) && (Object)(object)Player == (Object)(object)Player.m_localPlayer && ((Humanoid)Player).GetInventory().ContainsItem(Item) && !((Character)Player).IsDead()) { return !((Character)Player).IsTeleporting(); } return false; } internal override bool Ready() { if (Bound() && Allowed(Binding, Data, Container) && Item.m_customData.Count == savedData.Count && savedData.All((KeyValuePair<string, string> p) => Item.m_customData.TryGetValue(p.Key, out var value) && value == p.Value)) { if (!(Binding.OpenInfo == null) && Binding.OpenInfo.GetValue(null) == Data) { return Binding.OpenInventory.GetValue(null) == Inventory; } return true; } return false; } internal override bool Allows(ItemData item) { if (Ready()) { if (!(Binding.CanRemove == null)) { return (bool)Binding.CanRemove.Invoke(Container, new object[1] { item }); } return true; } return false; } internal override bool BeforeRemove(ItemData item) { if (Allows(item)) { if (!(Binding.Removing == null)) { return (bool)Binding.Removing.Invoke(Container, new object[1] { item }); } return true; } return false; } internal override void Save() { if (!Bound()) { throw new InvalidOperationException("The carried container moved before saving."); } if (Binding.Quiver) { Binding.Save.Invoke(null, new object[1] { Item }); } else if (Binding.SaveItems != null) { Binding.SaveItems.Invoke(Container, new object[1] { Inventory }); Binding.SaveInfo.Invoke(Data, Array.Empty<object>()); } else { Binding.Save.Invoke(Container, Array.Empty<object>()); } Remember(); ChestCatalog.Invalidate(); } internal void Changed() { ChestCatalog.Invalidate(); } } private static readonly List<Binding> Bindings = new List<Binding>(); private static readonly Dictionary<ItemData, Carried> Cached = new Dictionary<ItemData, Carried>(); private static readonly HashSet<string> Warnings = new HashSet<string>(); private static IReadOnlyList<ExtraInventory> lastRead = Array.Empty<ExtraInventory>(); private static Player lastPlayer; private static long lastRevision = -1L; private static float refreshAt; private static int parentCount; internal static void Install() { Bindings.Clear(); Bind("org.bepinex.plugins.backpacks", "Backpacks", quiver: false); Bind("org.bepinex.plugins.jewelcrafting", "Jewelcrafting", quiver: false); Bind("Azumatt.BowsBeforeHoes", "BowsBeforeHoes", quiver: true); } private static void Bind(string id, string name, bool quiver) { if (!Chainloader.PluginInfos.TryGetValue(id, out var value)) { return; } try { Assembly assembly = ((object)value.Instance).GetType().Assembly; Binding binding = new Binding { Id = id, Quiver = quiver }; if (quiver) { Type type = assembly.GetType(name + ".API", throwOnError: true); binding.Read = Required(type, "GetQuiverInventory", typeof(ItemData)); binding.Save = Required(type, "SaveQuiver", typeof(ItemData)); } else { Type type2 = assembly.GetType(name + ".ItemContainer", throwOnError: true); binding.Data = Required(assembly.GetType("ItemDataManager.ItemExtensions", throwOnError: true), "Data", typeof(ItemData)); binding.Get = binding.Data.ReturnType.GetMethods().Single((MethodInfo m) => m.Name == "Get" && m.IsGenericMethodDefinition && m.GetParameters().Length == 1).MakeGenericMethod(type2); binding.Key = type2.GetProperty("CustomDataKey") ?? throw new MissingMemberException("CustomDataKey"); if (name == "Backpacks") { binding.InventoryField = AccessTools.Field(type2, "Inventory"); binding.Save = Required(type2, "Save"); binding.CanRemove = Required(type2, "CanRemoveItem", typeof(ItemData)); binding.Removing = Required(type2, "RemoveItem", typeof(ItemData)); } else { binding.Bag = assembly.GetType("Jewelcrafting.ItemBag", throwOnError: true); binding.Forbidden = assembly.GetType("Jewelcrafting.DropChest", throwOnError: true); binding.Sealed = AccessTools.Field(type2, "boxSealed"); binding.InfoIndexer = binding.Data.ReturnType.GetProperty("Item", new Type[1] { typeof(string) }); binding.Read = Required(type2, "ReadInventory"); binding.SaveItems = Required(type2, "SaveSocketsInventory", typeof(Inventory)); binding.SaveInfo = Required(binding.Data.ReturnType, "Save"); Type type3 = assembly.GetType("Jewelcrafting.GemStones+AddFakeSocketsContainer", throwOnError: true); binding.OpenInfo = AccessTools.Field(type3, "openEquipment"); binding.OpenInventory = AccessTools.Field(type3, "openInventory"); } } Bindings.Add(binding); } catch (Exception error) { Warn(id, error); } } internal static MethodInfo Required(Type type, string name, params Type[] args) { return AccessTools.Method(type, name, args, (Type[])null) ?? throw new MissingMethodException(type.FullName, name); } internal static IReadOnlyList<ExtraInventory> Read(Player player) { //IL_01be: Unknown result type (might be due to invalid IL or missing references) //IL_01c5: Expected O, but got Unknown //IL_01f7: Unknown result type (might be due to invalid IL or missing references) //IL_01fe: Expected O, but got Unknown //IL_0246: Unknown result type (might be due to invalid IL or missing references) //IL_0231: Unknown result type (might be due to invalid IL or missing references) //IL_024d: Expected O, but got Unknown if (!Object.op_Implicit((Object)(object)player) || (Object)(object)player != (Object)(object)Player.m_localPlayer || Bindings.Count == 0) { return Array.Empty<ExtraInventory>(); } if ((Object)(object)player == (Object)(object)lastPlayer && lastRevision == ChestCatalog.Revision && Time.unscaledTime < refreshAt && parentCount == ((Humanoid)player).GetInventory().GetAllItems().Count && Cached.Values.All((Carried c) => c.Mutating || c.Ready())) { return lastRead; } List<ExtraInventory> list = new List<ExtraInventory>(); HashSet<ItemData> seen = new HashSet<ItemData>(); foreach (ItemData item in ((Humanoid)player).GetInventory().GetAllItemsInGridOrder()) { foreach (Binding binding in Bindings) { try { object obj = (binding.Quiver ? null : binding.Data.Invoke(null, new object[1] { item })); object obj2 = ((obj == null) ? null : binding.Get.Invoke(obj, new object[1] { "" })); if ((!binding.Quiver && obj2 == null) || !Allowed(binding, obj, obj2)) { continue; } Carried value; bool flag = Cached.TryGetValue(item, out value) && value.Binding == binding && value.Container == obj2 && value.Data == obj && (value.Mutating || value.Ready()); Inventory val = (Inventory)(binding.Quiver ? ((object)(Inventory)binding.Read.Invoke(null, new object[1] { item })) : ((binding.OpenInfo != null && binding.OpenInfo.GetValue(null) == obj) ? ((object)(Inventory)binding.OpenInventory.GetValue(null)) : ((!flag) ? ((object)((binding.InventoryField != null) ? ((Inventory)binding.InventoryField.GetValue(obj2)) : ((Inventory)binding.Read.Invoke(obj2, Array.Empty<object>())))) : ((object)value.Inventory)))); if (val == null) { continue; } if (!flag || value.Inventory != val) { Retire(value); value = new Carried { Binding = binding, Player = player, Item = item, Data = obj, Container = obj2, Inventory = val }; value.Remember(); val.m_onChanged = (Action)Delegate.Combine(val.m_onChanged, new Action(value.Changed)); Cached[item] = value; MaterialSources.Register(value); ChestCatalog.Invalidate(); } seen.Add(item); list.Add(value); break; } catch (Exception error) { Warn(binding.Id, error); } } } ItemData[] array = Cached.Keys.Where((ItemData i) => !seen.Contains(i)).ToArray(); foreach (ItemData key in array) { Retire(Cached[key]); Cached.Remove(key); ChestCatalog.Invalidate(); } lastPlayer = player; lastRevision = ChestCatalog.Revision; refreshAt = Time.unscaledTime + 0.2f; parentCount = ((Humanoid)player).GetInventory().GetAllItems().Count; return lastRead = list; } private static bool Allowed(Binding binding, object data, object container) { if (!(binding.Bag == null)) { if (binding.Bag.IsInstanceOfType(container) && !binding.Forbidden.IsInstanceOfType(container) && !(bool)binding.Sealed.GetValue(container) && binding.InfoIndexer.GetValue(data, new object[1] { "SocketsLock" }) == null) { return binding.InfoIndexer.GetValue(data, new object[1] { "Mirrored Item" }) == null; } return false; } return true; } private static void Retire(Carried source) { if (source != null) { source.Retired = true; Inventory inventory = source.Inventory; inventory.m_onChanged = (Action)Delegate.Remove(inventory.m_onChanged, new Action(source.Changed)); } } private static void Warn(string id, Exception error) { if (Warnings.Add(id)) { Plugin.Log.LogWarning((object)("Carried container integration " + id + " is unavailable. " + error.GetBaseException().Message)); } } internal static void Reset() { foreach (Carried value in Cached.Values) { Retire(value); } Cached.Clear(); Warnings.Clear(); lastRead = Array.Empty<ExtraInventory>(); lastPlayer = null; lastRevision = -1L; } } internal static class CarriedMaterialProviders { private sealed class View : ExtraInventory { internal Registration Owner; internal Player Player; internal ItemData Item; internal override ItemData Parent => Item; internal override bool PersistsParentData => true; internal override bool Rea