Decompiled source of LGU Russian Translation v1.1.3

BepInEx/plugins/LguRuTranslation/LguRuTranslation.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
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 BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Newtonsoft.Json;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("LguRuTranslation")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LguRuTranslation")]
[assembly: AssemblyCopyright("Copyright ©  2026")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("3dde88d2-ee5e-457f-92ee-a03bf1116303")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace LguRuTranslation;

[BepInPlugin("ru.lgu.translation", "LGU Russian Translation", "1.1.2")]
public class LguRuPlugin : BaseUnityPlugin
{
	public const string PluginGUID = "ru.lgu.translation";

	public const string PluginName = "LGU Russian Translation";

	public const string PluginVersion = "1.1.2";

	internal static ManualLogSource Log;

	internal static Dictionary<string, string> Dict;

	internal static Dictionary<string, string> NormalizedDict;

	internal static Dictionary<string, string> KeyReverse;

	public static ConfigEntry<bool> TranslateUpgradeNames;

	public static ConfigEntry<bool> SwapTerminalFont;

	public static ConfigEntry<bool> UseTranspilers;

	public static ConfigEntry<bool> PatchStaticConstructors;

	private static readonly OpCode[] OneByte;

	private static readonly OpCode[] TwoByte;

	private static HarmonyMethod TranspilerHook;

	private static object _fontAsset;

	private static bool _fontFailed;

	private void Awake()
	{
		Log = Logger.CreateLogSource("LGU-RU");
		TranslateUpgradeNames = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Translate upgrade names", false, "Переводить ли названия улучшений (ломает логику LGU, не включать).");
		SwapTerminalFont = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Swap terminal font", false, "Подменять ли шрифт терминала.");
		UseTranspilers = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Use transpilers", true, "Заменять строки описаний в коде LGU.");
		PatchStaticConstructors = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Patch static constructors", true, "Патчить статические конструкторы LGU (.cctor).");
		try
		{
			string configDir = Paths.ConfigPath;
			string pluginDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
			string text = FindFile("ru.json");
			Dict = ((text != null) ? (JsonConvert.DeserializeObject<Dictionary<string, string>>(File.ReadAllText(text)) ?? LoadEmbeddedDict("ru.json")) : LoadEmbeddedDict("ru.json"));
			List<string> list = new List<string>();
			string text2 = FindFile("names.json");
			if (text2 != null)
			{
				list = JsonConvert.DeserializeObject<List<string>>(File.ReadAllText(text2)) ?? new List<string>();
			}
			else
			{
				try
				{
					list = LoadEmbeddedList("names.json");
				}
				catch
				{
				}
			}
			List<string> list2 = new List<string>();
			string text3 = FindFile("infokeys.json");
			if (text3 != null)
			{
				list2 = JsonConvert.DeserializeObject<List<string>>(File.ReadAllText(text3)) ?? new List<string>();
			}
			else
			{
				try
				{
					list2 = LoadEmbeddedList("infokeys.json");
				}
				catch
				{
				}
			}
			ManualLogSource log = Log;
			if (log != null)
			{
				log.LogInfo((object)$"Словарь перевода загружен: {Dict.Count} записей");
			}
			if (!TranslateUpgradeNames.Value)
			{
				int num = 0;
				foreach (string item in list)
				{
					if (Dict.Remove(item))
					{
						num++;
					}
				}
				ManualLogSource log2 = Log;
				if (log2 != null)
				{
					log2.LogInfo((object)$"TranslateUpgradeNames=false — названия улучшений на английском (удалено {num} записей)");
				}
			}
			foreach (KeyValuePair<string, string> item2 in Dict)
			{
				string key = item2.Key.Replace("\r\n", "\n").Trim();
				if (!NormalizedDict.ContainsKey(key))
				{
					NormalizedDict[key] = item2.Value;
				}
			}
			string text4 = FindFile("ru_override.json");
			if (text4 != null)
			{
				try
				{
					Dictionary<string, string> dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(File.ReadAllText(text4));
					if (dictionary != null)
					{
						foreach (KeyValuePair<string, string> item3 in dictionary)
						{
							Dict[item3.Key] = item3.Value;
						}
						ManualLogSource log3 = Log;
						if (log3 != null)
						{
							log3.LogInfo((object)$"ru_override.json: применено {dictionary.Count} правок");
						}
					}
				}
				catch (Exception ex)
				{
					ManualLogSource log4 = Log;
					if (log4 != null)
					{
						log4.LogWarning((object)("ru_override.json не разобран: " + ex.Message));
					}
				}
			}
			foreach (string item4 in list2)
			{
				if (Dict.TryGetValue(item4, out var value) && !KeyReverse.ContainsKey(value))
				{
					KeyReverse[value] = item4;
				}
			}
			Assembly assembly = FindLguAssembly();
			if (assembly != null)
			{
				ManualLogSource log5 = Log;
				if (log5 != null)
				{
					log5.LogInfo((object)("Сборка MoreShipUpgrades найдена: " + assembly.FullName));
				}
				StartTranslation(assembly);
			}
			else
			{
				ManualLogSource log6 = Log;
				if (log6 != null)
				{
					log6.LogError((object)"Сборка MoreShipUpgrades не найдена при старте.");
				}
			}
			string FindFile(string fileName)
			{
				string text5 = Path.Combine(configDir, fileName);
				if (File.Exists(text5))
				{
					return text5;
				}
				string text6 = Path.Combine(pluginDir, fileName);
				if (File.Exists(text6))
				{
					return text6;
				}
				return null;
			}
		}
		catch (Exception arg)
		{
			ManualLogSource log7 = Log;
			if (log7 != null)
			{
				log7.LogError((object)$"Ошибка инициализации: {arg}");
			}
		}
	}

	private static Assembly FindLguAssembly()
	{
		Type type = AccessTools.TypeByName("MoreShipUpgrades.Misc.AssetBundleHandler");
		if (type != null)
		{
			return type.Assembly;
		}
		return AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault((Assembly a) => a != null && a.GetName().Name == "MoreShipUpgrades");
	}

	private void StartTranslation(Assembly lguAsm)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_000c: Expected O, but got Unknown
		Harmony harmony = new Harmony("ru.lgu.translation");
		ManualLogSource log = Log;
		if (log != null)
		{
			log.LogInfo((object)"Шаг 1/3: патч GetInfoFromJSON...");
		}
		PatchInfoStrings(harmony, lguAsm);
		if (SwapTerminalFont.Value)
		{
			ManualLogSource log2 = Log;
			if (log2 != null)
			{
				log2.LogInfo((object)"Шаг 2/3: подмена шрифта терминала...");
			}
			PatchFonts(harmony);
		}
		else
		{
			ManualLogSource log3 = Log;
			if (log3 != null)
			{
				log3.LogInfo((object)"Шаг 2/3: SwapTerminalFont=false — шрифт не меняем");
			}
		}
		if (UseTranspilers.Value)
		{
			ManualLogSource log4 = Log;
			if (log4 != null)
			{
				log4.LogInfo((object)"Шаг 3/3: транспайлер строк — применяю синхронно...");
			}
			ApplyTranspilersSync(harmony, lguAsm);
			ManualLogSource log5 = Log;
			if (log5 != null)
			{
				log5.LogInfo((object)"Перевод LGU на русский готов. Приятной игры!");
			}
		}
		else
		{
			ManualLogSource log6 = Log;
			if (log6 != null)
			{
				log6.LogWarning((object)"UseTranspilers=false — перевод только через InfoStrings и шрифт");
			}
		}
	}

	private static string ReadResource(string name)
	{
		Assembly executingAssembly = Assembly.GetExecutingAssembly();
		string text = executingAssembly.GetManifestResourceNames().FirstOrDefault((string n) => n.EndsWith(name, StringComparison.OrdinalIgnoreCase));
		if (text == null)
		{
			throw new FileNotFoundException("Встроенный ресурс не найден: " + name);
		}
		using Stream stream = executingAssembly.GetManifestResourceStream(text);
		if (stream == null)
		{
			throw new FileNotFoundException("Не удалось открыть поток ресурса: " + name);
		}
		using StreamReader streamReader = new StreamReader(stream);
		return streamReader.ReadToEnd();
	}

	private static Dictionary<string, string> LoadEmbeddedDict(string name)
	{
		return JsonConvert.DeserializeObject<Dictionary<string, string>>(ReadResource(name)) ?? new Dictionary<string, string>();
	}

	private static List<string> LoadEmbeddedList(string name)
	{
		return JsonConvert.DeserializeObject<List<string>>(ReadResource(name)) ?? new List<string>();
	}

	static LguRuPlugin()
	{
		//IL_004c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0056: Expected O, but got Unknown
		Dict = new Dictionary<string, string>();
		NormalizedDict = new Dictionary<string, string>();
		KeyReverse = new Dictionary<string, string>();
		OneByte = new OpCode[256];
		TwoByte = new OpCode[256];
		TranspilerHook = new HarmonyMethod(typeof(LguRuPlugin), "StringTranspiler", (Type[])null);
		FieldInfo[] fields = typeof(OpCodes).GetFields(BindingFlags.Static | BindingFlags.Public);
		foreach (FieldInfo fieldInfo in fields)
		{
			if (fieldInfo.GetValue(null) is OpCode { Size: >0 } opCode)
			{
				int num = opCode.Value & 0xFF;
				if (opCode.Size == 2)
				{
					TwoByte[num] = opCode;
				}
				else
				{
					OneByte[num] = opCode;
				}
			}
		}
	}

	private static bool ScanMethod(MethodBase m, out bool hasTranslatable, out bool hazardous)
	{
		hasTranslatable = false;
		hazardous = false;
		byte[] iLAsByteArray;
		try
		{
			MethodBody methodBody = m.GetMethodBody();
			if (methodBody == null)
			{
				return false;
			}
			iLAsByteArray = methodBody.GetILAsByteArray();
			if (iLAsByteArray == null)
			{
				return false;
			}
			foreach (ExceptionHandlingClause exceptionHandlingClause in methodBody.ExceptionHandlingClauses)
			{
				if ((exceptionHandlingClause.Flags & ExceptionHandlingClauseOptions.Filter) != ExceptionHandlingClauseOptions.Clause)
				{
					hazardous = true;
				}
			}
		}
		catch
		{
			return false;
		}
		int num = 0;
		while (num < iLAsByteArray.Length)
		{
			int num2 = iLAsByteArray[num];
			OpCode opCode;
			if (num2 == 254)
			{
				if (num + 1 >= iLAsByteArray.Length)
				{
					break;
				}
				opCode = TwoByte[iLAsByteArray[num + 1]];
				num += 2;
			}
			else
			{
				opCode = OneByte[num2];
				num++;
			}
			if (opCode.Size == 0)
			{
				hazardous = true;
				return false;
			}
			if (opCode == OpCodes.Localloc || opCode == OpCodes.Jmp || opCode == OpCodes.Tailcall)
			{
				hazardous = true;
			}
			if (opCode == OpCodes.Ldstr)
			{
				hasTranslatable = true;
			}
			int num3;
			switch (opCode.OperandType)
			{
			case OperandType.InlineNone:
				num3 = 0;
				break;
			case OperandType.ShortInlineBrTarget:
			case OperandType.ShortInlineI:
			case OperandType.ShortInlineVar:
				num3 = 1;
				break;
			case OperandType.InlineVar:
				num3 = 2;
				break;
			case OperandType.InlineI8:
			case OperandType.InlineR:
				num3 = 8;
				break;
			case OperandType.InlineSwitch:
				if (num + 4 > iLAsByteArray.Length)
				{
					hazardous = true;
					return false;
				}
				num3 = 4 + 4 * BitConverter.ToInt32(iLAsByteArray, num);
				break;
			default:
				num3 = 4;
				break;
			}
			if (num3 < 0 || num + num3 < 0 || num + num3 > iLAsByteArray.Length)
			{
				hazardous = true;
				return false;
			}
			num += num3;
		}
		return hasTranslatable;
	}

	private void ApplyTranspilersSync(Harmony harmony, Assembly asm)
	{
		Type[] array;
		try
		{
			array = asm.GetTypes();
		}
		catch (ReflectionTypeLoadException ex)
		{
			array = ex.Types.Where((Type t) => t != null).ToArray();
		}
		catch
		{
			array = new Type[0];
		}
		int num = 0;
		Type[] array2 = array;
		foreach (Type type in array2)
		{
			try
			{
				if (type == null || type.IsInterface || type.IsGenericTypeDefinition || (type.FullName != null && type.FullName.Contains("Compat")))
				{
					continue;
				}
				MethodInfo[] methods;
				ConstructorInfo[] constructors;
				try
				{
					methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
					constructors = type.GetConstructors(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				}
				catch
				{
					goto end_IL_0061;
				}
				foreach (MethodBase item in methods.Cast<MethodBase>().Concat(constructors))
				{
					try
					{
						if (!(item == null) && !item.IsAbstract && !item.ContainsGenericParameters && (!item.IsSpecialName || !(item.Name == ".cctor") || PatchStaticConstructors.Value) && ScanMethod(item, out var hasTranslatable, out var hazardous) && !(hasTranslatable && hazardous) && hasTranslatable)
						{
							harmony.Patch(item, (HarmonyMethod)null, (HarmonyMethod)null, TranspilerHook, (HarmonyMethod)null, (HarmonyMethod)null);
							num++;
						}
					}
					catch
					{
					}
				}
				end_IL_0061:;
			}
			catch
			{
			}
		}
		ManualLogSource log = Log;
		if (log != null)
		{
			log.LogInfo((object)$"Транспайлер завершён: литералы заменены в {num} методах.");
		}
	}

	private static IEnumerable<CodeInstruction> StringTranspiler(IEnumerable<CodeInstruction> instructions)
	{
		string s = default(string);
		foreach (CodeInstruction ci in instructions)
		{
			int num;
			if (ci.opcode == OpCodes.Ldstr)
			{
				object operand = ci.operand;
				s = operand as string;
				num = ((s != null) ? 1 : 0);
			}
			else
			{
				num = 0;
			}
			if (num != 0)
			{
				if ((s.Contains("LVL") || s.Contains("{0}") || s.Contains("{1}") || s.Length > 30) && TryTranslateString(s, out var translated))
				{
					ci.operand = translated;
				}
				translated = null;
			}
			yield return ci;
			s = null;
		}
	}

	private static bool TryTranslateString(string original, out string translated)
	{
		translated = original;
		string text = original.Replace("\r\n", "\n").Trim();
		if (NormalizedDict.TryGetValue(text, out var value))
		{
			translated = value;
			return true;
		}
		string key = text.Replace("your crew", "{0}");
		if (NormalizedDict.TryGetValue(key, out var value2))
		{
			translated = value2;
			return true;
		}
		return false;
	}

	private static void PatchInfoStrings(Harmony harmony, Assembly asm)
	{
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_0074: Expected O, but got Unknown
		//IL_0074: Expected O, but got Unknown
		try
		{
			Type type = asm.GetType("MoreShipUpgrades.Misc.AssetBundleHandler");
			MethodInfo methodInfo = AccessTools.Method(type, "GetInfoFromJSON", (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				ManualLogSource log = Log;
				if (log != null)
				{
					log.LogWarning((object)"AssetBundleHandler.GetInfoFromJSON не найден");
				}
				return;
			}
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(LguRuPlugin), "InfoKeyPrefix", (Type[])null), new HarmonyMethod(typeof(LguRuPlugin), "InfoValuePostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			ManualLogSource log2 = Log;
			if (log2 != null)
			{
				log2.LogInfo((object)"GetInfoFromJSON: перевод описаний info включён");
			}
		}
		catch (Exception arg)
		{
			ManualLogSource log3 = Log;
			if (log3 != null)
			{
				log3.LogError((object)$"PatchInfoStrings: {arg}");
			}
		}
	}

	private static void InfoKeyPrefix(ref string key)
	{
		if (key != null && KeyReverse.TryGetValue(key, out var value))
		{
			key = value;
		}
	}

	private static void InfoValuePostfix(ref string __result)
	{
		if (!string.IsNullOrEmpty(__result) && TryTranslateString(__result, out var translated))
		{
			__result = translated;
		}
	}

	private static object CreateCyrillicFontAsset()
	{
		if (_fontAsset != null || _fontFailed)
		{
			return _fontAsset;
		}
		try
		{
			Type type = Type.GetType("TMPro.TMP_FontAsset, Unity.TextMeshPro");
			if (type == null)
			{
				_fontFailed = true;
				return null;
			}
			MethodInfo method = type.GetMethod("CreateFontAsset", new Type[1] { typeof(Font) });
			if (method == null)
			{
				_fontFailed = true;
				return null;
			}
			Font val = null;
			try
			{
				val = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
			}
			catch
			{
			}
			if ((Object)(object)val == (Object)null)
			{
				try
				{
					val = Resources.GetBuiltinResource<Font>("Arial.ttf");
				}
				catch
				{
				}
			}
			if ((Object)(object)val == (Object)null)
			{
				try
				{
					val = Font.CreateDynamicFontFromOSFont("Arial", 16);
				}
				catch
				{
				}
			}
			if ((Object)(object)val != (Object)null)
			{
				object obj4 = method.Invoke(null, new object[1] { val });
				if (obj4 != null)
				{
					ManualLogSource log = Log;
					if (log != null)
					{
						log.LogInfo((object)"Шрифт терминала: TMP-ассет создан из встроенного шрифта");
					}
					_fontAsset = obj4;
					return _fontAsset;
				}
			}
			ManualLogSource log2 = Log;
			if (log2 != null)
			{
				log2.LogWarning((object)"Не удалось создать шрифт с кириллицей — терминал останется на стандартном шрифте");
			}
		}
		catch (Exception ex)
		{
			ManualLogSource log3 = Log;
			if (log3 != null)
			{
				log3.LogWarning((object)("CreateCyrillicFontAsset: " + ex.Message));
			}
		}
		_fontFailed = true;
		return null;
	}

	private static void SwapFontOnChildren(object gameObject)
	{
		object obj = CreateCyrillicFontAsset();
		if (obj == null)
		{
			return;
		}
		try
		{
			Type type = Type.GetType("TMPro.TMP_Text, Unity.TextMeshPro");
			if (type == null)
			{
				return;
			}
			Type type2 = gameObject.GetType();
			MethodInfo methodInfo = type2.GetMethods().FirstOrDefault((MethodInfo m) => m.Name == "GetComponentsInChildren" && m.IsGenericMethodDefinition && m.GetParameters().Length == 1 && m.GetParameters()[0].ParameterType == typeof(bool));
			if (methodInfo == null)
			{
				return;
			}
			MethodInfo methodInfo2 = methodInfo.MakeGenericMethod(type);
			if (!(methodInfo2.Invoke(gameObject, new object[1] { true }) is Array array))
			{
				return;
			}
			PropertyInfo property = type.GetProperty("font");
			foreach (object item in array)
			{
				try
				{
					property.SetValue(item, obj);
				}
				catch
				{
				}
			}
		}
		catch
		{
		}
	}

	private static void PatchFonts(Harmony harmony)
	{
		//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ee: Expected O, but got Unknown
		//IL_0084: Unknown result type (might be due to invalid IL or missing references)
		//IL_0091: Expected O, but got Unknown
		int num = 0;
		try
		{
			Type type = AccessTools.TypeByName("Terminal");
			if (type != null)
			{
				string[] array = new string[2] { "Start", "Awake" };
				foreach (string text in array)
				{
					MethodInfo methodInfo = AccessTools.Method(type, text, (Type[])null, (Type[])null);
					if (methodInfo != null && !methodInfo.IsAbstract)
					{
						harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(LguRuPlugin), "ApplyTerminalFont", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
						num++;
					}
				}
			}
			Type type2 = AccessTools.TypeByName("HUDManager");
			MethodInfo methodInfo2 = AccessTools.Method(type2, "DisplayTip", (Type[])null, (Type[])null);
			if (methodInfo2 != null)
			{
				harmony.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, new HarmonyMethod(typeof(LguRuPlugin), "ApplyHudFont", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				num++;
			}
			ManualLogSource log = Log;
			if (log != null)
			{
				log.LogInfo((object)((num > 0) ? "Шрифт: подмена включена (Terminal + HUD-уведомления)" : "Шрифт: методы Terminal/HUDManager не найдены — подмена выключена"));
			}
		}
		catch (Exception ex)
		{
			ManualLogSource log2 = Log;
			if (log2 != null)
			{
				log2.LogWarning((object)("PatchFonts: " + ex.Message));
			}
		}
	}

	private static void ApplyTerminalFont(object __instance)
	{
		try
		{
			PropertyInfo property = __instance.GetType().GetProperty("gameObject");
			SwapFontOnChildren(property.GetValue(__instance));
		}
		catch
		{
		}
	}

	private static void ApplyHudFont(object __instance)
	{
		object obj = CreateCyrillicFontAsset();
		if (obj == null)
		{
			return;
		}
		try
		{
			Type type = Type.GetType("TMPro.TMP_Text, Unity.TextMeshPro");
			if (type == null)
			{
				return;
			}
			PropertyInfo property = type.GetProperty("font");
			FieldInfo[] fields = __instance.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (FieldInfo fieldInfo in fields)
			{
				if (!type.IsAssignableFrom(fieldInfo.FieldType))
				{
					continue;
				}
				object value = fieldInfo.GetValue(__instance);
				if (value != null)
				{
					try
					{
						property.SetValue(value, obj);
					}
					catch
					{
					}
				}
			}
		}
		catch
		{
		}
	}
}