Decompiled source of BrutalCompanyMinus RU v1.0.3

plugins\BrutalCompanyMinus_RU\BrutalCompanyMinus_RU.dll

Decompiled 3 days ago
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.TextCore;
using UnityEngine.TextCore.LowLevel;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace KindEvil.BrutalMinusRU;

[BepInPlugin("KindEvil.BrutalMinusRU", "Brutal Company Minus RU", "1.0.3")]
[BepInDependency("Drinkable.BrutalCompanyMinus", "0.13.22")]
public sealed class Plugin : BaseUnityPlugin
{
	private sealed class PanelState
	{
		public float OriginalSize;

		public string LastText;

		public Text Overlay;

		public int OriginalMaxVisible;

		public LayoutElement Layout;

		public bool AddedLayout;
	}

	private const string RequiredGlyphs = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюяABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789−—…!?.,:;+-x×%()[]";

	private readonly Dictionary<string, string> words = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

	private readonly Dictionary<TextMeshProUGUI, PanelState> panels = new Dictionary<TextMeshProUGUI, PanelState>();

	private readonly string[,] labels = new string[15, 2]
	{
		{ "EventType Chances:", "Вероятности событий:" },
		{ "Events:", "СОБЫТИЯ:" },
		{ "Other:", "ПАРАМЕТРЫ:" },
		{ "Difficulty:", "Сложность:" },
		{ "Day:", "Дни:" },
		{ "Quota:", "Квота:" },
		{ "Ship Scrap:", "Лом на борту:" },
		{ "Moon risk:", "Риск луны:" },
		{ "Weather:", "Погода:" },
		{ "Scrap Value:", "Цена лома:" },
		{ "Scrap Amount:", "Кол-во лома:" },
		{ "Factory Size:", "Размер базы:" },
		{ "Spawn Chance:", "Частота спавна:" },
		{ "Spawn Cap:", "Лимит монстров:" },
		{ "Bonus enemy hp:", "Бонус здоровья:" }
	};

	private static readonly Regex Tokens = new Regex("<[^>]*>|[^<]+|<", RegexOptions.Compiled);

	private static readonly Regex ColorTags = new Regex("(?i)(<color=#)([0-9a-f]{6})(>)", RegexOptions.Compiled);

	private static readonly Dictionary<string, string> Palette = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
	{
		{ "00FF00", "A6DE95" },
		{ "008000", "78B99B" },
		{ "FF0000", "F18A80" },
		{ "800000", "E35D61" },
		{ "280000", "E35D61" },
		{ "140000", "E35D61" },
		{ "FFFF00", "E4CD79" },
		{ "FFFFFF", "E4E3DA" }
	};

	private ConfigEntry<string> fontChoice;

	private ConfigEntry<bool> preferBundledFont;

	private ConfigEntry<float> fontScale;

	private ConfigEntry<bool> softerColors;

	private ConfigEntry<bool> changeFont;

	private Font sourceFont;

	private TMP_FontAsset newFont;

	private bool fontAttempted;

	private float nextScan;

	private bool enabledTranslation;

	private bool errorLogged;

	private void Awake()
	{
		fontChoice = ((BaseUnityPlugin)this).Config.Bind<string>("Appearance", "Font", "JetBrains Mono", "Preferred installed Windows font; same selection as version 1.0.1.");
		preferBundledFont = ((BaseUnityPlugin)this).Config.Bind<bool>("Appearance", "PreferBundledFont", false, "False restores the 1.0.1 font selection and renderer; true prioritizes packaged JetBrains Mono.");
		fontScale = ((BaseUnityPlugin)this).Config.Bind<float>("Appearance", "FontScaleV2", 0.82f, "Relative to the original panel font size (0.65 - 1.20).");
		softerColors = ((BaseUnityPlugin)this).Config.Bind<bool>("Appearance", "MutedColors", false, "Optional muted colors. False preserves original neon green and event colors.");
		changeFont = ((BaseUnityPlugin)this).Config.Bind<bool>("Appearance", "ChangeFont", true, "Use one Cyrillic-capable font for the BCM panel.");
		try
		{
			string path = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), "translations.tsv");
			string[] array = File.ReadAllLines(path, Encoding.UTF8);
			foreach (string text in array)
			{
				if (text.Length != 0 && !text.StartsWith("#"))
				{
					int num = text.IndexOf('\t');
					if (num > 0)
					{
						words[text.Substring(0, num)] = text.Substring(num + 1);
					}
				}
			}
			enabledTranslation = words.Count > 0;
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Loaded " + words.Count + " Russian display translations."));
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogError((object)("Cannot load translations.tsv: " + ex));
		}
	}

	private void LateUpdate()
	{
		if (!enabledTranslation)
		{
			return;
		}
		try
		{
			if (Time.unscaledTime >= nextScan)
			{
				nextScan = Time.unscaledTime + 1.5f;
				List<TextMeshProUGUI> list = new List<TextMeshProUGUI>();
				foreach (TextMeshProUGUI key2 in panels.Keys)
				{
					if ((Object)(object)key2 == (Object)null)
					{
						list.Add(key2);
					}
				}
				foreach (TextMeshProUGUI item in list)
				{
					panels.Remove(item);
				}
				TextMeshProUGUI[] array = Resources.FindObjectsOfTypeAll<TextMeshProUGUI>();
				foreach (TextMeshProUGUI val in array)
				{
					if (!((Object)(object)val == (Object)null) && !panels.ContainsKey(val) && IsBrutalPanel(val))
					{
						panels.Add(val, new PanelState
						{
							OriginalSize = ((TMP_Text)val).fontSize,
							OriginalMaxVisible = ((TMP_Text)val).maxVisibleCharacters
						});
						((BaseUnityPlugin)this).Logger.LogInfo((object)"Brutal Company Minus EventText panel detected.");
					}
				}
			}
			foreach (KeyValuePair<TextMeshProUGUI, PanelState> panel in panels)
			{
				TextMeshProUGUI key = panel.Key;
				if ((Object)(object)key == (Object)null)
				{
					continue;
				}
				PanelState value = panel.Value;
				string text = ((TMP_Text)key).text;
				if (text != value.LastText)
				{
					string text2 = (string.IsNullOrEmpty(text) ? "" : Translate(text));
					if (text2 != text)
					{
						((TMP_Text)key).text = text2;
					}
					value.LastText = text2;
				}
				ApplyAppearance(key, value);
			}
		}
		catch (Exception ex)
		{
			if (!errorLogged)
			{
				errorLogged = true;
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Panel localization error: " + ex));
			}
		}
	}

	private static bool IsBrutalPanel(TextMeshProUGUI p)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		Scene scene = ((Component)p).gameObject.scene;
		if (((Scene)(ref scene)).IsValid())
		{
			Scene scene2 = ((Component)p).gameObject.scene;
			if (((Scene)(ref scene2)).isLoaded)
			{
				if (!string.Equals(((Object)((Component)p).gameObject).name, "EventText", StringComparison.Ordinal))
				{
					return false;
				}
				Transform parent = ((TMP_Text)p).transform.parent;
				while ((Object)(object)parent != (Object)null)
				{
					if (((Object)parent).name == "EventPanel" || ((Object)parent).name == "EventPanel(Clone)")
					{
						return true;
					}
					parent = parent.parent;
				}
				string text = ((TMP_Text)p).text ?? "";
				if (!text.Contains("Events:") && !text.Contains("Difficulty:"))
				{
					return text.Contains("СОБЫТИЯ:");
				}
				return true;
			}
		}
		return false;
	}

	private void ApplyAppearance(TextMeshProUGUI p, PanelState state)
	{
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		//IL_0063: Unknown result type (might be due to invalid IL or missing references)
		//IL_0046: Unknown result type (might be due to invalid IL or missing references)
		//IL_0068: Unknown result type (might be due to invalid IL or missing references)
		//IL_006a: Unknown result type (might be due to invalid IL or missing references)
		//IL_006f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: Unknown result type (might be due to invalid IL or missing references)
		//IL_016f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0175: Expected O, but got Unknown
		//IL_018d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0194: Expected O, but got Unknown
		//IL_0196: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
		//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
		//IL_0324: Unknown result type (might be due to invalid IL or missing references)
		//IL_0329: Unknown result type (might be due to invalid IL or missing references)
		//IL_0333: Unknown result type (might be due to invalid IL or missing references)
		//IL_03a3: Unknown result type (might be due to invalid IL or missing references)
		//IL_03af: Unknown result type (might be due to invalid IL or missing references)
		if (changeFont.Value && !fontAttempted)
		{
			InitializeFont(p);
		}
		Color color = ((Graphic)p).color;
		Color val = (softerColors.Value ? new Color(0.66f, 0.82f, 0.63f, color.a) : new Color(0f, 1f, 0f, color.a));
		if (((Graphic)p).color != val)
		{
			((Graphic)p).color = val;
		}
		if (!changeFont.Value)
		{
			return;
		}
		float num = state.OriginalSize * Mathf.Clamp(fontScale.Value, 0.65f, 1.2f);
		if ((Object)(object)newFont != (Object)null)
		{
			if ((Object)(object)((TMP_Text)p).font != (Object)(object)newFont)
			{
				((TMP_Text)p).font = newFont;
				((TMP_Text)p).fontSharedMaterial = ((TMP_Asset)newFont).material;
				((TMP_Text)p).fontStyle = (FontStyles)0;
				((TMP_Text)p).enableAutoSizing = false;
			}
			if (Mathf.Abs(((TMP_Text)p).fontSize - num) > 0.01f)
			{
				((TMP_Text)p).fontSize = num;
			}
		}
		else
		{
			if ((Object)(object)sourceFont == (Object)null)
			{
				return;
			}
			if ((Object)(object)state.Overlay == (Object)null)
			{
				GameObject val2 = new GameObject("KindEvil_RussianText", new Type[3]
				{
					typeof(RectTransform),
					typeof(CanvasRenderer),
					typeof(Text)
				});
				val2.transform.SetParent(((TMP_Text)p).transform, false);
				RectTransform val3 = (RectTransform)val2.transform;
				val3.anchorMin = Vector2.zero;
				val3.anchorMax = Vector2.one;
				val3.pivot = ((TMP_Text)p).rectTransform.pivot;
				Vector4 margin = ((TMP_Text)p).margin;
				val3.offsetMin = new Vector2(margin.x, margin.w);
				val3.offsetMax = new Vector2(0f - margin.z, 0f - margin.y);
				Text component = val2.GetComponent<Text>();
				component.font = sourceFont;
				component.fontStyle = (FontStyle)0;
				component.alignment = (TextAnchor)0;
				component.supportRichText = true;
				((Graphic)component).raycastTarget = false;
				component.horizontalOverflow = (HorizontalWrapMode)0;
				component.verticalOverflow = (VerticalWrapMode)1;
				component.resizeTextForBestFit = false;
				component.lineSpacing = 1f;
				state.Overlay = component;
				if ((Object)(object)((Component)p).GetComponent<ContentSizeFitter>() != (Object)null || ((Object)(object)((TMP_Text)p).transform.parent != (Object)null && (Object)(object)((Component)((TMP_Text)p).transform.parent).GetComponent<LayoutGroup>() != (Object)null))
				{
					LayoutElement component2 = ((Component)p).GetComponent<LayoutElement>();
					if ((Object)(object)component2 == (Object)null)
					{
						state.Layout = ((Component)p).gameObject.AddComponent<LayoutElement>();
						state.AddedLayout = true;
						state.Layout.layoutPriority = 100;
					}
				}
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Panel renderer: Unity UI Text (full Cyrillic; original TMP retained for BCM layout).");
			}
			Text overlay = state.Overlay;
			int num2 = Mathf.Max(1, Mathf.RoundToInt(num));
			if (overlay.fontSize != num2)
			{
				overlay.fontSize = num2;
			}
			if (Mathf.Abs(((TMP_Text)p).fontSize - num) > 0.01f)
			{
				((TMP_Text)p).fontSize = num;
			}
			if (((Graphic)overlay).color != val)
			{
				((Graphic)overlay).color = val;
			}
			string input = Regex.Replace(((TMP_Text)p).text ?? "", "(?i)<br\\s*/?>", "\n");
			input = Regex.Replace(input, "(?i)<#([0-9a-f]{6,8})>", "<color=#$1>");
			if (overlay.text != input)
			{
				overlay.text = input;
			}
			if ((Object)(object)state.Layout != (Object)null && state.AddedLayout)
			{
				float num3 = overlay.preferredHeight + ((TMP_Text)p).margin.y + ((TMP_Text)p).margin.w;
				if (Mathf.Abs(state.Layout.preferredHeight - num3) > 0.5f)
				{
					state.Layout.preferredHeight = num3;
				}
			}
			if (((TMP_Text)p).maxVisibleCharacters != 0)
			{
				((TMP_Text)p).maxVisibleCharacters = 0;
			}
		}
	}

	private void InitializeFont(TextMeshProUGUI panel)
	{
		fontAttempted = true;
		if (preferBundledFont.Value)
		{
			if (TryBundledFont(panel) || TrySystemFont())
			{
				return;
			}
		}
		else if (TrySystemFont() || TryBundledFont(panel))
		{
			return;
		}
		((BaseUnityPlugin)this).Logger.LogWarning((object)"No complete font could be loaded; keeping original panel.");
	}

	private bool TryBundledFont(TextMeshProUGUI panel)
	{
		try
		{
			string text = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), "JetBrainsMono-Regular.ttf");
			if (!File.Exists(text))
			{
				throw new FileNotFoundException("Bundled font missing", text);
			}
			newFont = CreateBundledFont(text, panel);
			((BaseUnityPlugin)this).Logger.LogInfo((object)"BUNDLED FONT OK: JetBrains Mono; Cyrillic, Latin and digits checked.");
			return true;
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("Bundled font failed: " + ex.GetBaseException()));
			return false;
		}
	}

	private bool TrySystemFont()
	{
		string[] array = new string[6] { fontChoice.Value, "JetBrains Mono", "Cascadia Mono", "Consolas", "Lucida Console", "Arial" };
		HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
		string[] array2 = array;
		foreach (string name in array2)
		{
			if (string.IsNullOrEmpty(name) || !hashSet.Add(name))
			{
				continue;
			}
			Font val = null;
			try
			{
				string[] oSInstalledFontNames = Font.GetOSInstalledFontNames();
				if (oSInstalledFontNames == null || Array.FindIndex(oSInstalledFontNames, (string n) => string.Equals(n, name, StringComparison.OrdinalIgnoreCase)) < 0)
				{
					continue;
				}
				val = Font.CreateDynamicFontFromOSFont(name, 32);
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				val.RequestCharactersInTexture("АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюяABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789−—…!?.,:;+-x×%()[]", 32, (FontStyle)0);
				bool flag = true;
				string text = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюяABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789−—…!?.,:;+-x×%()[]";
				foreach (char c in text)
				{
					if (!val.HasCharacter(c))
					{
						flag = false;
						break;
					}
				}
				if (!flag)
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)("Incomplete OS font: " + name));
					Object.Destroy((Object)(object)val);
					continue;
				}
				sourceFont = val;
				((BaseUnityPlugin)this).Logger.LogInfo((object)("OS font selected: " + name + " (Cyrillic, Latin, digits checked)"));
				break;
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("OS font " + name + ": " + ex.Message));
				if ((Object)(object)val != (Object)null)
				{
					Object.Destroy((Object)(object)val);
				}
			}
		}
		if ((Object)(object)sourceFont == (Object)null)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)"No complete OS font found; trying the packaged font.");
			return false;
		}
		try
		{
			MethodInfo method = typeof(TMP_FontAsset).GetMethod("CreateFontAsset", BindingFlags.Static | BindingFlags.Public, null, new Type[3]
			{
				typeof(string),
				typeof(string),
				typeof(int)
			}, null);
			if (method != null)
			{
				string[] fontNames = sourceFont.fontNames;
				string text2 = ((fontNames != null && fontNames.Length > 0) ? fontNames[0] : fontChoice.Value);
				object? obj = method.Invoke(null, new object[3] { text2, "Regular", 64 });
				TMP_FontAsset val2 = (TMP_FontAsset)((obj is TMP_FontAsset) ? obj : null);
				if ((Object)(object)val2 != (Object)null)
				{
					if (val2.TryAddCharacters("АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюяABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789−—…!?.,:;+-x×%()[]", false) && (Object)(object)((TMP_Asset)val2).material != (Object)null)
					{
						newFont = val2;
						((BaseUnityPlugin)this).Logger.LogInfo((object)("Panel renderer: TMP dynamic OS font: " + text2));
						return true;
					}
					Object.Destroy((Object)(object)val2);
				}
			}
		}
		catch (Exception ex2)
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)("TMP OS font unavailable: " + ex2.GetBaseException().Message));
		}
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Using Unity UI Text fallback with checked OS font.");
		return true;
	}

	private TMP_FontAsset CreateBundledFont(string path, TextMeshProUGUI panel)
	{
		//IL_024a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0253: Unknown result type (might be due to invalid IL or missing references)
		//IL_0258: Unknown result type (might be due to invalid IL or missing references)
		//IL_025a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0275: Unknown result type (might be due to invalid IL or missing references)
		//IL_027a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0263: Unknown result type (might be due to invalid IL or missing references)
		//IL_02e6: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ed: Expected O, but got Unknown
		//IL_0338: Unknown result type (might be due to invalid IL or missing references)
		//IL_0509: Unknown result type (might be due to invalid IL or missing references)
		//IL_0613: Unknown result type (might be due to invalid IL or missing references)
		//IL_061d: Expected O, but got Unknown
		//IL_06a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_06ad: Expected O, but got Unknown
		HashSet<char> hashSet = new HashSet<char>("АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюяABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789−—…!?.,:;+-x×%()[]");
		for (char c = ' '; c <= '~'; c = (char)(c + 1))
		{
			hashSet.Add(c);
		}
		foreach (string value4 in words.Values)
		{
			string text = value4;
			foreach (char c2 in text)
			{
				if (!char.IsControl(c2) && !char.IsSurrogate(c2))
				{
					hashSet.Add(c2);
				}
			}
		}
		StringBuilder stringBuilder = new StringBuilder();
		foreach (char item in hashSet)
		{
			stringBuilder.Append(item);
		}
		MethodInfo method = typeof(TMP_FontAsset).GetMethod("CreateFontAsset", BindingFlags.Static | BindingFlags.Public, null, new Type[7]
		{
			typeof(string),
			typeof(int),
			typeof(int),
			typeof(int),
			typeof(GlyphRenderMode),
			typeof(int),
			typeof(int)
		}, null);
		if (method != null)
		{
			TMP_FontAsset val = null;
			try
			{
				object? obj = method.Invoke(null, new object[7]
				{
					path,
					0,
					64,
					7,
					(object)(GlyphRenderMode)4165,
					2048,
					2048
				});
				val = (TMP_FontAsset)((obj is TMP_FontAsset) ? obj : null);
				if ((Object)(object)val != (Object)null)
				{
					val.TryAddCharacters(stringBuilder.ToString(), false);
					CheckRequiredGlyphs(val);
					((Object)val).name = "KindEvil JetBrains Mono";
					((BaseUnityPlugin)this).Logger.LogInfo((object)"Bundled font renderer: TMP file-path API.");
					return val;
				}
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("TMP file factory: " + ex.GetBaseException().Message));
			}
			if ((Object)(object)val != (Object)null)
			{
				Object.Destroy((Object)(object)val);
			}
		}
		FontEngine.InitializeFontEngine();
		FontEngineError val2 = FontEngine.LoadFontFace(path, 64);
		if ((int)val2 != 0)
		{
			throw new InvalidOperationException("FontEngine: " + val2);
		}
		FaceInfo faceInfo = FontEngine.GetFaceInfo();
		Dictionary<uint, uint> dictionary = new Dictionary<uint, uint>();
		HashSet<uint> hashSet2 = new HashSet<uint>();
		uint num = default(uint);
		foreach (char item2 in hashSet)
		{
			if (FontEngine.TryGetGlyphIndex((uint)item2, ref num) && num != 0)
			{
				dictionary.Add(item2, num);
				hashSet2.Add(num);
			}
		}
		Texture2D val3 = new Texture2D(2048, 2048, (TextureFormat)1, false);
		((Object)val3).name = "KindEvil JetBrains Mono Atlas";
		((Texture)val3).filterMode = (FilterMode)1;
		((Texture)val3).wrapMode = (TextureWrapMode)1;
		val3.LoadRawTextureData(new byte[4194304]);
		val3.Apply(false, false);
		List<GlyphRect> list = new List<GlyphRect>();
		list.Add(new GlyphRect(0, 0, 2047, 2047));
		List<GlyphRect> list2 = list;
		List<GlyphRect> list3 = new List<GlyphRect>();
		MethodInfo method2 = typeof(FontEngine).GetMethod("TryAddGlyphsToTexture", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[8]
		{
			typeof(List<uint>),
			typeof(int),
			typeof(GlyphPackingMode),
			typeof(List<GlyphRect>),
			typeof(List<GlyphRect>),
			typeof(GlyphRenderMode),
			typeof(Texture2D),
			typeof(Glyph[]).MakeByRefType()
		}, null);
		if (method2 == null)
		{
			throw new MissingMethodException("FontEngine atlas packing API not found");
		}
		object[] array = new object[8]
		{
			new List<uint>(hashSet2),
			7,
			(object)(GlyphPackingMode)0,
			list2,
			list3,
			(object)(GlyphRenderMode)4165,
			val3,
			null
		};
		method2.Invoke(null, array);
		if (!(array[7] is Glyph[] array2))
		{
			throw new InvalidOperationException("No packed glyphs");
		}
		Dictionary<uint, Glyph> dictionary2 = new Dictionary<uint, Glyph>();
		Glyph[] array3 = array2;
		foreach (Glyph val4 in array3)
		{
			if (val4 != null && !dictionary2.ContainsKey(val4.index))
			{
				dictionary2.Add(val4.index, val4);
			}
		}
		Glyph value2 = default(Glyph);
		if (dictionary.TryGetValue(32u, out var value) && !dictionary2.ContainsKey(value) && FontEngine.TryGetGlyphWithIndexValue(value, (GlyphLoadFlags)0, ref value2))
		{
			dictionary2.Add(value, value2);
		}
		TMP_FontAsset val5 = ScriptableObject.CreateInstance<TMP_FontAsset>();
		((Object)val5).name = "KindEvil JetBrains Mono";
		SetAssetMember(val5, "version", "1.1.0");
		val5.faceInfo = faceInfo;
		val5.atlasPopulationMode = (AtlasPopulationMode)0;
		SetAssetMember(val5, "atlasWidth", 2048);
		SetAssetMember(val5, "atlasHeight", 2048);
		SetAssetMember(val5, "atlasPadding", 7);
		SetAssetMember(val5, "atlasRenderMode", (object)(GlyphRenderMode)4165);
		val5.atlasTextures = (Texture2D[])(object)new Texture2D[1] { val3 };
		val5.glyphTable.Clear();
		val5.characterTable.Clear();
		foreach (Glyph value5 in dictionary2.Values)
		{
			val5.glyphTable.Add(value5);
		}
		foreach (KeyValuePair<uint, uint> item3 in dictionary)
		{
			if (dictionary2.TryGetValue(item3.Value, out var value3))
			{
				val5.characterTable.Add(new TMP_Character(item3.Key, val5, value3));
			}
		}
		Shader val6 = Shader.Find("TextMeshPro/Mobile/Distance Field");
		if ((Object)(object)val6 == (Object)null)
		{
			val6 = Shader.Find("TextMeshPro/Distance Field");
		}
		if ((Object)(object)val6 == (Object)null && (Object)(object)((TMP_Text)panel).fontSharedMaterial != (Object)null && ((TMP_Text)panel).fontSharedMaterial.HasProperty("_GradientScale"))
		{
			val6 = ((TMP_Text)panel).fontSharedMaterial.shader;
		}
		if ((Object)(object)val6 == (Object)null)
		{
			throw new InvalidOperationException("TMP SDF shader not found");
		}
		Material val7 = new Material(val6);
		((Object)val7).name = "KindEvil JetBrains Mono Material";
		val7.mainTexture = (Texture)(object)val3;
		val7.SetFloat("_TextureWidth", 2048f);
		val7.SetFloat("_TextureHeight", 2048f);
		val7.SetFloat("_GradientScale", 8f);
		((TMP_Asset)val5).material = val7;
		val3.Apply(false, false);
		val5.ReadFontAssetDefinition();
		CheckRequiredGlyphs(val5);
		((BaseUnityPlugin)this).Logger.LogInfo((object)("Bundled font renderer: TextCore static atlas; " + val5.characterTable.Count + " characters."));
		return val5;
	}

	private static void SetAssetMember(TMP_FontAsset asset, string name, object value)
	{
		PropertyInfo property = typeof(TMP_FontAsset).GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
		MethodInfo methodInfo = ((property == null) ? null : property.GetSetMethod(nonPublic: true));
		if (methodInfo == null)
		{
			throw new MissingMethodException("TMP font property setter: " + name);
		}
		methodInfo.Invoke(asset, new object[1] { value });
	}

	private static void CheckRequiredGlyphs(TMP_FontAsset asset)
	{
		if ((Object)(object)((TMP_Asset)asset).material == (Object)null)
		{
			throw new InvalidOperationException("Font material missing");
		}
		string text = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюяABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789−—…!?.,:;+-x×%()[]";
		foreach (char c in text)
		{
			if (!asset.HasCharacter(c, false, false))
			{
				int num = c;
				throw new InvalidOperationException("Missing bundled glyph U+" + num.ToString("X4"));
			}
		}
	}

	private string Translate(string raw)
	{
		string input = Tokens.Replace(raw, delegate(Match m)
		{
			string value = m.Value;
			return value.StartsWith("<") ? value : Regex.Replace(value, "[^\\r\\n]+", (Match line) => TranslateLine(line.Value));
		});
		input = Regex.Replace(input, "(?i)<color=#FFFFFF>(СОБЫТИЯ:)</color>", "<color=#00FF00>$1</color>");
		if (softerColors.Value)
		{
			input = ColorTags.Replace(input, (Match m) => (!Palette.TryGetValue(m.Groups[2].Value, out var value)) ? m.Value : (m.Groups[1].Value + value + m.Groups[3].Value));
		}
		return input;
	}

	private string TranslateLine(string line)
	{
		string text = line.Trim();
		if (text.Length == 0)
		{
			return line;
		}
		int num = line.IndexOf(text, StringComparison.Ordinal);
		string text2 = line.Substring(0, num);
		string text3 = line.Substring(num + text.Length);
		if (words.TryGetValue(text, out var value))
		{
			return text2 + value + text3;
		}
		string text4 = "";
		if (text.StartsWith("-") && text.Length > 1)
		{
			text4 = "− ";
			text = text.Substring(1).TrimStart(new char[0]);
			if (words.TryGetValue(text, out value))
			{
				return text2 + text4 + value + text3;
			}
		}
		for (int i = 0; i < labels.GetLength(0); i++)
		{
			if (text.StartsWith(labels[i, 0], StringComparison.OrdinalIgnoreCase))
			{
				string text5 = labels[i, 1];
				if (text4.Length > 0 && labels[i, 0] == "Difficulty:")
				{
					text5 = "Итог:";
				}
				string text6 = text.Substring(labels[i, 0].Length).TrimStart(new char[0]);
				if (words.TryGetValue(text6, out value))
				{
					text6 = value;
				}
				if (text4.Length > 0)
				{
					return text2 + text4 + text5 + " " + text6;
				}
				return text2 + text5 + ((text6.Length > 0) ? (" " + text6) : text3);
			}
		}
		if (line.Trim() == "-")
		{
			return text2 + "− " + text3;
		}
		return line;
	}
}