Decompiled source of GK2 Shopping List v0.12.0
GK2ShoppingList.dll
Decompiled 2 weeks 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.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using System.Text.RegularExpressions; using System.Threading; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using GK2.Framework; using HarmonyLib; using LazyBearTechnology; using Microsoft.CodeAnalysis; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using TMPro; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.Events; using UnityEngine.SceneManagement; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyVersion("0.0.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } internal sealed class ConfigurationManagerAttributes { public delegate void CustomHotkeyDrawerFunc(ConfigEntryBase setting, ref bool isCurrentlyAcceptingInput); public bool? ShowRangeAsPercent; public Action<ConfigEntryBase> CustomDrawer; public CustomHotkeyDrawerFunc CustomHotkeyDrawer; public bool? Browsable; public string Category; public object DefaultValue; public bool? HideDefaultButton; public bool? HideSettingName; public string Description; public string DispName; public int? Order; public bool? ReadOnly; public bool? IsAdvanced; public Func<object, string> ObjToStr; public Func<string, object> StrToObj; } namespace GK2ShoppingList { internal static class AlmanacPins { internal sealed class Need { public string[] Items; public int Count; public string Id => Items[0]; } private const string Key = "gk2.almanac.v1"; private static List<Need> _cache = new List<Need>(); private static float _askAt = -10f; private static bool _warned; internal static List<Need> Current() { float unscaledTime = Time.unscaledTime; if (unscaledTime < _askAt) { return _cache; } _askAt = unscaledTime + 1f; _cache = Read(); return _cache; } private static List<Need> Read() { List<Need> list = new List<Need>(); try { if (!(AppDomain.CurrentDomain.GetData("gk2.almanac.v1") is IDictionary<string, object> dictionary)) { return list; } Func<bool> func = null; Func<List<Dictionary<string, object>>> func2 = null; lock (dictionary) { if (dictionary.TryGetValue("on", out var value)) { func = value as Func<bool>; } if (dictionary.TryGetValue("pinNeeds", out value)) { func2 = value as Func<List<Dictionary<string, object>>>; } } if (func == null || func2 == null || !func()) { return list; } List<Dictionary<string, object>> list2 = func2(); if (list2 == null) { return list; } foreach (Dictionary<string, object> item in list2) { if (item == null) { continue; } object value2; string[] array = (item.TryGetValue("items", out value2) ? (value2 as string[]) : null); if (array == null || !item.TryGetValue("count", out var value3) || !(value3 is int num)) { continue; } List<string> list3 = new List<string>(); string[] array2 = array; foreach (string text in array2) { if (!string.IsNullOrEmpty(text) && !list3.Contains(text)) { list3.Add(text); } } if (list3.Count != 0 && num > 0) { list.Add(new Need { Items = list3.ToArray(), Count = num }); } } return list; } catch (Exception ex) { if (!_warned) { _warned = true; Plugin.Log.LogWarning((object)("Almanac pins: " + ex.Message + " (shown as none)")); } return new List<Need>(); } } internal static int Have(Need n) { int num = 0; string[] items = n.Items; foreach (string id in items) { num += GameApi.HaveCount(id, isGroup: false); } return num; } internal static int Carried(Need n) { int num = 0; string[] items = n.Items; foreach (string id in items) { num += GameApi.BackpackCount(id, isGroup: false); } return num; } } internal static class Sec { public const string Adding = "1 Adding"; public const string List = "2 List window"; public const string Orders = "3 Town orders"; public const string Hud = "4 HUD panel"; public const string Chests = "5 Chest icons"; public const string Gamepad = "Gamepad"; public const string Language = "Language"; } internal static class CfgMigrate { public static void Run(ConfigFile cfg) { Carry(cfg, "Hotkeys", "AddModifier", "1 Adding", "AddModifier"); Carry(cfg, "Hotkeys", "ShiftToTop", "1 Adding", "ShiftToTop"); Carry(cfg, "General", "SubRecipes", "1 Adding", "SubRecipes"); Carry(cfg, "Hotkeys", "ToggleWindow", "2 List window", "ToggleWindow"); Carry(cfg, "Window", "Scale", "2 List window", "Scale"); Carry(cfg, "General", "CountStorage", "2 List window", "CountStorage"); Carry(cfg, "General", "WhereFilter", "2 List window", "WhereFilter"); Carry(cfg, "General", "TownRepairs", "3 Town orders", "TownRepairs"); Carry(cfg, "Hotkeys", "AddAllOrders", "3 Town orders", "AddAllOrders"); Carry(cfg, "Hotkeys", "ToggleHud", "4 HUD panel", "ToggleHud"); string[] array = new string[6] { "OffsetRight", "OffsetTop", "MaxRows", "ByTask", "Scale", "WheelScroll" }; foreach (string text in array) { Carry(cfg, "HUD", text, "4 HUD panel", text); } array = new string[7] { "Enabled", "Size", "OffsetX", "OffsetY", "Range", "MaxIcons", "IconsPerRow" }; foreach (string text2 in array) { Carry(cfg, "Chest icons", text2, "5 Chest icons", text2); } Carry(cfg, "General", "Language", "Language", "Language"); } private static void Carry(ConfigFile cfg, string oldSection, string oldKey, string newSection, string newKey) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown try { ConfigDefinition key = new ConfigDefinition(oldSection, oldKey); ConfigDefinition key2 = new ConfigDefinition(newSection, newKey); Dictionary<ConfigDefinition, string> dictionary = Orphans(cfg); if (dictionary != null && dictionary.TryGetValue(key, out var value)) { if (!dictionary.ContainsKey(key2)) { dictionary[key2] = value; } dictionary.Remove(key); } } catch (Exception ex) { Plugin.Log.LogWarning((object)("Settings: could not carry " + oldSection + "." + oldKey + " over: " + ex.Message)); } } private static Dictionary<ConfigDefinition, string> Orphans(ConfigFile cfg) { PropertyInfo property = typeof(ConfigFile).GetProperty("OrphanedEntries", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (!(property != null)) { return null; } return property.GetValue(cfg, null) as Dictionary<ConfigDefinition, string>; } } internal sealed class ChestIcons { private sealed class Chest { public WgoData Data; public Component View; public Bounds Box; public HashSet<string> Holds; public readonly List<string> Items = new List<string>(); public RectTransform Root; public string Sig; public float MarkAt; public bool Marked; } internal static ChestIcons Instance; private readonly RectTransform _layer; private List<WgoData> _storages; private float _storagesAt = -100f; private readonly Dictionary<WgoData, Chest> _near = new Dictionary<WgoData, Chest>(); private readonly Dictionary<Item, Chest> _byContainer = new Dictionary<Item, Chest>(); private readonly HashSet<Item> _playerContainers = new HashSet<Item>(); private Dictionary<string, int> _wanted; private string _wantedSig; private bool _marksDirty = true; private float _nextNear; private bool _shown; private int _lastCount = -1; private readonly Vector3[] _corners = (Vector3[])(object)new Vector3[8]; private List<Rect> _avoidRects = new List<Rect>(); private float _avoidAt; private static readonly HashSet<string> NotStorage = new HashSet<string> { "survey_wgo", "town_supplies", "well_garden_1", "well_garden_2" }; private static readonly MethodInfo ViewOf = AccessTools.Method(AccessTools.TypeByName("GameScene"), "GetWgoViewGlobal", new Type[1] { typeof(SGuid) }, (Type[])null); private static Func<SGuid, bool> _isTarget; private static bool _isTargetProbed; private static Func<string, bool> _recordTarget; private static float _recordLookAt = -10f; private static PropertyInfo _eventsProp; private static bool _eventsProbed; private static FieldInfo _eventStr; private const string CodexLocateEvent = "gk2codex_locate_work"; public ChestIcons(RectTransform layer) { _layer = layer; Instance = this; } public void Destroy() { foreach (Chest value in _near.Values) { if ((Object)(object)value.Root != (Object)null) { Object.Destroy((Object)(object)((Component)value.Root).gameObject); } } _near.Clear(); _byContainer.Clear(); _playerContainers.Clear(); if (Instance == this) { Instance = null; } } internal static void StoragesChanged() { ChestIcons instance = Instance; if (instance != null) { instance._storages = null; } } internal static void WantedChanged() { ChestIcons instance = Instance; if (instance != null) { instance._wanted = null; } } internal static void ContainerChanged(Item container) { ChestIcons instance = Instance; if (instance != null && container != null) { if (instance._byContainer.TryGetValue(container, out var value)) { value.Holds = null; instance._marksDirty = true; } else if (instance._playerContainers.Contains(container)) { instance._wanted = null; } } } internal static void NearbyChanged() { ChestIcons instance = Instance; if (instance == null) { return; } foreach (Chest value in instance._near.Values) { value.Holds = null; } instance._marksDirty = true; } internal static void Patch(Harmony h) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown //IL_0164: Unknown result type (might be due to invalid IL or missing references) //IL_016a: Expected O, but got Unknown //IL_0125: Unknown result type (might be due to invalid IL or missing references) //IL_0132: Expected O, but got Unknown //IL_0235: Unknown result type (might be due to invalid IL or missing references) //IL_0242: Expected O, but got Unknown HarmonyMethod val = new HarmonyMethod(typeof(ChestIcons), "ItemPost", (Type[])null); string[] array = new string[7] { "AddItemToInventory", "RemoveItemFromInventory", "RemoveItemFromInventoryByUID", "RemoveItemAt", "InsertItemToInventory", "RemoveAllItems", "GetAndRemoveItemWithEnoughDurability" }; foreach (string text in array) { foreach (MethodInfo declaredMethod in AccessTools.GetDeclaredMethods(typeof(Item))) { if (declaredMethod.Name == text) { try { h.Patch((MethodBase)declaredMethod, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } catch (Exception ex) { Plugin.Log.LogWarning((object)("Chest icons patch " + text + ": " + ex.Message)); } } } } try { MethodInfo methodInfo = AccessTools.Method(typeof(Item), "TakeAllItemsExistingInMeFromOtherInventory", (Type[])null, (Type[])null); if (methodInfo != null) { h.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(ChestIcons), "TakeAllPost", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } catch (Exception ex2) { Plugin.Log.LogWarning((object)("Chest icons patch TakeAll: " + ex2.Message)); } HarmonyMethod val2 = new HarmonyMethod(typeof(ChestIcons), "NearbyPost", (Type[])null); MethodInfo[] array2 = new MethodInfo[2] { AccessTools.Method(typeof(MultiInventory), "AddItem", (Type[])null, (Type[])null), AccessTools.Method(typeof(MultiInventory), "TryAddItem", (Type[])null, (Type[])null) }; foreach (MethodInfo methodInfo2 in array2) { if (methodInfo2 != null) { try { h.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } catch (Exception ex3) { Plugin.Log.LogWarning((object)("Chest icons patch " + methodInfo2.Name + ": " + ex3.Message)); } } } try { MethodInfo methodInfo3 = AccessTools.Method(typeof(PlayerData), "CollectResDrop", (Type[])null, (Type[])null); if (methodInfo3 != null) { h.Patch((MethodBase)methodInfo3, (HarmonyMethod)null, new HarmonyMethod(typeof(ChestIcons), "WantedPost", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } catch (Exception ex4) { Plugin.Log.LogWarning((object)("Chest icons patch CollectResDrop: " + ex4.Message)); } } private static void ItemPost(Item __instance) { try { ContainerChanged(__instance); } catch { } } private static void TakeAllPost(Item __instance, Item __0) { try { ContainerChanged(__instance); ContainerChanged(__0); } catch { } } private static void NearbyPost() { try { NearbyChanged(); } catch { } } private static void WantedPost() { try { WantedChanged(); } catch { } } public void Tick(ShoppingList list, bool canShow, float uiScale) { if (!(Plugin.Instance.ChestIconsOn.Value && canShow) || list == null || list.Tasks.Count <= 0) { if (_shown) { SetAll(active: false); _shown = false; } return; } try { string text = list.Revision + "|" + Places.Filter; if (_wanted == null || text != _wantedSig) { _wanted = Wanted(list); _wantedSig = text; _marksDirty = true; } if (Time.unscaledTime >= _nextNear) { _nextNear = Time.unscaledTime + 0.5f; UpdateNear(); } if (_marksDirty) { _marksDirty = false; UpdateMarks(); } } catch (Exception ex) { Plugin.LogThrottled("Chest icons: " + ex.Message); } _shown = true; Place(uiScale); } private void SetAll(bool active) { foreach (Chest value in _near.Values) { if ((Object)(object)value.Root != (Object)null && ((Component)value.Root).gameObject.activeSelf != active) { ((Component)value.Root).gameObject.SetActive(active); } } } private Dictionary<string, int> Wanted(ShoppingList list) { Dictionary<string, int> dictionary = new Dictionary<string, int>(); int num = 0; foreach (BringLine item in list.Aggregate(Places.Visible(list))) { if (item == null || string.IsNullOrEmpty(item.Id) || GameApi.BackpackCount(item.Id, item.IsGroup) >= item.Need) { continue; } if (!item.IsGroup) { if (!dictionary.ContainsKey(item.Id)) { dictionary[item.Id] = num++; } continue; } foreach (ItemDef item2 in GameApi.GroupDefs(item.Id)) { if (item2 != null && !string.IsNullOrEmpty(((BalanceBaseObject)item2).id) && !dictionary.ContainsKey(((BalanceBaseObject)item2).id)) { dictionary[((BalanceBaseObject)item2).id] = num++; } } } _playerContainers.Clear(); try { AddContainers(MainGame.PlayerData.Inventory.Data, _playerContainers, 0); } catch { } return dictionary; } private static void AddContainers(Item item, HashSet<Item> into, int depth) { if (item == null) { return; } into.Add(item); if (depth >= 3 || item.Inventory == null) { return; } foreach (Item item2 in item.Inventory) { if (item2 != null && !item2.IsEmpty && item2.IsBag) { AddContainers(item2, into, depth + 1); } } } private static bool IsOutputStorage(WGODef def) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Invalid comparison between Unknown and I4 //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Invalid comparison between Unknown and I4 if (def != null && ((BalanceBaseObject)def).id == "crow_nest") { return true; } try { return (int)def.conveyorType == 9 && (int)def.interactionType == 6; } catch { return false; } } private List<WgoData> Storages() { if (_storages != null && Time.unscaledTime - _storagesAt < 60f) { return _storages; } List<WgoData> list = new List<WgoData>(); foreach (GameSceneData gameSceneData in MainGame.Instance.GameSave.worldData.gameSceneDataList) { if (gameSceneData == null || gameSceneData.wgoDataList == null) { continue; } foreach (WgoData wgoData in gameSceneData.wgoDataList) { if (wgoData == null || string.IsNullOrEmpty(((ObjectLinkedToDefinition<WGODef>)(object)wgoData).id) || NotStorage.Contains(((ObjectLinkedToDefinition<WGODef>)(object)wgoData).id)) { continue; } WGODef val = null; try { val = ((ObjectLinkedToDefinition<WGODef>)(object)wgoData).Definition; } catch { } if (val == null || (!val.OpenInMultiInventory && !IsOutputStorage(val))) { continue; } try { if (val.hasRefToOtherWgoInventory) { continue; } } catch { } list.Add(wgoData); } } _storages = list; _storagesAt = Time.unscaledTime; return list; } private void UpdateNear() { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0141: Unknown result type (might be due to invalid IL or missing references) //IL_0146: Unknown result type (might be due to invalid IL or missing references) Vector3 value; try { value = MainGame.PlayerData.position.Value; } catch { return; } float num = Mathf.Max(1f, Plugin.Instance.ChestIconRange.Value); float num2 = num * num; HashSet<WgoData> hashSet = new HashSet<WgoData>(); foreach (WgoData item in Storages()) { Vector3 position; try { position = item.Position; } catch { continue; } float num3 = position.x - value.x; float num4 = position.z - value.z; if (num3 * num3 + num4 * num4 > num2) { continue; } Component val = null; try { val = (Component)((ViewOf != null) ? /*isinst with value type is only supported in some contexts*/: null); } catch { } if ((Object)(object)val == (Object)null || !val.gameObject.activeInHierarchy) { continue; } hashSet.Add(item); if (!_near.TryGetValue(item, out var value2) || !((Object)(object)value2.View == (Object)(object)val)) { if (value2 == null) { Dictionary<WgoData, Chest> near = _near; Chest obj4 = new Chest { Data = item }; value2 = obj4; near[item] = obj4; } value2.View = val; value2.Box = Bounds(val); value2.Holds = null; _marksDirty = true; } } List<WgoData> list = null; foreach (WgoData key in _near.Keys) { if (!hashSet.Contains(key)) { (list ?? (list = new List<WgoData>())).Add(key); } } if (list == null) { return; } foreach (WgoData item2 in list) { Chest chest = _near[item2]; if ((Object)(object)chest.Root != (Object)null) { Object.Destroy((Object)(object)((Component)chest.Root).gameObject); } _near.Remove(item2); } _marksDirty = true; } private void UpdateMarks() { _byContainer.Clear(); int num = 0; foreach (Chest value2 in _near.Values) { Item val = null; try { Inventory inventory = value2.Data.Inventory; val = ((inventory != null) ? inventory.Data : null); } catch { } if (val != null) { HashSet<Item> hashSet = new HashSet<Item>(); AddContainers(val, hashSet, 0); foreach (Item item in hashSet) { _byContainer[item] = value2; } if (value2.Holds == null) { value2.Holds = new HashSet<string>(); Read(val.Inventory, value2.Holds, 0); } } value2.Items.Clear(); if (value2.Holds != null && _wanted != null) { List<KeyValuePair<string, int>> list = new List<KeyValuePair<string, int>>(); foreach (string hold in value2.Holds) { if (_wanted.TryGetValue(hold, out var value)) { list.Add(new KeyValuePair<string, int>(hold, value)); } } list.Sort((KeyValuePair<string, int> a, KeyValuePair<string, int> b) => a.Value.CompareTo(b.Value)); foreach (KeyValuePair<string, int> item2 in list) { value2.Items.Add(item2.Key); } } if (value2.Items.Count > 0) { num++; } } if (num != _lastCount) { _lastCount = num; Plugin.Log.LogInfo((object)("Chest icons: " + num + " of " + _near.Count + " chest(s) nearby hold something the list needs")); } } private static void Read(List<Item> items, HashSet<string> into, int depth) { if (items == null) { return; } foreach (Item item in items) { if (item == null || item.IsEmpty) { continue; } string text = null; try { text = ((((ObjectLinkedToDefinition<ItemDef>)(object)item).Definition != null) ? ((BalanceBaseObject)((ObjectLinkedToDefinition<ItemDef>)(object)item).Definition).id : null); } catch { } if (!string.IsNullOrEmpty(text) && item.Count > 0) { into.Add(text); } if (depth < 3 && item.IsBag) { try { Read(item.Inventory, into, depth + 1); } catch { } } } } private static Bounds Bounds(Component v) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) bool flag = false; Bounds bounds = default(Bounds); ((Bounds)(ref bounds))..ctor(v.transform.position, Vector3.zero); Renderer[] componentsInChildren = v.GetComponentsInChildren<Renderer>(false); foreach (Renderer val in componentsInChildren) { if (!((Object)(object)val == (Object)null) && val.enabled && !(((object)val).GetType().Name == "ParticleSystemRenderer")) { if (!flag) { bounds = val.bounds; flag = true; } else { ((Bounds)(ref bounds)).Encapsulate(val.bounds); } } } return bounds; } private static bool IsWaypointTarget(WgoData data) { if (data == null) { return false; } try { float unscaledTime = Time.unscaledTime; if (unscaledTime >= _recordLookAt) { _recordLookAt = unscaledTime + 2f; _recordTarget = null; if (AppDomain.CurrentDomain.GetData("gk2.almanac.v1") is IDictionary<string, object> dictionary) { lock (dictionary) { if (dictionary.TryGetValue("waypointTarget", out var value)) { _recordTarget = value as Func<string, bool>; } } } } if (_recordTarget != null) { return _recordTarget(((object)data.UniqueId).ToString()); } } catch { return false; } try { if (_isTarget == null) { if (_isTargetProbed) { return false; } _isTargetProbed = true; if (!Chainloader.PluginInfos.ContainsKey("gk2.Almanac")) { return false; } Type type = AccessTools.TypeByName("Almanac.Hud.Waypoint"); MethodInfo methodInfo = ((type != null) ? AccessTools.Method(type, "IsTarget", new Type[1] { typeof(SGuid) }, (Type[])null) : null); if (methodInfo == null) { return false; } _isTarget = (Func<SGuid, bool>)Delegate.CreateDelegate(typeof(Func<SGuid, bool>), methodInfo); } return data != null && _isTarget(data.UniqueId); } catch { return false; } } private void Place(float uiScale) { //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_021b: Unknown result type (might be due to invalid IL or missing references) //IL_021e: Unknown result type (might be due to invalid IL or missing references) //IL_0223: Unknown result type (might be due to invalid IL or missing references) //IL_0225: Unknown result type (might be due to invalid IL or missing references) //IL_0232: Unknown result type (might be due to invalid IL or missing references) //IL_0234: Unknown result type (might be due to invalid IL or missing references) //IL_0237: Unknown result type (might be due to invalid IL or missing references) //IL_023c: Unknown result type (might be due to invalid IL or missing references) Plugin instance = Plugin.Instance; if (uiScale <= 0f) { uiScale = 1f; } float num = Mathf.Clamp(instance.ChestIconSize.Value, 4f, 64f); float gap = Mathf.Max(1f, Mathf.Round(num / 16f)); int num2 = Mathf.Clamp(instance.ChestIconMax.Value, 1, 8); int perRow = Mathf.Clamp(instance.ChestIconRow.Value, 1, 8); Vector2 val = default(Vector2); ((Vector2)(ref val))..ctor(instance.ChestIconOffsetX.Value, instance.ChestIconOffsetY.Value); if (Time.unscaledTime >= _avoidAt) { _avoidAt = Time.unscaledTime + 0.25f; _avoidRects = Plugin.AlmanacRects(); } foreach (Chest value in _near.Values) { if (value.Items.Count == 0 || (Object)(object)value.View == (Object)null || !value.View.gameObject.activeInHierarchy || !TopOnScreen(value.Box, out var top) || IsWaypointTarget(value.Data)) { if ((Object)(object)value.Root != (Object)null && ((Component)value.Root).gameObject.activeSelf) { ((Component)value.Root).gameObject.SetActive(false); } continue; } int num3 = Mathf.Min(num2, value.Items.Count); string text = string.Join(",", value.Items.GetRange(0, num3).ToArray()) + "|" + num + "|" + perRow; if ((Object)(object)value.Root == (Object)null) { value.Root = UiKit.Rect("Chest", (Transform)(object)_layer); } if (value.Sig != text) { Draw(value, num3, num, gap, perRow); value.Sig = text; } value.Root.anchoredPosition = top / uiScale + val; bool flag = Covers(value, top + val * uiScale, uiScale); if (((Component)value.Root).gameObject.activeSelf == flag) { ((Component)value.Root).gameObject.SetActive(!flag); } } } private bool Covers(Chest c, Vector2 at, float uiScale) { //IL_005e: 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_0080: Unknown result type (might be due to invalid IL or missing references) //IL_008e: 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_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)c.Root == (Object)null) { return false; } if (Time.unscaledTime >= c.MarkAt) { c.MarkAt = Time.unscaledTime + 0.25f; c.Marked = HasLocateMark(c.Data); } if (c.Marked) { return true; } if (_avoidRects.Count == 0) { return false; } float num = c.Root.sizeDelta.x * uiScale; float num2 = c.Root.sizeDelta.y * uiScale; Rect val = default(Rect); ((Rect)(ref val))..ctor(at.x - num * 0.5f, at.y, num, num2); foreach (Rect avoidRect in _avoidRects) { Rect current = avoidRect; if (((Rect)(ref val)).Overlaps(new Rect(((Rect)(ref current)).x - 4f, ((Rect)(ref current)).y - 4f, ((Rect)(ref current)).width + 8f, ((Rect)(ref current)).height + 8f))) { return true; } } return false; } private static bool HasLocateMark(WgoData w) { try { if (!_eventsProbed) { _eventsProbed = true; _eventsProp = AccessTools.Property(typeof(WgoData), "Events"); } IList list = ((_eventsProp != null) ? (_eventsProp.GetValue(w, null) as IList) : null); if (list == null) { return false; } foreach (object item in list) { if (item != null) { if (_eventStr == null) { _eventStr = AccessTools.Field(item.GetType(), "str"); } if (_eventStr != null && _eventStr.GetValue(item) as string == "gk2codex_locate_work") { return true; } } } } catch { } return false; } private static void Draw(Chest c, int n, float size, float gap, int perRow) { //IL_0032: 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) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_009a: 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_0105: Unknown result type (might be due to invalid IL or missing references) //IL_010c: Unknown result type (might be due to invalid IL or missing references) //IL_0146: Unknown result type (might be due to invalid IL or missing references) //IL_0155: Unknown result type (might be due to invalid IL or missing references) //IL_015a: Unknown result type (might be due to invalid IL or missing references) //IL_0161: Unknown result type (might be due to invalid IL or missing references) RectTransform root = c.Root; for (int num = ((Transform)root).childCount - 1; num >= 0; num--) { Object.Destroy((Object)(object)((Component)((Transform)root).GetChild(num)).gameObject); } Vector2 anchorMin = (root.anchorMax = Vector2.zero); root.anchorMin = anchorMin; root.pivot = new Vector2(0.5f, 0f); float num2 = size + 2f * Mathf.Round(size / 6f); int num3 = Mathf.Min(perRow, n); int num4 = (n + perRow - 1) / perRow; root.sizeDelta = new Vector2((float)num3 * num2 + (float)(num3 - 1) * gap, (float)num4 * num2 + (float)(num4 - 1) * gap); for (int i = 0; i < n; i++) { int num5 = i / perRow; int num6 = i % perRow; int num7 = Mathf.Min(perRow, n - num5 * perRow); float num8 = ((float)num6 + (float)(num3 - num7) * 0.5f) * (num2 + gap); float num9 = (float)(num4 - 1 - num5) * (num2 + gap); RectTransform val = UiKit.Rect("Cell", (Transform)(object)root); UiKit.Place(val, Vector2.zero, Vector2.zero, new Vector2(num8, num9), new Vector2(num2, num2)); UiKit.Img(val, "comm-craft_item_cell"); RectTransform rt = UiKit.Rect("Icon", (Transform)(object)val); UiKit.Place(rt, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), Vector2.zero, new Vector2(size, size)); UiKit.Icon(rt, GameApi.ItemIcon(c.Items[i], isGroup: false)); } } private bool TopOnScreen(Bounds b, out Vector2 top) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000d: 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_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001a: 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) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0039: 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_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_008b: 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: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00e3: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: 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_00fa: Unknown result type (might be due to invalid IL or missing references) //IL_0100: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Unknown result type (might be due to invalid IL or missing references) //IL_0129: Unknown result type (might be due to invalid IL or missing references) //IL_012e: Unknown result type (might be due to invalid IL or missing references) //IL_01be: Unknown result type (might be due to invalid IL or missing references) //IL_01c3: Unknown result type (might be due to invalid IL or missing references) //IL_0154: Unknown result type (might be due to invalid IL or missing references) //IL_0159: Unknown result type (might be due to invalid IL or missing references) //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_016b: Unknown result type (might be due to invalid IL or missing references) //IL_017c: Unknown result type (might be due to invalid IL or missing references) //IL_018a: Unknown result type (might be due to invalid IL or missing references) //IL_0199: Unknown result type (might be due to invalid IL or missing references) top = Vector2.zero; Vector3 min = ((Bounds)(ref b)).min; Vector3 max = ((Bounds)(ref b)).max; _corners[0] = new Vector3(min.x, min.y, min.z); _corners[1] = new Vector3(max.x, min.y, min.z); _corners[2] = new Vector3(min.x, max.y, min.z); _corners[3] = new Vector3(max.x, max.y, min.z); _corners[4] = new Vector3(min.x, min.y, max.z); _corners[5] = new Vector3(max.x, min.y, max.z); _corners[6] = new Vector3(min.x, max.y, max.z); _corners[7] = new Vector3(max.x, max.y, max.z); float num = float.MaxValue; float num2 = float.MinValue; float num3 = float.MinValue; for (int i = 0; i < 8; i++) { Vector3 val; try { val = CameraSystem.WorldToScreenPoint(_corners[i]); } catch { return false; } if (val.z < 0f) { return false; } num = Mathf.Min(num, val.x); num2 = Mathf.Max(num2, val.x); num3 = Mathf.Max(num3, val.y); } top = new Vector2((num + num2) * 0.5f, num3); if (top.x > -50f && top.x < (float)Screen.width + 50f && top.y > -50f) { return top.y < (float)Screen.height + 80f; } return false; } } internal sealed class ChestTake { private sealed class Result { public readonly List<string> Shown = new List<string>(); public readonly List<string> From = new List<string>(); public readonly List<KeyValuePair<string, int>> Taken = new List<KeyValuePair<string, int>>(); public bool AnyInStorage; public bool Full; } [Serializable] [CompilerGenerated] private sealed class <>c { public static readonly <>c <>9 = new <>c(); public static UnityAction <>9__16_0; public static UnityAction <>9__16_3; public static UnityAction <>9__16_4; public static Func<Image, string> <>9__16_5; public static Func<ItemDef, string> <>9__20_0; public static Func<KeyValuePair<string, int>, string> <>9__23_0; internal void <Build>b__16_0() { Do(); } internal void <Build>b__16_3() { UITooltip.Hide(); } internal void <Build>b__16_4() { UITooltip.Hide(); } internal string <Build>b__16_5(Image i) { return ((Object)i).name + "=" + (((Object)(object)i.sprite != (Object)null) ? ((Object)i.sprite).name : "-"); } internal string <Plan>b__20_0(ItemDef d) { return ((BalanceBaseObject)d).id; } internal string <Do>b__23_0(KeyValuePair<string, int> kv) { return kv.Value + " " + GameApi.ItemName(kv.Key, isGroup: false); } } private GameObject _btn; private LazyButton _lazy; private InventoryHeaderWidget _host; private Component _win; private float _nextCheck; private bool _canTake = true; private bool _failed; private static bool _builtLogged; public ChestTake(RectTransform layer) { } public void Destroy() { Drop(); } private void Drop() { if ((Object)(object)_btn != (Object)null) { Object.Destroy((Object)(object)_btn); } _btn = null; _lazy = null; _host = null; _win = null; _failed = false; } private unsafe static string TipText() { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) try { KeyboardShortcut value = Plugin.Instance.TakeKey.Value; if ((int)((KeyboardShortcut)(ref value)).MainKey != 0) { string takeButton = Str.TakeButton; KeyboardShortcut val = value; return takeButton + " [" + ((object)(*(KeyboardShortcut*)(&val))/*cast due to .constrained prefix*/).ToString() + "]"; } } catch { } return Str.TakeButton; } internal static Component OpenChestWindow() { try { LazyWidgetBase activeWindow = LazyWindowsStackController.ActiveWindow; UIChestWindow val = (UIChestWindow)(object)((activeWindow is UIChestWindow) ? activeWindow : null); return (Component)(object)(((Object)(object)val != (Object)null && ((Component)val).gameObject.activeInHierarchy) ? val : null); } catch { return null; } } public void Tick(ShoppingList list, bool allowed, float uiScale) { Component val = ((allowed && list != null && Plugin.Instance.ChestTakeOn.Value && (list.Tasks.Count > 0 || ForPins())) ? OpenChestWindow() : null); if ((Object)(object)val == (Object)null) { if ((Object)(object)_btn != (Object)null || (Object)(object)_win != (Object)null) { Drop(); } return; } try { InventoryHeaderWidget val2 = FirstHeader(Traverse.Create((object)val).Field("rightMultiInventoryWidget").GetValue<MultiInventoryWidget>()); if ((Object)(object)val2 == (Object)null) { if ((Object)(object)_btn != (Object)null) { Drop(); } return; } if ((Object)(object)_win != (Object)(object)val || (Object)(object)_host != (Object)(object)val2 || ((Object)(object)_btn == (Object)null && !_failed)) { Drop(); _win = val; _host = val2; if (!Build(val, val2)) { _failed = true; return; } } if ((Object)(object)_btn == (Object)null) { return; } bool flag = !LazyInput.IsGamepadActive; if (_btn.activeSelf != flag) { _btn.SetActive(flag); } if (flag) { if (Time.unscaledTime >= _nextCheck) { _nextCheck = Time.unscaledTime + 0.4f; _canTake = Plan(val, execute: false)?.AnyInStorage ?? false; } if ((Object)(object)_lazy != (Object)null && ((Selectable)_lazy).interactable != _canTake) { ((Selectable)_lazy).interactable = _canTake; } } } catch (Exception ex) { Plugin.LogThrottled("Chest take button: " + ex.Message); } } private static bool ForPins() { Plugin instance = Plugin.Instance; if ((Object)(object)instance != (Object)null && instance.TakeForPins != null && instance.TakeForPins.Value) { return AlmanacPins.Current().Count > 0; } return false; } private static InventoryHeaderWidget FirstHeader(MultiInventoryWidget w) { if ((Object)(object)w == (Object)null || w.DrawnInventories == null) { return null; } foreach (InventoryWidget drawnInventory in w.DrawnInventories) { if ((Object)(object)drawnInventory != (Object)null && (Object)(object)drawnInventory.InventoryHeaderWidget != (Object)null && ((Component)drawnInventory).gameObject.activeInHierarchy) { return drawnInventory.InventoryHeaderWidget; } } return null; } private bool Build(Component win, InventoryHeaderWidget host) { //IL_0333: Unknown result type (might be due to invalid IL or missing references) //IL_0338: Unknown result type (might be due to invalid IL or missing references) //IL_0355: Unknown result type (might be due to invalid IL or missing references) //IL_035a: Unknown result type (might be due to invalid IL or missing references) //IL_0378: Unknown result type (might be due to invalid IL or missing references) //IL_037d: Unknown result type (might be due to invalid IL or missing references) //IL_039b: Unknown result type (might be due to invalid IL or missing references) //IL_03a0: Unknown result type (might be due to invalid IL or missing references) //IL_011c: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Expected O, but got Unknown //IL_0134: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Expected O, but got Unknown //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Expected O, but got Unknown //IL_0159: 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: Expected O, but got Unknown //IL_0184: Unknown result type (might be due to invalid IL or missing references) //IL_0189: Unknown result type (might be due to invalid IL or missing references) //IL_018f: Expected O, but got Unknown //IL_01dc: Unknown result type (might be due to invalid IL or missing references) //IL_01e1: Unknown result type (might be due to invalid IL or missing references) //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_01f2: Unknown result type (might be due to invalid IL or missing references) //IL_01f9: Unknown result type (might be due to invalid IL or missing references) //IL_0200: Unknown result type (might be due to invalid IL or missing references) //IL_0226: Unknown result type (might be due to invalid IL or missing references) //IL_022b: Unknown result type (might be due to invalid IL or missing references) //IL_0234: Unknown result type (might be due to invalid IL or missing references) //IL_023c: Unknown result type (might be due to invalid IL or missing references) //IL_0243: Unknown result type (might be due to invalid IL or missing references) //IL_024a: Unknown result type (might be due to invalid IL or missing references) //IL_02a3: Unknown result type (might be due to invalid IL or missing references) //IL_02aa: Expected O, but got Unknown InventoryHeaderWidget val = FirstHeader(Traverse.Create((object)win).Field("leftMultiInventoryWidget").GetValue<MultiInventoryWidget>()) ?? host; LazyButton moveAllSimilarItemsToBagBtn = val.MoveAllSimilarItemsToBagBtn; if ((Object)(object)moveAllSimilarItemsToBagBtn == (Object)null) { val = host; moveAllSimilarItemsToBagBtn = host.MoveAllSimilarItemsToBagBtn; } if ((Object)(object)moveAllSimilarItemsToBagBtn == (Object)null) { Plugin.Log.LogWarning((object)"Take button: the game's 'put similar items' button was not found; the pad key still works."); return false; } Transform val2 = Mapped(((Component)moveAllSimilarItemsToBagBtn).transform.parent, ((Component)val).transform, ((Component)host).transform); GameObject val3 = Object.Instantiate<GameObject>(((Component)moveAllSimilarItemsToBagBtn).gameObject, val2, false); ((Object)val3).name = "SLTakeButton"; LazyButton component = val3.GetComponent<LazyButton>(); ((UnityEventBase)((Button)component).onClick).RemoveAllListeners(); ButtonClickedEvent onClick = ((Button)component).onClick; object obj = <>c.<>9__16_0; if (obj == null) { UnityAction val4 = delegate { Do(); }; <>c.<>9__16_0 = val4; obj = (object)val4; } ((UnityEvent)onClick).AddListener((UnityAction)obj); ((UnityEventBase)component.onEnter).RemoveAllListeners(); ((UnityEventBase)component.onNotInteractableEnter).RemoveAllListeners(); ((UnityEventBase)component.onExit).RemoveAllListeners(); ((UnityEventBase)component.onNotInteractableExit).RemoveAllListeners(); Transform tip = val3.transform; ((UnityEvent)component.onEnter).AddListener((UnityAction)delegate { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) UITooltip.ShowSimpleInfo(tip, TipText(), default(Vector2), (string)null); }); ((UnityEvent)component.onNotInteractableEnter).AddListener((UnityAction)delegate { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) UITooltip.ShowSimpleInfo(tip, TipText(), default(Vector2), (string)null); }); LazyUIEvent onExit = component.onExit; object obj2 = <>c.<>9__16_3; if (obj2 == null) { UnityAction val5 = delegate { UITooltip.Hide(); }; <>c.<>9__16_3 = val5; obj2 = (object)val5; } ((UnityEvent)onExit).AddListener((UnityAction)obj2); LazyUIEvent onNotInteractableExit = component.onNotInteractableExit; object obj3 = <>c.<>9__16_4; if (obj3 == null) { UnityAction val6 = delegate { UITooltip.Hide(); }; <>c.<>9__16_4 = val6; obj3 = (object)val6; } ((UnityEvent)onNotInteractableExit).AddListener((UnityAction)obj3); component.onEnterSound = string.Empty; component.onNotInteractableEnterSound = string.Empty; bool flag = false; Image[] componentsInChildren = val3.GetComponentsInChildren<Image>(true); foreach (Image val7 in componentsInChildren) { if (!((Object)(object)((Component)val7).gameObject == (Object)(object)val3)) { Vector3 localScale = ((Transform)((Graphic)val7).rectTransform).localScale; ((Transform)((Graphic)val7).rectTransform).localScale = new Vector3(0f - localScale.x, localScale.y, localScale.z); flag = true; } } if (!flag) { Vector3 localScale2 = val3.transform.localScale; val3.transform.localScale = new Vector3(0f - localScale2.x, localScale2.y, localScale2.z); } _btn = val3; _lazy = component; _nextCheck = 0f; _canTake = true; val3.SetActive(!LazyInput.IsGamepadActive); if (!_builtLogged || Diag.On) { _builtLogged = true; RectTransform val8 = (RectTransform)val3.transform; string text = null; try { UIBaseChestWindowData value = Traverse.Create((object)win).Field("data").GetValue<UIBaseChestWindowData>(); text = ((value != null && value.Chest != null) ? ((ObjectLinkedToDefinition<WGODef>)(object)value.Chest).id : null); } catch { } Plugin.Log.LogInfo((object)("Take button copied into the storage header of " + ((object)win).GetType().Name + " (" + text + ") from the game's button in " + ((Object)val).name + ": anchors " + ((object)val8.anchorMin/*cast due to .constrained prefix*/).ToString() + "-" + ((object)val8.anchorMax/*cast due to .constrained prefix*/).ToString() + ", at " + ((object)val8.anchoredPosition/*cast due to .constrained prefix*/).ToString() + ", size " + ((object)val8.sizeDelta/*cast due to .constrained prefix*/).ToString() + ", picture(s) turned: " + flag + "; parts: " + string.Join(", ", (from i in val3.GetComponentsInChildren<Image>(true) select ((Object)i).name + "=" + (((Object)(object)i.sprite != (Object)null) ? ((Object)i.sprite).name : "-")).ToArray()))); } return true; } private static Transform Mapped(Transform node, Transform from, Transform to) { List<int> list = new List<int>(); Transform val = node; while ((Object)(object)val != (Object)null && (Object)(object)val != (Object)(object)from) { list.Add(val.GetSiblingIndex()); val = val.parent; } list.Reverse(); Transform val2 = to; foreach (int item in list) { if (item < 0 || item >= val2.childCount) { return to; } val2 = val2.GetChild(item); } return val2; } private static List<Inventory> Sources(UIBaseChestWindowData data) { List<Inventory> list = new List<Inventory>(); if (data.Chest != null && data.Chest.Inventory != null) { list.Add(data.Chest.Inventory); } MultiInventoryWidgetData secondMultiInventoryData = data.SecondMultiInventoryData; if (secondMultiInventoryData != null && secondMultiInventoryData.inventoriesData != null) { foreach (InventoryWidgetDataBase inventoriesDatum in secondMultiInventoryData.inventoriesData) { if (inventoriesDatum != null && !(inventoriesDatum is BagInventoryWidgetData) && inventoriesDatum.Inventory != null && !list.Contains(inventoriesDatum.Inventory)) { list.Add(inventoriesDatum.Inventory); } } } return list; } private static Result Plan(Component win, bool execute) { Plugin instance = Plugin.Instance; if ((Object)(object)win == (Object)null || (Object)(object)instance == (Object)null || instance.List == null) { return null; } UIBaseChestWindowData value = Traverse.Create((object)win).Field("data").GetValue<UIBaseChestWindowData>(); Inventory val = ((MainGame.PlayerData != null) ? MainGame.PlayerData.Inventory : null); if (value == null || val == null) { return null; } List<Inventory> list = Sources(value); Result result = new Result(); for (int i = 0; i < list.Count; i++) { result.Shown.Add(SourceName(value, list, i)); } foreach (BringLine item in instance.List.Aggregate(Places.Visible(instance.List))) { int num = item.Need - GameApi.BackpackCount(item.Id, item.IsGroup); if (num > 0 && Take(item.IsGroup ? (from d in GameApi.GroupDefs(item.Id) select ((BalanceBaseObject)d).id).ToList() : new List<string> { item.Id }, num, list, val, result, execute)) { return result; } } if (instance.TakeForPins != null && instance.TakeForPins.Value) { foreach (AlmanacPins.Need item2 in AlmanacPins.Current()) { int num2 = item2.Count - AlmanacPins.Carried(item2); if (num2 > 0 && Take(new List<string>(item2.Items), num2, list, val, result, execute)) { return result; } } } return result; } private static bool Take(List<string> ids, int missing, List<Inventory> sources, Inventory bag, Result res, bool execute) { foreach (string id in ids) { ItemDef data = ((GameBalanceBase)GameBalance.Me).GetData<ItemDef>(id); if (data == null) { continue; } for (int i = 0; i < sources.Count; i++) { if (missing <= 0) { break; } Inventory val = sources[i]; bool flag = i > 0; int totalCountInInventory = val.Data.GetTotalCountInInventory(id, (Item)null, flag); if (totalCountInInventory <= 0) { continue; } res.AnyInStorage = true; if (!execute) { return true; } int num = Math.Min(missing, totalCountInInventory); int num2 = bag.Data.CanAddItemCountToInventory(data, num, true, (Item)null, false); if (num2 < num) { res.Full = true; } if (num2 <= 0) { continue; } int num3 = 0; foreach (Item item in val.RemoveItemById(id, num2, (Item)null, (Item)null, flag)) { int count = item.Count; bag.AddItemToInventory(item, (Item)null, false); num3 += count - item.Count; if (item.Count > 0) { val.AddItemToInventory(item, (Item)null, false); } } if (num3 > 0) { res.Taken.Add(new KeyValuePair<string, int>(id, num3)); missing -= num3; if (!res.From.Contains(res.Shown[i])) { res.From.Add(res.Shown[i]); } } } if (missing <= 0) { break; } } return false; } private static string SourceName(UIBaseChestWindowData data, List<Inventory> sources, int s) { return ((s == 0 && data.Chest != null) ? ((ObjectLinkedToDefinition<WGODef>)(object)data.Chest).id : sources[s].ViewId) + "#" + s; } internal static void Do() { Plugin instance = Plugin.Instance; try { Component val = OpenChestWindow(); if ((Object)(object)val == (Object)null || (Object)(object)instance == (Object)null || instance.List == null) { return; } Result result = Plan(val, execute: true); if (result != null) { string[] array = result.Taken.Select((KeyValuePair<string, int> kv) => kv.Value + " " + GameApi.ItemName(kv.Key, isGroup: false)).ToArray(); Plugin.Log.LogInfo((object)("Take from the storage side of " + ((object)val).GetType().Name + ": it shows [" + string.Join(", ", result.Shown.ToArray()) + "]" + ((array.Length != 0) ? ("; took " + string.Join(", ", array) + " from [" + string.Join(", ", result.From.ToArray()) + "]") : ("; took nothing (" + ((result.AnyInStorage && result.Full) ? "backpack full" : "nothing wanted there") + ")")))); if (array.Length == 0) { instance.Say((result.AnyInStorage && result.Full) ? Str.TakeFull : Str.TakeNothing); } else { instance.Say(Str.TakeDone(string.Join(", ", array)) + (result.Full ? (" " + Str.TakeFullShort) : "")); } } } catch (Exception ex) { Plugin.Log.LogWarning((object)("Take from the chest: " + ex)); } } } internal static class Cm { public static ConfigDescription D(string description, string name, int order, bool advanced = false, AcceptableValueBase range = null, bool browsable = true) { //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Expected O, but got Unknown ConfigurationManagerAttributes configurationManagerAttributes = new ConfigurationManagerAttributes { DispName = name, Order = 1000 - order }; if (advanced) { configurationManagerAttributes.IsAdvanced = true; } if (!browsable) { configurationManagerAttributes.Browsable = false; } return new ConfigDescription(description, range, new object[1] { configurationManagerAttributes }); } } internal static class Diag { private const string Tag = "[Diag] "; private const float RecheckAfter = 10f; private static readonly string[] Others = new string[16] { "gk2.ZombieChores", "gk2.StockLimits", "gk2.Almanac", "gk2.BuildTools", "gk2.StorageAccess", "gk2.ClerkDesk", "gk2.ReporterDesk", "gk2.ZombieCare", "gk2.UnofficialPatch", "gk2.SmartBags", "gk2.SealedDepths", "gk2.NoSleepNoTomorrow", "gk2.CarouselVeterans", "gk2.SortedChests", "gk2.KeyboardComfort", "gk2.BattleComfort" }; internal static ConfigEntry<bool> Setting; private static string[] _ownKeys = new string[0]; private static string _wheelMod; private static string _wheelId; private static readonly object Gate = new object(); private static string _last; private static readonly HashSet<string> Seen = new HashSet<string>(); private static readonly Dictionary<string, string> Values = new Dictionary<string, string>(); private static bool _started; private static bool _wasIn; private static float _due; internal static bool On { get { try { return Setting != null && Setting.Value; } catch { return false; } } } internal static void Bind(ConfigFile cfg) { Setting = cfg.Bind<bool>("Debug", "Diagnostics", false, Cm.D("Writes \"[Diag]\" lines to the log: which of the other mods are loaded, which shared records exist, and the decisions this mod takes next to them. Never every frame. Meant for a compatibility test.", "Diagnostic log", 90, advanced: true)); } internal static void Own(string[] recordKeys, string wheelMod, string wheelId) { _ownKeys = recordKeys ?? new string[0]; _wheelMod = wheelMod; _wheelId = wheelId; } internal static void Log(string text) { if (!On || text == null) { return; } string text2 = "[Diag] " + text; lock (Gate) { if (text2 == _last) { return; } _last = text2; } try { Plugin.Log.LogInfo((object)text2); } catch { } } internal static void Once(string key, string text) { if (!On) { return; } lock (Gate) { if (!Seen.Add(key)) { return; } } Log(text); } internal static void Changed(string key, string value, string text) { if (!On) { return; } lock (Gate) { if (Values.TryGetValue(key, out var value2) && value2 == value) { return; } Values[key] = value; } Log(text); } internal static bool Reset(string key) { if (!On) { return false; } lock (Gate) { bool result = Values.Remove(key); Seen.Remove(key); return result; } } internal static void Forget(string prefix) { lock (Gate) { List<string> list = new List<string>(); foreach (string key in Values.Keys) { if (key.StartsWith(prefix, StringComparison.Ordinal)) { list.Add(key); } } foreach (string item in list) { Values.Remove(item); } Seen.RemoveWhere((string k) => k.StartsWith(prefix, StringComparison.Ordinal)); } } internal static string R(Rect r) { return "x " + Math.Round(((Rect)(ref r)).x, 1) + " y " + Math.Round(((Rect)(ref r)).y, 1) + " w " + Math.Round(((Rect)(ref r)).width, 1) + " h " + Math.Round(((Rect)(ref r)).height, 1); } internal static string VersionOf(string guid) { try { string version; return Find(Chainloader.PluginInfos, guid, out version) ? version : null; } catch { return null; } } internal static string Presence(string label, string guid) { string text = VersionOf(guid); if (text != null) { return label + " " + text + " is loaded"; } return label + " is not loaded"; } internal static void Start() { if (!_started) { _started = true; if (On) { Plugins(); Records("at start"); } } } internal static void Tick() { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Invalid comparison between Unknown and I4 if (!On) { return; } try { MainGame instance = MainGame.Instance; bool flag = (Object)(object)instance != (Object)null && (int)instance.gameState == 1; if (flag && !_wasIn) { _wasIn = true; _due = Time.realtimeSinceStartup + 10f; } else if (!flag && _wasIn) { _wasIn = false; _due = 0f; } if (_due > 0f && Time.realtimeSinceStartup >= _due) { _due = 0f; Records("10 s after the game loaded"); } } catch { } } private static void Plugins() { try { Dictionary<string, PluginInfo> pluginInfos = Chainloader.PluginInfos; List<string> list = new List<string>(); List<string> list2 = new List<string>(); HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase); string[] others = Others; foreach (string text in others) { hashSet.Add(text); if (Find(pluginInfos, text, out var version)) { list.Add(text + " " + version); } else { list2.Add(text); } } List<string> list3 = new List<string>(); foreach (KeyValuePair<string, PluginInfo> item in pluginInfos) { if (!hashSet.Contains(item.Key) && !item.Key.Equals("gk2.shoppinglist", StringComparison.OrdinalIgnoreCase)) { string text2 = "?"; try { text2 = item.Value.Metadata.Version.ToString(); } catch { } list3.Add(item.Key + " " + text2); } } Log(Name() + " plugins loaded: " + ((list.Count == 0) ? "none of the other family's" : string.Join(", ", list.ToArray())) + " | not loaded: " + ((list2.Count == 0) ? "none" : string.Join(", ", list2.ToArray()))); Log(Name() + " other plugins: " + ((list3.Count == 0) ? "none" : string.Join(", ", list3.ToArray()))); } catch (Exception ex) { Log(Name() + " plugin list failed: " + ex.Message); } } private static bool Find(IDictionary<string, PluginInfo> infos, string guid, out string version) { version = ""; foreach (KeyValuePair<string, PluginInfo> info in infos) { if (info.Key.Equals(guid, StringComparison.OrdinalIgnoreCase)) { try { version = info.Value.Metadata.Version.ToString(); } catch { version = "?"; } return true; } } return false; } private static string Name() { return "[gk2.shoppinglist 0.12.0]"; } internal static void Records(string when) { if (!On) { return; } try { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(Name()).Append(" records ").Append(when) .Append(": "); stringBuilder.Append("jobs.v1 ").Append(Jobs()).Append(" | "); stringBuilder.Append("zombieChores.v1 ").Append(ZombieChores()).Append(" | "); stringBuilder.Append("stockLimits.v1 ").Append(StockLimits()).Append(" | "); stringBuilder.Append("wheel.v1 ").Append(Wheel()).Append(" | "); stringBuilder.Append("hub.v1 ").Append(Hub()); Log(stringBuilder.ToString()); Log(Name() + " published " + when + ": " + Published()); } catch (Exception ex) { Log(Name() + " records failed: " + ex.Message); } } private static object Get(string key) { try { return AppDomain.CurrentDomain.GetData(key); } catch { return null; } } private static string Jobs() { object obj = Get("gk2kit.jobs.v1"); if (obj == null) { return "absent"; } if (!(obj is IDictionary dictionary)) { return "present, unexpected type " + obj.GetType().Name; } SortedDictionary<string, int> sortedDictionary = new SortedDictionary<string, int>(); int count; lock (dictionary) { count = dictionary.Count; foreach (DictionaryEntry item in dictionary) { string text = (item.Value as string) ?? "?"; int num = text.IndexOf(':'); string key = ((num > 0) ? text.Substring(0, num) : text); sortedDictionary.TryGetValue(key, out var value); sortedDictionary[key] = value + 1; } } List<string> list = new List<string>(); foreach (KeyValuePair<string, int> item2 in sortedDictionary) { list.Add(item2.Key + " " + item2.Value); } return "present, " + count + " held" + ((list.Count > 0) ? (" (" + string.Join(", ", list.ToArray()) + ")") : ""); } private static string ZombieChores() { object obj = Get("gk2kit.zombieChores.v1"); if (obj == null) { return "absent"; } if (!(obj is IDictionary<string, object> dictionary)) { return "present, unexpected type " + obj.GetType().Name; } Func<bool> func = null; Func<string[]> func2 = null; string text; lock (dictionary) { text = string.Join(",", new List<string>(dictionary.Keys).ToArray()); if (dictionary.TryGetValue("on", out var value)) { func = value as Func<bool>; } if (dictionary.TryGetValue("chores", out value)) { func2 = value as Func<string[]>; } } string text2 = "no on()"; string text3 = "no chores()"; if (func != null) { try { text2 = "on=" + func(); } catch (Exception ex) { text2 = "on() threw " + ex.GetType().Name; } } if (func2 != null) { try { string[] array = func2(); text3 = ((array == null) ? "chores()=null" : ("chores=[" + string.Join(",", array) + "]")); } catch (Exception ex2) { text3 = "chores() threw " + ex2.GetType().Name; } } return "present, " + text2 + ", " + text3 + " (fields " + text + ")"; } private static string StockLimits() { object obj = Get("gk2kit.stockLimits.v1"); if (obj == null) { return "absent"; } if (!(obj is IDictionary<string, object> dictionary)) { return "present, unexpected type " + obj.GetType().Name; } lock (dictionary) { return "present (fields " + string.Join(",", new List<string>(dictionary.Keys).ToArray()) + ")"; } } private static string Wheel() { object obj = Get("gk2kit.wheel.v1"); if (obj == null) { return "absent"; } if (!(obj is IList list)) { return "present, unexpected type " + obj.GetType().Name; } List<string> list2 = new List<string>(); lock (list) { foreach (object item in list) { if (!(item is IDictionary<string, object> dictionary)) { list2.Add("?"); continue; } dictionary.TryGetValue("mod", out var value); dictionary.TryGetValue("id", out var value2); list2.Add(((value as string) ?? "?") + "/" + ((value2 as string) ?? "?")); } } return list2.Count + " entries" + ((list2.Count > 0) ? (" (" + string.Join(", ", list2.ToArray()) + ")") : ""); } private static string Hub() { object obj = Get("gk2kit.hub.v1"); if (obj == null) { return "absent"; } if (!(obj is IDictionary<string, object> dictionary)) { return "present, unexpected type " + obj.GetType().Name; } object value = null; lock (dictionary) { dictionary.TryGetValue("host", out value); } string text = value as string; return "present, host " + ((text == null) ? "(none)" : ((text.Length == 0) ? "\"\" (none left)" : text)); } private static string Published() { List<string> list = new List<string>(); string[] ownKeys = _ownKeys; foreach (string text in ownKeys) { object obj = Get(text); IDictionary<string, object> dictionary = obj as IDictionary<string, object>; if (obj == null) { list.Add(text + " not published"); continue; } if (dictionary == null) { list.Add(text + " published (" + obj.GetType().Name + ")"); continue; } lock (dictionary) { list.Add(text + " published, " + dictionary.Count + " fields (" + string.Join(",", new List<string>(dictionary.Keys).ToArray()) + ")"); } } if (_wheelMod != null) { bool flag = false; if (Get("gk2kit.wheel.v1") is IList list2) { lock (list2) { foreach (object item in list2) { if (item is IDictionary<string, object> dictionary2 && dictionary2.TryGetValue("mod", out var value) && dictionary2.TryGetValue("id", out var value2) && _wheelMod.Equals(value as string) && _wheelId.Equals(value2 as string)) { flag = true; break; } } } } list.Add("wheel entry " + _wheelMod + "/" + _wheelId + (flag ? " in the list" : " NOT in the list")); } if (list.Count != 0) { return string.Join("; ", list.ToArray()); } return "nothing"; } } internal static class GameLang { private static string _stable; private static string _seen; private static float _seenAt; private const float Settle = 0.6f; public static string Code() { string text = null; try { if (LLBase.IsCurrentLangLoaded) { text = LLBase.CurrentLang; } } catch { } if (string.IsNullOrEmpty(text)) { return _stable ?? ""; } if (_stable == null) { _stable = (_seen = text); return text; } if (text == _stable) { _seen = text; return text; } float unscaledTime = Time.unscaledTime; if (text != _seen) { _seen = text; _seenAt = unscaledTime; } else if (unscaledTime - _seenAt >= 0.6f) { _stable = text; } return _stable; } } internal static class ExtLoc { public static string Override = ""; private static readonly Dictionary<string, Dictionary<string, string>> Loaded = new Dictionary<string, Dictionary<string, string>>(); public static string Lang() { string text = (Override ?? "").Trim(); if (text.Length > 0) { return text.ToLowerInvariant(); } string text2 = GameLang.Code(); return ((text2.Length > 0) ? text2 : "en").ToLowerInvariant(); } public static bool TryGet(string key, out string text) { return TryGet(Lang(), key, out text); } public static bool TryGet(string lang, string key, out string text) { text = null; if (key == null) { return false; } Dictionary<string, string> dictionary = For(lang); if (dictionary != null && dictionary.TryGetValue(key, out text)) { return !string.IsNullOrEmpty(text); } return false; } public static string ModDir() { string location = typeof(ExtLoc).Assembly.Location; if (!string.IsNullOrEmpty(location)) { return Path.GetDirectoryName(location); } return SaHelp.ModDir("GK2ShoppingList"); } public static string Folder() { try { return Path.Combine(ModDir(), "Localization"); } catch { return null; } } private static Dictionary<string, string> For(string lang) { lang = (lang ?? "en").Trim().ToLowerInvariant(); if (Loaded.TryGetValue(lang, out var value)) { return value; } value = null; try { string text = Folder(); if (text != null && Directory.Exists(text)) { foreach (string item in Candidates(lang)) { string text2 = Path.Combine(text, item + ".json"); if (File.Exists(text2)) { value = Parse(File.ReadAllText(text2, Encoding.UTF8)); Plugin.Log.LogInfo((object)("Localization: " + value.Count + " text(s) for '" + lang + "' from " + text2)); break; } } } } catch (Exception ex) { Plugin.Log.LogWarning((object)("Localization: could not read the file for '" + lang + "': " + ex.Message)); value = null; } Loaded[lang] = value; return value; } private static IEnumerable<string> Candidates(string lang) { HashSet<string> seen = new HashSet<string>(); string[] array = new string[4] { lang, lang.Replace('_', '-'), lang.Replace('-', '_'), (lang.Length > 2) ? lang.Substring(0, 2) : lang }; foreach (string text in array) { if (text.Length > 0 && seen.Add(text)) { yield return text; } } } private static Dictionary<string, string> Parse(string s) { Dictionary<string, string> dictionary = new Dictionary<string, string>(); int i = 0; Ws(s, ref i); if (i >= s.Length || s[i] != '{') { throw new FormatException("the file must be a JSON object { \"key\": \"text\", ... }"); } i++; while (true) { Ws(s, ref i); if (i >= s.Length) { throw new FormatException("unexpected end of file"); } if (s[i] == '}') { break; } if (s[i] == ',') { i++; continue; } string text = Str(s, ref i); Ws(s, ref i); if (i >= s.Length || s[i] != ':') { throw new FormatException("':' expected after \"" + text + "\""); } i++; Ws(s, ref i); if (i < s.Length && s[i] == '"') { dictionary[text] = Str(s, ref i); } else { Skip(s, ref i); } } return dictionary; } private static void Ws(string s, ref int i) { while (i < s.Length && (char.IsWhiteSpace(s[i]) || s[i] == '\ufeff')) { i++; } } private static string Str(string s, ref int i) { if (i >= s.Length || s[i] != '"') { throw new FormatException("a \"quoted\" string expected at " + i); } i++; StringBuilder stringBuilder = new StringBuilder(); while (i < s.Length) { char c = s[i++]; switch (c) { case '"': return stringBuilder.ToString(); default: stringBuilder.Append(c); continue; case '\\': break; } if (i >= s.Length) { break; } char c2 = s[i++]; switch (c2) { case 'n': stringBuilder.Append('\n'); break; case 't': stringBuilder.Append('\t'); break; case 'r': stringBuilder.Append('\r'); break; case 'b': stringBuilder.Append('\b'); break; case 'f': stringBuilder.Append('\f'); break; case 'u': if (i + 4 > s.Length) { throw new FormatException("bad \\u escape"); } stringBuilder.Append((char)Convert.ToInt32(s.Substring(i, 4), 16)); i += 4; break; default: stringBuilder.Append(c2); break; } } throw new FormatException("unterminated string"); } private static void Skip(string s, ref int i) { int num = 0; while (i < s.Length) { switch (s[i]) { case '"': Str(s, ref i); if (num != 0) { continue; } return; case '[': case '{': num++; break; case ']': case '}': if (num == 0) { return; } num--; break; case ',': if (num == 0) { return; } break; } i++; } } } internal static class Framework { private sealed class Entry : Gk2ModBase { private readonly Gk2ModMetadata _meta = new Gk2ModMetadata("gk2.shoppinglist", "GK2 Shopping List", "SaintArchI", "0.12.0", FwText.L("A shopping list kept per save slot: add recipes, buildings, quests and town orders; it crosses off by itself and adds up across tasks. Shows what to bring on a panel, in a window and over chests."), false, false); private readonly IReadOnlyList<Gk2ModDependency> _deps = (IReadOnlyList<Gk2ModDependency>)(object)new Gk2ModDependency[1] { new Gk2ModDependency("ru.superman4eg.gk2.framework", "0.1.0", "0.2.0", false) }; private static readonly string[] PadChoices = new string[29] { "None", "RightStick", "LeftStick", "RightBumper", "RightTrigger", "LeftTrigger", "RightTrigger+RightStick", "RightTrigger+LeftStick", "LeftTrigger+RightStick", "LeftTrigger+LeftStick", "Fold", "Inventory", "ChangeWeapon", "Map", "QuestTree", "TechTree", "Inspirations", "Plant", "StartResurrection", "AlchemyBoost", "SaveImport", "AcceptVendorDeal", "MoveAllItemsFromPlayer", "MoveAllItemsToPlayer", "EndPrefight", "AttackFocus", "FoldAdditionalInfo", "PrevSubTab", "NextSubTab" }; public override Gk2ModMetadata Metadata => _meta; public override IReadOnlyList<Gk2ModDependency> Dependencies => _deps; public override void OnRegister(Gk2ModContext context) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_01a0: Unknown result type (might be due to invalid IL or missing references) //IL_01de: Unknown result type (might be due to invalid IL or missing references) //IL_04c1: Unknown result type (might be due to invalid IL or missing references) Gk2Settings settings = context.Settings; settings.AddKeybind("1 Adding", "AddModifier", new KeyboardShortcut((KeyCode)306, Array.Empty<KeyCode>()), FwText.L("Add to the list: hold + right click"), FwText.L("Hold this and right-click a recipe to add it to the list."), 0); settings.AddToggle("1 Adding", "ShiftToTop", true, FwText.L("Shift adds to the top"), FwText.L("Holding Shift as well (Ctrl+Shift+right click) puts the recipe at the top of the list."), 1); settings.AddToggle("1 Adding", "SubRecipes", true, FwText.L("Crafts for ingredients"), FwText.L("Shows a \"+\" next to a missing ingredient that can be crafted; it puts that craft on the list."), 2); settings.AddKeybind("2 List window", "ToggleWindow", new KeyboardShortcut((KeyCode)283, Array.Empty<KeyCode>()), FwText.L("Open the list"), FwText.L("Opens and closes the shopping list window."), 0); settings.AddFloatSlider("2 List window", "Scale", 0.85f, 0.5f, 1.5f, FwText.L("Window size"), FwText.L("Size of the list window. 1 is the size of the game's own windows."), 0.05f, 1); settings.AddToggle("2 List window", "CountStorage", true, FwText.L("Count your chests"), FwText.L("Next to a missing ingredient, show how many more lie in your chests and storages (+N)."), 2); settings.AddToggle("2 List window", "WhereFilter", true, FwText.L("\"Where\" filter"), FwText.L("Shows the \"Where\" filter on the panel and in the window, to see only what can be done in one place."), 3); settings.AddToggle("2 List window", "ChestsCountAsHave", false, FwText.L("Chests of every place count as have"), FwText.L("Count what lies in your chests, in every place, as \"have\" (the have/need counter and the panel), not only the backpack. Off by default: a workbench only draws from the chests of its own place. With it on, a note next to the counter says how much is carried and how much lies where you stand."), 4); settings.AddToggle("3 Town orders", "TownRepairs", true, FwText.L("Town repairs and shops"), FwText.L("The Orders tab also lists what can be raised in town now - repairs of ruined houses and shops for the free sites - with what each takes and a \"+\" that puts it on the list."), 0); settings.AddKeybind("3 Town orders", "AddAllOrders", KeyboardShortcut.Empty, FwText.L("Add all town orders"), FwText.L("Adds every open town order to the list. Not set by default."), 1); settings.AddKeybind("4 HUD panel", "ToggleHud", new KeyboardShortcut((KeyCode)283, (KeyCode[])(object)new KeyCode[1] { (KeyCode)304 }), FwText.L("Collapse the panel"), FwText.L("Collapses and expands the HUD panel."), 0); settings.AddToggle("4 HUD panel", "ByTask", true, FwText.L("Group by task"), FwText.L("The HUD panel lists ingredients under the task they belong to instead of one total list."), 1); settings.AddIntSlider("4 HUD panel", "MaxRows", 8, 1, 20, FwText.L("Rows on the panel"), FwText.L("How many ingredient rows the HUD panel shows."), 1, 2); settings.AddFloatSlider("4 HUD panel", "Scale", 0.8f, 0.5f, 1.5f, FwText.L("Panel size"), FwText.L("Size of the HUD panel. 1 is the size of the game's own UI."), 0.05f, 3); settings.AddToggle("4 HUD panel", "WheelScroll", true, FwText.L("Scroll with the wheel"), FwText.L("The mouse wheel over the HUD panel scrolls it."), 4); settings.AddFloatSlider("4 HUD panel", "OffsetRight", 6f, 0f, 2000f, FwText.L("Offset from the right"), FwText.L("Panel position, in game UI pixels. Dragging the panel's header changes these two."), 1f, 5); settings.AddFloatSlider("4 HUD panel", "OffsetTop", 36f, 0f, 2000f, FwText.L("Offset from the top"), FwText.L("Panel position, in game UI pixels. Dragging the panel's header changes these two."), 1f, 6); settings.AddToggle("5 Chest icons", "Enabled", true, FwText.L("Icons over chests"), FwText.L("Small icons over the chests in this place that hold something the list still needs (an ingredient you don't carry enough of)."), 0); settings.AddFloatSlider("5 Chest icons", "Size", 12f, 6f, 40f, FwText.L("Icon size"), FwText.L("Size of the icons over the chests, in game UI pixels."), 1f, 1); settings.AddFloatSlider("5 Chest icons", "Range", 10f, 2f, 40f, FwText.L("Range (distance to the chest)"), FwText.L("Only chests this close to you get icons, in game world units."), 1f, 2); settings.AddIntSlider("5 Chest icons", "MaxIcons", 3, 1, 8, FwText.L("Icons per chest"), FwText.L("At most this many icons over one chest, in the list's order."), 1, 3); settings.AddIntSlider("5 Chest icons", "IconsPerRow", 3, 1, 8, FwText.L("Icons per row"), FwText.L("How many icons stand side by side over a chest; the rest go in rows above."), 1, 4); settings.AddFloatSlider("5 Chest icons", "OffsetX", 0f, -80f, 80f, FwText.L("Shift sideways"), FwText.L("Moves the icons sideways from the middle of the chest's top, in game UI pixels (negative: to the left)."), 1f, 5); settings.AddFloatSlider("5 Chest icons", "OffsetY", 0f, -80f, 80f, FwText.L("Shift up"), FwText.L("Moves the icons up from the chest's top, in game UI pixels (negative: down onto the chest)."), 1f, 6); settings.AddToggle("5 Chest icons", "TakeButton", true, FwText.L("Take what the list needs (button in the chest window)"), FwText.L("Shows a button in the storage header of an open chest's window that moves what the list still needs from the chests shown there into the backpack (never more than is missing, never more than fits)."), 7); settings.AddKeybind("5 Chest icons", "TakeKey", new KeyboardShortcut((KeyCode)120, Array.Empty<KeyCode>()), FwText.L("Take what the list needs: key (chest window)"), FwText.L("Keyboard key that does the same as the button while a chest window is open (the button's tooltip shows it). Not read while you type in a text field. Leave it empty to turn the key off."), 8); settings.AddToggle("5 Chest icons", "TakeForPins", false, FwText.L("Also take for Almanac pins"), FwText.L("The take button and key also take what Almanac's pins still need, after the list's own needs (each pin need on its own, never added to the list's amounts). Off: only what the list needs."), 9); string text = " " + FwText.L("Button names: see Settings.txt."); settings.AddText("Gamepad", "AddKey", "RightStick", FwText.L("Add to the list"), FwText.L("Gamepad action that adds the focused recipe to the list, by the game's own name for it (RightStick, Fold, RightTrigger+RightStick for a chord...). Turn Log pad input on to see which actions each button of your pad sends.") + text, 0); settings.AddText("Gamepad", "WindowKey", "LeftTrigger+RightBumper", FwText.L("Open the list"), FwText.L("Gamepad action that opens and closes the list window.") + text, 1); settings.AddText("Gamepad", "HudKey", "RightTrigger+LeftStick", FwText.L("Collapse the panel"), FwText.L("Gamepad action that collapses and expands the HUD panel.") + text, 2); settings.AddText("Gamepad", "ClearKey", "LeftTrigger+RightStick", FwText.L("Clear the list"), FwText.L("Gamepad action that clears the whole list: the first press asks, a second press within 4 seconds clears.") + text, 3); settings.AddText("Gamepad", "TakeKey", "None", FwText.L("Take what the list needs"), FwText.L("Gamepad action that, in an open chest window, moves what the list needs from the chest into the backpack. None leaves it unbound.") + text, 5); settings.AddToggle("Gamepad", "ForceL3", false, FwText.L("Use L3 with the Keeper's Lantern wheel"), FwText.L("The bindings that use the left stick press are off while another mod's Keeper's Lantern wheel is installed (it opens on any L3 hold, over the list). Turn this on to keep them."), 4); settings.AddText("Language", "Language", "", FwText.L("Language"), FwText.L("Language of this mod's texts: a code such as en, ru, pt-br, zh_cn, or your own with a file in the mod's Localization folder. Empty follows the game."), 0); } } public const string FrameworkGuid = "ru.superman4eg.gk2.framework"; public static void TryRegister(BaseUnityPlugin plugin) { try { if (AppDomain.CurrentDomain.GetAssemblies().Any((Assembly a) => a.GetName().Name == "GK2.Framework")) { Register(plugin); } } catch (Exception ex) { Plugin.Log.LogInfo((object)("Mod Framework not used: " + ex.Message)); } } [MethodImpl(MethodImplOptions.NoInlining)] private static void Register(BaseUnityPlugin plugin) { foreach (RegisteredMod mod in FrameworkApi.Mods) { if (mod != null && mod.Metadata != null && string.Equals(mod.Metadata.Id, "gk2.shoppinglist", StringComparison.OrdinalIgnoreCase)) { return; } } SectionNames.Install(); FrameworkApi.RegisterMod((IGk2Mod)(object)new Entry(), plugin.Config); Plugin.Log.LogInfo((object)"Registered in GK2 Mod Framework"); } } internal static class FwText { private static readonly string[] Langs = new string[10] { "ru", "de", "fr", "es", "pt", "pl", "tr", "ja", "zh", "ko" }; private static int _idx = -2; private static readonly Dictionary<string, string[]> Table = new Dictionary<string, string[]> { { "Scroll with the wheel", new string[10] { "Прокрутка колесом", "Mit dem Mausrad scrollen", "Défiler avec la molette", "Desplazar con la rueda", "Rolar com a roda", "Przewijanie kółkiem", "Tekerlekle kaydır", "ホイールでスクロール", "滚轮滚动", "휠로 스크롤" } }, { "The mouse wheel over the HUD panel scrolls it.", new string[10] { "Колесо мыши над панелью прокручивает её.", "Das Mausrad über dem Panel scrollt es.", "La molette au-dessus du panneau le fait défiler.", "La rueda del ratón sobre el panel lo desplaza.", "A roda do mouse sobre o painel o rola.", "Kółko myszy nad panelem przewija go.", "Panelin üzerindeyken fare tekerleği onu kaydırır.", "パネルの上でマウスホイールを回すとスクロールします。", "在面板上滚动鼠标滚轮即可滚动面板。", "패널 위에서 마우스 휠을 굴리면 스크롤됩니다." } }, { "\"Where\" filter", new string[10] { "Фильтр «Где»", "Filter „Wo“", "Filtre « Où »", "Filtro «Dónde»", "Filtro «Onde»", "Filtr „Gdzie”", "\"Nerede\" filtresi", "「場所」フィルター", "“地点”筛选", "'장소' 필터" } }, { "Shows the \"Where\" filter on the panel and in the window, to see only what can be done in one place.", new string[10] { "Показывает фильтр «Где» на панели и в окне, чтобы видеть только то, что делается в одном месте.", "Zeigt den Filter „Wo“ im Panel und im Fenster, um nur zu sehen, was an einem Ort gemacht wird.", "Affiche le filtre « Où » sur le panneau et dans la fenêtre, pour ne voir que ce qui se fait à un endroit.", "Muestra el filtro «Dónde» en el panel y en la ventana, para ver solo lo que se hace en un lugar.", "Mostra o filtro «Onde» no painel e na janela, para ver só o que se faz num lugar.", "Pokazuje filtr „Gdzie” na panelu i w oknie, by widzieć tylko to, co robi się w jednym miejscu.", "Panelde ve pencerede \"Nerede\" filtresini gösterir; yalnızca tek bir yerde yapılanları görmek için.", "パネルとウィンドウに「場所」フィルターを表示し、ひとつの場所でできるものだけを見られます。", "在面板和窗口中显示“地点”筛选,只看在某一处能完成的内容。", "패널과 창에 '장소' 필터를 표시해 한 장소에서 할 수 있는 것만 볼 수 있습니다." } }, { "Town repairs and shops", new string[10] { "Ремонт и лавки в городе", "Reparaturen und Läden in der Stadt", "Réparations et boutiques en ville", "Reparaciones y tiendas en la ciudad", "Reparos e lojas no povoado", "Naprawy i sklepy w mieście", "Kasabada onarım ve dükkânlar", "町の修理と店", "镇上的修缮与店铺", "마을 수리와 가게" } }, { "The Orders tab also lists what can be raised in town now - repairs of ruined houses and shops for the free sites - with what each takes and a \"+\" that puts it on the list.", new string[10] { "Во вкладке «Заказы» показывается и то, что сейчас можно построить в городе: ремонт разрушенных домов и лавки для свободных мест — что нужно на каждое и «+», который добавляет в список.", "Der Reiter Aufträge zeigt auch, was sich jetzt in der Stadt errichten lässt: Reparaturen zerstörter Häuser und Läden für freie Plätze – was jedes braucht, und ein „+“, das es auf die Liste setzt.", "L'onglet Commandes liste aussi ce qu'on peut bâtir en ville maintenant : réparations des maisons en ruine et boutiques pour les emplacements libres – ce que demande chacun, et un « + » qui l'ajoute à la liste.", "La pestaña Pedidos también muestra lo que se puede levantar ahora en la ciudad: reparaciones de casas en ruinas y tiendas para los solares libres, lo que pide cada una y un «+» que la añade a la lista.", "A aba Pedidos também mostra o que dá para erguer no povoado agora: reparos de casas em ruínas e lojas para os terrenos livres – o que cada um pede e um «+» que o põe na lista.", "Karta Zlecenia pokazuje też, co można teraz postawić w mieście: naprawy zrujnowanych domów i sklepy na wolne miejsca – czego wymaga każde, i „+”, który dodaje je do listy.", "Siparişler sekmesi kasabada şimdi yapılabilecekleri de gösterir: yıkık evlerin onarımı ve boş yerler için dükkânlar – her birinin ne istediği ve onu listeye ekleyen bir «+».", "注文タブに、今町で建てられるもの(廃墟の家の修理と空き地の店)も表示します。それぞれに必要なものと、リストに加える「+」付き。", "订单页也会列出现在镇上能建的东西:废墟房屋的修缮和空地上的店铺——每项需要什么,以及加入清单的“+”。", "주문 탭에 지금 마을에서 세울 수 있는 것(폐허 집 수리와 빈 자리의 가게)도 보여 줍니다. 각각 필요한 것과 목록에 넣는 '+'가 있습니다." } }, { "Crafts for ingredients", new string[10] { "Крафт ингредиентов", "Herstellung von Zutaten", "Fabrication des ingrédients", "Fabricar ingredientes", "Fabricar ingredientes", "Wytwarzanie składników", "Malzeme üretimi", "材料の製作", "材料制作", "재료 제작" } }, { "Shows a \"+\" next to a missing ingredient that can be crafted; it puts that craft on the list.", new string[10] { "Показывает «+» рядом с недостающим ингредиентом, который можно скрафтить; он добавляет этот крафт в список.", "Zeigt ein „+“ neben einer fehlenden Zutat, die man herstellen kann; es setzt diese Herstellung auf die Liste.", "Affiche un « + » à côté d'un ingrédient manquant qui peut être fabriqué ; il ajoute cette fabrication à la liste.", "Muestra un «+» junto a un ingrediente que falta y se puede fabricar; añade esa fabricación a la lista.", "Mostra um «+» ao lado de um ingrediente em falta que pode ser fabricado; ele põe essa fabricação na lista.", "Pokazuje „+” przy brakującym składniku, który można wytworzyć; dodaje to wytwarzanie do listy.", "Üretilebilen eksik bir malzemenin yanında \"+\" gösterir; bu üretimi listeye ekler.", "製作できる足りない材料の横に「+」を表示し、その製作をリストに追加します。", "在可制作的缺少材料旁显示“+”,点击即把该制作加入清单。", "제작할 수 있는 부족한 재료 옆에 '+'를 표시하며, 누르면 그 제작을 목록에 추가합니다." } }, { "Shift adds to the top", new string[10] { "Shift — добавить наверх", "Umschalt fügt oben ein", "Maj ajoute en tête", "Mayús añade arriba", "Shift adiciona no topo", "Shift dodaje na górę", "Shift en üste ekler", "Shiftで先頭に追加", "Shift 添加到顶部", "Shift로 맨 위에 추가" } }, { "Holding Shift as well (Ctrl+Shift+right click) puts the recipe at the top of the list.", new string[10] { "Если зажать ещё и Shift (Ctrl+Shift+ПКМ), рецепт встаёт в начало списка.", "Wird zusätzlich Umschalt gehalten (Strg+Umschalt+Rechtsklick), kommt das Rezept an den Anfang der Liste.", "En maintenant aussi Maj (Ctrl+Maj+clic droit), la recette se place en tête de liste.", "Si además mantienes Mayús (Ctrl+Mayús+clic derecho), la receta va al principio de la lista.", "Segurando também Shift (Ctrl+Shift+clique direito), a receita vai para o topo da lista.", "Z wciśniętym też Shiftem (Ctrl+Shift+PPM) receptura trafia na początek listy.", "Shift'i de basılı tutarsanız (Ctrl+Shift+sağ tık) tarif listenin en üstüne gelir.", "Shiftも押す(Ctrl+Shift+右クリック)と、レシピがリストの先頭に入ります。", "同时按住 Shift(Ctrl+Shift+右键)时,配方会加到清单顶部。", "Shift도 함께 누르면(Ctrl+Shift+우클릭) 레시피가 목록 맨 위에 들어갑니다." } }, { "Log pad input", new string[10] { "Писать кнопки геймпада в лог", "Gamepad-Eingaben protokollieren", "Journaliser la manette", "Registrar el mando", "Registrar o controle", "Zapisuj pad do logu", "Gamepad girdilerini kaydet", "パッド入力をログに記録", "记录手柄输入", "패드 입력 기록" } }, { "Writes every gamepad action to BepInEx/LogOutput.log, so a free button can be found.", new string[10] { "Пишет каждое действие геймпада в BepInEx/LogOutput.log, чтобы найти свободную кнопку.", "Schreibt jede Gamepad-Aktion in BepInEx/LogOutput.log, damit sich eine freie Taste finden lässt.", "Écrit chaque action de la manette dans BepInEx/LogOutput.log, pour trouver un bouton libre.", "Escribe cada acción del mando en BepInEx/LogOutput.log para encontrar un botón libre.", "Grava cada ação do controle em BepInEx/LogOutput.log, para achar um botão livre.", "Zapisuje każdą akcję pada w BepInEx/LogOutput.log, żeby znaleźć wolny przycisk.", "Boş bir tuş bulmak için her gamepad eylemini BepInEx/LogOutput.log dosyasına yazar.", "空いているボタンを探せるよう、パッドの操作をすべて BepInEx/LogOutput.log に書き出します。", "将手柄的每个动作写入 BepInEx/LogOutput.log,便于找到空闲按键。", "빈 버튼을 찾을 수 있도록 패드의 모든 동작을 BepInEx/LogOutput.log에 기록합니다." } }, { "Use L3 with the Keeper's Lantern wheel", new string[10] { "L3 вместе с колесом Keeper's Lantern", "L3 trotz Keeper's-Lantern-Rad", "L3 avec la roue Keeper's Lantern", "L3 con la rueda de Keeper's Lantern", "L3 com a roda do Keeper's Lantern", "L3 razem z kołem Keeper's Lantern", "Keeper's Lantern çarkıyla L3", "Keeper's Lanternのホイールとの併用でL3を使う", "与 Keeper's Lantern 轮盘并用 L3", "Keeper's Lantern 휠과 L3 함께 사용" } }, { "The bindings that use the left stick press are off while another mod's Keeper's Lantern wheel is installed (it opens on any L3 hold, over the list). Turn this on to keep them.", new string[10] { "Сочетания с нажатием левого стика выключены, пока стоит колесо Keeper's Lantern из другого мода (оно открывается при любом удержании L3 поверх списка). Включите, чтобы оставить их.", "Die Belegungen mit Druck auf den linken Stick sind aus, solange das Keeper's-Lantern-Rad eines anderen Mods installiert ist (es öffnet sich bei jedem L3-Halten über der Liste). Einschalten, um sie zu behalten.", "Les raccourcis avec appui sur le stick gauche sont désactivés tant que la roue Keeper's Lantern d'un autre mod est installée (elle s'ouvre à chaque maintien de L3, par-dessus la liste). Activez pour les garder.", "Los atajos con pulsación del stick izquierdo están desactivados mientras esté instalada la rueda Keeper's Lantern de otro mod (se abre con cualquier L3 mantenido, sobre la lista). Actívalo para conservarlos.", "Os atalhos com clique do analógico esquerdo ficam desligados enquanto a roda Keeper's Lantern de outro mod estiver instalada (ela abre com qualquer L3 segurado, por cima da lista). Ligue para mantê-los.", "Skróty z naciśnięciem lewego drążka są wyłączone, gdy zainstalowano koło Keeper's Lantern z innego moda (otwiera się przy każdym przytrzymaniu L3, nad listą). Włącz, aby je zachować.", "Başka bir modun Keeper's Lantern çarkı yüklüyken sol çubuğa basma kısayolları kapalıdır (L3'e her basılı tutuşta listenin üstünde açılır). Tutmak için açın.", "他のモッドのKeeper's Lanternホイールが入っている間、左スティック押し込みの割り当ては無効です(L3長押しでリストの上に開くため)。維持するにはオンにします。", "安装了其他模组的 Keeper's Lantern 轮盘时,左摇杆按下的绑定会关闭(按住 L3 就会在列表上方打开)。开启则保留它们。", "다른 모드의 Keeper's Lantern 휠이 설치되어 있으면 왼쪽 스틱 누름 입력이 꺼집니다(L3를 누르면 목록 위로 열림). 유지하려면 켜세요." } }, { "Add to the list: hold + right click", new string[10] { "Добавить в список: удерживать + правый клик", "Zur Liste hinzufügen: halten + Rechtsklick", "Ajouter à la liste : maintenir + clic droit", "Añadir a la lista: mantener + clic derecho", "Adicionar à lista: segurar + clique direito", "Dodaj do listy: przytrzymaj + prawy klik", "Listeye ekle: basılı tut + sağ tık", "リストに追加:押したまま右クリック", "添加到清单:按住 + 右键", "목록에 추가: 누른 채 오른쪽 클릭" } }, { "Range (distance to the chest)", new string[10] { "Дальность (расстояние до сундука)", "Reichweite (Abstand zur Kiste)", "Portée (distance au coffre)", "Alcance (distancia al cofre)", "Alcance (distância até o baú)", "Zasięg (odległość od skrzyni)", "Menzil (sandığa uzaklık)", "範囲(宝箱までの距離)", "范围(与箱子的距离)", "범위(상자까지의 거리)" } }, { "Button names: see Settings.txt.", new