Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of TypedRefits v1.0.1
TypedRefits.dll
Decompiled 2 weeks agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Logging; using HarmonyLib; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("TypedRefits")] [assembly: AssemblyFileVersion("1.0.1.0")] [assembly: AssemblyMetadata("AI_Assisted_Creation", "This assembly was fully created with Generative AI assistance (code written by an AI agent).")] [assembly: AssemblyMetadata("AI_Model_Vendor", "Anthropic (Claude Opus 5.5)")] [assembly: AssemblyVersion("1.0.1.0")] namespace TypedRefits; [BepInPlugin("maskperson.typedrefits", "TypedRefits", "1.0.1")] [BepInDependency(/*Could not decode attribute arguments.*/)] public class Plugin : BaseUnityPlugin { public const string Guid = "maskperson.typedrefits"; public const string Name = "TypedRefits"; public const string Version = "1.0.1"; public const string ShipSystemsGuid = "com.y4ngz.company.shipsystems"; internal static ManualLogSource Log; private void Awake() { //IL_0027: Unknown result type (might be due to invalid IL or missing references) Log = ((BaseUnityPlugin)this).Logger; if (!Bridge.Bind()) { Log.LogError((object)"Could not find Ship Systems' refit code (was Ship Systems updated?). Typed refit commands are off."); return; } new Harmony("maskperson.typedrefits").PatchAll(typeof(TerminalPatches)); Log.LogInfo((object)"TypedRefits 1.0.1 loaded. Type 'refits' at the terminal."); } } internal sealed class RefitInfo { public object Id; public string Key; public string Title; public string Description; public int Level; public int MaxLevel; public bool CanBuyNext; public int Price; public int Availability; } internal static class Bridge { private const string Layout = "Y4NGZCompany.ShipSystems.Layout."; private static Type _idType; private static Type _resultType; private static Type _defType; private static Type _ctrlType; private static Type _catalogType; private static Type _presenceType; private static MethodInfo _ensureInstance; private static MethodInfo _getInstance; private static MethodInfo _refresh; private static MethodInfo _getLevel; private static MethodInfo _getAvailability; private static MethodInfo _tryGetPrice; private static MethodInfo _tryPurchase; private static MethodInfo _formatResult; private static MethodInfo _catalogAll; private static MethodInfo _isModPresent; private static MethodInfo _defId; private static MethodInfo _defTitle; private static MethodInfo _defDescription; private static MethodInfo _defMaxLevel; private static MethodInfo _addResultEvent; internal static event Action<string> VerdictReceived; internal static bool Bind() { try { PluginInfo value; Assembly assembly = ((Chainloader.PluginInfos.TryGetValue("com.y4ngz.company.shipsystems", out value) && (Object)(object)((value != null) ? value.Instance : null) != (Object)null) ? ((object)value.Instance).GetType().Assembly : null); if (assembly == null) { Plugin.Log.LogError((object)"Ship Systems is not loaded."); return false; } _idType = assembly.GetType("Y4NGZCompany.ShipSystems.Layout.ShipUpgradeId"); _resultType = assembly.GetType("Y4NGZCompany.ShipSystems.Layout.ShipUpgradePurchaseResult"); _defType = assembly.GetType("Y4NGZCompany.ShipSystems.Layout.ShipUpgradeDefinition"); _ctrlType = assembly.GetType("Y4NGZCompany.ShipSystems.Layout.ShipCommandController"); _catalogType = assembly.GetType("Y4NGZCompany.ShipSystems.Layout.ShipUpgradeCatalog"); _presenceType = assembly.GetType("Y4NGZCompany.ShipSystems.Layout.RefitModPresence"); if (_idType == null || _resultType == null || _defType == null || _ctrlType == null || _catalogType == null || _presenceType == null) { Plugin.Log.LogError((object)"A Ship Systems type is missing."); return false; } _ensureInstance = AccessTools.Method(_ctrlType, "EnsureInstance", (Type[])null, (Type[])null); _getInstance = AccessTools.PropertyGetter(_ctrlType, "Instance"); _refresh = AccessTools.Method(_ctrlType, "RefreshUpgradeStateForTerminal", (Type[])null, (Type[])null); _getLevel = AccessTools.Method(_ctrlType, "GetUpgradeLevel", new Type[1] { _idType }, (Type[])null); _getAvailability = AccessTools.Method(_ctrlType, "GetUpgradeAvailability", new Type[1] { _idType }, (Type[])null); _tryGetPrice = AccessTools.Method(_ctrlType, "TryGetRefitPrice", new Type[3] { _idType, typeof(int), typeof(int).MakeByRefType() }, (Type[])null); _tryPurchase = AccessTools.Method(_ctrlType, "TryPurchaseUpgradeFromTerminal", new Type[4] { _idType, typeof(int), typeof(Terminal), typeof(int).MakeByRefType() }, (Type[])null); _formatResult = AccessTools.Method(_ctrlType, "FormatPurchaseResult", new Type[4] { _resultType, _idType, typeof(int), typeof(int) }, (Type[])null); _addResultEvent = AccessTools.Method(_ctrlType, "add_RefitPurchaseResultReceived", (Type[])null, (Type[])null); _catalogAll = AccessTools.PropertyGetter(_catalogType, "All"); _isModPresent = AccessTools.Method(_presenceType, "IsRequiredModPresent", new Type[1] { _idType }, (Type[])null); _defId = AccessTools.PropertyGetter(_defType, "Id"); _defTitle = AccessTools.PropertyGetter(_defType, "Title"); _defDescription = AccessTools.PropertyGetter(_defType, "ShortDescription"); _defMaxLevel = AccessTools.PropertyGetter(_defType, "MaxLevel"); foreach (KeyValuePair<string, MethodInfo> item in new Dictionary<string, MethodInfo> { { "EnsureInstance", _ensureInstance }, { "Instance", _getInstance }, { "GetUpgradeLevel", _getLevel }, { "GetUpgradeAvailability", _getAvailability }, { "TryGetRefitPrice", _tryGetPrice }, { "TryPurchaseUpgradeFromTerminal", _tryPurchase }, { "FormatPurchaseResult", _formatResult }, { "Catalog.All", _catalogAll }, { "IsRequiredModPresent", _isModPresent }, { "Definition.Id", _defId }, { "Definition.Title", _defTitle }, { "Definition.MaxLevel", _defMaxLevel } }) { if (item.Value == null) { Plugin.Log.LogError((object)("Ship Systems method missing: " + item.Key)); return false; } } if (_addResultEvent != null) { try { MethodInfo method = typeof(Bridge).GetMethod("OnResult", BindingFlags.Static | BindingFlags.NonPublic).MakeGenericMethod(_idType); Type type = typeof(Action<, , >).MakeGenericType(_idType, typeof(int), typeof(string)); _addResultEvent.Invoke(null, new object[1] { Delegate.CreateDelegate(type, method) }); } catch (Exception ex) { Plugin.Log.LogWarning((object)("Could not listen for host purchase replies: " + ex.Message)); } } return true; } catch (Exception ex2) { Plugin.Log.LogError((object)("Binding to Ship Systems failed: " + ex2)); return false; } } private static void OnResult<TId>(TId id, int level, string text) { try { Bridge.VerdictReceived?.Invoke(text); } catch (Exception ex) { Plugin.Log.LogWarning((object)("Showing host reply failed: " + ex.Message)); } } private static object Controller() { try { _ensureInstance.Invoke(null, null); object obj = _getInstance.Invoke(null, null); Object val = (Object)((obj is Object) ? obj : null); if (val != null && val == (Object)null) { return null; } return obj; } catch (Exception e) { Plugin.Log.LogWarning((object)("Ship Systems controller unavailable: " + Inner(e).Message)); return null; } } internal static List<RefitInfo> ReadRefits() { object ctrl = Controller(); if (ctrl == null) { return null; } try { _refresh?.Invoke(ctrl, null); } catch { } List<RefitInfo> list = new List<RefitInfo>(); if (!(_catalogAll.Invoke(null, null) is IEnumerable enumerable)) { return list; } foreach (object def in enumerable) { if (def == null) { continue; } object id = _defId.Invoke(def, null); if (!(bool)_isModPresent.Invoke(null, new object[1] { id })) { continue; } int num = SafeInt(() => _getLevel.Invoke(ctrl, new object[1] { id })); int num2 = Math.Max(1, SafeInt(() => _defMaxLevel.Invoke(def, null))); bool flag = false; int price = 0; if (num < num2) { object[] array = new object[3] { id, num + 1, 0 }; try { flag = (bool)_tryGetPrice.Invoke(ctrl, array); price = (int)array[2]; } catch { flag = false; } } if (flag || num > 0) { list.Add(new RefitInfo { Id = id, Key = id.ToString(), Title = ((_defTitle.Invoke(def, null) as string) ?? id.ToString()), Description = ((_defDescription != null) ? ((_defDescription.Invoke(def, null) as string) ?? "") : ""), Level = num, MaxLevel = num2, CanBuyNext = flag, Price = price, Availability = SafeInt(() => _getAvailability.Invoke(ctrl, new object[1] { id })) }); } } return list; } internal static int Purchase(Terminal terminal, RefitInfo refit, out string message) { message = "Company purchasing relay is unavailable."; object obj = Controller(); if (obj == null) { return 7; } object[] array = new object[4] { refit.Id, refit.Level + 1, terminal, 0 }; int result = Convert.ToInt32(_tryPurchase.Invoke(obj, array)); int cost = (int)array[3]; message = Format(result, refit.Id, cost, ((Object)(object)terminal != (Object)null) ? terminal.groupCredits : 0); return result; } internal static string Format(int result, object id, int cost, int credits) { try { string text = _formatResult.Invoke(null, new object[4] { Enum.ToObject(_resultType, result), id, cost, credits }) as string; if (!string.IsNullOrWhiteSpace(text)) { return text; } } catch { } return Enum.ToObject(_resultType, result).ToString(); } private static int SafeInt(Func<object> read) { try { return Convert.ToInt32(read()); } catch { return 0; } } private static Exception Inner(Exception e) { if (!(e is TargetInvocationException { InnerException: not null } ex)) { return e; } return ex.InnerException; } } internal static class Commands { private const int ResultSuccess = 0; private const int ResultRequestSent = 1; private const int ResultNotEnoughCredits = 2; private const int ResultNotInOrbit = 4; private static RefitInfo _pending; private static float _pendingSince; private static bool _awaitingHost; static Commands() { Bridge.VerdictReceived += OnHostVerdict; } internal static void ClearPending() { _pending = null; } internal static TerminalNode Handle(Terminal terminal, string raw) { string text = Normalize(raw); if (text.Length == 0) { return null; } if (_pending != null) { RefitInfo pending = _pending; _pending = null; bool flag = Time.realtimeSinceStartup - _pendingSince < 120f; if (flag && IsOneOf(text, "confirm", "c", "yes", "y")) { return Buy(terminal, pending); } if (flag && IsOneOf(text, "deny", "d", "no", "n", "cancel")) { return Nodes.Make("Cancelled. Nothing was bought.\n\nType REFITS to see the list again."); } } if (IsOneOf(text, "refits", "refit", "refits list", "refit list")) { return ListNode(terminal); } if (text.StartsWith("refit ") || text.StartsWith("refits ")) { string arg = text.Substring(text.IndexOf(' ') + 1).Trim(); return SelectNode(terminal, arg); } return null; } private static TerminalNode ListNode(Terminal terminal) { List<RefitInfo> list = Bridge.ReadRefits(); if (list == null) { return Nodes.Make("Ship Systems isn't ready yet. Try again in a moment."); } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("SHIP REFITS"); stringBuilder.AppendLine("Credits: $" + terminal.groupCredits); stringBuilder.AppendLine(); if (list.Count == 0) { stringBuilder.AppendLine("No refits are offered. Check [Ship Upgrades]"); stringBuilder.AppendLine("in the Ship Systems config."); } for (int i = 0; i < list.Count; i++) { RefitInfo refitInfo = list[i]; string text = refitInfo.Title + ((refitInfo.MaxLevel > 1) ? (" " + Roman(Math.Min(refitInfo.Level + 1, refitInfo.MaxLevel))) : ""); stringBuilder.AppendLine(string.Concat(str2: refitInfo.CanBuyNext ? ("$" + refitInfo.Price + ((refitInfo.Level > 0) ? (" (have " + refitInfo.Level + "/" + refitInfo.MaxLevel + ")") : "")) : "OWNED", str0: PadDots((i + 1).ToString().PadLeft(2) + ". " + text, 30), str1: " ")); } stringBuilder.AppendLine(); stringBuilder.AppendLine("Buy: REFIT <name or number>"); stringBuilder.AppendLine(" e.g. refit turret or refit 3"); if (list.Exists((RefitInfo r) => r.CanBuyNext && r.Availability == 4)) { stringBuilder.AppendLine("Refits can only be bought in orbit."); } return Nodes.Make(stringBuilder.ToString()); } private static TerminalNode SelectNode(Terminal terminal, string arg) { List<RefitInfo> list = Bridge.ReadRefits(); if (list == null) { return Nodes.Make("Ship Systems isn't ready yet. Try again in a moment."); } List<RefitInfo> list2 = Find(list, arg); if (list2.Count == 0) { return Nodes.Make("No refit called \"" + arg + "\".\n\nType REFITS to see the list."); } if (list2.Count > 1) { StringBuilder stringBuilder = new StringBuilder("\"" + arg + "\" matches more than one refit:\n\n"); foreach (RefitInfo item in list2) { stringBuilder.AppendLine(" " + item.Title); } stringBuilder.AppendLine("\nType a bit more of the name, or use its number."); return Nodes.Make(stringBuilder.ToString()); } RefitInfo refitInfo = list2[0]; if (!refitInfo.CanBuyNext) { return Nodes.Make(refitInfo.Title + " is already installed" + ((refitInfo.MaxLevel > 1) ? " at max level" : "") + "."); } if (refitInfo.Availability == 4) { return Nodes.Make(Bridge.Format(4, refitInfo.Id, refitInfo.Price, terminal.groupCredits)); } if (refitInfo.Availability != 0) { return Nodes.Make(Bridge.Format(refitInfo.Availability, refitInfo.Id, refitInfo.Price, terminal.groupCredits)); } if (terminal.groupCredits < refitInfo.Price) { return Nodes.Make(Bridge.Format(2, refitInfo.Id, refitInfo.Price, terminal.groupCredits) + "\nYou have $" + terminal.groupCredits + "."); } _pending = refitInfo; _pendingSince = Time.realtimeSinceStartup; StringBuilder stringBuilder2 = new StringBuilder(); string text = ((refitInfo.MaxLevel > 1) ? (" " + Roman(refitInfo.Level + 1)) : ""); stringBuilder2.AppendLine("Buy " + refitInfo.Title.ToUpperInvariant() + text + " for $" + refitInfo.Price + "?"); if (!string.IsNullOrEmpty(refitInfo.Description)) { stringBuilder2.AppendLine(refitInfo.Description); } stringBuilder2.AppendLine(); stringBuilder2.AppendLine("Credits: $" + terminal.groupCredits + " -> $" + (terminal.groupCredits - refitInfo.Price)); stringBuilder2.AppendLine(); stringBuilder2.AppendLine("Type CONFIRM to buy or DENY to cancel."); return Nodes.Make(stringBuilder2.ToString()); } private static TerminalNode Buy(Terminal terminal, RefitInfo r) { string message; switch (Bridge.Purchase(terminal, r, out message)) { case 0: { TerminalNode obj = Nodes.Make(message + "\n\nType REFITS to see the list."); obj.playSyncedClip = 0; return obj; } case 1: _awaitingHost = true; return Nodes.Make(message + "\nWaiting for the host to confirm..."); default: return Nodes.Make(message); } } private static void OnHostVerdict(string text) { if (!_awaitingHost) { return; } _awaitingHost = false; Terminal val = Object.FindObjectOfType<Terminal>(); if (!((Object)(object)val == (Object)null) && val.terminalInUse) { if (text != null && text.IndexOf("installed for", StringComparison.OrdinalIgnoreCase) >= 0 && (Object)(object)val.terminalAudio != (Object)null && val.syncedAudios != null && val.syncedAudios.Length != 0) { val.terminalAudio.PlayOneShot(val.syncedAudios[0]); } val.LoadNewNode(Nodes.Make((text ?? "No reply from host.") + "\n\nType REFITS to see the list.")); } } private static List<RefitInfo> Find(List<RefitInfo> refits, string arg) { List<RefitInfo> list = new List<RefitInfo>(); if (int.TryParse(arg, out var result)) { if (result >= 1 && result <= refits.Count) { list.Add(refits[result - 1]); } return list; } string text = Squash(arg); if (text.Length == 0) { return list; } foreach (RefitInfo refit in refits) { if (Squash(refit.Title) == text || Squash(refit.Key) == text) { list.Add(refit); } } if (list.Count > 0) { return list; } foreach (RefitInfo refit2 in refits) { if (Squash(refit2.Title).StartsWith(text) || Squash(refit2.Key).StartsWith(text) || WordStarts(refit2.Title, arg)) { list.Add(refit2); } } if (list.Count > 0) { return list; } if (text.Length >= 3) { foreach (RefitInfo refit3 in refits) { if (Squash(refit3.Title).Contains(text) || Squash(refit3.Key).Contains(text)) { list.Add(refit3); } } } return list; } private static bool WordStarts(string title, string arg) { string text = Squash(arg); if (text.Length < 3) { return false; } string[] array = title.Split(' ', '-'); for (int i = 0; i < array.Length; i++) { if (Squash(array[i]).StartsWith(text)) { return true; } } return false; } private static string Normalize(string raw) { if (raw == null) { return ""; } StringBuilder stringBuilder = new StringBuilder(); bool flag = false; string text = raw.Trim().ToLowerInvariant(); foreach (char c in text) { if (char.IsWhiteSpace(c)) { flag = true; continue; } if (flag && stringBuilder.Length > 0) { stringBuilder.Append(' '); } flag = false; stringBuilder.Append(c); } return stringBuilder.ToString(); } private static string Squash(string s) { StringBuilder stringBuilder = new StringBuilder(); string text = (s ?? "").ToLowerInvariant(); foreach (char c in text) { if (char.IsLetterOrDigit(c)) { stringBuilder.Append(c); } } return stringBuilder.ToString(); } private static bool IsOneOf(string s, params string[] options) { foreach (string text in options) { if (s == text) { return true; } } return false; } private static string PadDots(string s, int width) { if (s.Length >= width) { return s; } return s + " " + new string('.', Math.Max(0, width - s.Length - 1)); } private static string Roman(int n) { return n switch { 1 => "I", 2 => "II", 3 => "III", 4 => "IV", 5 => "V", _ => n.ToString(), }; } } internal static class Nodes { internal static TerminalNode Make(string text) { TerminalNode obj = ScriptableObject.CreateInstance<TerminalNode>(); ((Object)obj).name = "TypedRefitsNode"; obj.displayText = text.TrimEnd() + "\n\n"; obj.clearPreviousText = true; obj.maxCharactersToType = 25; obj.terminalEvent = ""; obj.buyItemIndex = -1; obj.buyVehicleIndex = -1; obj.buyRerouteToMoon = -1; obj.displayPlanetInfo = -1; obj.shipUnlockableID = -1; obj.creatureFileID = -1; obj.storyLogFileID = -1; obj.playSyncedClip = -1; obj.itemCost = 0; obj.isConfirmationNode = false; obj.acceptAnything = false; obj.overrideOptions = false; obj.terminalOptions = (CompatibleNoun[])(object)new CompatibleNoun[0]; return obj; } } [HarmonyPatch] internal static class TerminalPatches { private static TerminalNode _handled; [HarmonyPatch(typeof(Terminal), "ParsePlayerSentence")] [HarmonyPrefix] [HarmonyPriority(800)] private static bool ParsePrefix(Terminal __instance, ref TerminalNode __result) { _handled = null; string raw; try { string text = __instance.screenText.text; int textAdded = __instance.textAdded; if (textAdded <= 0 || textAdded > text.Length) { return true; } raw = text.Substring(text.Length - textAdded); } catch { return true; } TerminalNode val; try { val = Commands.Handle(__instance, raw); } catch (Exception ex) { Plugin.Log.LogError((object)("Refit command failed: " + ex)); val = Nodes.Make("The refit command hit an error. See the BepInEx log."); } if ((Object)(object)val == (Object)null) { return true; } _handled = val; __result = val; return false; } [HarmonyPatch(typeof(Terminal), "ParsePlayerSentence")] [HarmonyPostfix] [HarmonyPriority(0)] private static void ParsePostfix(ref TerminalNode __result) { if (!((Object)(object)_handled == (Object)null)) { __result = _handled; _handled = null; } } [HarmonyPatch(typeof(Terminal), "QuitTerminal")] [HarmonyPostfix] private static void QuitPostfix() { Commands.ClearPending(); } }