Decompiled source of QoL Unknown v1.1.5
QoL Unknown.dll
Decompiled 5 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Net.Http; 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.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Logging; using Costura; using DiscordRPC; using DiscordRPC.Events; using DiscordRPC.IO; using DiscordRPC.Logging; using DiscordRPC.Message; using HarmonyLib; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using QoL_Unknown.Images; using TMPro; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.Events; using UnityEngine.Experimental.Rendering.Universal; using UnityEngine.Networking; using UnityEngine.Rendering.Universal; using UnityEngine.SceneManagement; using UnityEngine.Tilemaps; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("QoL Unknown")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("HP")] [assembly: AssemblyProduct("QoL Unknown")] [assembly: AssemblyCopyright("Copyright © 2026 Jimmyking (https://github.com/jimmyking9999999/)")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("5d41aeb4-7bbc-435f-bc68-077bf18aa764")] [assembly: AssemblyFileVersion("1.1.5")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyVersion("1.1.5.0")] internal class <Module> { static <Module>() { AssemblyLoader.Attach(subscribe: true); } } namespace QoL_Unknown { internal class CtrlDragPatcher { private enum LocationKind { BodySlot, Wearable, Container, Unknown } private struct ItemLocation { public LocationKind kind; public int slotIndex; public Container container; public string wearSlotId; } private static ManualLogSource Logger; private static bool initialized; public static void Initialize(ManualLogSource logger) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) if (!initialized) { initialized = true; Logger = logger; new Harmony("org.bepinex.plugins.qol.liquidquicktransfer").PatchAll(typeof(CtrlDragPatcher)); } } [HarmonyPatch(typeof(PlayerCamera), "TryPerformInventoryAction")] [HarmonyPrefix] private static bool ShiftDrag_Prefix(PlayerCamera __instance, RaycastResult hit, List<RaycastResult> uiCasts, ref bool __result) { //IL_0145: Unknown result type (might be due to invalid IL or missing references) if (!ModKeybinds.VanillaBindHeld("expanddesc")) { return true; } InvButton component = ((RaycastResult)(ref hit)).gameObject.GetComponent<InvButton>(); if ((Object)(object)component == (Object)null || !component.Overlaps(uiCasts)) { return true; } Item dragItem = __instance.dragItem; Item item = component.GetItem(); if ((Object)(object)dragItem == (Object)null || (Object)(object)item == (Object)null || (Object)(object)dragItem == (Object)(object)item) { return true; } WaterContainerItem component2 = ((Component)dragItem).GetComponent<WaterContainerItem>(); WaterContainerItem component3 = ((Component)item).GetComponent<WaterContainerItem>(); Container component4 = ((Component)dragItem).GetComponent<Container>(); Container component5 = ((Component)item).GetComponent<Container>(); if ((Object)(object)component2 != (Object)null && (Object)(object)component3 != (Object)null && component2.CurrentTotal > 0f && component3.SpaceLeft > 0f) { float num = Mathf.Min(component2.CurrentTotal, component3.SpaceLeft); if (!MultiplayerCompat.TryEnsureItemSync(item) || !MultiplayerCompat.TryEnsureItemSync(dragItem)) { __instance.PlayUISound((UISoundType)6, 1f); __result = false; return false; } __instance.body.CombineLiquids(component3, component2, num); if (!MultiplayerCompat.TryAnnounceLiquidTransfer(__instance.body, item, dragItem, num)) { __instance.PlayUISound((UISoundType)6, 1f); } component.UpdateGraphic(); __result = true; return false; } if ((Object)(object)component4 != (Object)null && (Object)(object)component5 != (Object)null) { Item val = default(Item); foreach (Transform item2 in ((Component)component4).transform) { if (((Component)item2).TryGetComponent<Item>(ref val) && component5.CanHoldItem(val)) { return true; } } __result = true; return false; } return true; } [HarmonyPatch(typeof(PlayerCamera), "TryPerformInventoryAction")] [HarmonyPrefix] private static bool CtrlDrag_Prefix(PlayerCamera __instance, RaycastResult hit, List<RaycastResult> uiCasts, ref bool __result) { if (!ModKeybinds.GetAction("inventoryinteraction")) { return true; } InvButton component = ((RaycastResult)(ref hit)).gameObject.GetComponent<InvButton>(); if ((Object)(object)component == (Object)null || !component.Overlaps(uiCasts)) { return true; } Item dragItem = __instance.dragItem; Item item = component.GetItem(); if ((Object)(object)dragItem == (Object)null || (Object)(object)item == (Object)null || (Object)(object)dragItem == (Object)(object)item) { return true; } Body body = __instance.body; bool num = (Object)(object)((Component)dragItem).GetComponent<Container>() != (Object)null || (Object)(object)((Component)dragItem).GetComponent<WaterContainerItem>() != (Object)null; bool flag = (Object)(object)((Component)item).GetComponent<Container>() != (Object)null || (Object)(object)((Component)item).GetComponent<WaterContainerItem>() != (Object)null; Container component2 = ((Component)item).GetComponent<Container>(); if (num && flag) { ItemLocation itemLocation = GetItemLocation(body, dragItem); ItemLocation itemLocation2 = GetItemLocation(body, item); if (itemLocation.kind == LocationKind.Unknown || itemLocation2.kind == LocationKind.Unknown) { __instance.PlayUISound((UISoundType)6, 1f); __result = false; return false; } if (!CanPlaceAtLocation(dragItem, itemLocation2) || !CanPlaceAtLocation(item, itemLocation)) { __instance.PlayUISound((UISoundType)6, 1f); __result = false; return false; } if (itemLocation.kind == LocationKind.BodySlot && itemLocation2.kind == LocationKind.BodySlot) { body.SwapSlots(itemLocation.slotIndex, itemLocation2.slotIndex); } else { DetachItem(body, dragItem); DetachItem(body, item); PlaceAtLocation(body, dragItem, itemLocation2); PlaceAtLocation(body, item, itemLocation); } __instance.PlayBackpackSound(); RefreshUI(__instance); __result = true; return false; } if ((Object)(object)component2 != (Object)null && component2.CanHoldItem(dragItem)) { if (GetItemLocation(body, dragItem).kind == LocationKind.Unknown) { __instance.PlayUISound((UISoundType)6, 1f); __result = false; return false; } DetachItem(body, dragItem); component2.LoadItem(dragItem); __instance.PlayBackpackSound(); RefreshUI(__instance); __result = true; return false; } return true; } [HarmonyPatch(typeof(PlayerCamera), "TryPerformWorldActions")] [HarmonyPrefix] private static bool WorldActions_Prefix(PlayerCamera __instance) { //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) if (!ModKeybinds.GetAction("inventoryinteraction")) { return true; } Item dragItem = __instance.dragItem; if ((Object)(object)dragItem == (Object)null) { return true; } Body body = __instance.body; Camera main = Camera.main; if ((Object)(object)body == (Object)null || (Object)(object)main == (Object)null) { return true; } bool flag = (Object)(object)((Component)dragItem).GetComponent<Container>() != (Object)null || (Object)(object)((Component)dragItem).GetComponent<WaterContainerItem>() != (Object)null; Collider2D val = Physics2D.OverlapPoint(Vector2.op_Implicit(main.ScreenToWorldPoint(Input.mousePosition)), LayerMask.GetMask(new string[1] { "Item" })); Item val2 = (((Object)(object)val != (Object)null) ? ((Component)val).GetComponent<Item>() : null); if ((Object)(object)val2 != (Object)null && (Object)(object)val2 != (Object)(object)dragItem) { bool flag2 = (Object)(object)((Component)val2).GetComponent<Container>() != (Object)null || (Object)(object)((Component)val2).GetComponent<WaterContainerItem>() != (Object)null; Container component = ((Component)val2).GetComponent<Container>(); if (flag && flag2) { ItemLocation itemLocation = GetItemLocation(body, dragItem); ItemLocation itemLocation2 = GetItemLocation(body, val2); if (itemLocation.kind != LocationKind.Unknown && itemLocation2.kind != LocationKind.Unknown && CanPlaceAtLocation(dragItem, itemLocation2) && CanPlaceAtLocation(val2, itemLocation)) { if (itemLocation.kind == LocationKind.BodySlot && itemLocation2.kind == LocationKind.BodySlot) { body.SwapSlots(itemLocation.slotIndex, itemLocation2.slotIndex); } else { DetachItem(body, dragItem); DetachItem(body, val2); PlaceAtLocation(body, dragItem, itemLocation2); PlaceAtLocation(body, val2, itemLocation); } __instance.PlayBackpackSound(); RefreshUI(__instance); return false; } } if ((Object)(object)component != (Object)null && component.CanHoldItem(dragItem)) { DetachItem(body, dragItem); component.LoadItem(dragItem); __instance.PlayBackpackSound(); RefreshUI(__instance); return false; } } Container currentContainer = __instance.currentContainer; if ((Object)(object)currentContainer != (Object)null && (Object)(object)((Component)currentContainer).gameObject != (Object)(object)((Component)dragItem).gameObject && currentContainer.CanHoldItem(dragItem) && (Object)(object)((Component)dragItem).transform.parent != (Object)(object)((Component)currentContainer).transform) { DetachItem(body, dragItem); currentContainer.LoadItem(dragItem); __instance.PlayBackpackSound(); RefreshUI(__instance); return false; } return true; } [HarmonyPatch(typeof(PlayerCamera), "TryPerformSpecialUIAction")] [HarmonyPrefix] private static bool TryPerformSpecialUIAction_Prefix(PlayerCamera __instance, RaycastResult hit, ref bool __result) { //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) if (!IsLiquidDrainTarget(__instance, ((RaycastResult)(ref hit)).gameObject)) { return true; } Item dragItem = __instance.dragItem; if ((Object)(object)dragItem == (Object)null) { return true; } if ((Object)(object)WorldGeneration.world == (Object)null || (Object)(object)FluidManager.main == (Object)null) { return true; } if (FluidManager.main.HasLiquid(WorldGeneration.world.WorldToBlockPos(Vector2.op_Implicit(((Component)dragItem).transform.position)))) { return true; } if (!__instance.body.DoPickupCheck(dragItem, true)) { return true; } WaterContainerItem component = ((Component)dragItem).GetComponent<WaterContainerItem>(); if ((Object)(object)component == (Object)null || component.CurrentTotal <= 0f) { return true; } List<float> list = component.CalculateDrain(component.CurrentTotal); if (list == null || list.Count == 0) { return true; } if (!MultiplayerCompat.TryEnsureItemSync(dragItem)) { __instance.PlayUISound((UISoundType)6, 1f); __result = false; return false; } using (MultiplayerCompat.BeginInventoryMutation(__instance.body)) { component.Drain(list); MultiplayerCompat.TryAnnounceLiquidDrain(dragItem, component.CurrentTotal); MultiplayerCompat.MarkItemMoved(dragItem, containerChanged: false); } RefreshUI(__instance); __result = true; return false; } private static void RefreshUI(PlayerCamera cam) { if (cam.containerMenu.activeSelf && (Object)(object)cam.currentContainer != (Object)null) { cam.RepopulateContainer(); } cam.UpdateWearables(); } private static bool IsLiquidDrainTarget(PlayerCamera cam, GameObject hitObject) { GameObject val = (((Object)(object)cam != (Object)null) ? cam.liquidDrainObject : null); if ((Object)(object)val == (Object)null || (Object)(object)hitObject == (Object)null) { return false; } Transform transform = hitObject.transform; Transform transform2 = val.transform; if (!((Object)(object)hitObject == (Object)(object)val) && !((Object)(object)transform == (Object)(object)transform2)) { return transform.IsChildOf(transform2); } return true; } private static ItemLocation GetItemLocation(Body body, Item item) { for (int i = 0; i < body.slots.Length; i++) { if ((Object)(object)body.GetItem(i) == (Object)(object)item) { return new ItemLocation { kind = LocationKind.BodySlot, slotIndex = i }; } } if (item.Stats.wearable && (Object)(object)body.GetWearableBySlotID(item.Stats.wearSlotId) == (Object)(object)item) { return new ItemLocation { kind = LocationKind.Wearable, wearSlotId = item.Stats.wearSlotId }; } if ((Object)(object)((Component)item).transform.parent != (Object)null) { Container component = ((Component)((Component)item).transform.parent).GetComponent<Container>(); if ((Object)(object)component != (Object)null) { return new ItemLocation { kind = LocationKind.Container, container = component }; } } return new ItemLocation { kind = LocationKind.Unknown }; } private static bool CanPlaceAtLocation(Item item, ItemLocation loc) { return loc.kind switch { LocationKind.BodySlot => true, LocationKind.Wearable => item.Stats.wearable && item.Stats.wearSlotId == loc.wearSlotId, LocationKind.Container => loc.container.CanHoldItem(item), _ => false, }; } private static void DetachItem(Body body, Item item) { if ((Object)(object)((Component)item).transform.parent != (Object)null) { Container component = ((Component)((Component)item).transform.parent).GetComponent<Container>(); if ((Object)(object)component != (Object)null) { component.UnloadItem(item, (Body)null); return; } } if (body.HoldingItem(item)) { body.DropItem(item); } else if (item.Stats.wearable && (Object)(object)body.GetWearableBySlotID(item.Stats.wearSlotId) == (Object)(object)item) { body.DropWearable(item); } } private static void PlaceAtLocation(Body body, Item item, ItemLocation loc) { switch (loc.kind) { case LocationKind.BodySlot: body.PickUpItem(item, loc.slotIndex, true); break; case LocationKind.Wearable: body.WearWearable(item); break; case LocationKind.Container: loc.container.LoadItem(item); break; } } } internal static class RepeatCommandManager { private class RepeatEntry { public string Name; public string Commands; public float Delay; public int TimesTotal; public int TimesRemaining; public float Elapsed; public bool Paused; } private static readonly List<RepeatEntry> entries = new List<RepeatEntry>(); private static int autoNameCounter; private static bool driverRunning; public static void StartRepeat(string[] args) { if (args.Length <= 3) { throw new Exception(string.Format("Expected at least {0} argument{1}, but got {2}.", 3, "s", args.Length - 1)); } if (!int.TryParse(args[1], out var result)) { throw new Exception("\"" + args[1] + "\" is not a valid integer value! (0, 1, 5, etc)"); } if (!float.TryParse(args[2], NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out var result2)) { throw new Exception("\"" + args[2] + "\" is not a valid float value! (2, 0.7, 14.1, etc)"); } if (result >= 1) { string text = ((args.Length > 4) ? string.Join(" ", args.Skip(4)).Trim() : ""); if (text.Length == 0) { text = GenerateName(); } else if (Find(text) != null) { throw new Exception("A repeat command named \"" + text + "\" is already active!"); } ConsoleHelper.RunCommandString(ConsoleScript.instance, args[3]); if (result != 1) { entries.Add(new RepeatEntry { Name = text, Commands = args[3], Delay = result2, TimesTotal = result, TimesRemaining = result - 1, Elapsed = 0f, Paused = false }); RefreshAutofill(); EnsureDriver(); ConsoleHelper.LogToConsole(ConsoleScript.instance, "<color=green>Repeat \"" + text + "\" started: " + result + "x \"" + args[3] + "\" every " + result2 + "s.</color>"); } } } public static void Control(string[] args) { if (args.Length < 2) { throw new Exception("Expected at least 1 argument, but got " + (args.Length - 1) + "."); } string text = args[1].ToLowerInvariant(); if (text == "list") { ListAll(); return; } if (text != "pause" && text != "unpause" && text != "stop") { throw new Exception("\"" + args[1] + "\" is not a valid controlrepeat action! (pause, unpause, stop, list)"); } if (args.Length < 3) { throw new Exception("Expected a repeat command name after \"" + text + "\"."); } string text2 = string.Join(" ", args.Skip(2)).Trim(); RepeatEntry repeatEntry = Find(text2); if (repeatEntry == null) { throw new Exception("No active repeat command named \"" + text2 + "\". Use controlrepeat list to see active repeats."); } switch (text) { case "pause": repeatEntry.Paused = true; ConsoleHelper.LogToConsole(ConsoleScript.instance, "<color=yellow>Paused repeat \"" + repeatEntry.Name + "\".</color>"); break; case "unpause": repeatEntry.Paused = false; ConsoleHelper.LogToConsole(ConsoleScript.instance, "<color=green>Unpaused repeat \"" + repeatEntry.Name + "\".</color>"); break; case "stop": entries.Remove(repeatEntry); RefreshAutofill(); ConsoleHelper.LogToConsole(ConsoleScript.instance, "<color=orange>Stopped repeat \"" + repeatEntry.Name + "\".</color>"); break; } } public static void RefreshAutofill() { Command val = ConsoleScript.SearchExact("controlrepeat"); if (val != null && val.argAutofill != null) { val.argAutofill[1] = entries.Select((RepeatEntry e) => e.Name).ToList(); } } private static void ListAll() { if (entries.Count == 0) { ConsoleHelper.LogToConsole(ConsoleScript.instance, "No active repeat commands."); return; } string text = "<color=green>Active repeat commands (" + entries.Count + "):</color>"; foreach (RepeatEntry entry in entries) { int num = entry.TimesTotal - entry.TimesRemaining; text = text + "\n<color=yellow>" + entry.Name + "</color> - " + (entry.Paused ? "<color=orange>paused</color>" : "<color=green>running</color>") + ", " + num + "/" + entry.TimesTotal + " repeats done, every " + entry.Delay + "s <color=#888888>[" + entry.Commands + "]</color>"; } ConsoleHelper.LogToConsole(ConsoleScript.instance, text); } private static RepeatEntry Find(string name) { return entries.FirstOrDefault((RepeatEntry e) => e.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); } private static string GenerateName() { string text; do { autoNameCounter++; text = "repeat" + autoNameCounter; } while (Find(text) != null); return text; } private static void EnsureDriver() { if (!driverRunning && !((Object)(object)ConsoleScript.instance == (Object)null)) { driverRunning = true; ((MonoBehaviour)ConsoleScript.instance).StartCoroutine(Driver()); } } private static IEnumerator Driver() { while (entries.Count > 0) { float unscaledDeltaTime = Time.unscaledDeltaTime; for (int num = entries.Count - 1; num >= 0; num--) { RepeatEntry repeatEntry = entries[num]; if (!repeatEntry.Paused) { repeatEntry.Elapsed += unscaledDeltaTime; if (!(repeatEntry.Elapsed < repeatEntry.Delay)) { repeatEntry.Elapsed -= repeatEntry.Delay; ConsoleHelper.RunCommandString(ConsoleScript.instance, repeatEntry.Commands); repeatEntry.TimesRemaining--; if (repeatEntry.TimesRemaining <= 0) { entries.RemoveAt(num); RefreshAutofill(); } } } } yield return null; } driverRunning = false; } } internal class CtrlItemLabelPatcher { private readonly struct ItemCandidate { internal readonly Item Item; internal readonly bool Contained; internal readonly float Distance; internal ItemCandidate(Item item, bool contained, float distance) { Item = item; Contained = contained; Distance = distance; } } internal const string ModuleId = "qol_ui_ctrlitemlabels"; private const int LabelPoolSize = 64; private const float ScanRadius = 14f; private const int MaxScanHits = 256; private const float RowGap = 4f; private const float MaxRise = 5000f; private static readonly FieldInfo SpawnedLabelsField = AccessTools.Field(typeof(AltHoverScript), "spawnedLabels"); private static readonly FieldInfo IsActiveField = AccessTools.Field(typeof(AltHoverScript), "active"); private static readonly Collider2D[] scanHits = (Collider2D[])(object)new Collider2D[256]; private static readonly HashSet<Item> scannedItems = new HashSet<Item>(); private static readonly List<ItemCandidate> candidates = new List<ItemCandidate>(256); private static readonly List<ItemLabel> shownLabels = new List<ItemLabel>(64); private static readonly List<Rect> placedRects = new List<Rect>(64); private static AltHoverScript poolInstance; private static List<ItemLabel> pool; private static int itemLayerMask = -1; public static void Initialize(ManualLogSource pluginLogger) { RuntimePatchRegistry.PatchAllOnce("org.bepinex.plugins.qol.ctrlitemlabels", typeof(CtrlItemLabelPatcher), pluginLogger); } [HarmonyPatch(typeof(AltHoverScript), "Start")] [HarmonyPrefix] private static void Start_Prefix() { if (QoLModuleManager.IsEnabled("qol_ui_ctrlitemlabels")) { AltHoverScript.allocSize = 64; } } [HarmonyPatch(typeof(AltHoverScript), "Update")] [HarmonyPrefix] private static bool Update_Prefix(AltHoverScript __instance) { if (!QoLModuleManager.IsEnabled("qol_ui_ctrlitemlabels")) { pool = null; poolInstance = null; return true; } Refresh(__instance); return false; } private static void Refresh(AltHoverScript instance) { //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_0122: Unknown result type (might be due to invalid IL or missing references) //IL_0127: Unknown result type (might be due to invalid IL or missing references) //IL_012c: Unknown result type (might be due to invalid IL or missing references) //IL_0220: Unknown result type (might be due to invalid IL or missing references) //IL_0242: Unknown result type (might be due to invalid IL or missing references) //IL_026a: Unknown result type (might be due to invalid IL or missing references) //IL_026c: Unknown result type (might be due to invalid IL or missing references) //IL_0271: Unknown result type (might be due to invalid IL or missing references) //IL_028b: Unknown result type (might be due to invalid IL or missing references) //IL_0284: Unknown result type (might be due to invalid IL or missing references) //IL_0292: Unknown result type (might be due to invalid IL or missing references) //IL_0297: Unknown result type (might be due to invalid IL or missing references) //IL_02a0: Unknown result type (might be due to invalid IL or missing references) //IL_02ae: Unknown result type (might be due to invalid IL or missing references) List<ItemLabel> list = GetPool(instance); PlayerCamera main = PlayerCamera.main; Camera main2 = Camera.main; if (list == null || list.Count == 0 || (Object)(object)main == (Object)null || (Object)(object)main.body == (Object)null || (Object)(object)main2 == (Object)null) { return; } for (int i = 0; i < list.Count; i++) { ((Component)list[i]).gameObject.SetActive(false); } if (!UpdateDisplayState(instance)) { return; } Vector2 val = Vector2.op_Implicit(((Component)main.body).transform.position); int num = Physics2D.OverlapAreaNonAlloc(val - Vector2.one * 14f, val + Vector2.one * 14f, scanHits, GetItemLayerMask()); candidates.Clear(); scannedItems.Clear(); for (int j = 0; j < num; j++) { Collider2D val2 = scanHits[j]; scanHits[j] = null; if ((Object)(object)val2 == (Object)null) { continue; } Item component = ((Component)val2).GetComponent<Item>(); if (!((Object)(object)component == (Object)null) && scannedItems.Add(component)) { float num2 = Vector2.Distance(Vector2.op_Implicit(((Component)val2).transform.position), val); if (!(num2 >= 14f)) { candidates.Add(new ItemCandidate(component, (Object)(object)((Component)component).transform.parent != (Object)null, num2)); } } } candidates.Sort(CompareCandidates); shownLabels.Clear(); float num3 = (Object.op_Implicit((Object)(object)main.dragItem) ? 0.2f : 1f); Vector2 val4 = default(Vector2); for (int k = 0; k < candidates.Count; k++) { if (shownLabels.Count >= list.Count) { break; } Item item = candidates[k].Item; SpriteRenderer component2 = ((Component)item).GetComponent<SpriteRenderer>(); if (!((Object)(object)component2 == (Object)null) && !((Object)(object)component2.sprite == (Object)null)) { ItemLabel val3 = list[shownLabels.Count]; ((Component)val3).gameObject.SetActive(true); val3.SetItem(item); ((Vector2)(ref val4))..ctor(Mathf.Round(((Component)item).transform.position.x * 8f) / 8f, Mathf.Round(((Component)item).transform.position.y * 8f) / 8f); ((Component)val3).transform.position = main2.WorldToScreenPoint(Vector2.op_Implicit(val4)); Color color = Utils.WithAlpha(val3.hovered ? Color.gray : Color.white, num3); ((Graphic)val3.image).color = color; ((Graphic)val3.icon).color = color; val3.hovered = false; shownLabels.Add(val3); } } LayoutLabels(); } private static void LayoutLabels() { //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0041: 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_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) shownLabels.Sort(CompareLabels); placedRects.Clear(); for (int i = 0; i < shownLabels.Count; i++) { ItemLabel val = shownLabels[i]; Vector2 anchoredPosition = val.rect.anchoredPosition; anchoredPosition.x = Mathf.Round(anchoredPosition.x); anchoredPosition.y = Mathf.Round(anchoredPosition.y); float num = anchoredPosition.y - 5000f; Rect rect = val.GetRect(anchoredPosition); bool flag; do { flag = false; for (int j = 0; j < placedRects.Count; j++) { Rect val2 = placedRects[j]; if (((Rect)(ref rect)).Overlaps(val2)) { flag = true; anchoredPosition.y = Mathf.Max(((Rect)(ref val2)).yMin - ((Rect)(ref rect)).height - 4f + ((Rect)(ref rect)).height * 0.5f, num); rect = val.GetRect(anchoredPosition); } } } while (flag); val.rect.anchoredPosition = anchoredPosition; placedRects.Add(rect); } } private static int CompareCandidates(ItemCandidate left, ItemCandidate right) { if (left.Contained != right.Contained) { if (!left.Contained) { return -1; } return 1; } float distance = left.Distance; int num = distance.CompareTo(right.Distance); if (num != 0) { return num; } return ((Object)left.Item).GetInstanceID().CompareTo(((Object)right.Item).GetInstanceID()); } private static int CompareLabels(ItemLabel left, ItemLabel right) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0012: 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_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) Vector2 anchoredPosition = left.rect.anchoredPosition; Vector2 anchoredPosition2 = right.rect.anchoredPosition; int num = anchoredPosition2.y.CompareTo(anchoredPosition.y); if (num != 0) { return num; } int num2 = anchoredPosition.x.CompareTo(anchoredPosition2.x); if (num2 != 0) { return num2; } return GetItemId(left).CompareTo(GetItemId(right)); } private static int GetItemId(ItemLabel label) { if (!((Object)(object)label.refItem != (Object)null)) { return 0; } return ((Object)label.refItem).GetInstanceID(); } private static bool UpdateDisplayState(AltHoverScript instance) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000a: 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) //IL_0033: Unknown result type (might be due to invalid IL or missing references) KeyCode bind = KeyBinds.GetBind("altview"); bool flag = IsActiveField != null && (bool)IsActiveField.GetValue(instance); if (AltHoverScript.toggleActivated) { if (Input.GetKeyDown(bind)) { flag = !flag; } } else { flag = Input.GetKey(bind); } if (IsActiveField != null) { IsActiveField.SetValue(instance, flag); } return flag; } private static List<ItemLabel> GetPool(AltHoverScript instance) { if (pool != null && (Object)(object)poolInstance == (Object)(object)instance && SpawnedLabelsField != null) { return pool; } pool = ((SpawnedLabelsField != null) ? (SpawnedLabelsField.GetValue(instance) as List<ItemLabel>) : null); poolInstance = instance; return pool; } private static int GetItemLayerMask() { if (itemLayerMask < 0) { itemLayerMask = LayerMask.GetMask(new string[1] { "Item" }); } return itemLayerMask; } } internal class TraderItemTooltipPatcher { public static void Initialize(ManualLogSource pluginLogger) { RuntimePatchRegistry.PatchAllOnce("org.bepinex.plugins.qol.tradertooltips", typeof(TraderItemTooltipPatcher), pluginLogger); } [HarmonyPatch(typeof(UIUtil), "GetUITooltip")] [HarmonyPostfix] private static void GetUITooltip_Postfix(List<RaycastResult> UICasts, ref (string, string) __result) { PlayerCamera main = PlayerCamera.main; if ((Object)(object)main == (Object)null || (Object)(object)main.currentTrader == (Object)null || (Object)(object)main.traderInventory == (Object)null || (Object)(object)main.tradeMenu == (Object)null || !main.tradeMenu.activeSelf) { return; } UITooltip hoveredTooltip = GetHoveredTooltip(UICasts); if (!((Object)(object)hoveredTooltip == (Object)null) && ((Component)hoveredTooltip).transform.IsChildOf(main.traderInventory)) { ItemInfo val = FindTraderItem(main.currentTrader, hoveredTooltip.tipName); if (val != null) { bool expanded = PlayerCamera.alwaysExpandDescriptions || ModKeybinds.VanillaBindHeld("expanddesc"); __result = (hoveredTooltip.tipName, BuildTooltip(val, expanded)); } } } private static UITooltip GetHoveredTooltip(List<RaycastResult> raycasts) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) UITooltip result = default(UITooltip); for (int i = 0; i < raycasts.Count; i++) { RaycastResult val = raycasts[i]; if ((Object)(object)((RaycastResult)(ref val)).gameObject != (Object)null) { val = raycasts[i]; if (((RaycastResult)(ref val)).gameObject.TryGetComponent<UITooltip>(ref result)) { return result; } } } return null; } private static ItemInfo FindTraderItem(TraderScript trader, string displayName) { if (string.IsNullOrEmpty(displayName) || trader.items == null) { return null; } for (int i = 0; i < trader.items.Count; i++) { ItemInfo val = ((trader.items[i] != null) ? trader.items[i].info : null); if (val != null && val.fullName == displayName) { return val; } } return null; } private static string BuildTooltip(ItemInfo info, bool expanded) { string text = (info.description ?? string.Empty) + "\n\n"; List<LiquidStack> contents = DefaultContents(info); text += ContentsBlock(info, contents, expanded); text = text + "<color=#ffffff><sprite index=0 tint=1>" + Locale.GetOther("weight") + ": " + info.weight.ToString("0.##") + "u\n"; if (!expanded) { return text + "<color=#a2e8af><sprite index=2 tint=1><i>" + Locale.GetOther("shifttoexpand") + "</i>"; } if (info.rotSpeed > 0f && info.decayMinutes > 0f) { string newValue = PlayerCamera.TimeToString(TimeSpan.FromMinutes(info.decayMinutes)); text = text + "<color=#a2dec2><sprite index=5 tint=1>" + Locale.GetOther("decaysin").Replace("<>", newValue); text += DecayConditions(info); text += "\n"; } if (info.onlyHoldInHands) { text = text + "<color=#ff8787><sprite index=6 tint=1>" + Locale.GetOther("itemonlyinhands") + "\n"; } if (info.wearable) { text = text + "<color=#91d1ff><sprite index=7 tint=1>" + Locale.GetOther("itemwearable") + " \"" + info.wearSlotId + "\"\n"; if (info.wearableArmor > 0f) { text = text + "<color=#91d1ff><sprite index=13 tint=1>" + Locale.GetOther("itemwearableprotection") + Mathf.RoundToInt(info.wearableArmor * 100f) + "%\n"; } if (info.wearableIsolation > 0f) { text = text + "<color=#91d1ff><sprite index=14 tint=1>" + Locale.GetOther("itemwearableisolation") + info.wearableIsolation * 100f + "%\n"; } } if (info.usable || IsUsableOnLimb(info, contents)) { text = text + "<color=#a3a3a3><sprite index=11 tint=1>" + Locale.GetOther("itemusable"); if (info.usable) { text = text + "<color=#a6ffaa><sprite index=6 tint=1>" + Locale.GetOther(info.usableWithLMB ? "itemusablehand" : "itemusableinventory"); } if (info.usable && IsUsableOnLimb(info, contents)) { text += "<color=#ffffff>/"; } if (IsUsableOnLimb(info, contents)) { text = text + "<color=#fffb91><sprite index=12 tint=1>" + Locale.GetOther("itemusablewound"); } text += "\n"; } if (info.qualities != null && info.qualities.Count > 0) { text = text + "<color=#ffc814><sprite index=26 tint=1>" + Locale.GetOther("itemqualities") + QualityList(info.qualities) + "\n"; } if (info.DefaultValue() > 0) { text = text + "<color=#f6ff73><sprite index=9 tint=1>" + Locale.GetOther("itemvalue") + info.DefaultValue() + "\n"; } return text.TrimEnd(new char[1] { '\n' }); } private static List<LiquidStack> DefaultContents(ItemInfo info) { LiquidItemInfo val = (LiquidItemInfo)(object)((info is LiquidItemInfo) ? info : null); if (val != null && val.defaultContents != null && val.defaultContents.Count > 0) { return val.defaultContents; } return null; } private static string ContentsBlock(ItemInfo info, List<LiquidStack> contents, bool expanded) { //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_01ae: Unknown result type (might be due to invalid IL or missing references) //IL_01df: Unknown result type (might be due to invalid IL or missing references) //IL_01e4: Unknown result type (might be due to invalid IL or missing references) //IL_01ee: Unknown result type (might be due to invalid IL or missing references) if (contents == null) { return string.Empty; } float num = 0f; for (int i = 0; i < contents.Count; i++) { num += contents[i].amount; } string text = string.Empty; if (Liquids.Registry.TryGetValue(contents[0].liquidId, out var value)) { text = text + "<color=#" + ColorUtility.ToHtmlStringRGB(value.color) + "><sprite index=21 tint=1>"; } text = text + Mathf.RoundToInt(num) + "/" + Mathf.RoundToInt(CapacityOf(info)) + "mL\n"; List<string> list = new List<string>(); List<string> list2 = new List<string>(); for (int j = 0; j < contents.Count; j++) { LiquidStack val = contents[j]; if (!Liquids.Registry.TryGetValue(val.liquidId, out var value2)) { list.Add(val.liquidId + " " + Mathf.RoundToInt(val.amount) + "mL"); list2.Add(val.liquidId + " " + Mathf.RoundToInt(val.amount) + "mL"); continue; } string text2 = (value2.localeFromItem ? Locale.GetItem(val.liquidId) : Locale.GetOther(value2.localeName)); string text3 = Mathf.RoundToInt(val.amount) + "mL"; string text4 = "<color=#" + ColorUtility.ToHtmlStringRGB(value2.color) + ">" + text2 + " (" + text3 + ")<color=#" + ColorUtility.ToHtmlStringRGB(Color.Lerp(value2.color, Color.white, 0.5f)) + ">"; list.Add(text4); string text5 = (value2.localeFromItem ? val.liquidId : value2.localeName) + "dsc"; string text6 = text4 + "\n<alpha=#88>" + Locale.GetOther(text5) + "<alpha=#FF>\n"; if (value2.qualities != null && value2.qualities.Count > 0) { text6 = text6 + "<sprite index=26 tint=1>" + Locale.GetOther("itemqualities") + QualityList(value2.GetScaledQualities(val.amount)) + "\n"; } list2.Add(text6); } if (!expanded) { return string.Join(", ", list) + "\n"; } return string.Join(string.Empty, list2); } private static float CapacityOf(ItemInfo info) { return ((LiquidItemInfo)(((info is LiquidItemInfo) ? info : null)?)).capacity ?? 0f; } private static string QualityList(List<CraftingQuality> qualities) { List<string> list = new List<string>(); for (int i = 0; i < qualities.Count; i++) { list.Add(qualities[i].LocaleName + $" ({qualities[i].amount:0.#})"); } return string.Join(", ", list); } private static bool IsUsableOnLimb(ItemInfo info, List<LiquidStack> contents) { if (info.usableOnLimb) { return true; } if (contents == null) { return false; } for (int i = 0; i < contents.Count; i++) { if (Liquids.Registry.TryGetValue(contents[i].liquidId, out var value) && value.healthUsable) { return true; } } return false; } private static string DecayConditions(ItemInfo info) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) DecayType val = (DecayType)info.decayInfo; bool flag = ((Enum)val).HasFlag((Enum)(object)(DecayType)1); bool flag2 = ((Enum)val).HasFlag((Enum)(object)(DecayType)4); bool flag3 = ((Enum)val).HasFlag((Enum)(object)(DecayType)2); if (!flag && !flag2 && !flag3) { return string.Empty; } List<string> list = new List<string>(); if (flag3) { list.Add(Locale.GetOther("decayonlyworn")); } if (flag2) { list.Add(Locale.GetOther("decayonlymoving")); } if (flag) { list.Add(Locale.GetOther("decayonlyhasitems")); } return " (" + Locale.GetOther("decayonlyif") + string.Join(", ", list) + ")"; } } internal static class CuCoreLibTransitionCompat { internal static void CaptureBodyState(Body body, JObject save) { //IL_0057: Unknown result type (might be due to invalid IL or missing references) Type type = AccessTools.TypeByName("CUCoreLib.Saving.SaveCoordinator"); if (type == null) { return; } object? obj = AccessTools.Method(type, "CaptureBodyState", (Type[])null, (Type[])null)?.Invoke(null, new object[1] { body }); JObject val = (JObject)((obj is JObject) ? obj : null); if (val == null) { return; } JToken obj2 = save["CUCoreLib"]; JObject val2 = (JObject)(((object)((obj2 is JObject) ? obj2 : null)) ?? ((object)new JObject())); foreach (JProperty item in val.Properties()) { val2[item.Name] = item.Value.DeepClone(); } save["CUCoreLib"] = (JToken)(object)val2; } internal static void RestoreBodyState(Body body, JObject save) { JToken obj = save["CUCoreLib"]; JObject val = (JObject)(object)((obj is JObject) ? obj : null); if (val != null) { Type type = AccessTools.TypeByName("CUCoreLib.Saving.SaveCoordinator"); if (!(type == null)) { AccessTools.Method(type, "RestoreBodyState", (Type[])null, (Type[])null)?.Invoke(null, new object[2] { body, val }); } } } } public static class WorldSettingsRegistry { public enum Kind { Section, Toggle, Slider, Dropdown, InputField, Button } public enum InputType { Integer, Decimal, Text } public class WorldSetting { public string Id; public Kind Kind; public string Label; public string Tooltip; public Func<object> Default; public bool Persist = true; public Action<object> OnChanged; public float Min; public float Max = 1f; public bool WholeNumbers; public string Postfix = string.Empty; public string[] Choices; public InputType InputType = InputType.Text; public string Placeholder; public Func<string, object> Validate; public Action OnClick; internal string Group; internal string Anchor; internal bool PlaceBelow; } public static class GameSection { public const string RunWide = "runwide"; public const string Layer = "layer"; public const string Player = "player"; public const string Trader = "trader"; public const string Other = "other"; public const string Challenges = "challenges"; } private class GameGroup { public string Name; public readonly List<RectTransform> Rows = new List<RectTransform>(); } private const string GamePrefix = "game:"; public const string SaveKey = "qolWorldSettings"; private static ManualLogSource Logger; private static bool initialized; private static readonly List<WorldSetting> settings = new List<WorldSetting>(); private static readonly Dictionary<string, object> values = new Dictionary<string, object>(); private static readonly List<Action> refreshers = new List<Action>(); private const string PresetTagOpen = "/*qolWorld:"; private const string PresetTagClose = "*/"; private static readonly Regex PresetTag = new Regex("/\\*qolWorld:([A-Za-z0-9+/=]*)\\*/\\s*$"); private const float ControlMinWidth = 190f; private const float ControlMinHeight = 36f; public static IReadOnlyList<WorldSetting> Settings => settings; public static bool HasPersistedValues => settings.Any((WorldSetting s) => s.Persist && values.ContainsKey(s.Id)); public static void Initialize(ManualLogSource logger) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) if (!initialized) { initialized = true; Logger = logger; new Harmony("org.bepinex.plugins.qol.worldsettings").PatchAll(typeof(WorldSettingsRegistry)); } } public static WorldSetting Register(WorldSetting setting) { Validate(setting); if (setting.Kind != Kind.Section) { setting.Group = settings.LastOrDefault((WorldSetting s) => s.Kind == Kind.Section)?.Id; } settings.Add(setting); return setting; } public static WorldSetting Register(WorldSetting setting, string gameSection) { if (string.IsNullOrEmpty(gameSection)) { return Register(setting); } if (setting != null && setting.Kind == Kind.Section) { throw new ArgumentException("Use Section(id, label, gameSection, below) to place a section."); } Validate(setting); setting.Group = "game:" + gameSection; settings.Add(setting); return setting; } public static WorldSetting Section(string id, string label) { return Register(new WorldSetting { Id = id, Kind = Kind.Section, Label = label, Persist = false }); } public static WorldSetting Section(string id, string label, string gameSection, bool below = false) { WorldSetting worldSetting = Section(id, label); worldSetting.Anchor = gameSection; worldSetting.PlaceBelow = below; return worldSetting; } private static void Validate(WorldSetting setting) { if (setting == null || string.IsNullOrEmpty(setting.Id)) { throw new ArgumentException("World setting needs an Id."); } if (settings.Any((WorldSetting s) => s.Id == setting.Id)) { throw new ArgumentException("World setting '" + setting.Id + "' is already registered."); } } public static object Get(string id) { if (values.TryGetValue(id, out var value)) { return value; } return Find(id)?.Default?.Invoke(); } public static T Get<T>(string id, T fallback = default(T)) { object obj = Get(id); if (obj == null) { return fallback; } if (obj is T) { return (T)obj; } try { return (T)Convert.ChangeType(obj, typeof(T), CultureInfo.InvariantCulture); } catch { return fallback; } } public static bool IsSet(string id) { return values.ContainsKey(id); } public static void Set(string id, object value) { if (value == null) { values.Remove(id); } else { values[id] = value; } Find(id)?.OnChanged?.Invoke(value); } public static void ResetToDefaults() { values.Clear(); } private static WorldSetting Find(string id) { return settings.FirstOrDefault((WorldSetting s) => s.Id == id); } public static void WriteToSave(JObject save) { if (save != null) { JObject val = WriteValues(); if (((JContainer)val).Count > 0) { save["qolWorldSettings"] = (JToken)(object)val; } else { save.Remove("qolWorldSettings"); } } } public static void ReadFromSave(JObject save) { JToken obj = ((save != null) ? save["qolWorldSettings"] : null); ReadValues((JObject)(object)((obj is JObject) ? obj : null)); } private static JObject WriteValues() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown JObject val = new JObject(); foreach (WorldSetting setting in settings) { if (setting.Persist && values.TryGetValue(setting.Id, out var value) && value != null) { val[setting.Id] = JToken.FromObject(value); } } return val; } private static void ReadValues(JObject obj) { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Invalid comparison between Unknown and I4 ResetToDefaults(); if (obj == null) { return; } foreach (WorldSetting setting in settings) { if (!setting.Persist) { continue; } JToken val = obj[setting.Id]; if (val == null || (int)val.Type == 10) { continue; } try { values[setting.Id] = ConvertToken(setting, val); } catch (Exception ex) { ManualLogSource logger = Logger; if (logger != null) { logger.LogWarning((object)("[WorldSettings] Ignoring saved '" + setting.Id + "': " + ex.Message)); } } } } [HarmonyPatch(typeof(PreRunScript), "CopyToClipboard")] [HarmonyPostfix] [HarmonyPriority(800)] private static void CopyToClipboard_Postfix() { if (!settings.Any((WorldSetting s) => s.Persist)) { return; } try { string input = PreRunScript.DecompressString(GUIUtility.systemCopyBuffer); input = PresetTag.Replace(input, string.Empty).TrimEnd(Array.Empty<char>()); string text = Convert.ToBase64String(Encoding.UTF8.GetBytes(((JToken)WriteValues()).ToString((Formatting)0, Array.Empty<JsonConverter>()))); GUIUtility.systemCopyBuffer = PreRunScript.CompressString(input + "/*qolWorld:" + text + "*/"); } catch (Exception ex) { ManualLogSource logger = Logger; if (logger != null) { logger.LogWarning((object)("[WorldSettings] Could not add world settings to preset code: " + ex.Message)); } } } [HarmonyPatch(typeof(PreRunScript), "PasteFromClipboard")] [HarmonyPostfix] private static void PasteFromClipboard_Postfix() { try { Match match = PresetTag.Match(PreRunScript.DecompressString(GUIUtility.systemCopyBuffer)); if (match.Success) { ReadValues(JObject.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(match.Groups[1].Value)))); RefreshDisplays(); } } catch (Exception ex) { ManualLogSource logger = Logger; if (logger != null) { logger.LogWarning((object)("[WorldSettings] Could not read world settings from preset code: " + ex.Message)); } } } public static void RefreshDisplays() { foreach (Action refresher in refreshers) { try { refresher(); } catch (Exception ex) { ManualLogSource logger = Logger; if (logger != null) { logger.LogWarning((object)("[WorldSettings] Display refresh failed: " + ex.Message)); } } } } private static object ConvertToken(WorldSetting setting, JToken token) { return setting.Kind switch { Kind.Toggle => Extensions.Value<bool>((IEnumerable<JToken>)token), Kind.Slider => Extensions.Value<float>((IEnumerable<JToken>)token), Kind.Dropdown => Extensions.Value<int>((IEnumerable<JToken>)token), Kind.InputField => setting.InputType switch { InputType.Integer => Extensions.Value<int>((IEnumerable<JToken>)token), InputType.Decimal => Extensions.Value<float>((IEnumerable<JToken>)token), _ => Extensions.Value<string>((IEnumerable<JToken>)token), }, _ => token.ToObject<object>(), }; } [HarmonyPatch(typeof(PreRunScript), "Start")] [HarmonyPostfix] [HarmonyPriority(0)] private static void PreRunScript_Start_Postfix(PreRunScript __instance) { if (settings.Count == 0 || (Object)(object)__instance == (Object)null || (Object)(object)__instance.customSettingContent == (Object)null) { return; } ResetToDefaults(); try { BuildRows(__instance.customSettingContent); } catch (Exception arg) { ManualLogSource logger = Logger; if (logger != null) { logger.LogError((object)$"[WorldSettings] Failed to build rows: {arg}"); } } } private static void BuildRows(RectTransform content) { //IL_0372: Unknown result type (might be due to invalid IL or missing references) //IL_0384: Unknown result type (might be due to invalid IL or missing references) //IL_0392: Unknown result type (might be due to invalid IL or missing references) //IL_03c0: Unknown result type (might be due to invalid IL or missing references) //IL_03cc: Unknown result type (might be due to invalid IL or missing references) List<GameGroup> list = CollectGameGroups(content); HashSet<string> knownGroups = new HashSet<string>(from g in list where g.Name != null select g.Name); refreshers.Clear(); Dictionary<WorldSetting, RectTransform> built = new Dictionary<WorldSetting, RectTransform>(); foreach (WorldSetting setting in settings) { GameObject val = CreateRow(setting, content); if ((Object)(object)val != (Object)null) { built[setting] = val.GetComponent<RectTransform>(); } } List<WorldSetting> source = settings.Where((WorldSetting s) => s.Kind == Kind.Section).ToList(); foreach (WorldSetting item in source.Where((WorldSetting s) => s.Anchor != null && !knownGroups.Contains(s.Anchor))) { ManualLogSource logger = Logger; if (logger != null) { logger.LogWarning((object)("Unknown game section '" + item.Anchor + "' for '" + item.Id + "'.")); } } List<RectTransform> list2 = new List<RectTransform>(); list2.AddRange(Block(null)); foreach (WorldSetting item2 in source.Where(AtTop)) { list2.AddRange(Block(item2)); } foreach (GameGroup group in list) { foreach (WorldSetting item3 in source.Where((WorldSetting s) => !AtTop(s) && s.Anchor == group.Name && !s.PlaceBelow)) { list2.AddRange(Block(item3)); } list2.AddRange(group.Rows); list2.AddRange(Rows((WorldSetting s) => s.Group == "game:" + group.Name)); foreach (WorldSetting item4 in source.Where((WorldSetting s) => !AtTop(s) && s.Anchor == group.Name && s.PlaceBelow)) { list2.AddRange(Block(item4)); } } list2.AddRange(Rows((WorldSetting s) => s.Group != null && s.Group.StartsWith("game:") && !knownGroups.Contains(s.Group.Substring("game:".Length)))); float num = 0f; foreach (RectTransform item5 in list2) { item5.anchoredPosition = new Vector2(0f, 0f - (num + item5.sizeDelta.y * 0.5f)); num += item5.sizeDelta.y - 3f; } content.sizeDelta = new Vector2(content.sizeDelta.x, num); bool AtTop(WorldSetting s) { if (s.Anchor != null) { return !knownGroups.Contains(s.Anchor); } return true; } List<RectTransform> Block(WorldSetting section) { List<RectTransform> list3 = new List<RectTransform>(); if (section != null && built.TryGetValue(section, out var value)) { list3.Add(value); } string group2 = section?.Id; list3.AddRange(Rows((WorldSetting s) => s.Group == group2)); return list3; } IEnumerable<RectTransform> Rows(Func<WorldSetting, bool> match) { return from s in settings where s.Kind != Kind.Section && match(s) && built.ContainsKey(s) select built[s]; } } private static List<GameGroup> CollectGameGroups(RectTransform content) { //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Expected O, but got Unknown //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Expected O, but got Unknown Queue<string> queue = new Queue<string>(from t in RunSettings.settingTypes where !string.IsNullOrEmpty(t.divider) select t.divider); List<GameGroup> list = new List<GameGroup>(); GameGroup gameGroup = new GameGroup(); foreach (Transform item in (Transform)content) { Transform val = item; if (((Object)val).name.StartsWith("QoLWorldSetting_")) { continue; } if ((Object)(object)((Component)val).GetComponent<RunSettingDisplay>() == (Object)null) { if (gameGroup.Rows.Count > 0) { list.Add(gameGroup); } gameGroup = new GameGroup { Name = ((queue.Count > 0) ? queue.Dequeue() : null) }; } gameGroup.Rows.Add((RectTransform)val); } if (gameGroup.Rows.Count > 0) { list.Add(gameGroup); } return list; } private static GameObject CreateRow(WorldSetting setting, RectTransform content) { switch (setting.Kind) { case Kind.Section: { GameObject obj = Utils.Create("Special/RunSettingDivider", (Transform)(object)content); ((Object)obj).name = "QoLWorldSetting_" + setting.Id; ((TMP_Text)((Component)obj.transform.GetChild(0)).GetComponent<TextMeshProUGUI>()).text = setting.Label; return obj; } case Kind.Toggle: { GameObject val5 = CreateLabeledRow("Special/RunSettingBool", setting, content); Toggle toggle = ((Component)val5.transform.GetChild(1)).GetComponent<Toggle>(); toggle.SetIsOnWithoutNotify(Get(setting.Id, fallback: false)); refreshers.Add(delegate { toggle.SetIsOnWithoutNotify(Get(setting.Id, fallback: false)); }); ((UnityEvent<bool>)(object)toggle.onValueChanged).AddListener((UnityAction<bool>)delegate(bool v) { Set(setting.Id, v); }); return val5; } case Kind.Slider: { GameObject val3 = CreateLabeledRow("Special/RunSettingFloat", setting, content); Slider slider = ((Component)val3.transform.GetChild(1)).GetComponent<Slider>(); TextMeshProUGUI valueText = ((Component)val3.transform.GetChild(2)).GetComponent<TextMeshProUGUI>(); slider.minValue = setting.Min; slider.maxValue = setting.Max; slider.wholeNumbers = setting.WholeNumbers; Show(); refreshers.Add(Show); ((UnityEvent<float>)(object)slider.onValueChanged).AddListener((UnityAction<float>)delegate(float v) { Set(setting.Id, v); ((TMP_Text)valueText).text = FormatSlider(v) + setting.Postfix; }); return val3; } case Kind.Dropdown: { GameObject val2 = CreateLabeledRow("Special/RunSettingDropdown", setting, content); TMP_Dropdown dropdown = ((Component)val2.transform.GetChild(1)).GetComponent<TMP_Dropdown>(); dropdown.ClearOptions(); dropdown.AddOptions((setting.Choices ?? new string[0]).ToList()); QoLModSettings.MakeDropdownScrollable(dropdown); dropdown.SetValueWithoutNotify(Get(setting.Id, 0)); refreshers.Add(delegate { dropdown.SetValueWithoutNotify(Get(setting.Id, 0)); }); ((UnityEvent<int>)(object)dropdown.onValueChanged).AddListener((UnityAction<int>)delegate(int v) { Set(setting.Id, v); }); return val2; } case Kind.InputField: { GameObject val4 = CreateLabeledRow("Special/RunSettingFloat", setting, content); TextMeshProUGUI component2 = ((Component)val4.transform.GetChild(0)).GetComponent<TextMeshProUGUI>(); TMP_InputField input = CreateInputField(val4, (component2 != null) ? ((TMP_Text)component2).font : null, setting); refreshers.Add(delegate { input.SetTextWithoutNotify(InputText(setting)); }); ((UnityEvent<string>)(object)input.onValueChanged).AddListener((UnityAction<string>)delegate(string text) { Set(setting.Id, ParseInput(setting, text)); }); ((UnityEvent<string>)(object)input.onEndEdit).AddListener((UnityAction<string>)delegate(string text) { object obj2 = ParseInput(setting, text); Set(setting.Id, obj2); input.SetTextWithoutNotify((obj2 == null) ? string.Empty : Convert.ToString(obj2, CultureInfo.InvariantCulture)); }); return val4; } case Kind.Button: { GameObject val = CreateLabeledRow("Special/RunSettingFloat", setting, content); RectTransform slot = ReplaceControlSlot(val, typeof(Image), typeof(Button)); TextMeshProUGUI component = ((Component)val.transform.GetChild(0)).GetComponent<TextMeshProUGUI>(); CreateButton(slot, (component != null) ? ((TMP_Text)component).font : null, setting); return val; } default: return null; } } private static GameObject CreateLabeledRow(string prefab, WorldSetting setting, RectTransform content) { GameObject obj = Utils.Create(prefab, (Transform)(object)content); ((Object)obj).name = "QoLWorldSetting_" + setting.Id; GameObject gameObject = ((Component)obj.transform.GetChild(0)).gameObject; ((TMP_Text)gameObject.GetComponent<TextMeshProUGUI>()).text = setting.Label; if (!string.IsNullOrEmpty(setting.Tooltip)) { UITooltip obj2 = gameObject.AddComponent<UITooltip>(); obj2.skipLocale = true; obj2.tipName = setting.Label; obj2.tipDesc = setting.Tooltip; } return obj; } private static RectTransform ReplaceControlSlot(GameObject row, params Type[] components) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Expected O, but got Unknown //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_00fa: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Unknown result type (might be due to invalid IL or missing references) //IL_0154: Unknown result type (might be due to invalid IL or missing references) //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_0164: Unknown result type (might be due to invalid IL or missing references) //IL_0169: Unknown result type (might be due to invalid IL or missing references) //IL_016d: Unknown result type (might be due to invalid IL or missing references) //IL_0172: Unknown result type (might be due to invalid IL or missing references) //IL_0180: Unknown result type (might be due to invalid IL or missing references) RectTransform component = row.GetComponent<RectTransform>(); Transform child = row.transform.GetChild(1); Bounds val = LocalBounds(component, (RectTransform)(object)((child is RectTransform) ? child : null)); if (row.transform.childCount > 2) { Transform child2 = row.transform.GetChild(2); ((Bounds)(ref val)).Encapsulate(LocalBounds(component, (RectTransform)(object)((child2 is RectTransform) ? child2 : null))); ((Component)row.transform.GetChild(2)).gameObject.SetActive(false); } ((Component)row.transform.GetChild(1)).gameObject.SetActive(false); GameObject val2 = new GameObject("Control", new Type[1] { typeof(RectTransform) }); val2.SetActive(false); val2.transform.SetParent(row.transform, false); foreach (Type type in components) { val2.AddComponent(type); } RectTransform component2 = val2.GetComponent<RectTransform>(); Vector2 val3 = default(Vector2); ((Vector2)(ref val3))..ctor(0.5f, 0.5f); component2.pivot = val3; Vector2 anchorMin = (component2.anchorMax = val3); component2.anchorMin = anchorMin; float num = Mathf.Max(((Bounds)(ref val)).size.x, 190f); float num2 = Mathf.Max(((Bounds)(ref val)).size.y + 8f, 36f); Vector2 val5 = new Vector2(((Bounds)(ref val)).max.x - num * 0.5f, ((Bounds)(ref val)).center.y); Rect rect = component.rect; component2.anchoredPosition = val5 - ((Rect)(ref rect)).center; component2.sizeDelta = new Vector2(num, num2); return component2; } private static Bounds LocalBounds(RectTransform space, RectTransform target) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) Vector3[] array = (Vector3[])(object)new Vector3[4]; target.GetWorldCorners(array); Bounds result = default(Bounds); ((Bounds)(ref result))..ctor(((Transform)space).InverseTransformPoint(array[0]), Vector3.zero); for (int i = 1; i < 4; i++) { ((Bounds)(ref result)).Encapsulate(((Transform)space).InverseTransformPoint(array[i])); } return result; } private static Sprite ControlSprite() { PreRunScript instance = PreRunScript.instance; object obj; if (instance == null) { obj = null; } else { Canvas mainCanvas = instance.mainCanvas; obj = ((mainCanvas != null) ? ((Component)mainCanvas).transform.Find("RunSettings/CharSelect/Bottom/Start") : null); } object obj2; if (obj == null) { obj2 = null; } else { Image component = ((Component)obj).GetComponent<Image>(); obj2 = ((component != null) ? component.sprite : null); } if (obj2 == null) { obj2 = ResourceLookupCache.FindSpriteContains("uiBlockNano"); } return (Sprite)obj2; } private static TMP_FontAsset ControlFont(TMP_FontAsset fallback) { return FontPatcher.GetRetroGamingFont() ?? fallback; } private static TMP_InputField CreateInputField(GameObject row, TMP_FontAsset font, WorldSetting setting) { //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Unknown result type (might be due to invalid IL or missing references) //IL_0177: Unknown result type (might be due to invalid IL or missing references) //IL_018b: Unknown result type (might be due to invalid IL or missing references) RectTransform val = ReplaceControlSlot(row, typeof(Image), typeof(TMP_InputField)); font = ControlFont(font); Image component = ((Component)val).GetComponent<Image>(); component.sprite = ControlSprite(); component.type = (Type)1; ((Graphic)component).color = Color.white; RectTransform component2 = new GameObject("Text Area", new Type[2] { typeof(RectTransform), typeof(RectMask2D) }).GetComponent<RectTransform>(); ((Transform)component2).SetParent((Transform)(object)val, false); component2.anchorMin = Vector2.zero; component2.anchorMax = Vector2.one; component2.offsetMin = new Vector2(12f, 5f); component2.offsetMax = new Vector2(-12f, -5f); TextMeshProUGUI textComponent = CreateText(component2, "Text", string.Empty, font, new Color(0.33f, 0.7f, 1f)); TextMeshProUGUI placeholder = CreateText(component2, "Placeholder", setting.Placeholder ?? string.Empty, font, new Color(1f, 1f, 1f, 0.45f)); TMP_InputField component3 = ((Component)val).GetComponent<TMP_InputField>(); component3.textViewport = component2; component3.textComponent = (TMP_Text)(object)textComponent; component3.placeholder = (Graphic)(object)placeholder; component3.lineType = (LineType)0; component3.characterLimit = 64; ((Selectable)component3).targetGraphic = (Graphic)(object)component; component3.selectionColor = new Color(0.35f, 0.62f, 1f, 0.45f); component3.customCaretColor = true; component3.caretColor = Color.white; component3.caretWidth = 3; component3.caretBlinkRate = 0.65f; switch (setting.InputType) { case InputType.Integer: component3.contentType = (ContentType)2; break; case InputType.Decimal: component3.contentType = (ContentType)3; break; default: component3.contentType = (ContentType)0; break; } component3.SetTextWithoutNotify(InputText(setting)); ((Component)val).gameObject.SetActive(true); return component3; } private static void CreateButton(RectTransform slot, TMP_FontAsset font, WorldSetting setting) { //IL_0059: 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_0086: Expected O, but got Unknown Image component = ((Component)slot).GetComponent<Image>(); component.sprite = ControlSprite(); component.type = (Type)1; Button component2 = ((Component)slot).GetComponent<Button>(); ((Selectable)component2).targetGraphic = (Graphic)(object)component; CreateText(slot, "Text", setting.Placeholder ?? setting.Label, ControlFont(font), Color.white); ((Component)slot).gameObject.SetActive(true); ((UnityEvent)component2.onClick).AddListener((UnityAction)delegate { try { setting.OnClick?.Invoke(); } catch (Exception arg) { ManualLogSource logger = Logger; if (logger != null) { logger.LogError((object)$"[WorldSettings] Button '{setting.Id}' failed: {arg}"); } } }); } private static TextMeshProUGUI CreateText(RectTransform parent, string name, string value, TMP_FontAsset font, Color color) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) GameObject val = new GameObject(name, new Type[2] { typeof(RectTransform), typeof(TextMeshProUGUI) }); val.transform.SetParent((Transform)(object)parent, false); RectTransform component = val.GetComponent<RectTransform>(); component.anchorMin = Vector2.zero; component.anchorMax = Vector2.one; component.offsetMin = Vector2.zero; component.offsetMax = Vector2.zero; TextMeshProUGUI component2 = val.GetComponent<TextMeshProUGUI>(); ((TMP_Text)component2).text = value; if ((Object)(object)font != (Object)null) { ((TMP_Text)component2).font = font; } ((TMP_Text)component2).fontSize = 20f; ((TMP_Text)component2).alignment = (TextAlignmentOptions)514; ((TMP_Text)component2).enableWordWrapping = false; ((TMP_Text)component2).overflowMode = (TextOverflowModes)1; ((Graphic)component2).color = color; ((Graphic)component2).raycastTarget = false; return component2; } private static string InputText(WorldSetting setting) { if (!values.TryGetValue(setting.Id, out var value) || value == null) { return string.Empty; } return Convert.ToString(value, CultureInfo.InvariantCulture); } private static object ParseInput(WorldSetting setting, string text) { if (setting.Validate != null) { return setting.Validate(text); } if (string.IsNullOrWhiteSpace(text)) { return null; } switch (setting.InputType) { case InputType.Integer: { if (!int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result2)) { return null; } return result2; } case InputType.Decimal: { if (!float.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var result)) { return null; } return result; } default: return text; } } private static string FormatSlider(float v) { if (!(v >= 10f) && !(v < 0f)) { return v.ToString("0.##"); } return v.ToString("0.#"); } } internal static class WorldSizePatcher { public const string ChunkWidthId = "qol_layer_chunk_width"; public const string ChunkHeightId = "qol_layer_chunk_height"; private const string VanillaWidthPref = "qol_vanilla_chunk_width"; private const string VanillaHeightPref = "qol_vanilla_chunk_height"; private const int MinChunks = 4; private const int MaxScale = 4; private static ManualLogSource Logger; private static uint vanillaWidth; private static uint vanillaHeight; private static Transform[] sceneBounds; private static Vector3[] sceneBoundsPos; private static Vector3[] sceneBoundsScale; public static void Initialize(ManualLogSource logger) { //IL_0049: Unknown result type (might be due to invalid IL or missing references) Logger = logger; WorldSettingsRegistry.Initialize(logger); WorldSettingsRegistry.Section("qol_world_size", "World Size"); RegisterChunkSetting("qol_layer_chunk_width", "Layer chunks (width)", "qol_vanilla_chunk_width"); RegisterChunkSetting("qol_layer_chunk_height", "Layer chunks (height)", "qol_vanilla_chunk_height"); new Harmony("org.bepinex.plugins.qol.worldsize").PatchAll(typeof(WorldSizePatcher)); } private static void RegisterChunkSetting(string id, string label, string vanillaPref) { int num = PlayerPrefs.GetInt(vanillaPref, 0); WorldSettingsRegistry.Register(new WorldSettingsRegistry.WorldSetting { Id = id, Kind = WorldSettingsRegistry.Kind.InputField, InputType = WorldSettingsRegistry.InputType.Integer, Label = label, Tooltip = $"Number of 64-tile chunks per layer for this run. Leave empty for the normal world size. Clamped to {4}-{4}x normal.", Placeholder = ((num > 0) ? $"Default ({num})" : "Default"), Validate = delegate(string text) { if (!int.TryParse(text, out var result) || result <= 0) { return (object)null; } int num2 = PlayerPrefs.GetInt(vanillaPref, 0); return (num2 > 0 && result == num2) ? null : ((object)result); } }); } [HarmonyPatch(typeof(WorldGeneration), "Awake")] [HarmonyPostfix] private static void WorldGeneration_Awake_Postfix(WorldGeneration __instance) { //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Expected O, but got Unknown //IL_0102: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Unknown result type (might be due to invalid IL or missing references) vanillaWidth = __instance.chunkWidth; vanillaHeight = __instance.chunkHeight; if (PlayerPrefs.GetInt("qol_vanilla_chunk_width", 0) != (int)vanillaWidth || PlayerPrefs.GetInt("qol_vanilla_chunk_height", 0) != (int)vanillaHeight) { PlayerPrefs.SetInt("qol_vanilla_chunk_width", (int)vanillaWidth); PlayerPrefs.SetInt("qol_vanilla_chunk_height", (int)vanillaHeight); } if ((Object)(object)__instance.fogSprite == (Object)null) { return; } List<Transform> list = new List<Transform>(); foreach (Transform item in ((Component)__instance.fogSprite).transform.parent) { Transform val = item; if ((Object)(object)((Component)val).GetComponent<SpriteRenderer>() != (Object)null) { list.Add(val); } } sceneBounds = list.ToArray(); sceneBoundsPos = (Vector3[])(object)new Vector3[sceneBounds.Length]; sceneBoundsScale = (Vector3[])(object)new Vector3[sceneBounds.Length]; for (int i = 0; i < sceneBounds.Length; i++) { sceneBoundsPos[i] = sceneBounds[i].localPosition; sceneBoundsScale[i] = sceneBounds[i].localScale; } } [HarmonyPatch(typeof(WorldGeneration), "InstantiateWorld")] [HarmonyPrefix] private static void InstantiateWorld_Prefix(WorldGeneration __instance) { //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_00fc: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) if (vanillaWidth == 0 || vanillaHeight == 0) { return; } bool num = !MultiplayerCompat.IsActive; uint num2 = (num ? Resolve("qol_layer_chunk_width", vanillaWidth) : vanillaWidth); uint num3 = (num ? Resolve("qol_layer_chunk_height", vanillaHeight) : vanillaHeight); if (__instance.chunkWidth != num2 || __instance.chunkHeight != num3) { ManualLogSource logger = Logger; if (logger != null) { logger.LogInfo((object)$"With a {num2}x{num3} world? Oh, my."); } } __instance.chunkWidth = num2; __instance.chunkHeight = num3; if (sceneBounds == null) { return; } Vector3 val = default(Vector3); ((Vector3)(ref val))..ctor((float)num2 / (float)vanillaWidth, (float)num3 / (float)vanillaHeight, 1f); for (int i = 0; i < sceneBounds.Length; i++) { if (!((Object)(object)sceneBounds[i] == (Object)null)) { sceneBounds[i].localPosition = Vector3.Scale(sceneBoundsPos[i], val); sceneBounds[i].localScale = Vector3.Scale(sceneBoundsScale[i], val); } } } private static uint Resolve(string id, uint vanilla) { int num = WorldSettingsRegistry.Get(id, 0); if (num <= 0) { return vanilla; } return (uint)Mathf.Clamp(num, 4, (int)(vanilla * 4)); } } internal static class QuickstartPatcher { public const string LayerId = "qol_quickstart_layer"; private const int OffChoice = 0; private static readonly float[] XpTier = new float[12] { 0f, 0f, 1f, 2f, 3f, 3.5f, 4f, 4.5f, 4.75f, 5f, 5.75f, 6.5f }; private const float StrXpPerTier = 210f; private const float ResXpPerTier = 220f; private const float IntXpPerTier = 150f; private const float XpVariance = 0.2f; private static ManualLogSource Logger; private static WorldGeneration kitGivenFor; private static int kitItemCount; private static WorldGeneration remoteKitWorld; private static readonly HashSet<string> remoteKitGiven = new HashSet<string>(); private const int ProstheticMinLayer = 3; private static readonly int[] ProstheticAnchorLayers = new int[3] { 3, 6, 11 }; private static readonly float[][] ProstheticAnchorWeights = new float[3][] { new float[3] { 0.5f, 0.25f, 0.25f }, new float[3] { 0.1f, 0.6f, 0.3f }, new float[3] { 0f, 0.1f, 0.9f } }; private static readonly int[] ProstheticLimbs = new int[4] { 3, 6, 9, 12 }; private static readonly Action<Limb, ProstheticInfo> ApplyProsthetic = AccessTools.MethodDelegate<Action<Limb, ProstheticInfo>>(AccessTools.Method(typeof(Limb), "ApplyProstheticValues", (Type[])null, (Type[])null), (object)null, true); public static void Initialize(ManualLogSource logger) { //IL_00e0: Unknown result type (might be due to invalid IL or missing references) Logger = logger; WorldSettingsRegistry.Initialize(logger); WorldSettingsRegistry.WorldSetting worldSetting = new WorldSettingsRegistry.WorldSetting(); worldSetting.Id = "qol_quickstart_layer"; worldSetting.Kind = WorldSettingsRegistry.Kind.Dropdown; worldSetting.Label = "Quickstart"; worldSetting.Tooltip = "Starts a new run on the chosen layer, with weighted random equipment and experience scaled to the depth."; worldSetting.Default = () => 0; worldSetting.Choices = new string[12] { "Off", "1. Gravel lands", "2. Deeper gravel lands", "3. Dried desert", "4. Wasteland", "5. Overgrown depths", "6. Frozen chasm", "7. Fungal pools", "8. Crystalline hollow", "9. Geothermal vents", "10. WHERE WE MUST REACH", "11. CRIMSON ASCENT" }; WorldSettingsRegistry.Register(worldSetting, "runwide"); new Harmony("org.bepinex.plugins.qol.quickstart").PatchAll(typeof(QuickstartPatcher)); MultiplayerCompat.RemotePlayerPlaced += GiveRemoteKit; } private static int ActiveLayer() { if (SaveSystem.loadedRun || MultiplayerCompat.IsClient) { return 0; } int num = WorldSettingsRegistry.Get("qol_quickstart_layer", 0); if (num <= 1 || num >= XpTier.Length) { return 0; } return num; } [HarmonyPatch(typeof(WorldGeneration), "Awake")] [HarmonyPostfix] private static void WorldGeneration_Awake_Postfix(WorldGeneration __instance) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) int num = ActiveLayer(); if (num == 0 || (int)__instance.biomeOverride != 0) { return; } int num2 = num - 1; if (__instance.amountOfLayers <= 0 || num2 < __instance.amountOfLayers) { __instance.debugStartDepth = num2; __instance.biomeDepth = num2; ManualLogSource logger = Logger; if (logger != null) { logger.LogInfo((object)$"[Quickstart] Starting run on layer {num}."); } } } [HarmonyPatch(typeof(WorldGeneration), "Start")] [HarmonyPostfix] private static void WorldGeneration_Start_Postfix(WorldGeneration __instance) { if (ActiveLayer() == 0 || __instance.debugStartDepth <= 0 || SaveSystem.loadedRun) { return; } try { __instance.lootRarityMultiplier *= Mathf.Pow(WorldGeneration.GetRunSettingFloat("lootmultiplier"), (float)__instance.debugStartDepth); int num = (int)((float)(__instance.chunkHeight * (uint)WorldGeneration.CHUNKSIZE) * 0.3f); __instance.totalTraveled = ((__instance.debugStartDepth != 10) ? (__instance.debugStartDepth * num) : 0); ApplyChallenges(PlayerCamera.main?.body); } catch (Exception arg) { ManualLogSource logger = Logger; if (logger != null) { logger.LogError((object)$"[Quickstart] Failed to apply run-start settings: {arg}"); } } } private static void ApplyChallenges(Body body) { //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_016a: Unknown result type (might be due to invalid IL or missing references) //IL_017d: Unknown result type (might be due to invalid IL or missing references) //IL_0191: Unknown result type (might be due to invalid IL or missing references) //IL_01a5: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)body == (Object)null)) { if (WorldGeneration.GetRunSettingBool("permanentaddiction")) { Painkillers obj = ((Component)body).gameObject.AddComponent<Painkillers>(); obj.permanent = true; obj.opiateTolerance = 40f; obj.opiateReception = 40f; obj.actualOpiateReception = 40f; obj.opiateAmount = 40f; body.AutoPickUpItem(Utils.Create("heroin", Vector2.op_Implicit(((Component)body).transform.position), 0f).GetComponent<Item>()); } if (WorldGeneration.GetRunSettingBool("mindwiped")) { ((Component)body).gameObject.AddComponent<MindwipeScript>().active = true; body.skills.INT = 0; body.skills.expINT = 0f; body.skills.UpdateExpBoundaries(); } if (WorldGeneration.GetRunSettingBool("zeroskills")) { body.skills.STR = 0; body.skills.RES = 0; body.skills.INT = 0; body.skills.expSTR = 0f; body.skills.expRES = 0f; body.skills.expINT = 0f; body.skills.UpdateExpBoundaries(); } if (WorldGeneration.GetRunSettingBool("blind")) { body.eyeGone = true; body.bothEyesGone = true; ((Component)body).GetComponentInChildren<FacialExpression>().eyeTimeHealed = 500f; } if (WorldGeneration.GetRunSettingBool("amputee")) { body.limbs[3].AttachProsthetic(Item.PegLimbInfo(), true); body.limbs[6].AttachProsthetic(Item.PegLimbInfo(), true); body.limbs[9].AttachProsthetic(Item.PegLimbInfo(), true); body.limbs[12].AttachProsthetic(Item.PegLimbInfo(), true); } } } [HarmonyPatch(typeof(WorldGeneration), "WorldPlacePlayer")] [HarmonyPostfix] private static void WorldPlacePlayer_Postfix(WorldGeneration __instance, ref IEnumerator __result) { if (ActiveLayer() != 0) { __result = Append(__result, delegate { GiveStarterKit(__instance); }); } } private static IEnumerator Append(IEnumerator inner, Action after) { while (inner.MoveNext()) { yield return inner.Current; } try { after(); } catch (Exception arg) { ManualLogSource logger = Logger; if (logger != null) { logger.LogError((object)$"[Quickstart] Starter kit failed: {arg}"); } } } private static void GiveStarterKit(WorldGeneration world) { if ((Object)(object)kitGivenFor == (Object)(object)world) { return; } int num = ActiveLayer(); if (num != 0 && world.biomeDepth == num - 1) { Body val = PlayerCamera.main?.body; if (!((Object)(object)val == (Object)null)) { kitGivenFor = world; GiveKit(val, num, prosthetics: true); } } } private static void GiveRemoteKit(Body body, string persistentId) { WorldGeneration world = WorldGeneration.world; int num = ActiveLayer(); if ((Object)(object)world == (Object)null || num == 0 || world.biomeDepth != num - 1 || (Object)(object)body == (Object)null || !body.alive) { return; } if ((Object)(object)remoteKitWorld != (Object)(object)world) { remoteKitWorld = world; remoteKitGiven.Clear(); } if (!remoteKitGiven.Add(string.IsNullOrEmpty(persistentId) ? ((Object)body).GetInstanceID().ToString() : persistentId)) { return; } try { GiveKit(body, num, prosthetics: false); } catch (Exception arg) { ManualLogSource logger = Logger; if (logger != null) { logger.LogError((object)$"[Quickstart] Remote starter kit failed: {arg}"); } } } private static void GiveKit(Body body, int layer, bool prosthetics) { kitItemCount = 0; GrantExperience(body.skills, XpTier[layer]); if (prosthetics) { GiveProsthetics(body, layer); } switch (layer) { case 2: Give(body, "foliagebag"); Give(body, "slingbag"); Give(body, "emergencylight"); Give(body, "flimsyknife"); GiveFilled(body, "canteen", "biochem", Vary(150f)); GiveCraftable(body, Vary(5)); break; case 3: Give(body, "foliagebag", 2); GiveRandom(body, "container", Vary(2)); Give(body, "makeshifthelmet"); Give(body, "firestarter"); Give(body, "makeshiftdiggingtool"); Give(body, "machete"); GiveFilled(body, "canteen", "biochem", Vary(300f)); GiveRandom(body, "water", Vary(1)); GiveDressings(body, Vary(1)); GiveRandom(body, "drug", Vary(3)); GiveRandom(body, "utility", Vary(2)); break; case 4: Give(body, "bigpack"); GiveRandom(body, "container", Vary(4), "bigpack"); Give(body, "makeshifthelmet"); Give(body, "pickaxe"); Give(body, "machete"); Give(body, "wrench"); Give(body, "flashlight"); GiveFilled(body, "saline", "biochem", Vary(300f)); GiveDressings(body, Vary(1)); GiveRandom(body, "drug", Vary(4)); GiveRandom(body, "utility", Vary(4)); GiveRandom(body, "water", Vary(2)); break; case 5: Give(body, "bigpack"); GiveRandom(body, "container", Vary(3), "bigpack"); if (Random.value < 0.5f) { Give(body, "materialpouch"); } GiveSomeOf(body, 1, "makeshifthelmet", "makeshifthelmet", "bikehelmet"); Give(body, "pickaxe"); Give(body, "machete"); Give(body, "wrench"); GiveSomeOf(body, 1, "flashlight", "flashlight", "lantern"); GiveFilled(body, "saline", "biochem", Vary(400f)); Give(body, "smallbattery", Random.Range(1, 3)); GiveDressings(body, Vary(1)); GiveRandom(body, "drug", Vary(4)); GiveRandom(body, "utility", Vary(4)); GiveRandom(body, "water", Vary(2)); break; case 6: Give(body, "bigpack"); Give(body, "materialpouch"); Give(body, "belt"); Give(body, "gravbag"); GiveRandom(body, "container", Vary(2)); Give(body, "bikehelmet"); GiveSomeOf(body, 1, "minilaserdrill", "plasmacutter"); GiveSomeOf(body, 1, "flashlight", "lantern"); GiveFilled(body, "saline", "biochem", Vary(500f)); Give(body, "smallbattery", Random.Range(2, 5)); Give(body, "mediumbattery", Random.Range(1, 3)); GiveDressings(body, Random.Range(1, 4)); GiveRandom(body, "utility", Vary(5)); GiveRandom(body, "water", Vary(3)); GiveRandom(body, "drug", Vary(5)); break; case 7: GiveDeepBags(body); Give(body, "bikehelmet"); GiveSomeOf(body, 1, "flashlight", "lantern"); GiveSomeOf(body, 1, "titaniummachete", "titaniumpickaxe"); Give(body, "titaniummultitool"); Give(body, "smallbattery", Random.Range(3, 6)); Give(body, "mediumbattery", Random.Range(1, 3)); GiveDressings(body, Random.Range(2, 5)); GiveRandom(body, "utility", Vary(5)); GiveRandom(body, "water", Vary(3)); GiveRandom(body, "drug", Vary(5)); GiveSomeOf(body, 1, "traumarig", "tacticalgloves", "tacticalboots", "traumarig"); break; case 8: GiveDeepBags(body); GiveSomeOf(body, 1, "bikehelmet", "riothelmet"); GiveSomeOf(body, 1, "flashlight", "lantern", "pulselantern"); GiveSomeOf(body, 1, "titaniummachete", "titaniumpickaxe"); Give(body, "titaniummultitool"); Give(body, "smallbattery", Random.Range(3, 6)); Give(body, "mediumbattery", Random.Range(1, 3)); GiveDressings(body, Random.Range(2, 5)); GiveRandom(body, "utility", Vary(5)); GiveRandom(body, "water", Vary(3)); GiveRandom(body, "drug", Vary(5)); GiveSomeOf(body, (!(Random.value < 0.5f)) ? 1 : 2, "traumarig", "tacticalgloves", "tacticalboots", "traumarig"); break; case 9: GiveDeepBags(body); Give(body, "riothelmet"); GiveSomeOf(body, 1, "flashlight", "lantern", "pulselantern"); GiveSomeOf(body, 1, "titaniummachete", "titaniumpickaxe"); Give(body, "titaniummultitool"); Give(body, "smallbattery", Random.Range(3, 6)); Give(body, "mediumbattery", Random.Range(1, 3)); Give(body, "pulsecore"); GiveDressings(body, Random.Range(2, 5)); GiveRandom(body, "utility", Vary(5)); GiveRandom(body, "water", Vary(3)); GiveRandom(body, "drug", Vary(5)); GiveSomeOf(body, 2, "traumarig", "tacticalgloves", "tacticalboots", "traumarig"); if (Random.value < 0.5f) { Give(body, "bioluminescentgel"); } break; case 10: case 11: { bool flag = layer == 11; GiveDeepBags(body); Give(body, "riothelmet"); GiveSomeOf(body, 1, "headlamp", "lantern", "pulselantern"); Give(body, "titaniummachete"); Give(body, "titaniumpickaxe"); Give(body, "titaniummultitool"); if (Random.value < (flag ? 0.6f : 0.35f)) { Give(body, "heavydrill"); } Give(body, "smallbattery", Random.Range(3, 6)); Give(body, "mediumbattery", Random.Range(2, 4)); Give(body, "largebattery", flag ? Random.Range(1, 3) : Random.Range(0, 2)); Give(body, "pulsecore"); GiveDressings(body, Random.Range(3, flag ? 7 : 6)); GiveRandom(body, "utility", Vary(flag ? 7 : 6)); GiveRandom(body, "water", Vary(3)); GiveRandom(body, "drug", Vary(flag ? 7 : 6)); GiveSomeOf(body, flag ? 3 : 2, "traumarig", "tacticalgloves", "tacticalboots", "traumarig"); GiveSomeOf(body, (!flag) ? 1 : 2, "kneepads", "bellyarmor", "armwarmers"); if (Random.value < 0.5f) { Give(body, "bioluminescentgel"); } break; } } ManualLogSource logger = Logger; if (logger != null) { logger.LogInfo((object)$"[Quickstart] Layer {layer} kit for {((Object)body).name}: {kitItemCount} item(s)."); } } private static void GiveProsthetics(Body body, int layer) { //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) if (layer < 3 || body.limbs == null) { return; } float value = Random.value; int num = ((value < 0.05f) ? 2 : ((value < 0.15f) ? 1 : 0)); if (num == 0) { return; } foreach (Limb item in (from i in ProstheticLimbs where i < body.limbs.Length && (Object)(object)body.limbs[i] != (Object)null && !body.limbs[i].prostheticInfo.hasProsthetic select body.limbs[i] into _ orderby Random.value select _).Take(num).ToList()) { ProstheticInfo val = RollProsthetic(layer); foreach (Limb lowerLimb in TourniquetScript.GetLowerLimbs(item, (List<Limb>)null)) { ApplyProsthetic(lowerLimb, val); } ManualLogSource logger = Logger; if (logger != null) { logger.LogInfo((object)("[Quickstart] Fitted " + val.itemId + " to " + ((Object)item).name + ".")); } } } private static ProstheticInfo RollProsthetic(int layer) { //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Unknown result type (might be due to invalid IL or missing references) //IL_0178: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_00fc: Unknown result type (might be due to invalid IL or missing references) int num = ((layer >= ProstheticAnchorLayers[1]) ? 1 : 0); float num2 = Mathf.InverseLerp((float)ProstheticAnchorLayers[num], (float)ProstheticAnchorLayers[num + 1], (float)layer); float[] obj = ProstheticAnchorWeights[num]; float[] array = ProstheticAnchorWeights[num + 1]; float num3 = Mathf.Lerp(obj[0], array[0], num2); float num4 = Mathf.Lerp(obj[1], array[1], num2); float num5 = Mathf.Lerp(obj[2], array[2], num2); float num6 = Random.value * (num3 + num4 + num5); if (num6 < num3) { return Item.PegLimbInfo(); } if (num6 < num3 + num4) { return new ProstheticInfo { hasProsthetic = true, itemId = "steelprosthesis", forceChange = 0f, armorChange = 0.2f, destroyItem = "scrapmetal", appearancePath = "Sprites/steelprosthesisoverlay", maxHoles = 15, r = 0.5f, g = 0.5f, b = 0.5f }; } return new ProstheticInfo { hasProsthetic = true, itemId = "peo", forceChange = 0.25f, armorChange = 0.6f, destroyItem = "titaniumsheet", appearancePath = "Sprites/peooverlay", maxHoles = 20, r = 0.361f, g = 0.729f, b = 0.729f }; } private static void GiveDeepBags(Body body) { Give(body, "bigpack"); Give(body, "materialpouch"); Give(body, "legpouch"); Give(body, "brokenbag"); Give(body, "gravbag"); GiveRandom(body, "container", Vary(2)); } private static void GrantExperience(Skills skills, float tier) { if (skills != null && !(tier <= 0f)) { skills.expSTR += tier * 210f * XpRoll() * skills.STRGainMult; skills.expRES += tier * 220f * XpRoll() * skills.RESGainMult; skills.expINT += tier * 150f * XpRoll() * skills.INTGainMult; skills.CheckForLevelUp(ref skills.STR, skills.expSTR, ref skills.maxSTR); skills.CheckForLevelUp(ref skills.RES, skills.expRES, ref skills.maxRES); skills.CheckForLevelUp(ref skills.INT, skills.expINT, ref skills.maxINT); skills.UpdateExpBoundaries(); } } private static float XpRoll() { return Random.Range(0.8f, 1.2f); } private static int Vary(int count) { int num = Mathf.Max(1, Mathf.RoundToInt((float)count * 0.35f)); return Mathf.Max(0, Random.Range(count - num, count + num + 1)); } private static float Vary(float amount) { return amount * Random.Range(0.7f, 1.3f); } private static void Give(Body body, string id, int count = 1) { if (!Resolves(id)) { return; } for (int i = 0; i < count; i++) { GameObject val = Create(id, body); if ((Object)(object)val == (Object)null) { break; } Stow(body, val.GetComponent<Item>()); kitItemCount++; } } private static GameObject Create(string id, Body body) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) try { return Utils.Create(id, Vector2.op_Implicit(((Component)body).transform.position), 0f); } catch (Exception ex) { ManualLogSource logger = Logger; if (logger != null) { logger.LogWarning((object)("[Quickstart] Could not create '" + id + "': " + ex.Message)); } return null; } } private static void GiveFilled(Body body, string id, string liquid, float ml) { if (!Resolves(id)) { return; } GameObject val = Create(id, body); if (!((Object)(object)val == (Object)null)) { WaterContainerItem component = val.GetComponent<WaterContainerItem>(); if ((Object)(object)component != (Object)null) { component.DrainAll(); component.AddLiquid(liquid, ml); } Stow(body, val.GetComponent<Item>()); kitItemCount++; } } private static void Stow(Body body, Item item) { if (!((Object)(object)item == (Object)null)) { bool flag = item.Stats.wearable && (Object)(object)body.GetWearableBySlotID(item.Stats.wearSlotId) != (Object)null; if (item.Stats.wearable && !flag) { body.AutoPickUpItem(item); } else if ((Object)(object)item.container != (Object)null) { Hold(body, item); } else if ((!flag || (!TryLoad(body, item) && !Hold(body, item))) && (item.Stats.HasTag("noautopickup") || (!TryLoad(body, item) && !Hold(body, item)))) { body.AutoPickUpItem(item); } } } private static bool Hold(Body body, Item item) { for (int num = body.slots.Length - 1; num >= 0; num--) { if (!body.HoldingItem(num) && body.slots[num].canPickUp) { body.PickUpItem(item, num, true); return true; } } return false; } private static bool TryLoad(Body body, Item item) { foreach (Item surfaceInventoryItem in body.GetSurfaceInventoryItems()) { if (!((Object)(object)surfaceInventoryItem.container == (Object)null) && surfaceInventoryItem.container.CanHoldItem(item)) { surfaceInventoryItem.container.LoadItem(item); if ((Object)(object)((Component)item).transform.parent == (Object)(object)((Component)surfaceInventoryItem).transform) { return true; } } } return false; } private static void GiveRandom(Body body, string category, int count, params string[] except) { if (count > 0 && ItemLootPool.pool != null && ItemLootPool.pool.TryGetValue(category, out var value)) { GiveDistinct(body, value.Where((string id) => !except.Contains(id)), count); } } private static void GiveDressings(Body body, int count) { GiveDistinct(body, from kv in Item.GlobalItems where kv.Value.tags != null && kv.Value.tags.Split(new char[1] { ',' }).Contains("dressing") select kv.Key, count); } private static void GiveDistinct(Body body, IEnumerable<string> ids, int count) { if (count <= 0) { return; } foreach (string item in (from id in ids.Distinct() orderby Random.value where Resolves(id) && SlotFree(body, id) select id).Take(count)) { Give(body, item); } } private static void GiveSomeO