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 Tolmach v0.13.0
plugins/Tolmach.dll
Decompiled a month 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.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Text; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: InternalsVisibleTo("Tolmach.Tests")] [assembly: ComVisible(false)] [assembly: AssemblyCompany("Tolmach")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyDescription("Client-side Russian translations for Valheim mods and the game's closed captions.")] [assembly: AssemblyFileVersion("0.13.0.0")] [assembly: AssemblyInformationalVersion("0.13.0")] [assembly: AssemblyProduct("Tolmach")] [assembly: AssemblyTitle("Tolmach")] [assembly: AssemblyVersion("0.13.0.0")] namespace Tolmach; internal static class CallSites { private sealed class Site { public Module Module; public MethodBase Caller; public bool ScopedTerminal; public string ComposedSite; } private static readonly Dictionary<IntPtr, List<Site>> Sinks = new Dictionary<IntPtr, List<Site>>(); private static readonly HashSet<IntPtr> Patched = new HashSet<IntPtr>(); private static readonly string[] DerivedSinkTypes = new string[3] { "Player", "TMPro.TextMeshProUGUI", "TMPro.TextMeshPro" }; private const int LastArgument = 7; internal static void Cover(Harmony harmony, Module module, string owner, MethodBase method, List<CodeInstruction> body, string reason, string composedSite = null) { PatchEvidence patchEvidence = new PatchEvidence { method = owner, notPatched = reason }; module.Patches[RuntimeAccess.MethodKey(method)] = patchEvidence; HashSet<IntPtr> hashSet = new HashSet<IntPtr>(); foreach (CodeInstruction item in body) { FieldInfo fieldInfo = item.operand as FieldInfo; if (fieldInfo != null && item.opcode == OpCodes.Stfld && DisplayPatches.DisplayField(fieldInfo, module)) { Add(patchEvidence.leftAsIs, fieldInfo.DeclaringType.Name + "." + fieldInfo.Name); continue; } MethodBase methodBase = item.operand as MethodBase; if (methodBase == null || (!(item.opcode == OpCodes.Call) && !(item.opcode == OpCodes.Callvirt) && !(item.opcode == OpCodes.Newobj))) { continue; } bool[] array = DisplayPatches.StringSinkAt(methodBase, module, method); if (!array.Any((bool b) => b) || !hashSet.Add(methodBase.MethodHandle.Value)) { continue; } if (DisplayPatches.LocalizedReturn(methodBase)) { Add(patchEvidence.leftAsIs, Name(methodBase)); continue; } foreach (MethodBase item2 in WithOverrides(methodBase)) { if (!Install(harmony, item2, array)) { Add(patchEvidence.leftAsIs, Name(item2)); continue; } if (!Sinks.TryGetValue(item2.MethodHandle.Value, out var value)) { value = (Sinks[item2.MethodHandle.Value] = new List<Site>()); } value.Add(new Site { Module = module, Caller = method, ScopedTerminal = DisplayPatches.ScopedTerminalSink(methodBase, module, method), ComposedSite = composedSite }); Add(patchEvidence.callSites, Name(item2)); } } if (patchEvidence.leftAsIs.Count != 0 && HoldsCatalogText(body, module)) { module.Warn("UI patch skipped " + owner + ": " + reason + "; left untranslated: " + string.Join(", ", patchEvidence.leftAsIs.ToArray())); } } internal static void Reset() { Sinks.Clear(); Patched.Clear(); } private static void Add(List<string> list, string name) { if (!list.Contains(name)) { list.Add(name); } } private static string Name(MethodBase method) { return method.DeclaringType.Name + "." + method.Name; } private static bool HoldsCatalogText(List<CodeInstruction> body, Module module) { if (module.Table != null) { return body.Any(delegate(CodeInstruction i) { string text = ((i.opcode == OpCodes.Ldstr) ? (i.operand as string) : null); return text != null && module.Table.Translate(text) != text; }); } return false; } private static IEnumerable<MethodBase> WithOverrides(MethodBase sink) { yield return sink; MethodInfo method = sink as MethodInfo; if (method == null || !method.IsVirtual || method.IsFinal) { yield break; } Type[] parameters = (from p in method.GetParameters() select p.ParameterType).ToArray(); string[] derivedSinkTypes = DerivedSinkTypes; for (int num = 0; num < derivedSinkTypes.Length; num++) { Type type = RuntimeAccess.ExactType(derivedSinkTypes[num]); if (!(type == null) && !(type == method.DeclaringType) && method.DeclaringType.IsAssignableFrom(type)) { MethodInfo methodInfo = AccessTools.DeclaredMethod(type, method.Name, parameters, (Type[])null); if (methodInfo != null && methodInfo.GetBaseDefinition() == method.GetBaseDefinition()) { yield return methodInfo; } } } } private static bool Install(Harmony harmony, MethodBase target, bool[] selected) { //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_00d6: Expected O, but got Unknown if (Patched.Contains(target.MethodHandle.Value)) { return true; } if (!RuntimeAccess.ManagedBody(target) || DisplayPatches.UnsupportedHandler(target) != null) { return false; } ParameterInfo[] parameters = target.GetParameters(); if (parameters.Length != selected.Length) { return false; } List<MethodInfo> list = new List<MethodInfo>(); for (int i = 0; i < selected.Length; i++) { if (selected[i]) { if (i > 7) { return false; } list.Add(typeof(CallSites).GetMethod(((parameters[i].ParameterType == typeof(string[])) ? "Texts" : "Text") + i, AccessTools.all)); } } try { foreach (MethodInfo item in list) { harmony.Patch(target, new HarmonyMethod(item) { priority = 0 }, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } catch (Exception) { return false; } Patched.Add(target.MethodHandle.Value); return true; } private static void Text0(MethodBase __originalMethod, ref string __0) { __0 = Translate(__originalMethod, __0); } private static void Text1(MethodBase __originalMethod, ref string __1) { __1 = Translate(__originalMethod, __1); } private static void Text2(MethodBase __originalMethod, ref string __2) { __2 = Translate(__originalMethod, __2); } private static void Text3(MethodBase __originalMethod, ref string __3) { __3 = Translate(__originalMethod, __3); } private static void Text4(MethodBase __originalMethod, ref string __4) { __4 = Translate(__originalMethod, __4); } private static void Text5(MethodBase __originalMethod, ref string __5) { __5 = Translate(__originalMethod, __5); } private static void Text6(MethodBase __originalMethod, ref string __6) { __6 = Translate(__originalMethod, __6); } private static void Text7(MethodBase __originalMethod, ref string __7) { __7 = Translate(__originalMethod, __7); } private static void Texts0(MethodBase __originalMethod, ref string[] __0) { __0 = TranslateAll(__originalMethod, __0); } private static void Texts1(MethodBase __originalMethod, ref string[] __1) { __1 = TranslateAll(__originalMethod, __1); } private static void Texts2(MethodBase __originalMethod, ref string[] __2) { __2 = TranslateAll(__originalMethod, __2); } private static void Texts3(MethodBase __originalMethod, ref string[] __3) { __3 = TranslateAll(__originalMethod, __3); } private static void Texts4(MethodBase __originalMethod, ref string[] __4) { __4 = TranslateAll(__originalMethod, __4); } private static void Texts5(MethodBase __originalMethod, ref string[] __5) { __5 = TranslateAll(__originalMethod, __5); } private static void Texts6(MethodBase __originalMethod, ref string[] __6) { __6 = TranslateAll(__originalMethod, __6); } private static void Texts7(MethodBase __originalMethod, ref string[] __7) { __7 = TranslateAll(__originalMethod, __7); } private static string Translate(MethodBase sink, string value) { if (!TextEngine.IsRussian || string.IsNullOrEmpty(value) || !Sinks.TryGetValue(sink.MethodHandle.Value, out var value2)) { return value; } MethodBase methodBase = null; foreach (Site item in value2) { if (item.ScopedTerminal && (!item.Module.UiAllowed || !TextEngine.Modules.TryGetValue(item.Module.id, out var value3) || item.Module != value3)) { continue; } string text = ((item.ComposedSite != null) ? TextEngine.DisplaySite(value, item.ComposedSite) : TextEngine.Display(value, item.Module.id)); if (!(text == value)) { if (methodBase == null) { methodBase = Caller(sink); } if (methodBase != null && Same(methodBase, item.Caller)) { return text; } } } return value; } private static string[] TranslateAll(MethodBase sink, string[] values) { if (!TextEngine.IsRussian || values == null || !Sinks.ContainsKey(sink.MethodHandle.Value)) { return values; } string[] array = null; for (int i = 0; i < values.Length; i++) { string text = Translate(sink, values[i]); if (!(text == values[i])) { if (array == null) { array = (string[])values.Clone(); } array[i] = text; } } return array ?? values; } private static MethodBase Caller(MethodBase sink) { StackTrace stackTrace = new StackTrace(fNeedFileInfo: false); for (int i = 0; i < stackTrace.FrameCount; i++) { StackFrame frame = stackTrace.GetFrame(i); MethodBase methodBase = frame.GetMethod(); if (!(methodBase == null) && !(methodBase.DeclaringType == typeof(CallSites))) { try { methodBase = Harmony.GetMethodFromStackframe(frame) ?? methodBase; } catch (Exception) { } if (!(methodBase.DeclaringType == null) && !methodBase.DeclaringType.Assembly.IsDynamic && !Same(methodBase, sink)) { return methodBase; } } } return null; } private static bool Same(MethodBase a, MethodBase b) { try { return a.MethodHandle.Value == b.MethodHandle.Value; } catch (Exception) { return false; } } } internal sealed class PluginIdentity { internal readonly string Guid; internal readonly Assembly Assembly; internal readonly Version Version; internal PluginIdentity(string guid, Assembly assembly, Version version) { Guid = guid; Assembly = assembly; Version = version; } } internal static class CatalogLoader { private static readonly Regex Hole = new Regex("\\{(\\d+)\\}", RegexOptions.CultureInvariant); private static readonly Regex IdolName = new Regex("\\A\\$item_upgrader_tier([0-7]) \\$item_upgrader_(weapon|armor) \\$item_upgrader_name\\z", RegexOptions.CultureInvariant); private static readonly JsonSerializer Serializer = JsonSerializer.Create(new JsonSerializerSettings { MissingMemberHandling = (MissingMemberHandling)1 }); internal static readonly Regex CllcNameplate = new Regex("\\A(?:[^\\[\\]{}]|\\[[^\\[\\]{}]*\\{(?:effect|infusion|affix)\\}[^\\[\\]{}]*\\])*\\{name\\}(?:[^\\[\\]{}]|\\[[^\\[\\]{}]*\\{(?:effect|infusion|affix)\\}[^\\[\\]{}]*\\])*\\z", RegexOptions.CultureInvariant); internal const string GameGuid = "valheim"; internal const string FilePrefix = "tolmach-"; internal static Module Read(string path) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Expected O, but got Unknown //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Expected O, but got Unknown //IL_0104: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Invalid comparison between Unknown and I4 if (new FileInfo(path).Length > 2097152) { throw new InvalidDataException("Catalog is larger than 2 MiB."); } using StreamReader streamReader = new StreamReader(path, Encoding.UTF8, detectEncodingFromByteOrderMarks: true); JsonTextReader val = new JsonTextReader((TextReader)streamReader) { MaxDepth = 32, DateParseHandling = (DateParseHandling)0 }; try { JObject val2 = JObject.Load((JsonReader)(object)val, new JsonLoadSettings { DuplicatePropertyNameHandling = (DuplicatePropertyNameHandling)2 }); if (((JsonReader)val).Read()) { throw new InvalidDataException("Unexpected data after catalog object."); } Module module = ((JToken)val2).ToObject<Module>(Serializer); if (val2.Property("codeAssembly") != null && module.codeAssembly.Length == 0) { throw new InvalidDataException("codeAssembly cannot be empty when declared."); } string[] array = new string[2] { "patterns", "rawPatterns" }; foreach (string text in array) { if (!(val2[text] is JArray)) { continue; } foreach (JToken item in (IEnumerable<JToken>)val2[text]) { if (item[(object)"singleLine"] != null && (int)item[(object)"singleLine"].Type != 9) { throw new InvalidDataException("singleLine must be a boolean."); } } } Validate(module); return module; } finally { ((IDisposable)val)?.Dispose(); } } internal static void Validate(Module m) { if (m == null || string.IsNullOrEmpty(m.id) || !Regex.IsMatch(m.id, "\\A[A-Za-z0-9_.]+\\z") || string.IsNullOrEmpty(m.assembly) || m.guids.Count == 0 || m.guids.Any(string.IsNullOrWhiteSpace) || m.namespaces.Any(string.IsNullOrWhiteSpace)) { throw new InvalidDataException("Missing or invalid module identity."); } if (m.codeAssembly.Length != 0 && (!Regex.IsMatch(m.codeAssembly, "\\A[A-Za-z0-9_.-]+\\z") || m.codeAssembly == m.assembly)) { throw new InvalidDataException("codeAssembly must name a distinct helper assembly."); } if (!Version.TryParse(m.version, out Version result) || !Version.TryParse(m.pluginVersion, out result)) { throw new InvalidDataException("Package version and BepInPlugin version must both be declared."); } if (m.namespaces.Count == 0 && m.NeedsIlAdapters) { throw new InvalidDataException("Scoped adapters need plugin namespaces."); } if (!new HashSet<string>(m.words.Keys).SetEquals(m.englishWords.Keys)) { throw new InvalidDataException("English/Russian localization keys differ."); } if (m.replaceNative.Any((string key) => key == null || !m.words.ContainsKey(key)) || m.replaceNative.Distinct().Count() != m.replaceNative.Count) { throw new InvalidDataException("A replaceNative key is not one of the module's words."); } if (m.terms.Any((KeyValuePair<string, Dictionary<string, string>> t) => !Regex.IsMatch(t.Key, "\\A[A-Za-z0-9_]+\\z") || t.Value == null || t.Value.Count == 0)) { throw new InvalidDataException("Invalid term vocabulary."); } foreach (Dictionary<string, string> item in new Dictionary<string, string>[5] { m.words, m.englishWords, m.texts, m.mapLabels, m.rawTexts }.Concat(m.terms.Values)) { if (item.Any((KeyValuePair<string, string> p) => string.IsNullOrEmpty(p.Key) || string.IsNullOrEmpty(p.Value))) { throw new InvalidDataException("Empty translation key/value."); } } foreach (KeyValuePair<string, string> nameAlias in m.nameAliases) { Match match = IdolName.Match(nameAlias.Key); if (m.id != "Valheim" || m.assembly != "assembly_valheim" || !m.guids.SequenceEqual(new string[1] { "valheim" }) || !match.Success) { throw new InvalidDataException("Invalid native idol name alias."); } string text = "tolmach_idol_" + match.Groups[1].Value + "_" + match.Groups[2].Value; if (nameAlias.Value != "$" + text || !m.words.ContainsKey(text) || !m.englishWords.ContainsKey(text) || m.rawTexts.ContainsKey(nameAlias.Key)) { throw new InvalidDataException("Invalid native idol name alias."); } if (Regex.IsMatch(m.words[text] + m.englishWords[text], "[$<>{}]") || m.replaceNative.Contains(text)) { throw new InvalidDataException("An idol name alias needs plain full-name words."); } } foreach (PatternSpec pattern in m.patterns) { ValidatePattern(m, pattern, "text", "message", "mapLabel", "item", "itemSet"); } foreach (PatternSpec rawPattern in m.rawPatterns) { ValidatePattern(m, rawPattern, "text"); if (Hole.Replace(rawPattern.source, "").Trim().Length == 0) { throw new InvalidDataException("Raw pattern has no fixed text."); } } foreach (MethodSpec @return in m.returns) { if (@return == null || string.IsNullOrEmpty(@return.type) || string.IsNullOrEmpty(@return.method)) { throw new InvalidDataException("Invalid return adapter."); } } foreach (ComposedSpec item2 in m.composed) { ValidateComposed(m, item2); } foreach (LiteralSpec item3 in m.literals.Concat(m.configTexts)) { if (item3 == null || string.IsNullOrEmpty(item3.type) || string.IsNullOrEmpty(item3.method) || item3.values.Count == 0 || item3.values.Any((KeyValuePair<string, string> p) => string.IsNullOrEmpty(p.Key) || string.IsNullOrEmpty(p.Value))) { throw new InvalidDataException("Invalid literal or config text adapter."); } } foreach (PrefabSpec prefab in m.prefabs) { if (prefab == null || prefab.fields.Values.Any(string.IsNullOrEmpty)) { throw new InvalidDataException("Invalid display fallback."); } } if (m.cllc != null) { ValidateCllc(m.cllc); } } private static void ValidateCllc(CllcLanguage t) { if (!t.creatureGender.ContainsKey("default") || t.creatureGender.Values.Any((string g) => g == null || !t.genderedCreatureTranslations.ContainsKey(g))) { throw new InvalidDataException("Every CLLC gender, including the default one, needs a nameplate template."); } foreach (string value in t.genderedCreatureTranslations.Values) { if (value == null || !CllcNameplate.IsMatch(value)) { throw new InvalidDataException("Invalid CLLC nameplate template: " + value); } } if (t.genderedTranslations.Any((KeyValuePair<string, Dictionary<string, string>> g) => g.Value == null || !t.genderedCreatureTranslations.ContainsKey(g.Key))) { throw new InvalidDataException("CLLC gendered words for a gender without a template."); } foreach (Dictionary<string, string> item in new Dictionary<string, string>[4] { t.creatureGender, t.genderedCreatureTranslations, t.translations, t.settingGroups }.Concat(t.genderedTranslations.Values).Concat(t.enumTranslations.Values)) { if (item == null || item.Any((KeyValuePair<string, string> p) => string.IsNullOrEmpty(p.Key) || string.IsNullOrEmpty(p.Value))) { throw new InvalidDataException("Empty CLLC key/value."); } } if (t.settings.Any((KeyValuePair<string, CllcSetting> p) => string.IsNullOrEmpty(p.Key) || p.Value == null || string.IsNullOrEmpty(p.Value.display) || string.IsNullOrEmpty(p.Value.desc))) { throw new InvalidDataException("A CLLC setting needs a name and a description."); } } private static void ValidateComposed(Module m, ComposedSpec c) { if (c == null || (c.sites.Count == 0 && c.containerOwners.Count == 0) || (c.texts.Count == 0 && c.patterns.Count == 0) || c.sites.Any((MethodSpec s) => s == null || string.IsNullOrEmpty(s.type) || string.IsNullOrEmpty(s.method)) || c.containerOwners.Any(string.IsNullOrEmpty) || c.items.Any(string.IsNullOrEmpty) || c.texts.Any((KeyValuePair<string, string> p) => string.IsNullOrEmpty(p.Key) || string.IsNullOrEmpty(p.Value))) { throw new InvalidDataException("Invalid composed text rule."); } if (c.texts.Any((KeyValuePair<string, string> p) => m.texts.TryGetValue(p.Key, out var existing) && existing != p.Value)) { throw new InvalidDataException("A composed text differs from the module's text."); } bool flag = c.containerOwners.Count != 0 || c.sites.Any((MethodSpec s) => !m.OwnTypeName(s.type)); if (c.items.Count != 0 && (c.containerOwners.Count != 0 || c.sites.Any((MethodSpec s) => m.OwnTypeName(s.type)))) { throw new InvalidDataException("A composed item filter needs game sites only."); } foreach (PatternSpec pattern in c.patterns) { ValidatePattern(m, pattern, "text", "message", "mapLabel", "item", "itemSet", "name"); if (flag && Hole.Replace(pattern.source, "").Trim().Length == 0) { throw new InvalidDataException("A composed pattern at a game site or container has no fixed text."); } } } private static void ValidatePattern(Module m, PatternSpec p, params string[] semantics) { if (p == null || string.IsNullOrEmpty(p.source) || string.IsNullOrEmpty(p.target)) { throw new InvalidDataException("Invalid pattern."); } if (p.singleLine && (p.source.IndexOfAny(new char[2] { '\r', '\n' }) >= 0 || p.target.IndexOfAny(new char[2] { '\r', '\n' }) >= 0)) { throw new InvalidDataException("A single-line pattern cannot contain line breaks."); } HashSet<string> holes = new HashSet<string>(from Match h in Hole.Matches(p.source) select h.Groups[1].Value); if (!holes.SetEquals(from Match h in Hole.Matches(p.target) select h.Groups[1].Value)) { throw new InvalidDataException("Pattern placeholders differ."); } if (p.numeric.Any((int n) => !holes.Contains(n.ToString(CultureInfo.InvariantCulture)))) { throw new InvalidDataException("Numeric argument has no source placeholder."); } foreach (KeyValuePair<string, string> argument in p.arguments) { bool flag = argument.Value != null && (Array.IndexOf(semantics, argument.Value) >= 0 || (argument.Value.StartsWith("term:", StringComparison.Ordinal) && m.terms.ContainsKey(argument.Value.Substring(5)))); if (!holes.Contains(argument.Key) || !flag || p.numeric.Contains(int.Parse(argument.Key, CultureInfo.InvariantCulture))) { throw new InvalidDataException("Unknown or conflicting semantic argument."); } } } internal static PluginIdentity GameIdentity(Type versionType) { object instanceOrType = ((versionType == null) ? null : RuntimeAccess.Read(versionType, "CurrentVersion")); object obj = RuntimeAccess.Read(instanceOrType, "m_major"); object obj2 = RuntimeAccess.Read(instanceOrType, "m_minor"); object obj3 = RuntimeAccess.Read(instanceOrType, "m_patch"); if (!(obj is int) || !(obj2 is int) || !(obj3 is int) || (int)obj < 0 || (int)obj2 < 0 || (int)obj3 < 0) { return null; } return new PluginIdentity("valheim", versionType.Assembly, new Version((int)obj, (int)obj2, (int)obj3)); } internal static bool SameVersion(Version expected, Version actual) { if (expected == null || actual == null) { return false; } if (expected.Major == actual.Major && expected.Minor == actual.Minor && Math.Max(0, expected.Build) == Math.Max(0, actual.Build)) { return Math.Max(0, expected.Revision) == Math.Max(0, actual.Revision); } return false; } internal static bool TryBind(Module module, Func<string, PluginIdentity> lookup, bool onlyAuditedVersions, out string reason) { return TryBind(module, lookup, onlyAuditedVersions, (Assembly assembly) => assembly.GetReferencedAssemblies(), () => AppDomain.CurrentDomain.GetAssemblies(), out reason); } internal static bool TryBind(Module module, Func<string, PluginIdentity> lookup, bool onlyAuditedVersions, Func<Assembly, IEnumerable<AssemblyName>> references, Func<IEnumerable<Assembly>> loadedAssemblies, out string reason) { module.RuntimeAssembly = null; module.RuntimeCodeAssembly = null; module.Table = null; module.ExactVersion = false; module.UiAllowed = false; PluginIdentity pluginIdentity = null; foreach (string guid in module.guids) { pluginIdentity = lookup(guid); if (pluginIdentity != null) { break; } } if (pluginIdentity == null || pluginIdentity.Assembly == null) { reason = "not installed/loaded"; return false; } if (!module.guids.Contains(pluginIdentity.Guid) || pluginIdentity.Assembly.GetName().Name != module.assembly) { reason = "GUID/assembly identity mismatch; skipped"; return false; } module.RuntimeAssembly = pluginIdentity.Assembly; module.ExactVersion = SameVersion(new Version(module.pluginVersion), pluginIdentity.Version); module.UiAllowed = module.ExactVersion || !onlyAuditedVersions; if (module.codeAssembly.Length != 0) { string text = null; try { AssemblyName[] direct = (from name in references(pluginIdentity.Assembly) where name.Name == module.codeAssembly select name).ToArray(); if (direct.Length != 1) { text = "helper is not a unique direct plugin reference"; } else { Assembly[] array = (from assembly in loadedAssemblies() where assembly.GetName().FullName == direct[0].FullName select assembly).ToArray(); if (array.Length != 1) { text = "helper exact identity is not uniquely loaded"; } else { module.RuntimeCodeAssembly = array[0]; } } } catch (Exception ex) { text = "helper resolution failed: " + ex.GetType().Name; } if (text != null) { module.UiAllowed = false; module.Warn("Scoped display helper " + module.codeAssembly + " unavailable: " + text + "; native dictionaries only."); } } if (!module.ExactVersion) { module.Warn("Expected plugin " + module.pluginVersion + " (package " + module.version + "), loaded " + pluginIdentity.Version?.ToString() + "."); } module.Table = new TextTable(module); reason = ((!module.UiAllowed && module.codeAssembly.Length != 0 && module.RuntimeCodeAssembly == null) ? "native dictionaries only; display helper unavailable" : (module.ExactVersion ? "loaded" : (module.UiAllowed ? "loaded; different plugin version, adapters apply where the catalog strings are found" : "native dictionaries only; different plugin version"))); return true; } } internal static class CcsDisplay { private sealed class Reason { internal string Prefix; internal string Message; } private sealed class CaptureContext { internal CaptureContext Previous; internal Module Owner; internal object Before; internal object Published; internal Dictionary<string, Reason> Lines; internal bool Invalid; } [ThreadStatic] private static CaptureContext context; private static readonly object Gate = new object(); private static Dictionary<string, Reason> lines = new Dictionary<string, Reason>(StringComparer.Ordinal); private static readonly HashSet<string> Headers = new HashSet<string>(StringComparer.Ordinal) { "Conditional Config Sync rejected this connection.", "The following synchronization checks failed:", "A missing handshake can mean that the mod is missing or disabled, an older pre-CCS build is installed, Conditional Config Sync did not load, or duplicate or outdated DLL files are present.", "Check that the listed mods and Conditional Config Sync are installed, enabled, and up to date. Remove duplicate or outdated DLL files, then fully restart the game.", "The server rejected the connection because a required synchronization check failed, but no detailed reason was provided." }; private static Module owner; private static FieldInfo modName; private static FieldInfo message; private static FieldInfo pendingField; private static FieldInfo reportMessage; private static object boundReport; private static string boundMessage; internal static void Install(Harmony harmony, Module module) { //IL_041e: Unknown result type (might be due to invalid IL or missing references) //IL_0423: Unknown result type (might be due to invalid IL or missing references) //IL_0447: Unknown result type (might be due to invalid IL or missing references) //IL_044c: Unknown result type (might be due to invalid IL or missing references) //IL_046d: Unknown result type (might be due to invalid IL or missing references) //IL_0472: Unknown result type (might be due to invalid IL or missing references) //IL_047f: Expected O, but got Unknown //IL_047f: Expected O, but got Unknown //IL_047f: Expected O, but got Unknown //IL_049d: Unknown result type (might be due to invalid IL or missing references) //IL_04a2: Unknown result type (might be due to invalid IL or missing references) //IL_04b1: Expected O, but got Unknown if (module.id != "ConditionalConfigSync") { return; } Reset(); if (!module.UiAllowed || module.RuntimeCodeAssembly == null || module.codeAssembly != "ConditionalConfigSync") { return; } try { Type type = module.RuntimeCodeAssembly.GetType("ConditionalConfigSync.VersionCheck", throwOnError: false); Type type2 = ((type == null) ? null : type.GetNestedType("DisconnectReasonItem", BindingFlags.NonPublic)); Type type3 = ((type == null) ? null : type.GetNestedType("PendingDisconnectReport", BindingFlags.NonPublic)); FieldInfo fieldInfo = ((type2 == null) ? null : type2.GetField("ModName", AccessTools.allDeclared)); FieldInfo fieldInfo2 = ((type2 == null) ? null : type2.GetField("Message", AccessTools.allDeclared)); MethodInfo methodInfo = ((type == null) ? null : type.GetMethods(AccessTools.allDeclared).SingleOrDefault((MethodInfo m) => m.Name == "NormalizeDisconnectReasons")); FieldInfo fieldInfo3 = ((type == null) ? null : type.GetField("pendingDisconnectReport", AccessTools.allDeclared)); FieldInfo fieldInfo4 = ((type3 == null) ? null : type3.GetField("Message", AccessTools.allDeclared)); MethodInfo methodInfo2 = ((type == null) ? null : type.GetMethods(AccessTools.allDeclared).SingleOrDefault((MethodInfo m) => m.Name == "SetPendingDisconnectReport")); if (type2 == null || fieldInfo == null || fieldInfo2 == null || fieldInfo.IsStatic || fieldInfo2.IsStatic || !module.OwnType(type) || fieldInfo.FieldType != typeof(string) || fieldInfo2.FieldType != typeof(string) || methodInfo == null || !methodInfo.IsStatic || methodInfo.ContainsGenericParameters || methodInfo.ReturnType != type2.MakeArrayType() || methodInfo.GetParameters().Length != 1 || methodInfo.GetParameters()[0].ParameterType != typeof(IEnumerable<>).MakeGenericType(type2) || !RuntimeAccess.ManagedBody(methodInfo) || DisplayPatches.UnsupportedHandler(methodInfo) != null || type3 == null || fieldInfo3 == null || !fieldInfo3.IsStatic || fieldInfo3.FieldType != type3 || fieldInfo4 == null || fieldInfo4.IsStatic || fieldInfo4.FieldType != typeof(string) || methodInfo2 == null || !methodInfo2.IsStatic || methodInfo2.ContainsGenericParameters || methodInfo2.ReturnType != typeof(void) || !(from p in methodInfo2.GetParameters() select p.ParameterType).SequenceEqual(new Type[3] { typeof(long), typeof(string), typeof(IEnumerable<>).MakeGenericType(type2) }) || !RuntimeAccess.ManagedBody(methodInfo2) || DisplayPatches.UnsupportedHandler(methodInfo2) != null) { throw new MissingMethodException("Structured setter, normalized reasons or pending report shape differs."); } lock (Gate) { owner = module; modName = fieldInfo; message = fieldInfo2; pendingField = fieldInfo3; reportMessage = fieldInfo4; } harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(CcsDisplay).GetMethod("Begin", AccessTools.all)) { priority = 800 }, new HarmonyMethod(typeof(CcsDisplay).GetMethod("Bind", AccessTools.all)) { priority = 0 }, (HarmonyMethod)null, new HarmonyMethod(typeof(CcsDisplay).GetMethod("Finish", AccessTools.all)) { priority = 0 }, (HarmonyMethod)null); harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(CcsDisplay).GetMethod("Capture", AccessTools.all)) { priority = 0 }, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } catch (Exception ex) { Reset(); module.Warn("CCS structured rejection display unavailable: " + ex.GetType().Name + "; unstructured reasons stay unchanged."); } } private static void Begin(ref CaptureContext __state) { lock (Gate) { __state = new CaptureContext { Previous = context, Owner = owner }; context = __state; if (owner == null) { return; } try { __state.Before = pendingField.GetValue(null); } catch (Exception ex) { __state.Invalid = true; owner.Warn("CCS report context skipped: " + ex.GetType().Name); } } } private static void Capture(object __result) { lock (Gate) { CaptureContext captureContext = context; if (owner == null || captureContext == null || captureContext.Owner != owner) { return; } if (captureContext.Lines != null) { captureContext.Invalid = true; return; } try { captureContext.Lines = new Dictionary<string, Reason>(StringComparer.Ordinal); if (!(__result is Array { Rank: 1, Length: <=1024 } array)) { throw new InvalidOperationException("Normalized reason array is unavailable or exceeds the display bound."); } foreach (object item in array) { if (item == null) { continue; } string text = modName.GetValue(item) as string; string text2 = message.GetValue(item) as string; if (text == null || text2 == null || (text + text2).IndexOfAny(new char[2] { '\r', '\n' }) >= 0) { throw new InvalidOperationException("Reason fields are not normalized single-line strings."); } string text3 = "- " + (string.IsNullOrWhiteSpace(text) ? "" : (text + ": ")); string text4 = text3 + text2; if (text4.Length > 4096) { throw new InvalidOperationException("Reason line exceeds the display bound."); } if (captureContext.Lines.TryGetValue(text4, out var value)) { if (value == null || value.Prefix != text3 || value.Message != text2) { captureContext.Lines[text4] = null; } } else { captureContext.Lines.Add(text4, new Reason { Prefix = text3, Message = text2 }); } } } catch (Exception ex) { captureContext.Invalid = true; owner.Warn("CCS normalized rejection metadata skipped: " + ex.GetType().Name); } } } private static void Bind(CaptureContext __state) { lock (Gate) { if (__state == null || __state.Invalid || __state.Lines == null || owner == null || __state.Owner != owner) { return; } try { object value = pendingField.GetValue(null); if (value != null && value != __state.Before) { if (!(reportMessage.GetValue(value) is string text)) { throw new InvalidOperationException("Pending report text is unavailable."); } HashSet<string> present = new HashSet<string>(text.Replace("\r", "").Split(new char[1] { '\n' }), StringComparer.Ordinal); lines = __state.Lines.Where((KeyValuePair<string, Reason> p) => present.Contains(p.Key)).ToDictionary<KeyValuePair<string, Reason>, string, Reason>((KeyValuePair<string, Reason> p) => p.Key, (KeyValuePair<string, Reason> p) => p.Value, StringComparer.Ordinal); boundReport = (__state.Published = value); boundMessage = text; } } catch (Exception ex) { __state.Invalid = true; owner.Warn("CCS report binding skipped: " + ex.GetType().Name); } } } private static Exception Finish(Exception __exception, CaptureContext __state) { lock (Gate) { if (__state != null && (__exception != null || __state.Invalid) && boundReport == __state.Published) { lines.Clear(); boundReport = null; boundMessage = null; } context = ((__state != null && context == __state) ? __state.Previous : null); return __exception; } } internal static string Translate(Module module, string text) { if (!module.UiAllowed || module.RuntimeCodeAssembly == null) { return text; } return TextTable.TranslateRaw(text, delegate(string value) { bool flag = value.EndsWith("\r", StringComparison.Ordinal); string text2 = (flag ? value.Substring(0, value.Length - 1) : value); string text3 = text2; lock (Gate) { if (owner == module && module.UiAllowed && module.RuntimeCodeAssembly != null && boundReport != null && boundReport == pendingField.GetValue(null) && boundMessage == reportMessage.GetValue(boundReport) as string && lines.TryGetValue(text2, out var value2) && value2 != null) { text3 = value2.Prefix + module.Table.Translate(value2.Message); } else if (Headers.Contains(text2)) { text3 = module.Table.TranslateWhole(text2); } } return text3 + (flag ? "\r" : ""); }, splitMarkup: false); } internal static void Reset() { lock (Gate) { lines.Clear(); owner = null; modName = (message = (pendingField = (reportMessage = null))); boundReport = null; boundMessage = null; context = null; } } } internal static class CllcAdapter { private const string WrapperType = "CreatureLevelControl.LocalizationWrapper"; private const string AttributesType = "CreatureLevelControl.ConfigurationManagerAttributes"; private static readonly string[] Tables = new string[7] { "creatureGender", "genderedCreatureTranslations", "genderedTranslations", "translations", "enumTranslations", "settingGroups", "settings" }; private static readonly Regex Placeholder = new Regex("\\{[^{}]+\\}", RegexOptions.CultureInvariant); private static readonly Regex GroupNumber = new Regex("\\A\\d+ - ", RegexOptions.CultureInvariant); internal static void Refresh(Module m) { if (m.cllc == null) { return; } ConfigFile config = null; foreach (string guid in m.guids) { if (Chainloader.PluginInfos.TryGetValue(guid, out var value) && (Object)(object)value.Instance != (Object)null) { config = value.Instance.Config; break; } } Apply(m, config); } internal static void Apply(Module m, ConfigFile config) { if (m.cllc == null || m.RuntimeAssembly == null || !TextEngine.IsRussian) { return; } Type wrapper = m.RuntimeAssembly.GetType("CreatureLevelControl.LocalizationWrapper"); FieldInfo fieldInfo = ((wrapper == null) ? null : AccessTools.Field(wrapper, "instance")); FieldInfo fieldInfo2 = ((wrapper == null) ? null : AccessTools.Field(wrapper, "language")); object obj = ((wrapper == null) ? null : RuntimeAccess.Read(wrapper, "English")); object obj2 = ((fieldInfo == null || !fieldInfo.IsStatic) ? null : fieldInfo.GetValue(null)); if (obj2 == null || obj == null || fieldInfo2 == null || fieldInfo2.IsStatic || Tables.Any(delegate(string name) { FieldInfo fieldInfo3 = AccessTools.Field(wrapper, name); return fieldInfo3 == null || fieldInfo3.IsStatic || !typeof(IDictionary).IsAssignableFrom(fieldInfo3.FieldType); })) { m.Warn("CLLC LocalizationWrapper API not found; the mod keeps its own texts."); return; } object obj3 = obj2; if (fieldInfo2.GetValue(obj2) as string != "Russian") { obj3 = Activator.CreateInstance(wrapper, nonPublic: true); fieldInfo2.SetValue(obj3, "Russian"); } m.NativeWords += Fill(obj3, obj, m); if (obj3 != obj2) { fieldInfo.SetValue(null, obj3); } if (config != null) { Relabel(m, wrapper, obj, config); } } private static int Fill(object table, object english, Module m) { CllcLanguage cllc = m.cllc; int num = 0; int unknown = 0; IDictionary dictionary = Dictionary(table, "genderedCreatureTranslations", create: true); if (dictionary.Count == 0) { IDictionary dictionary2 = Dictionary(table, "creatureGender", create: true); IDictionary dictionary3 = Dictionary(table, "genderedTranslations", create: true); foreach (KeyValuePair<string, string> item in cllc.creatureGender) { dictionary2[item.Key] = item.Value; } foreach (KeyValuePair<string, string> genderedCreatureTranslation in cllc.genderedCreatureTranslations) { dictionary[genderedCreatureTranslation.Key] = genderedCreatureTranslation.Value; } foreach (KeyValuePair<string, Dictionary<string, string>> genderedTranslation in cllc.genderedTranslations) { dictionary3[genderedTranslation.Key] = new Dictionary<string, string>(genderedTranslation.Value); } num += cllc.creatureGender.Count + cllc.genderedCreatureTranslations.Count + cllc.genderedTranslations.Values.Sum((Dictionary<string, string> f) => f.Count); } num += FillWords(Dictionary(table, "translations", create: true), Dictionary(english, "translations", create: false), cllc.translations, placeholders: true, m, ref unknown); num += FillWords(Dictionary(table, "settingGroups", create: true), Dictionary(english, "settingGroups", create: false), cllc.settingGroups, placeholders: false, m, ref unknown); IDictionary dictionary4 = Dictionary(table, "enumTranslations", create: true); IDictionary dictionary5 = Dictionary(english, "enumTranslations", create: false); foreach (KeyValuePair<string, Dictionary<string, string>> enumTranslation in cllc.enumTranslations) { if (!(dictionary5[enumTranslation.Key] is IDictionary dictionary6)) { unknown += enumTranslation.Value.Count; continue; } IDictionary dictionary7 = dictionary4[enumTranslation.Key] as IDictionary; if (dictionary7 == null) { dictionary7 = new Dictionary<string, string>(); dictionary4[enumTranslation.Key] = dictionary7; } foreach (KeyValuePair<string, string> item2 in enumTranslation.Value) { string english2 = (dictionary6[item2.Key] as string) ?? item2.Key; if (LocalizationBridge.ShouldFill(dictionary7[item2.Key] as string, english2, item2.Key)) { dictionary7[item2.Key] = item2.Value; num++; } } } num += FillSettings(Dictionary(table, "settings", create: true), Dictionary(english, "settings", create: false), cllc.settings, m, ref unknown); if (unknown != 0) { m.Warn(unknown + " CLLC catalog entries are unknown to the installed version and were skipped."); } return num; } private static int FillWords(IDictionary target, IDictionary english, Dictionary<string, string> ours, bool placeholders, Module m, ref int unknown) { int num = 0; foreach (KeyValuePair<string, string> our in ours) { if (!(english[our.Key] is string english2)) { unknown++; } else if (placeholders && !SamePlaceholders(english2, our.Value)) { m.Warn("CLLC entry skipped, placeholders differ from English: " + our.Key); } else if (LocalizationBridge.ShouldFill(target[our.Key] as string, english2, our.Key)) { target[our.Key] = our.Value; num++; } } return num; } private static int FillSettings(IDictionary target, IDictionary english, Dictionary<string, CllcSetting> ours, Module m, ref int unknown) { Type type = target.GetType().GetGenericArguments()[1]; FieldInfo fieldInfo = AccessTools.Field(type, "display"); FieldInfo fieldInfo2 = AccessTools.Field(type, "desc"); if (fieldInfo == null || fieldInfo2 == null) { m.Warn("CLLC SettingTexts fields not found; setting texts are not filled."); return 0; } int num = 0; foreach (KeyValuePair<string, CllcSetting> our in ours) { object obj = english[our.Key]; if (obj == null) { unknown++; continue; } string english2 = (fieldInfo.GetValue(obj) as string) ?? our.Key; string english3 = (fieldInfo2.GetValue(obj) as string) ?? ""; if (!SamePlaceholders(english2, our.Value.display) || !SamePlaceholders(english3, our.Value.desc)) { m.Warn("CLLC setting skipped, placeholders differ from English: " + our.Key); continue; } object obj2 = target[our.Key]; bool flag = LocalizationBridge.ShouldFill((obj2 == null) ? null : (fieldInfo.GetValue(obj2) as string), english2, our.Key); bool flag2 = LocalizationBridge.ShouldFill((obj2 == null) ? null : (fieldInfo2.GetValue(obj2) as string), english3, our.Key); if (flag || flag2) { object obj3 = obj2 ?? Activator.CreateInstance(type); if (obj3 == obj) { obj3 = AccessTools.Method(typeof(object), "MemberwiseClone", (Type[])null, (Type[])null).Invoke(obj3, null); } if (flag) { fieldInfo.SetValue(obj3, our.Value.display); } if (flag2) { fieldInfo2.SetValue(obj3, our.Value.desc); } target[our.Key] = obj3; num++; } } return num; } private static void Relabel(Module m, Type wrapper, object english, ConfigFile config) { MethodInfo methodInfo = AccessTools.Method(wrapper, "getSettingGroupTranslation", new Type[1] { typeof(string) }, (Type[])null); MethodInfo methodInfo2 = AccessTools.Method(wrapper, "getSettingTranslation", new Type[1] { typeof(string) }, (Type[])null); MethodInfo methodInfo3 = AccessTools.Method(wrapper, "getTranslation", new Type[1] { typeof(string) }, (Type[])null); Type attributes = m.RuntimeAssembly.GetType("CreatureLevelControl.ConfigurationManagerAttributes"); FieldInfo fieldInfo = ((methodInfo2 == null) ? null : AccessTools.Field(methodInfo2.ReturnType, "display")); FieldInfo fieldInfo2 = ((methodInfo2 == null) ? null : AccessTools.Field(methodInfo2.ReturnType, "desc")); FieldInfo fieldInfo3 = ((attributes == null) ? null : AccessTools.Field(attributes, "Category")); FieldInfo fieldInfo4 = ((attributes == null) ? null : AccessTools.Field(attributes, "DispName")); FieldInfo fieldInfo5 = ((attributes == null) ? null : AccessTools.Field(attributes, "Description")); if (methodInfo == null || methodInfo2 == null || methodInfo3 == null || fieldInfo == null || fieldInfo2 == null || fieldInfo3 == null || fieldInfo4 == null || fieldInfo5 == null) { m.Warn("CLLC setting lookups not found; the config window keeps the texts the mod bound."); return; } IDictionary dictionary = Dictionary(english, "settings", create: false); List<KeyValuePair<string, Regex>> list = new List<KeyValuePair<string, Regex>>(); foreach (object key in dictionary.Keys) { string text = key as string; Match match = ((text == null) ? Match.Empty : Placeholder.Match(text)); if (match.Success) { list.Add(new KeyValuePair<string, Regex>(text, new Regex("\\A" + Regex.Escape(text.Substring(0, match.Index)) + "(.+?)" + Regex.Escape(text.Substring(match.Index + match.Length)) + "\\z", RegexOptions.CultureInvariant))); } } int num = 0; foreach (KeyValuePair<ConfigDefinition, ConfigEntryBase> item in config) { object[] array = ((item.Value == null || item.Value.Description == null) ? null : item.Value.Description.Tags); if (array == null || !array.Any((object tag) => tag != null && tag.GetType() == attributes)) { continue; } string text2 = null; string text3 = null; if (dictionary.Contains(item.Key.Key)) { text2 = item.Key.Key; } else { foreach (KeyValuePair<string, Regex> item2 in list) { Match match2 = item2.Value.Match(item.Key.Key); if (match2.Success) { text2 = item2.Key; text3 = match2.Groups[1].Value; break; } } } if (text2 == null) { continue; } try { string value = GroupNumber.Match(item.Key.Section).Value; string value2 = value + (string)methodInfo.Invoke(null, new object[1] { item.Key.Section.Substring(value.Length) }); object obj = methodInfo2.Invoke(null, new object[1] { text2 }); string text4 = (fieldInfo.GetValue(obj) as string) ?? text2; string text5 = fieldInfo2.GetValue(obj) as string; if (text3 != null) { string value3 = Placeholder.Match(text2).Value; string newValue = (string)methodInfo3.Invoke(null, new object[1] { text3 }); text4 = text4.Replace(value3, newValue); if (text5 != null) { text5 = text5.Replace(value3, newValue); } } object[] array2 = array; foreach (object obj2 in array2) { if (obj2 != null && !(obj2.GetType() != attributes)) { if (fieldInfo3.GetValue(obj2) != null) { fieldInfo3.SetValue(obj2, value2); } if (fieldInfo4.GetValue(obj2) != null) { fieldInfo4.SetValue(obj2, text4); } if (fieldInfo5.GetValue(obj2) != null && text5 != null) { fieldInfo5.SetValue(obj2, text5); } } } } catch (TargetInvocationException) { num++; } } if (num != 0) { m.Warn(num + " CLLC config entries kept their texts: the mod's lookup failed."); } } private static IDictionary Dictionary(object owner, string name, bool create) { FieldInfo fieldInfo = AccessTools.Field(owner.GetType(), name); IDictionary dictionary = fieldInfo.GetValue(owner) as IDictionary; if (dictionary == null && create) { dictionary = (IDictionary)Activator.CreateInstance(fieldInfo.FieldType); fieldInfo.SetValue(owner, dictionary); } return dictionary ?? new Hashtable(); } private static bool SamePlaceholders(string english, string russian) { return new HashSet<string>(from Match p in Placeholder.Matches(english) select p.Value).SetEquals(from Match p in Placeholder.Matches(russian ?? "") select p.Value); } } internal static class ComposedNames { private sealed class Site { public Module Module; public TextTable Table; public HashSet<string> Items; } private static readonly Dictionary<string, List<Site>> Sites = new Dictionary<string, List<Site>>(StringComparer.Ordinal); private static readonly HashSet<string> PatchedGameSites = new HashSet<string>(StringComparer.Ordinal); internal static void Reset() { Sites.Clear(); PatchedGameSites.Clear(); } internal static TextTable OwnTable(Module m, ComposedSpec c) { Dictionary<string, string> dictionary = new Dictionary<string, string>(m.texts, StringComparer.Ordinal); foreach (KeyValuePair<string, string> text in c.texts) { dictionary[text.Key] = text.Value; } return new TextTable(dictionary, m.patterns.Concat(c.patterns), m.mapLabels, m.terms); } internal static TextTable SharedTable(Module m, ComposedSpec c) { return new TextTable(c.texts, c.patterns, new Dictionary<string, string>(), m.terms); } internal static string RegisterOwn(Module m, Type type, MethodBase method) { string text = null; foreach (ComposedSpec item in m.composed) { foreach (MethodSpec site in item.sites) { if (!(site.type != type.FullName) && !(site.method != method.Name) && m.OwnTypeName(site.type)) { text = RuntimeAccess.MethodKey(method); Add(text, m, OwnTable(m, item)); } } } return text; } internal static bool IsSite(string key) { if (key != null) { return Sites.ContainsKey(key); } return false; } internal static void InstallGameSites(Harmony harmony, Module m) { if (!m.UiAllowed) { return; } foreach (ComposedSpec item in m.composed) { foreach (MethodSpec s in item.sites) { if (m.OwnTypeName(s.type)) { continue; } Type type = RuntimeAccess.ExactType(s.type); List<MethodInfo> list = new List<MethodInfo>(); try { if (type != null) { list = (from x in AccessTools.GetDeclaredMethods(type) where x.Name == s.method && x.ReturnType == typeof(string) && RuntimeAccess.ManagedBody(x) select x).ToList(); } } catch (Exception ex) { m.Warn("Composed game site skipped " + s.type + "." + s.method + ": " + ex.GetType().Name); continue; } if (list.Count == 0) { m.Warn("Composed game site not found: " + s.type + "." + s.method); continue; } foreach (MethodInfo item2 in list) { PatchGameSite(harmony, m, item, item2); } } } } private static void PatchGameSite(Harmony harmony, Module m, ComposedSpec c, MethodInfo method) { //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_008e: Expected O, but got Unknown string text = RuntimeAccess.MethodKey(method); string text2 = method.DeclaringType.FullName + "." + method.Name; string text3 = text2 + " [composed]"; string text4 = DisplayPatches.UnsupportedHandler(method); if (text4 != null) { m.Warn("Composed game site skipped " + text2 + ": " + text4); return; } if (!PatchedGameSites.Contains(text)) { try { harmony.Patch((MethodBase)method, (HarmonyMethod)null, new HarmonyMethod(typeof(ComposedNames).GetMethod("AfterGameSite", AccessTools.all)) { priority = 0 }, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); PatchedGameSites.Add(text); } catch (Exception ex) { m.Warn("Composed game site skipped " + text2 + ": " + ex.GetType().Name); return; } } Add(text, m, SharedTable(m, c), (c.items.Count == 0) ? null : new HashSet<string>(c.items, StringComparer.Ordinal)); if (!m.Patches.ContainsKey(text3)) { m.ScannedMethods++; m.PatchedMethods++; m.Patches[text3] = new PatchEvidence { method = text3, returnAdapter = true }; } } private static void AfterGameSite(MethodBase __originalMethod, object __instance, object[] __args, ref string __result) { string key = RuntimeAccess.MethodKey(__originalMethod); List<Site> value; string item = ((Sites.TryGetValue(key, out value) && value.Any((Site s) => s.Items != null)) ? ShownItem(__instance, __args) : null); __result = Translate(__result, key, item); } private static string ShownItem(object instance, object[] args) { foreach (object item in new object[1] { instance }.Concat(args ?? new object[0])) { if (item != null && !(AccessTools.Field(item.GetType(), "m_dropPrefab") == null)) { object obj = RuntimeAccess.Read(item, "m_dropPrefab"); return (obj == null) ? null : (RuntimeAccess.Read(obj, "name") as string); } } return null; } private static void Add(string key, Module m, TextTable table, HashSet<string> items = null) { if (!Sites.TryGetValue(key, out var value)) { value = (Sites[key] = new List<Site>()); } value.Add(new Site { Module = m, Table = table, Items = items }); } internal static string Translate(string text, string key, string item = null) { if (!TextEngine.IsRussian || string.IsNullOrEmpty(text) || key == null || !Sites.TryGetValue(key, out var value)) { return text; } foreach (Site item2 in value) { if (item2.Module.UiAllowed && TextEngine.Modules.TryGetValue(item2.Module.id, out var value2) && item2.Module == value2 && (item2.Items == null || (item != null && item2.Items.Contains(item)))) { string text2 = item2.Table.Translate(text); if (text2 != text) { return text2; } } } return text; } } public static class ContainerNameDisplay { private sealed class Rule { public Module Module; public TextTable Table; public Type[] Owners; } private static readonly List<Module> Owners = new List<Module>(); private static readonly List<Rule> Rules = new List<Rule>(); private static FieldInfo nameField; private static MethodInfo getComponent; internal static void Reset() { Owners.Clear(); Rules.Clear(); nameField = null; getComponent = null; } internal static void Install(Harmony harmony, Type containerType) { //IL_03f7: Unknown result type (might be due to invalid IL or missing references) //IL_03fe: Expected O, but got Unknown //IL_0414: Unknown result type (might be due to invalid IL or missing references) //IL_0419: Unknown result type (might be due to invalid IL or missing references) //IL_0429: Expected O, but got Unknown Reset(); Owners.AddRange(TextEngine.Modules.Values.Where((Module m) => m.UiAllowed && m.id.StartsWith("DynamicStorage", StringComparison.Ordinal) && m.rawTexts.Count != 0).OrderBy<Module, string>((Module m) => m.id, StringComparer.Ordinal)); getComponent = ((containerType == null) ? null : AccessTools.Method(containerType, "GetComponent", new Type[1] { typeof(Type) }, (Type[])null)); foreach (Module item in TextEngine.Modules.Values.Where((Module m) => m.UiAllowed).OrderBy<Module, string>((Module m) => m.id, StringComparer.Ordinal)) { foreach (ComposedSpec item2 in item.composed.Where((ComposedSpec c) => c.containerOwners.Count != 0)) { Assembly assembly = item.RuntimeCodeAssembly ?? item.RuntimeAssembly; Type[] owners = item2.containerOwners.Select((string name) => (!(assembly == null)) ? assembly.GetType(name, throwOnError: false) : null).ToArray(); foreach (string item3 in item2.containerOwners.Where((string name, int i) => owners[i] == null)) { item.Warn("Container owner component not found: " + item3 + "; its composed names stay unchanged."); } owners = owners.Where((Type t) => t != null).ToArray(); if (owners.Length != 0) { if (getComponent == null || getComponent.IsStatic) { item.Warn("Container GetComponent unavailable; composed container names stay unchanged."); continue; } Rules.Add(new Rule { Module = item, Table = ComposedNames.SharedTable(item, item2), Owners = owners }); } } } if (Owners.Count == 0 && Rules.Count == 0) { return; } nameField = ((containerType == null) ? null : AccessTools.Field(containerType, "m_name")); if (nameField == null || nameField.IsStatic || nameField.FieldType != typeof(string)) { Warn("Container name field unavailable; original names retained."); return; } nameField = AccessTools.DeclaredField(nameField.DeclaringType, nameField.Name); string[] array = new string[2] { "GetHoverName", "GetHoverText" }; foreach (string text in array) { try { MethodInfo methodInfo = AccessTools.Method(containerType, text, Type.EmptyTypes, (Type[])null); if (methodInfo == null || methodInfo.IsStatic || methodInfo.ReturnType != typeof(string) || !RuntimeAccess.ManagedBody(methodInfo)) { Warn("Container name display target unavailable: " + text); continue; } string text2 = DisplayPatches.UnsupportedHandler(methodInfo); if (text2 != null) { Record(methodInfo, 0, text2); continue; } HarmonyMethod val = new HarmonyMethod(AccessTools.Method(typeof(ContainerNameDisplay), "Transpile", (Type[])null, (Type[])null)); harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(AccessTools.Method(typeof(ContainerNameDisplay), "AfterHover", (Type[])null, (Type[])null)) { priority = 0 }, val, (HarmonyMethod)null, (HarmonyMethod)null); } catch (Exception ex) { Warn("Container name display target " + text + ": " + ex.GetType().Name); } } } private static IEnumerable<CodeInstruction> Transpile(IEnumerable<CodeInstruction> instructions, MethodBase __originalMethod) { List<CodeInstruction> code = new List<CodeInstruction>(instructions); int count = 0; for (int i = 0; i < code.Count; i++) { CodeInstruction instruction = code[i]; yield return instruction; if (i != 0 && !(instruction.opcode != OpCodes.Ldfld) && object.Equals(instruction.operand, nameField) && !(code[i - 1].opcode != OpCodes.Ldarg_0) && instruction.labels.Count == 0 && instruction.blocks.Count == 0 && code[i - 1].blocks.Count == 0) { yield return new CodeInstruction(OpCodes.Ldarg_0, (object)null); yield return new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(ContainerNameDisplay), "Display", (Type[])null, (Type[])null)); count++; } } Record(__originalMethod, count, (count == 0) ? "no safe container name read" : null); } private static void AfterHover(object __instance, ref string __result) { if (!TextEngine.IsRussian || string.IsNullOrEmpty(__result) || nameField == null) { return; } string text = nameField.GetValue(__instance) as string; if (string.IsNullOrEmpty(text) || text.IndexOf('$') >= 0) { return; } string text2 = Display(text, __instance); if (!(text2 == text) && __result.IndexOf(text2, StringComparison.Ordinal) < 0) { int num = __result.IndexOf(text, StringComparison.Ordinal); if (num >= 0) { __result = __result.Substring(0, num) + text2 + __result.Substring(num + text.Length); } } } private static IEnumerable<Module> Modules() { return Owners.Concat(Rules.Select((Rule r) => r.Module)).Distinct(); } private static void Record(MethodBase method, int count, string reason) { string text = method.DeclaringType.FullName + "." + method.Name + " [container name]"; foreach (Module item in Modules()) { if (!item.Patches.TryGetValue(text, out var value)) { item.ScannedMethods++; } if (value != null && value.displayFields > 0) { item.PatchedMethods--; } if (count > 0) { item.PatchedMethods++; } item.Patches[text] = new PatchEvidence { method = text, displayFields = count, notPatched = reason }; } } private static void Warn(string message) { foreach (Module item in Modules()) { item.Warn(message); } } private static bool Active(Module m) { if (m.UiAllowed && TextEngine.Modules.TryGetValue(m.id, out var value)) { return m == value; } return false; } public static string Display(string value, object container) { if (!TextEngine.IsRussian || string.IsNullOrEmpty(value)) { return value; } foreach (Module owner in Owners) { if (Active(owner) && owner.rawTexts.TryGetValue(value, out var value2)) { return value2; } } if (container == null) { return value; } foreach (Rule rule in Rules) { if (Active(rule.Module)) { string value2 = rule.Table.Translate(value); if (value2 != value && Carries(container, rule.Owners)) { return value2; } } } return value; } private static bool Carries(object container, Type[] owners) { foreach (Type type in owners) { object obj; try { obj = getComponent.Invoke(container, new object[1] { type }); } catch (Exception) { return false; } if (obj != null && type.IsInstanceOfType(obj)) { return true; } } return false; } } public static class CreatureNameDisplay { internal const string ModuleId = "HumanoidRandomizer"; private static Module owner; private static TextTable table; private static CreatureNameOwner provenance; private static FieldInfo nameField; private static FieldInfo tameableCharacter; internal static void Reset() { owner = null; table = null; provenance = null; nameField = null; tameableCharacter = null; } internal static void Install(Harmony harmony, Type characterType, Type tameableType = null, Type sceneType = null) { Reset(); if (!TextEngine.Modules.TryGetValue("HumanoidRandomizer", out var value) || !value.UiAllowed || value.rawPatterns.Count == 0) { return; } owner = value; try { nameField = ((characterType == null) ? null : AccessTools.Field(characterType, "m_name")); if (nameField != null) { nameField = AccessTools.DeclaredField(nameField.DeclaringType, nameField.Name); } provenance = new CreatureNameOwner(value, characterType); if (nameField == null || nameField.IsStatic || nameField.FieldType != typeof(string) || !provenance.Available) { value.Warn("Creature-name display API unavailable; variant names are left unchanged. No global name-template fallback is used."); return; } provenance.BindClones(value, characterType, sceneType); table = new TextTable(value.rawTexts, value.rawPatterns, new Dictionary<string, string>(), value.terms); } catch (Exception ex) { value.Warn("Creature-name display initialization: " + ex.GetType().Name + "; original names retained, other adapters remain available."); Reset(); return; } Patch(harmony, characterType, "GetHoverName"); tameableCharacter = ((tameableType == null) ? null : AccessTools.Field(tameableType, "m_character")); if (tameableCharacter == null || tameableCharacter.IsStatic || !nameField.DeclaringType.IsAssignableFrom(tameableCharacter.FieldType)) { value.Warn("Creature-name Tameable API unavailable; tameable default names are left unchanged."); } else { Patch(harmony, tameableType, "GetName"); } } private static void Patch(Harmony harmony, Type type, string methodName) { //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Expected O, but got Unknown try { MethodInfo methodInfo = AccessTools.Method(type, methodName, Type.EmptyTypes, (Type[])null); if (methodInfo == null || methodInfo.IsStatic || methodInfo.ReturnType != typeof(string) || !RuntimeAccess.ManagedBody(methodInfo)) { owner.Warn("Creature-name display target unavailable: " + type.FullName + "." + methodName); return; } string text = DisplayPatches.UnsupportedHandler(methodInfo); if (text != null) { Record(methodInfo, 0, text + "; no global fallback"); owner.Warn("Creature-name display target skipped " + methodName + ": " + text); } else { harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(AccessTools.Method(typeof(CreatureNameDisplay), "Transpile", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null); } } catch (Exception ex) { owner.Warn("Creature-name display target " + methodName + ": " + ex.GetType().Name); } } private static IEnumerable<CodeInstruction> Transpile(IEnumerable<CodeInstruction> instructions, MethodBase __originalMethod) { List<CodeInstruction> code = new List<CodeInstruction>(instructions); int fields = 0; for (int i = 0; i < code.Count; i++) { CodeInstruction instruction = code[i]; yield return instruction; if (i == 0 || instruction.opcode != OpCodes.Ldfld || !object.Equals(instruction.operand, nameField) || instruction.labels.Count != 0 || instruction.blocks.Count != 0 || code[i - 1].blocks.Count != 0) { continue; } bool num = code[i - 1].opcode == OpCodes.Ldarg_0; bool tameable = i >= 2 && code[i - 2].opcode == OpCodes.Ldarg_0 && code[i - 1].opcode == OpCodes.Ldfld && object.Equals(code[i - 1].operand, tameableCharacter) && code[i - 1].labels.Count == 0 && code[i - 2].blocks.Count == 0; if (num || tameable) { yield return new CodeInstruction(OpCodes.Ldarg_0, (object)null); if (tameable) { yield return new CodeInstruction(OpCodes.Ldfld, (object)tameableCharacter); } yield return new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(CreatureNameDisplay), "Display", (Type[])null, (Type[])null)); fields++; } } Record(__originalMethod, fields, (fields == 0) ? "no safe creature-name read; no global fallback" : null); if (owner != null && fields == 0) { owner.Warn("No safe creature-name field read in " + __originalMethod.Name + "; that method was left unchanged."); } } private static void Record(MethodBase method, int fields, string reason) { if (owner != null) { string text = method.DeclaringType.FullName + "." + method.Name + " [creature name]"; if (!owner.Patches.TryGetValue(text, out var value)) { owner.ScannedMethods++; } if (value != null && value.displayFields > 0) { owner.PatchedMethods--; } if (fields > 0) { owner.PatchedMethods++; } owner.Patches[text] = new PatchEvidence { method = text, displayFields = fields, notPatched = reason }; } } public static string Display(string value, object character) { if (!TextEngine.IsRussian || value == null || character == null || owner == null || table == null || !owner.UiAllowed) { return value; } if (!TextEngine.Modules.TryGetValue("HumanoidRandomizer", out var value2) || owner != value2) { return value; } try { string text = table.TranslateWhole(value); return (text != value && provenance.Owns(character)) ? text : value; } catch (Exception ex) { owner.Warn("Creature-name ownership check failed: " + ex.GetType().Name + "; original text retained."); return value; } } } internal sealed class CreatureNameOwner { private readonly Type markerType; private readonly MethodInfo getComponent; private readonly MethodInfo isPlayer; private FieldInfo viewField; private FieldInfo builderField; private FieldInfo prefabsField; private MethodInfo getZdo; private MethodInfo getPrefabId; private MethodInfo sceneInstance; private MethodInfo getPrefab; private bool clonesAvailable; internal bool Available { get { if (markerType != null && getComponent != null && !getComponent.IsStatic && getComponent.ReturnType.IsAssignableFrom(markerType) && isPlayer != null && !isPlayer.IsStatic) { return isPlayer.ReturnType == typeof(bool); } return false; } } internal CreatureNameOwner(Module module, Type characterType) { markerType = ((module.RuntimeAssembly == null) ? null : module.RuntimeAssembly.GetType("BalrondHumanoidRandomizer.HumanoidRandomizer")); getComponent = ((characterType == null) ? null : AccessTools.Method(characterType, "GetComponent", new Type[1] { typeof(Type) }, (Type[])null)); isPlayer = ((characterType == null) ? null : AccessTools.Method(characterType, "IsPlayer", Type.EmptyTypes, (Type[])null)); } internal void BindClones(Module module, Type characterType, Type sceneType) { Type type = module.RuntimeAssembly.GetType("BalrondHumanoidRandomizer.Launch"); builderField = ((type == null) ? null : AccessTools.Field(type, "itemSetBuilder")); prefabsField = ((builderField == null) ? null : AccessTools.Field(builderField.FieldType, "prefabs")); viewField = AccessTools.Field(characterType, "m_nview"); getZdo = ((viewField == null) ? null : AccessTools.Method(viewField.FieldType, "GetZDO", Type.EmptyTypes, (Type[])null)); getPrefabId = ((getZdo == null) ? null : AccessTools.Method(getZdo.ReturnType, "GetPrefab", Type.EmptyTypes, (Type[])null)); sceneInstance = ((sceneType == null) ? null : AccessTools.PropertyGetter(sceneType, "instance")); getPrefab = ((sceneType == null) ? null : AccessTools.Method(sceneType, "GetPrefab", new Type[1] { typeof(int) }, (Type[])null)); clonesAvailable = builderField != null && builderField.IsStatic && prefabsField != null && !prefabsField.IsStatic && typeof(IList).IsAssignableFrom(prefabsField.FieldType) && viewField != null && !viewField.IsStatic && getZdo != null && !getZdo.IsStatic && getPrefabId != null && !getPrefabId.IsStatic && getPrefabId.ReturnType == typeof(int) && sceneInstance != null && sceneInstance.IsStatic && sceneType.IsAssignableFrom(sceneInstance.ReturnType) && getPrefab != null && !getPrefab.IsStatic && !getPrefab.ReturnType.IsValueType; if (!clonesAvailable) { module.Warn("Creature-name prefab ownership API unavailable; unmarked variants are left unchanged."); } } internal bool Owns(object character) { if ((bool)isPlayer.Invoke(character, null)) { return false; } object obj = getComponent.Invoke(character, new object[1] { markerType }); if (obj != null && markerType.IsInstanceOfType(obj)) { return true; } if (!clonesAvailable) { return false; } object value = viewField.GetValue(character); object obj2 = ((value == null) ? null : getZdo.Invoke(value, null)); object obj3 = sceneInstance.Invoke(null, null); if (obj2 == null || obj3 == null) { return false; } object obj4 = getPrefab.Invoke(obj3, new object[1] { getPrefabId.Invoke(obj2, null) }); object value2 = builderField.GetValue(null); IList list = ((value2 == null) ? null : (prefabsField.GetValue(value2) as IList)); if (obj4 == null || list == null) { return false; } foreach (object item in list) { if (obj4 == item) { return true; } } return false; } } internal static class DisplayPatches { private static readonly Dictionary<string, Module> Owners = new Dictionary<string, Module>(); private static readonly MethodInfo Display = typeof(TextEngine).GetMethod("Display"); private static readonly MethodInfo DisplayOwned = typeof(TextEngine).GetMethod("DisplayOwned"); private static readonly MethodInfo DisplaySite = typeof(TextEngine).GetMethod("DisplaySite"); private static readonly MethodInfo DisplayArray = typeof(TextEngine).GetMethod("DisplayArray"); private static readonly MethodInfo Literal = typeof(TextEngine).GetMethod("Literal"); private static readonly MethodInfo ConfigText = typeof(TextEngine).GetMethod("ConfigText"); private static readonly HashSet<string> GuiMethods = new HashSet<string>(new string[9] { "Label", "Button", "RepeatButton", "Toggle", "Box", "Window", "ModalWindow", "Toolbar", "SelectionGrid" }); internal static void Install(Harmony harmony, Module module) { if (!module.NeedsIlAdapters) { return; } if (!module.UiAllowed) { if (module.codeAssembly.Length == 0 || module.RuntimeCodeAssembly != null) { module.Warn("Version differs from snapshot and OnlyAuditedVersions is on; scoped IL/return adapters skipped. Native key adapters remain enabled."); } return; } Assembly assembly = module.RuntimeCodeAssembly ?? module.RuntimeAssembly; if (assembly == null || (module.codeAssembly.Length != 0 && module.RuntimeCodeAssembly == null)) { module.Warn("Scoped code assembly is unavailable; IL/return adapters skipped."); return; } if (!module.ExactVersion) { module.Warn("Version differs from snapshot; adapters apply where the catalog strings are found. Strings not found are listed below and stay in English."); } CcsDisplay.Install(harmony, module); HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal); Type[] typesFromAssembly = AccessTools.GetTypesFromAssembly(assembly); foreach (Type type in typesFromAssembly) { List<MethodBase> list; try { if (!module.OwnType(type) || type.ContainsGenericParameters) { continue; } list = AccessTools.GetDeclaredMethods(type).Cast<MethodBase>().ToList(); list.AddRange(AccessTools.GetDeclaredConstructors(type, (bool?)false).Cast<MethodBase>()); goto IL_0126; } catch (Exception ex) { module.Warn("Type skipped " + type.Name + ": " + ex.GetType().Name); } continue; IL_0126: foreach (MethodBase item in list) { try { InstallMethod(harmony, module, type, item, hashSet); } catch (Exception ex2) { module.Warn("UI adapter skipped " + type.FullName + "." + item.Name + ": " + ex2.GetType().Name); } } } foreach (MethodSpec @return in module.returns) { if (!Declares(module, @return.type, @return.method)) { module.Warn("Expected return adapter not found: " + @return.type + "." + @return.method); } } foreach (MethodSpec ownSite in module.OwnSites) { if (!Declares(module, ownSite.type, ownSite.method)) { module.Warn("Expected composed site not found: " + ownSite.type + "." + ownSite.method); } } foreach (LiteralSpec literal in module.literals) { if (!Declares(module, literal.type, literal.method)) { module.Warn("Expected literal adapter not found: " + literal.type + "." + literal.method); continue; } foreach (string key in literal.values.Keys) { if (!hashSet.Contains(LiteralKey(literal, key))) { module.Warn("Literal not found in IL: " + literal.type + "." + literal.method + " :: " + Shown(key)); } } } foreach (LiteralSpec configText in module.configTexts) { if (!Declares(module, configText.type, configText.method)) { module.Warn("Expected config text adapter not found: " + configText.type + "." + configText.method); } else if (!hashSet.Contains(ConfigKey(configText))) { module.Warn("Config value read not found in IL: " + configText.type + "." + configText.method); } } } private static string LiteralKey(LiteralSpec spec, string value) { return spec.type + "\n" + spec.method + "\n" + value; } private static string ConfigKey(LiteralSpec spec) { return "config\n" + spec.type + "\n" + spec.method; } private static bool ConfigRead(CodeInstruction instruction) { MethodInfo methodInfo = instruction.operand as MethodInfo; if (methodInfo != null && (instruction.opcode == OpCodes.Call || instruction.opcode == OpCodes.Callvirt) && methodInfo.Name == "get_Value" && methodInfo.ReturnType == typeof(string) && methodInfo.DeclaringType != null && methodInfo.DeclaringType.IsGenericType) { return methodInfo.DeclaringType.GetGenericTypeDefinition() == typeof(ConfigEntry<>); } return false; } private static string Shown(string value) { return value.Replace("\r", "\\r").Replace("\n", "\\n").Replace("\t", "\\t"); } private static void InstallMethod(Harmony harmony, Module module, Type type, MethodBase method, HashSet<string> seen) { //IL_043a: Unknown result type (might be due to invalid IL or missing references) //IL_0461: Unknown result type (might be due to invalid IL or missing references) if (!RuntimeAccess.ManagedBody(method)) { return; } module.ScannedMethods++; LiteralSpec[] array = module.literals.Where((LiteralSpec p) => p.type == type.FullName && p.method == method.Name).ToArray(); LiteralSpec[] array2 = module.configTexts.Where((LiteralSpec p) => p.type == type.FullName && p.method == method.Name).ToArray(); MethodInfo methodInfo = method as MethodInfo; string text = ComposedNames.RegisterOwn(module, type, method); bool flag = module.HasDisplayText || text != null; bool flag2 = methodInfo != null && methodInfo.ReturnType == typeof(string) && (text != null || module.returns.Any((MethodSpec p) => p.type == type.FullName && p.method == method.Name)); if (array.Length == 0 && array2.Length == 0 && !flag2 && !flag) { return; } bool flag3 = false; bool flag4 = false; bool flag5 = false; List<CodeInstruction> list = null; try { list = PatchProcessor.GetOriginalInstructions(method, (ILGenerator)null); foreach (CodeInstruction item in list) { string text2 = ((item.opcode == OpCodes.Ldstr) ? (item.operand as string) : null); if (text2 == null) { continue; } LiteralSpec[] array3 = array; foreach (LiteralSpec literalSpec in array3) { if (literalSpec.values.ContainsKey(text2)) { flag3 = true; seen.Add(LiteralKey(literalSpec, text2)); } } } flag4 = flag && list.Any((CodeInstruction instruction) => Relevant(instruction, module, method)); flag5 = array2.Length != 0 && list.Any(ConfigRead); if (flag5) { LiteralSpec[] array3 = array2; foreach (LiteralSpec spec in array3) { seen.Add(ConfigKey(spec)); } } } catch (Exception ex) { module.Warn("IL inspection skipped " + type.Name + "." + method.Name + ": " + ex.GetType().Name); flag3 = array.Length != 0; LiteralSpec[] array3 = array; foreach (LiteralSpec literalSpec2 in array3) { foreach (string key2 in literalSpec2.values.Keys) { seen.Add(LiteralKey(literalSpec2, key2)); } } flag5 = array2.Length != 0; array3 = array2; foreach (LiteralSpec spec2 in array3) { seen.Add(ConfigKey(spec2)); } } if (text != null && !flag2 && !flag4) { module.Warn("Composed site has no display call or string result: " + type.FullName + "." + method.Name); } if (!flag3 && !flag2 && !flag4 && !flag5) { return; } string text3 = UnsupportedHandler(method); if (text3 != null) { string text4 = type.FullName + "." + method.Name; if (flag4) { CallSites.Cover(harmony, module, text4, method, list, text3, text); } if (flag3 || flag5 || flag2) { module.Warn("UI patch skipped " + text4 + ": " + text3); } return; } string key = RuntimeAccess.MethodKey(method); Owners[key] = module; try { HarmonyMethod val = ((!(flag3 || flag4 || flag5)) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(DisplayPatches).GetMethod("Transpile", AccessTools.all))); HarmonyMethod val2 = ((!flag2) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(DisplayPatches).GetMethod("TranslateReturn", AccessTools.all))); if (val != null) { val.priority = 0; } if (val2 != null) { val2.priority = 0; } harmony.Patch(method, (HarmonyMethod)null, val2, val, (HarmonyMethod)null, (HarmonyMethod)null); module.PatchedMethods++; if (!module.Patches.TryGetValue(key, out var value)) { value = new PatchEvidence { method = type.FullName + "." + method.Name }; module.Patches[key] = value; } value.returnAdapter = flag2; } catch (Exception ex2) { module.Warn("UI patch skipped " + type.FullName + "." + method.Name + ": " + ex2.GetType().Name); } } private static bool Declares(Module module, string typeName, string methodName) { try { Type type = (module.RuntimeCodeAssembly ?? module.RuntimeAssembly).GetType(typeName, throwOnError: false); if (type != null && methodName == ".ctor") { return AccessTools.GetDeclaredConstructors(type, (bool?)false).Count != 0; } return type != null && type.GetMethods(AccessTools.allDeclared).Any((MethodInfo m) => m.Name == methodName); } catch (Exception) { return false; } } internal static void Reset() { Owners.Clear(); CallSites.Reset(); CcsDisplay.Reset(); ComposedNames.Reset(); } private static bool Relevant(CodeInstruction instruction, Module module, MethodBase caller) { MethodBase methodBase = instruction.operand as MethodBase; if (methodBase != null && (instruction.opcode == OpCodes.Call || instruction.opcode == OpCodes.Callvirt || instruction.opcode == OpCodes.Newobj)) { return StringSinkAt(methodBase, module, caller).Any((bool b) => b); } FieldInfo fieldInfo = instruction.operand as FieldInfo; if (fieldInfo != null && instruction.opcode == OpCodes.Stfld) { return DisplayField(fieldInfo, module); } return false; } internal static bool DisplayField(FieldInfo f, Module m) { if (f.FieldType != typeof(string) || f.DeclaringType == null) { return false; } string fullName = f.DeclaringType.FullName; if (!(m.id == "ExpertExplorer") || !(fullName == "MessageHud+UnlockMsg") || (!(f.Name == "m_topic") && !(f.Name == "m_description"))) { if (m.id == "SpeedyPaths" && fullName == "StatusEffect") { return f.Name == "m_name"; } return false; } return true; } internal static bool[] StringSink(MethodBase method) { ParameterInfo[] parameters = method.GetParameters(); bool[] array = new bool[parameters.Length]; if (method.DeclaringType == null || method.ContainsGenericParameters) { return array; } if (parameters.Any((ParameterInfo p) => p.ParameterType.IsByRef || p.ParameterType.IsPointer)) { return array; } string fullName = method.DeclaringType.FullName; string name = method.Name; bool flag = false; if ((fullName == "UnityEngine.GUI" || fullName == "UnityEngine.GUILayout") && GuiMethods.Contains(name)) { flag = true; } if (fullName == "UnityEngine.GUIContent" && (method.IsConstructor || name == "set_text" || name == "set_tooltip")) { flag = true; } switch (fullName) { case "UnityEngine.UI.Text": case "TMPro.TMP_Text": case "TMPro.TextMeshProUGUI": case "TMPro.TextMeshPro": if (name == "set_text" || name == "SetText") { flag = true; } break; } switch (fullName) { case "Character": case "Player": case "MessageHud": case "Hud": if (name == "Message" || name == "ShowMessage") { flag = true; } break; } if (fullName == "Chat" && (name == "SetNpcText" || name == "AddInworldText")) { flag = true; } if ((fullName == "Localization" && name == "Localize") || (fullName == "Jotunn.Entities.CustomLocalization" && name == "TryTranslate")) { flag = true; } if (!flag) { return array; } for (int num = 0; num < parameters.Length; num++) { Type parameterType = parameters[num].ParameterType; array[num] = parameterType == typeof(string) || parameterType == typeof(string[]); if ((fullName == "Localization" && name == "Localize") || (fullName == "Jotunn.Entities.CustomLocalization" && name == "TryTranslate")) { array[num] = num == 0 && parameterType == typeof(string); } } return array; } internal static bool ScopedTerminalSink(MethodBase sink, Module module, MethodBase caller) { if (module == null || module.id != "PortalPreview" || caller == null || caller.DeclaringType == null || caller.DeclaringType.FullName != "PortalPreview.FrozenPortals+<>c" || !caller.Name.StartsWith("<Initialize>b__", StringComparison.Ordinal) || sink.DeclaringType == null || sink.DeclaringType.FullName != "Terminal" || sink.Name != "AddString" || sink.IsStatic) { return false; } ParameterInfo[] parameters = sink.GetParameters(); if (parameters.Length == 1) { return parameters[0].ParameterType == typeof(string); } return false; } internal static bool[] StringSinkAt(MethodBase sink, Module module, MethodBase caller) { bool[] array = StringSink(sink); if (ScopedTerminalSink(sink, module, caller)) { array[0] = true; } return array; } internal static string TranslateOwned(string value, string callerKey) { if (!TextEngine.IsRussian || callerKey == null || !Owners.TryGetValue(callerKey, out var value2) || !value2.UiAllowed || !TextEngine.Modules.TryGetValue(value2.id, out var value3) || value2 != value3) { return value; } return TextEngine.Display(value, value2.id); } internal static bool LocalizedReturn(MethodBase method) { MethodInfo methodInfo = method as MethodInfo; if (methodInfo == null || methodInfo.ReturnType != typeof(string) || methodInfo.DeclaringType == null) { return false; } if (!(methodInfo.DeclaringType.FullName == "Localization") || !(methodInfo.Name == "Localize")) { if (methodInfo.DeclaringType.FullName == "Jotunn.Entities.CustomLocalization") { return methodInfo.Name == "TryTranslate"; } return false; } return true; } private static void TranslateReturn(MethodBase __originalMethod, ref string __result) { string text = RuntimeAccess.MethodKey(__originalMethod); if (Owners.TryGetValue(text, out var value)) { __result = (ComposedNames.IsSite(text) ? TextEngine.DisplaySite(__result, text) : TextEngine.Display(__result, value.id)); } } private static IEnumerable<CodeInstruction> Transpile(IEnumerable<CodeInstruction> instructions, ILGenerator generator, MethodBase __originalMethod) { //IL_0228: Unknown result type (might be due to invalid IL or missing references) //IL_0232: Expected O, but got Unknown //IL_024e: Unknown result type (might be due to invalid IL or missing references) //IL_0258: Expected O, but got Unknown //IL_026f: Unknown result type (might be due to invalid IL or missing references) //IL_0279: Expected O, but got Unknown //IL_0284: Unknown result type (might be due to invalid IL or missing references) //IL_028e: Expected O, but got Unknown //IL_02c6: Unknown result type (might be due to invalid IL or missing references) //IL_02d0: Expected O, but got Unknown //IL_02dc: Unknown result type (might be due to invalid IL or missing references) //IL_02e6: Expected O, but got Unknown //IL_02f7: Unknown result type (might be due to invalid IL or missing references) //IL_0301: Expected O, but got Unknown //IL_030c: Unknown result type (might be due to invalid IL or missing references) //IL_0316: Expected O, but got Unknown //IL_036a: Unknown result type (might be due to invalid IL or missing references) //IL_0371: Expected O, but got Unknown //IL_038b: Unknown result type (might be due to invalid IL or missing references) //IL_0395: Expected O, but got Unknown //IL_04a5: Unknown result type (might be due to invalid IL or missing references) //IL_04af: Expected O, but got Unknown //IL_04ce: Unknown result type (might be due to invalid IL or missing references) //IL_04d8: Expected O, but got Unknown //IL_0596: Unknown result type (might be due to invalid IL or missing references) //IL_05a0: Expected O, but got Unknown //IL_05a9: Unknown result type (might be due to invalid IL or missing references) //IL_05b3: Expected O, but got Unknown //IL_0527: Unknown result type (might be due to invalid IL or missing references) //IL_0531: Expected O, but got Unknown //IL_0550: Unknown result type (might be due to invalid IL or missing references) //IL_055a: Expected O, but got Unknown List<CodeInstruction> list = instructions.ToList(); if (!Owners.TryGetValue(RuntimeAccess.MethodKey(__originalMethod), out var value)) { return list; } List<CodeInstruction> list2 = new List<CodeInstruction>(); string text = RuntimeAccess.MethodKey(__originalMethod); if (!value.Patches.TryGetValue(text, out var value2)) { value2 = new PatchEvidence { method = __originalMethod.DeclaringType.FullName + "." + __originalMethod.Name }; value.Patches[text] = value2; } value2.displayCalls = (value2.displayFields = (value2.literals = (value2.configTexts = (value2.skippedBoundaries = 0)))); value2.matchedLiterals.Clear(); string declaring = __originalMethod.DeclaringType.FullName; bool flag = value.configTexts.Any((LiteralSpec p) => p.type == declaring && p.method == __originalMethod.Name); bool flag2 = ComposedNames.IsSite(text); bool flag3 = value.HasDisplayText || flag2; string text2 = (flag2 ? text : value.id); MethodInfo methodInfo = (flag2 ? DisplaySite : Display); for (int num = 0; num < list.Count; num++) { CodeInstruction val = list[num]; if (val.blocks.Count != 0 || (num > 0 && list[num - 1].opcode.OpCodeType == OpCodeType.Prefix)) { value2.skippedBoundaries++; list2.Add(val); continue; } if (val.opcode == OpCodes.Ldstr) { string value3 = val.operand as string; if (value.literals.Any((LiteralSpec p) => p.type == __originalMethod.DeclaringType.FullName && p.method == __originalMethod.Name && value3 != null && p.values.ContainsKey(value3))) { value2.literals++; value2.matchedLiterals.Add(value3); list2.Add(val); list2.Add(new CodeInstruction(OpCodes.Ldstr, (object)value.id)); list2.Add(new CodeInstruction(OpCodes.Ldstr, (object)__originalMethod.DeclaringType.FullName)); list2.Add(new CodeInstruction(OpCodes.Ldstr, (object)__originalMethod.Name)); list2.Add(new CodeInstruction(OpCodes.Call, (object)Literal)); continue; } } if (flag && ConfigRead(val)) { value2.configTexts++; list2.Add(val); list2.Add(new CodeInstruction(OpCodes.Ldstr, (object)value.id)); list2.Add(new CodeInstruction(OpCodes.Ldstr, (object)declaring)); list2.Add(new CodeInstruction(OpCodes.Ldstr, (object)__originalMethod.Name)); list2.Add(new CodeInstruction(OpCodes.Call, (object)ConfigText)); continue; } FieldInfo fieldInfo = val.operand as FieldInfo; if (flag3 && val.opcode == OpCodes.Stfld && fieldInfo != null && DisplayField(fieldInfo, value)) { value2.displayFields++; CodeInstruction val2 = new CodeInstruction(OpCodes.Ldstr, (object)text2); CodeInstructionExtensions.MoveLabelsFrom(val2, val); list2.Add(val2); list2.Add(new CodeInstruction(OpCodes.Call, (object)methodInfo)); list2.Add(val); continue; } MethodBase methodBase = val.operand as MethodBase; bool flag4 = val.opcode == OpCodes.Call || val.opcode == OpCodes.Callvirt || val.opcode == OpCodes.Newobj; if (!flag3 || methodBase == null || !flag4) { list2.Add(val); continue; } bool[] array = StringSinkAt(methodBase, value, __originalMethod); if (!array.Any((bool b) => b)) { list2.Add(val); continue; } ParameterInfo[] parameters = methodBase.GetParameters(); LocalBuilder[] array2 = parameters.Select((ParameterInfo p) => generator.DeclareLocal(p.ParameterType)).ToArray(); List<CodeInstruction> list3 = new List<CodeInstruction>(); for (int num2 = array2.Length - 1; num2 >= 0; num2--) { list3.Add(new CodeInstruction(OpCodes.Stloc, (object)array2[num2])); } for (int num3 = 0; num3 < array2.Length; num3++) { list3.Add(new CodeInstruction(OpCodes.Ldloc, (object)array2[num3])); if (array[num3]) { bool flag5 = ScopedTerminalSink(methodBase, value, __originalMethod); bool flag6 = parameters[num3].ParameterType == typeof(string[]); list3.Add(new CodeInstruction(OpCodes.Ldstr, (object)(flag5 ? text : (flag6 ? value.id : text2)))); list3.Add(new CodeInstruction(OpCodes.Call, (object)(flag5 ? DisplayOwned : (flag6 ? DisplayArray : methodInfo)))); } } CodeInstructionExtensions.MoveLabelsFrom(list3[0], val); list3.Add(val); if (LocalizedReturn(methodBase)) { list3.Add(new CodeInstruction(OpCodes.Ldstr, (object)text2)); list3.Add(new CodeInstruction(OpCodes.Call, (object)methodInfo)); } value2.displayCalls++; list2.AddRange(list3); } string text3 = __originalMethod.DeclaringType.FullName + "." + __originalMethod.Name; HashSet<string> hashSet = new HashSet<string>(from i in list where i.opcode == OpCodes.Ldstr && i.operand is string select (string)i.operand, StringComparer.Ordinal); foreach (LiteralSpec item in value.literals.Where((LiteralSpec p) => p.type == __originalMethod.DeclaringType.FullName && p.method == __originalMethod.Name)) { foreach (string key in item.values.Keys) { if (hashSet.Contains(key) && !value2.matchedLiterals.Contains(key)) { value.Warn("Literal not replaced: " + text3 + " :: " + Shown(key)); } } } if (flag && value2.configTexts == 0 && list.Any(ConfigRead)) { value.Warn("Config value read not replaced: " + text3); } if (value2.displayCalls + value2.displayFields + value2.literals + value2.configTexts == 0) { value.Warn("Transpiler installed but no display site changed: " + text3); } return list2; } internal static string UnsupportedHandler(MethodBase method) { MethodBody methodBody = method.GetMethodBody(); if (methodBody == null) { return null; } foreach (ExceptionHandlingClause exceptionHandlingClause in methodBody.ExceptionHandlingClauses) { if (exceptionHandlingClause.Flags == ExceptionHandlingClauseOptions.Filter) { return "exception filter"; } if (exceptionHandlingClause.Flags == ExceptionHandlingClauseOptions.Fault) { return "fault block"; } } return null; } } internal static class ExtraHooks { internal static void Install(Harmony harmony) { //IL_0075: 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_0089: Expected O, but got Unknown //IL_0135: Unknown result type (might be due to invalid IL or missing references) //IL_013a: Unknown result type (might be due to invalid IL or missing references) //IL_014a: Expected O, but got Unknown Type type = RuntimeAccess.ExactType("FejdStartup"); if (type != null) { foreach (MethodInfo item in from x in type.GetMethods(AccessTools.allDeclared) where x.Name == "SetupGui" || x.Name == "SetupObjectDB" select x) { harmony.Patch((MethodBase)item, (HarmonyMethod)null, new HarmonyMethod(typeof(ExtraHooks).GetMethod("AfterMenu", AccessTools.all)) { priority = 0 }, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } if (!TextEngine.Modules.TryGetValue("OreMines", out var value) || !value.UiAllowed) { return; } Type type2 = RuntimeAccess.ExactType("Chat"); MethodInfo methodInfo = ((type2 == null) ? null : type2.GetMethods(AccessTools.allDeclared).FirstOrDefault((MethodInfo x) => x.Name == "OnNewChatMessage" && x.GetParameters().Any((ParameterInfo p) => p.Name == "text" && p.ParameterType == typeof(string)))); if (methodInfo == null) { value.Warn("Chat.OnNewChatMessage(text) was not found; mine-reset chat message is not patched."); return; } try { harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(ExtraHooks).GetMethod("ReceivedChat", AccessTools.all)) { priority = 0 }, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } catch (Exception ex) { value.Warn("Chat message adapter: " + ex.GetType().Name); } } private static void AfterMenu() { NativeAdapters.Refresh(); Plugin.WriteReport(); } private static void ReceivedChat(ref string text) { if (TextEngine.IsRussian && text == "Mines have been reset!") { text = TextEngine.Display(text, "OreMines"); } } } internal static class GameItems { internal static Func<string, string> ItemToken = FindItemToken; internal static Func<string, string> SetToken = FindSetToken; internal static Func<string, Type> TypeResolver = RuntimeAccess.ExactType; internal static Func<object, Type, object> ComponentResolver = FindComponent; private static Type databaseType; private static Type dropType; private static readonly Dictionary<Type, Dictionary<string, Func<object, object>>> Readers = new Dictionary<Type, Dictionary<string, Func<object, object>>>(); private static readonly Dictionary<Type, MethodInfo> PrefabGetters = new Dictionary<Type, MethodInfo>(); private static readonly Dictionary<string, string> ItemTokens = new Dictionary<string, string>(StringComparer.Ordinal); private static object databaseOf; private static object itemsOf; private static int itemCount = -1; private static Dictionary<string, string> sets; private static MethodInfo localize; internal static string ItemName(string prefab) { return Shown(Lookup(ItemToken, prefab)); } internal static string SetName(string shown) { return Shown(Lookup(SetToken, shown)); } internal static void Install(Harmony harmony) { //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Expected O, but got Unknown try { if (databaseType == null) { databaseType = TypeResolver("ObjectDB"); } MethodInfo methodInfo = ((databaseType == null) ? null : AccessTools.Method(databaseType, "UpdateRegisters", Type.EmptyTypes, (Type[])null)); if (methodInfo == null || methodInfo.IsStatic || methodInfo.ReturnType != typeof(void) || !RuntimeAccess.ManagedBody(methodInfo)) { Plugin.Warn("ObjectDB.UpdateRegisters API unavailable; game-name caches refresh on database/list changes and adapter refresh."); return; } harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(AccessTools.Method(typeof(GameItems), "Invalidate", (Type[])null, (Type[])null)) { priority = 0 }, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } catch (Exception ex) { Plugin.Warn("Game-name registration hook: " + ex.GetType().Name); } } internal static void Invalidate() { sets = null; ItemTokens.Clear(); foreach (Module value in TextEngine.Modules.Values) { if (value.Table != null) { value.Table.Clear(); } } } internal static void Reset() { ItemToken = FindItemToken; SetToken = FindSetToken; TypeResolver = RuntimeAccess.ExactType; ComponentResolver = FindComponent; databaseType = null; dropType = null; Readers.Clear(); PrefabGetters.Clear(); databaseOf = null; itemsOf = null; itemCount = -1; localize = null; Invalidate(); } private static string Lookup(Func<string, string> lookup, string value) { if (string.IsNullOrEmpty(value)) { return null; } try { return lookup(value); } catch (Exception ex) { Plugin.Warn("Game name lookup failed for " + value + ": " + ex.GetType().Name); return null; } } private static string Shown(string token) { if (string.IsNullOrEmpty(token)) { return null; } object main = LocalizationBridge.Main; if (main == null) { return token; } if (localize == null || localize.DeclaringType != main.GetType()) { localize = AccessTools.Method(main.GetType(), "Localize", new Type[1] { typeof(string) }, (Type[])null); } object obj; if (!(localize == null)) { obj = localize.Invoke(main, new object[1] { token }) as string; if (obj == null) { return token; } } else { obj = token; } return (string)obj; } private static object Database() { if (databaseType == null) { databaseType = TypeResolver("ObjectDB"); } object obj = Read(databaseType, "instance"); object obj2 = Read(obj, "m_items"); int num = ((!(obj2 is ICollection collection)) ? (-1) : collection.Count); if (obj != databaseOf || obj2 != itemsOf || num != itemCount) { databaseOf = obj; itemsOf = obj2; itemCount = num; Invalidate(); } return obj; } private static object Read(object instanceOrType, string name) { if (instanceOrType == null) { return null; } Type type = (instanceOrType as Type) ?? instanceOrType.GetType(); if (!Readers.TryGetValue(type, out var value)) { value = (Readers[type] = new Dictionary<string, Func<object, object>>(StringComparer.Ordinal)); } if (!value.TryGetValue(name, out var value2)) { FieldInfo fieldInfo = AccessTools.FindIncludingBaseTypes<FieldInfo>(type, (Func<Type, FieldInfo>)((Type t) => t.GetField(name, AccessTools.all))); PropertyInfo property = ((fieldInfo == null) ? AccessTools.FindIncludingBaseTypes<PropertyInfo>(type, (Func<Type, PropertyInfo>)((Type t) => t.GetProperty(name, AccessTools.all))) : null); value2 = ((fieldInfo != null) ? new Func<object, object>(fieldInfo.GetValue) : ((property != null) ? ((Func<object, object>)((object receiver) => property.GetValue(receiver, null))) : ((Func<object, object>)((object receiver) => (object)null)))); value[name] = value2; } re