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 NajRoles v1.7.3
BepInEx/plugins/NajRoles/NajRoles.dll
Decompiled a day 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.Security; using System.Security.Cryptography; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using ExitGames.Client.Photon; using HarmonyLib; using MenuLib; using MenuLib.MonoBehaviors; using Microsoft.CodeAnalysis; using NuageRoles.Roles; using NuageRoles.Roles.Patches; using Photon.Pun; using Photon.Realtime; using REPOLib; using REPOLib.Modules; using TMPro; using Unity.VisualScripting; using UnityEngine; using UnityEngine.AI; using UnityEngine.EventSystems; using UnityEngine.Events; using UnityEngine.Networking; using UnityEngine.Rendering; using UnityEngine.SceneManagement; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("NajRoles")] [assembly: AssemblyDescription("R.E.P.O. roles with EN/RU localization and role upgrades.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("TheoHay, GangDesNuages")] [assembly: AssemblyProduct("NajRoles")] [assembly: AssemblyCopyright("")] [assembly: ComVisible(false)] [assembly: Guid("b55829e7-8346-4258-b5db-23566f7af06b")] [assembly: AssemblyFileVersion("1.7.3")] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.7.3.0")] [module: UnverifiableCode] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } } namespace NuageRoles { internal static class AbilityHudText { internal static string GnomeSummonLine(string key, string name, int count, int limit, bool available, bool active) { bool flag = limit - count < 5; return Line(key, $"{name} {count}/{limit}", 0.0, available && !flag, "s", active && !flag); } internal static string Line(string key, string name, double remaining = 0.0, bool available = true, string seconds = "s", bool active = false) { bool flag = remaining > 0.0; string text = (active ? "FFFFFF" : ((flag || !available) ? "FF5555" : "66FF66")); string text2 = (flag ? (" " + Math.Ceiling(remaining).ToString("0", CultureInfo.InvariantCulture) + " " + seconds) : string.Empty); return "<color=#" + text + ">[" + key + "] <size=90%>" + name + text2 + "</size></color>"; } } internal static class ConfigTranslations { internal const string MagnetDisplayName = "Magnet (WIP)"; internal static readonly string[] RoleIds = LobbyRoleChoice.Names; private static readonly string[] RussianRoles = new string[13] { "Случайная", "Бегун", "Танк", "Лудоман", "Силач", "", "Атлет", "Маг", "Жнец", "Скаут", "Обычный", "Инженер", "Магнит (WIP)" }; private static readonly Dictionary<string, string> descriptions = new Dictionary<string, string> { ["Runner"] = "У вас больше выносливости, и вы бегаете намного быстрее остальных!", ["Tank"] = "Вы медленнее, но у вас вдвое больше здоровья!", ["Gambler"] = "Любитель риска и случайных исходов.", ["Strongman"] = "Вы невероятно сильны!", ["Athletic"] = "У вас больше выносливости и силы, и вы прыгаете выше!", ["Mage"] = "Используйте ману для лечения, восстановления выносливости и атаки!", ["Reaper"] = "Смерть врага в радиусе [RADIUS] м восстанавливает здоровье и даёт одну душу независимо от запаса здоровья.", ["Scout"] = "Ваша выносливость эффективнее. [C] Сенсор открывает ближайшие ценности для команды. [F] Чутье хищника на 60 секунд подсвечивает вам всех активных врагов через стены; остальные игроки видят их красными точками на карте во время действия. Затем начинается перезарядка. Улучшение перезарядки сокращает оба независимых таймера.", ["Regular"] = "Бонусы от улучшений характеристик усилены на [BONUS]%.", ["Engineer"] = "Вы заряжаете снаряжение в инвентаре и чините ценности.", ["Magnet"] = "Вы управляете движением и инерцией предметов." }; private static readonly Dictionary<string, string[]> entries = new Dictionary<string, string[]> { ["Your selected role"] = new string[2] { "Выбранная роль", "Предпочтительная роль игрока. Если она отключена, временно выбирается случайная доступная роль." }, ["Reaasign roles after being revived"] = new string[2] { "Менять роль после воскрешения", "После смерти и воскрешения игрок получает новую роль согласно выбранным настройкам." }, ["Place where mana is shown"] = new string[2] { "Показывать ману сверху", "Включено: мана сверху экрана. Выключено: рядом с индикатором выносливости." }, ["Show GUI when being assigned a role"] = new string[2] { "Показывать описание при выдаче роли", "Открывает окно с названием и описанием выданной роли." }, ["Ability HUD Font Size Percent"] = new string[2] { "Размер текста подсказок способностей, %", "Локальный размер подсказок способностей под полосой выносливости. 100% — стандартный размер." }, ["Enable Role Upgrades in Shop"] = new string[2] { "Улучшения ролей в магазине", "Разрешает продажу улучшений NajRoles." }, ["Only Team Role Upgrades in Shop"] = new string[2] { "В магазине появляются только апгрейды из пула ролей", "Настройка хоста. Ролевые апгрейды учитывают выбор команды перед входом в магазин. Для Random берётся последняя назначенная роль. Обычные апгрейды остаются." }, ["Only Own Role Upgrades"] = new string[2] { "Только апгрейды своей роли", "Настройка хоста. Ролевые апгрейды можно использовать только на уровне и только для своей роли." }, ["GUI Toggle Key"] = new string[2] { "Клавиша окна роли", "Показать или скрыть окно с описанием текущей роли." }, ["Activate Scout Ability"] = new string[2] { "Клавиша сенсора", "Активирует сенсор скаута. По умолчанию C." }, ["Scout Predator Sense"] = new string[2] { "Клавиша чутья хищника", "Активирует чутье хищника скаута. По умолчанию F." }, ["Show Spells"] = new string[2] { "Клавиша списка заклинаний", "Показать или скрыть список заклинаний мага." }, ["Healing Spell"] = new string[2] { "Клавиша лечения", "Удерживайте для облака лечения вокруг мага." }, ["Godzilla Beam"] = new string[2] { "Клавиша «Годзиллы»", "Удерживайте, чтобы выпустить луч мага." }, ["Jump Boost Spell"] = new string[2] { "Клавиша невесомости", "Применить к себе эффект невесомости посоха." }, ["You Shall Not Pass Spell"] = new string[2] { "Клавиша «Ты не пройдешь!»", "Оттолкнуть монстров; Маг получает 10 урона за каждого задетого монстра без собственного отбрасывания." }, ["Stamina Refill Spell"] = new string[2] { "Клавиша восстановления выносливости", "Полностью восстановить выносливость заклинанием мага." }, ["Charge Held Item"] = new string[2] { "Клавиша ремонта", "Инженер чинит ценность в хвате." }, ["Magnetic Pull Key"] = new string[2] { "Клавиша магнитного притяжения", "Нажмите, чтобы притянуть выбранный предмет. Нажмите ещё раз, чтобы отпустить. По умолчанию C." }, ["Magnetic Launch Key"] = new string[2] { "Клавиша магнитного броска", "Удерживайте для зарядки и отпустите для броска. По умолчанию F." }, ["Speed Multiplier"] = new string[2] { "Множитель скорости", "Множитель скорости передвижения выбранной роли или её заклинания." }, ["Stamina Multiplier"] = new string[2] { "Множитель выносливости", "Множитель максимальной и текущей выносливости роли." }, ["Health Multiplier"] = new string[2] { "Множитель здоровья", "Множитель максимального и текущего здоровья при выдаче роли." }, ["Passive Regen Amount"] = new string[2] { "Количество пассивного лечения", "Здоровье, восстанавливаемое танком за один такт пассивного лечения." }, ["Passive Regen Interval Seconds"] = new string[2] { "Интервал пассивного лечения, с", "Время между тактами пассивного лечения танка в секундах." }, ["Strength Multiplier"] = new string[2] { "Множитель силы", "Множитель силы захвата роли." }, ["Strength Bonus"] = new string[2] { "Прибавка силы", "Дополнительная сила захвата после применения множителя силача." }, ["Grab Range Multiplier"] = new string[2] { "Множитель дальности захвата", "Множитель расстояния, с которого можно захватывать предметы." }, ["Stamina Bonus"] = new string[2] { "Прибавка выносливости", "Добавка к максимальной и текущей выносливости." }, ["Jump Force Bonus"] = new string[2] { "Прибавка силы прыжка", "Добавка к силе прыжка роли." }, ["Extra Jumps"] = new string[2] { "Дополнительные прыжки", "Дополнительные прыжки Атлета в воздухе. Один даёт двойной прыжок; складывается с купленными улучшениями прыжков." }, ["Heal Amount Per Enemy"] = new string[2] { "Лечение за врага", "Здоровье, восстанавливаемое живому Жнецу при смерти врага в радиусе вампиризма." }, ["Vampirism Radius"] = new string[2] { "Радиус вампиризма, м", "Максимальная дистанция до умирающего врага для лечения и сбора душ." }, ["Buff Cooldown Frames"] = new string[2] { "Перезарядка лечения, кадров", "Количество кадров обновления между срабатываниями лечения за смерть врага." }, ["Sprint Recharge Multiplier"] = new string[2] { "Множитель восстановления выносливости", "Множитель скорости восстановления выносливости скаута." }, ["Ability Cooldown Seconds"] = new string[2] { "Перезарядка чутья хищника, с", "Базовый кулдаун чутья хищника после 60 секунд действия. Улучшение сокращает оба независимых таймера." }, ["Sensor Cooldown Seconds"] = new string[2] { "Перезарядка сенсора, с", "Базовый кулдаун сенсора. Улучшение сокращает оба независимых таймера." }, ["Treasure Sense Radius"] = new string[2] { "Радиус сенсора, м", "Настройка хоста: радиус обнаружения ценностей и скинов в метрах." }, ["Max Mana"] = new string[2] { "Максимум маны", "Максимальный запас маны мага." }, ["Heal Amount"] = new string[2] { "Сила лечения", "Количество здоровья каждому игроку за тик облака лечения." }, ["Charge Stamina Cost"] = new string[2] { "Цена ремонта в выносливости", "Временная потеря максимума выносливости при ремонте ценности." }, ["Stamina Restore Amount"] = new string[2] { "Восстановление максимума выносливости", "Количество потраченного максимума выносливости, возвращаемое инженеру за один такт." }, ["Stamina Restore Interval Seconds"] = new string[2] { "Интервал возврата выносливости, с", "Время между тактами восстановления потраченного максимума выносливости инженера." } }; public static string RoleName(string id) { int num = Array.IndexOf(RoleIds, (id == "Magnet (WIP)") ? "Magnet" : id); if (num < 0) { return id; } return RussianRoles[num]; } internal static string EnglishRoleName(string id) { if (!(id == "Magnet")) { return id; } return "Magnet (WIP)"; } public static string RoleDescription(string key) { string key2 = (key.EndsWith(" Description", StringComparison.Ordinal) ? key.Substring(0, key.Length - 12) : key); if (!descriptions.TryGetValue(key2, out string value)) { return key; } return value; } public static string Section(string section) { return section switch { "General" => "Общие", "GUI" => "Интерфейс и клавиши", "Role" => "Роли", "Role Names" => "Названия ролей", "Role Descriptions" => "Описания ролей", "Upgrades" => "Улучшения", "Reaper Upgrade" => "Улучшение Жнеца", _ => RoleName(section), }; } public static bool IsLegacyRoleDescription(string value) { switch (value) { default: return value == "Your stamina is more efficient and by pressing [G] you can see all enemies around you."; case "Используйте ману для лечения и усиливающих заклинаний!": case "Your stamina is more efficient. [C] Sensor discovers nearby valuables for the team. [F] Predator Sense highlights all active enemies through walls for you for 60 seconds, then starts its cooldown. Scout Cooldown Upgrade reduces both independent cooldowns.": case "Ваша выносливость эффективнее. [C] Сенсор открывает ближайшие ценности для команды. [F] Чутье хищника на 60 секунд подсвечивает вам всех активных врагов через стены. Затем начинается перезарядка. Улучшение перезарядки сокращает оба независимых таймера.": case "Your stamina is more efficient. [C] Sensor discovers nearby valuables for the team. [F] Predator Sense marks nearby enemies on everyone's map temporarily. Scout Cooldown Upgrade reduces both independent cooldowns.": case "Ваша выносливость эффективнее. [C] Сенсор открывает ближайшие ценности для команды. [F] Чутье хищника временно отмечает врагов на карте всех игроков. Улучшение перезарядки сокращает оба независимых таймера.": case "Enemies dying within [RADIUS] m restore your health. At full health, Harvest grants one soul per enemy.": case "Смерть врага в радиусе [RADIUS] м восстанавливает здоровье. При полном здоровье «Жатва» даёт одну душу за каждого врага.": case "Your stamina is more efficient. [C] Treasure Sense discovers nearby valuables for the team. [F] Predator Sense marks nearby enemies on everyone's map temporarily. Scout Cooldown Upgrade reduces both independent cooldowns.": case "Ваша выносливость эффективнее. [C] Чутьё сокровищ открывает ближайшие ценности для команды. [F] Чутьё хищника временно отмечает врагов на карте всех игроков. Улучшение перезарядки сокращает оба независимых таймера.": case "Your stamina is more efficient. [G] Treasure Sense discovers nearby valuables for the team. [H] Predator Sense marks nearby enemies on everyone's map temporarily. Scout Cooldown Upgrade reduces both independent cooldowns.": case "Ваша выносливость эффективнее. [G] Чутьё сокровищ открывает ближайшие ценности для команды. [H] Чутьё хищника временно отмечает врагов на карте всех игроков. Улучшение перезарядки сокращает оба независимых таймера.": case "For each enemy you and your friends kill, you become stronger!": case "Enemies dying within [RADIUS]m restore your health and increase your maximum health. Distant deaths grant no bonus.": case "Смерть врага в радиусе [RADIUS] м восстанавливает здоровье и повышает его максимум. Дальние смерти бонуса не дают.": case "You can recharge Items with on charge but you lose Stamina": case "You rolled random effects:": case "Shots at yourself or teammates have a [CHANCE]% chance to heal. A consumed upgrade can give 0, 1 or 2 levels.": case "Выстрелы по себе и союзникам лечат с шансом [CHANCE]%. Апгрейды могут дать 0, 1 или 2 уровня.": case "Shots at yourself or teammates have a 50% chance to heal. Each consumed upgrade gives 0, 1 or 2 levels with equal odds.": case "Выстрелы по себе и союзникам лечат с шансом 50%. Апгрейды дают 0, 1 или 2 уровня с равным шансом.": case "Your stat upgrades are 10% stronger.": case "Бонусы от улучшений характеристик усилены на 10%.": case "Вы получили случайные эффекты:": case "You are just a regular Semibot. Nothing special.": return true; } } public static void RegisterAll(ConfigFile config) { foreach (KeyValuePair<ConfigDefinition, ConfigEntryBase> item in config) { ConfigEntryBase value = item.Value; string key = value.Definition.Key; if (!(key == "Language") && !(value.Definition.Section == "Internal")) { string[] value2; if (value.Definition.Section == "Role Names") { string id = key.Substring(0, key.Length - 5); ModLocalization.RegisterSetting(value, "Название: " + RoleName(id), "Собственное название роли. Изменённое пользователем значение сохраняется при смене языка."); } else if (value.Definition.Section == "Role Descriptions") { string id2 = key.Substring(0, key.Length - 12); ModLocalization.RegisterSetting(value, "Описание: " + RoleName(id2), "Собственное описание роли. Изменённый пользователем текст сохраняется при смене языка. Обозначения клавиш и [RADIUS] подставляются автоматически."); } else if (key.StartsWith("Enable ", StringComparison.Ordinal) && value.Definition.Section == "Role") { string id3 = key.Substring(7); ModLocalization.RegisterSetting(value, "Включить: " + RoleName(id3), "Разрешает выбрать роль «" + RoleName(id3) + "» и выдать её случайно."); } else if (entries.TryGetValue(key, out value2)) { ModLocalization.RegisterSetting(value, value2[0], value2[1]); } else { NuageRolesPlugin.Logger.LogWarning((object)("Missing Russian settings translation: " + (object)value.Definition)); } } } } } internal sealed class LateJoinRoles : MonoBehaviourPunCallbacks { private const string RunStartedProperty = "NajRoles.RunStarted"; private REPOPopupPage? choicePage; private Scene choiceScene; private bool awaitingChoice; private int? queuedRole; private float nextPhasePublish; public override void OnJoinedRoom() { Reset(); awaitingChoice = !PhotonNetwork.IsMasterClient && ((Dictionary<object, object>)(object)((RoomInfo)PhotonNetwork.CurrentRoom).CustomProperties).TryGetValue((object)"NajRoles.RunStarted", out object value) && value is bool && (bool)value; } public override void OnLeftRoom() { Reset(); } private void Reset() { CloseChoicePage(); awaitingChoice = false; queuedRole = null; nextPhasePublish = 0f; Sender.ResetAssignment(); } private void LateUpdate() { //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) RunManager instance = RunManager.instance; if ((Object)(object)instance == (Object)null || (Object)(object)instance.levelCurrent == (Object)null) { return; } bool inIntermission = RoleGameplayRelay.InIntermission; bool inPlay = RoleGameplayRelay.InPlay; bool started = SemiFunc.RunIsLobby() || SemiFunc.RunIsShop() || SemiFunc.RunIsLevel(); PublishRunPhase(started); if (awaitingChoice) { if ((Object)(object)choicePage != (Object)null && (choiceScene != SceneManager.GetActiveScene() || !Sender.ArrivalReady)) { CloseChoicePage(); } if ((Object)(object)choicePage == (Object)null && CanChooseRole() && (Object)(object)MenuManager.instance.currentMenuPage == (Object)null && ((Object)(object)ChatManager.instance == (Object)null || !ChatManager.instance.chatActive)) { OpenChoicePage(); } return; } CloseChoicePage(); int? num = queuedRole; int valueOrDefault = default(int); int num2; if (num.HasValue) { valueOrDefault = num.GetValueOrDefault(); num2 = 1; } else { num2 = 0; } if (((uint)num2 & (inIntermission ? 1u : 0u)) != 0 && Sender.SpawnReady && LobbySettings.Ready && Sender.TryGetSpawnedPlayer(out PlayerAvatar avatar, out PlayerController _)) { ((Component)avatar).GetComponent<RoleGameplayRelay>()?.StageIntermissionRole(valueOrDefault); } if (inPlay && Sender.AssignRoleOncePerScene(queuedRole)) { queuedRole = null; } } private void PublishRunPhase(bool started) { //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Expected O, but got Unknown if (PhotonNetwork.InRoom && PhotonNetwork.IsMasterClient && !(Time.unscaledTime < nextPhasePublish)) { Room currentRoom = PhotonNetwork.CurrentRoom; if (!((Dictionary<object, object>)(object)((RoomInfo)currentRoom).CustomProperties).TryGetValue((object)"NajRoles.RunStarted", out object value) || !object.Equals(value, started)) { nextPhasePublish = Time.unscaledTime + 0.25f; currentRoom.SetCustomProperties(new Hashtable { [(object)"NajRoles.RunStarted"] = started }, (Hashtable)null, (WebFlags)null); } } } private static bool CanChooseRole() { PlayerAvatar avatar; PlayerController controller; if (PhotonNetwork.InRoom && LobbySettings.Ready && Sender.ArrivalReady && (RoleGameplayRelay.InPlay || RoleGameplayRelay.InIntermission) && (Object)(object)MenuManager.instance != (Object)null && !MenuManager.instance.textInputActive) { return Sender.TryGetSpawnedPlayer(out avatar, out controller); } return false; } private void OpenChoicePage() { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) if (NuageRolesPlugin.Settings.GetAvailableRoleChoices().Length <= 1) { UseChosenRole(); return; } choiceScene = SceneManager.GetActiveScene(); try { choicePage = new LobbyRolePicker(NuageRolesPlugin.Settings).CreateLateJoinPage(UseChosenRole, CanChooseRole); } catch (Exception arg) { NuageRolesPlugin.Logger.LogError((object)$"Could not open the late-join role picker: {arg}"); UseChosenRole(); } } private void UseChosenRole() { if (awaitingChoice) { queuedRole = Sender.manager.RollSelectedRole(); awaitingChoice = false; } } private void CloseChoicePage() { if ((Object)(object)choicePage != (Object)null) { LobbyRolePicker.CloseLateJoinPage(choicePage); } choicePage = null; } } [HarmonyPatch(typeof(MenuPlayerListed), "Update")] internal static class LobbyPlayerRoleLabels { private static readonly FieldInfo? PlayerField = AccessTools.Field(typeof(MenuPlayerListed), "playerPhoton"); private static readonly ConditionalWeakTable<MenuPlayerListed, TextMeshProUGUI> Labels = new ConditionalWeakTable<MenuPlayerListed, TextMeshProUGUI>(); [HarmonyPostfix] private static void UpdateRole(MenuPlayerListed __instance) { //IL_01d5: Unknown result type (might be due to invalid IL or missing references) //IL_0223: Unknown result type (might be due to invalid IL or missing references) //IL_0228: Unknown result type (might be due to invalid IL or missing references) //IL_022c: 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_0268: Unknown result type (might be due to invalid IL or missing references) //IL_026c: Unknown result type (might be due to invalid IL or missing references) //IL_0248: Unknown result type (might be due to invalid IL or missing references) //IL_024d: Unknown result type (might be due to invalid IL or missing references) //IL_0251: Unknown result type (might be due to invalid IL or missing references) //IL_0256: Unknown result type (might be due to invalid IL or missing references) //IL_0271: Unknown result type (might be due to invalid IL or missing references) //IL_0284: Unknown result type (might be due to invalid IL or missing references) //IL_0286: Unknown result type (might be due to invalid IL or missing references) //IL_028b: Unknown result type (might be due to invalid IL or missing references) //IL_02a9: Unknown result type (might be due to invalid IL or missing references) //IL_02ae: Unknown result type (might be due to invalid IL or missing references) //IL_02b3: Unknown result type (might be due to invalid IL or missing references) //IL_02c6: Unknown result type (might be due to invalid IL or missing references) //IL_02c8: Unknown result type (might be due to invalid IL or missing references) //IL_02e2: Unknown result type (might be due to invalid IL or missing references) TextMeshProUGUI source = __instance.playerName; if ((Object)(object)source == (Object)null || (Object)(object)((Component)__instance).GetComponentInParent<MenuPageLobby>() == (Object)null || !SemiFunc.RunIsLobbyMenu()) { if (Labels.TryGetValue(__instance, out TextMeshProUGUI value) && (Object)(object)value != (Object)null) { ((Behaviour)value).enabled = false; } return; } MenuPageLobby componentInParent = ((Component)__instance).GetComponentInParent<MenuPageLobby>(); TextMeshProUGUI value2 = Labels.GetValue(__instance, (MenuPlayerListed _) => CreateLabel(source, ((Component)__instance).transform)); if ((Object)(object)value2 == (Object)null) { return; } object? obj = PlayerField?.GetValue(__instance); object obj2 = ((obj is Player) ? obj : null); if (obj2 == null) { PlayerAvatar playerAvatar = __instance.playerAvatar; if (playerAvatar == null) { obj2 = null; } else { PhotonView photonView = playerAvatar.photonView; obj2 = ((photonView != null) ? photonView.Owner : null); } } Player val = (Player)obj2; bool flag = __instance.isLocal || (val != null && val.IsLocal) || ((Object)(object)__instance.playerAvatar != (Object)null && __instance.playerAvatar.isLocal); string text = null; string choice; if (flag) { text = NuageRolesPlugin.Settings.SelectedRoleChoice; } else if (LobbyRoleNetwork.TryGetRole(val, out choice)) { text = choice; } string text2 = ((string.IsNullOrEmpty(text) || Array.IndexOf(ConfigTranslations.RoleIds, text) < 0) ? "—" : NuageRolesPlugin.Settings.RoleDisplayName(text)); if (((TMP_Text)value2).text != text2) { ((TMP_Text)value2).text = text2; } if ((Object)(object)((TMP_Text)value2).font != (Object)(object)((TMP_Text)source).font) { ((TMP_Text)value2).font = ((TMP_Text)source).font; ((TMP_Text)value2).fontSharedMaterial = ((TMP_Text)source).fontSharedMaterial; ModLocalization.EnsureCyrillicFallback((TMP_Text?)(object)value2); } ((Graphic)value2).color = ((Graphic)source).color; ((TMP_Text)value2).alignment = (TextAlignmentOptions)513; ((Behaviour)value2).enabled = ((Behaviour)source).enabled; ((TMP_Text)value2).fontSizeMax = 12f; ((TMP_Text)value2).fontSizeMin = 8f; ((TMP_Text)value2).fontSize = ((TMP_Text)value2).fontSizeMax; Bounds textBounds = ((TMP_Text)source).textBounds; Vector3 val2; if (!(((Bounds)(ref textBounds)).size.y > 0f)) { Rect rect = ((TMP_Text)source).rectTransform.rect; val2 = Vector2.op_Implicit(((Rect)(ref rect)).center); } else { textBounds = ((TMP_Text)source).textBounds; val2 = ((Bounds)(ref textBounds)).center; } Vector3 val3 = val2; float y = ((Component)componentInParent).transform.InverseTransformPoint(((Transform)((TMP_Text)source).rectTransform).TransformPoint(val3)).y; Vector3 val4 = ((Component)componentInParent).transform.TransformPoint(new Vector3(360f, y, 0f)); ((Transform)((TMP_Text)value2).rectTransform).localPosition = ((Component)__instance).transform.InverseTransformPoint(val4); ((TMP_Text)value2).rectTransform.sizeDelta = new Vector2(95f, 28f); } private static TextMeshProUGUI CreateLabel(TextMeshProUGUI source, Transform row) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005e: 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_0093: Unknown result type (might be due to invalid IL or missing references) GameObject val = new GameObject("NajRoles Lobby Player Role", new Type[1] { typeof(RectTransform) }); val.layer = ((Component)source).gameObject.layer; TextMeshProUGUI val2 = val.AddComponent<TextMeshProUGUI>(); RectTransform rectTransform = ((TMP_Text)val2).rectTransform; ((Transform)rectTransform).SetParent(row, false); Vector2 val3 = default(Vector2); ((Vector2)(ref val3))..ctor(0f, 0.5f); rectTransform.anchorMax = val3; rectTransform.anchorMin = val3; rectTransform.pivot = new Vector2(0f, 0.5f); ((TMP_Text)val2).font = ((TMP_Text)source).font; ((TMP_Text)val2).fontSharedMaterial = ((TMP_Text)source).fontSharedMaterial; ((TMP_Text)val2).fontStyle = ((TMP_Text)source).fontStyle; ((TMP_Text)val2).alignment = (TextAlignmentOptions)513; ((TMP_Text)val2).enableAutoSizing = true; ((TMP_Text)val2).enableWordWrapping = false; ((TMP_Text)val2).overflowMode = (TextOverflowModes)1; ((TMP_Text)val2).richText = false; ((Graphic)val2).raycastTarget = false; ModLocalization.EnsureCyrillicFallback((TMP_Text?)(object)val2); return val2; } } internal static class LobbyRoleChoice { internal static readonly string[] Names = new string[13] { "Random", "Runner", "Tank", "Gambler", "Strongman", "", "Athletic", "Mage", "Reaper", "Scout", "Regular", "Engineer", "Magnet" }; internal static bool IsKnown(string? choice) { if (!string.IsNullOrEmpty(choice)) { return Array.IndexOf<string>(Names, choice) >= 0; } return false; } } internal sealed class LobbyRoleNetwork : MonoBehaviourPunCallbacks { internal const string PropertyKey = "NajRoles.RoleChoice"; private ConfigEntry<string>? savedRole; private Func<string>? selectedRole; private float nextCheck; internal void Bind(ConfigEntry<string> role, Func<string>? resolveSelection = null) { if (savedRole != null) { savedRole.SettingChanged -= SelectionChanged; } savedRole = role; selectedRole = resolveSelection; savedRole.SettingChanged += SelectionChanged; Publish(); } private void SelectionChanged(object? sender, EventArgs args) { Publish(); } private void Publish(bool force = false) { //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Expected O, but got Unknown Player localPlayer = PhotonNetwork.LocalPlayer; string text = selectedRole?.Invoke() ?? savedRole?.Value; if (localPlayer != null && LobbyRoleChoice.IsKnown(text) && (force || !TryGetRole(localPlayer, out string choice) || !(choice == text))) { localPlayer.SetCustomProperties(new Hashtable { [(object)"NajRoles.RoleChoice"] = text }, (Hashtable)null, (WebFlags)null); } } internal static bool TryGetRole(Player? player, out string choice) { choice = string.Empty; if (player == null || !((Dictionary<object, object>)(object)player.CustomProperties).TryGetValue((object)"NajRoles.RoleChoice", out object value) || !(value is string text) || !LobbyRoleChoice.IsKnown(text)) { return false; } choice = text; return true; } public override void OnJoinedRoom() { Publish(force: true); } private void Update() { if (!(Time.unscaledTime < nextCheck)) { nextCheck = Time.unscaledTime + 1f; Publish(); } } private void OnDestroy() { if (savedRole != null) { savedRole.SettingChanged -= SelectionChanged; } } } internal sealed class LobbyRolePicker { private sealed class PickerView : MonoBehaviour { private NuageRolesConfig config; private string draft = string.Empty; private RoleInfoWindow? descriptionPage; private REPOLabel? roleLabel; private float nextRefresh; private Action? onConfirmed; private Func<bool>? canChoose; private int lastInfoEscapeFrame = -1; internal bool ReturnedFromInfoThisFrame => lastInfoEscapeFrame == Time.frameCount; internal void Initialize(NuageRolesConfig settings, Action? onConfirmed, Func<bool>? canChoose) { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0054: 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_0097: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_0161: Unknown result type (might be due to invalid IL or missing references) //IL_0187: Unknown result type (might be due to invalid IL or missing references) //IL_0196: Unknown result type (might be due to invalid IL or missing references) //IL_01d7: Unknown result type (might be due to invalid IL or missing references) //IL_01e6: Unknown result type (might be due to invalid IL or missing references) //IL_027e: Unknown result type (might be due to invalid IL or missing references) //IL_0299: Unknown result type (might be due to invalid IL or missing references) //IL_02b3: Unknown result type (might be due to invalid IL or missing references) //IL_022f: Unknown result type (might be due to invalid IL or missing references) //IL_023e: Unknown result type (might be due to invalid IL or missing references) config = settings; draft = config.SelectedRoleChoice; this.onConfirmed = onConfirmed; this.canChoose = canChoose; ArrowButton(right: false, Previous, new Vector2(-86f, 0f)); roleLabel = MenuAPI.CreateREPOLabel(string.Empty, ((Component)this).transform, Vector2.zero); ((REPOElement)roleLabel).rectTransform.sizeDelta = new Vector2(140f, 30f); ((REPOElement)roleLabel).rectTransform.pivot = new Vector2(0.5f, 0.5f); ((TMP_Text)roleLabel.labelTMP).rectTransform.pivot = new Vector2(0.5f, 0.5f); ((TMP_Text)roleLabel.labelTMP).rectTransform.sizeDelta = new Vector2(140f, 30f); ((TMP_Text)roleLabel.labelTMP).alignment = (TextAlignmentOptions)514; ((TMP_Text)roleLabel.labelTMP).enableAutoSizing = true; ((TMP_Text)roleLabel.labelTMP).fontSizeMax = 24f; ((TMP_Text)roleLabel.labelTMP).fontSizeMin = 10f; ModLocalization.ApplyFont((TMP_Text)(object)roleLabel.labelTMP); ArrowButton(right: true, Next, new Vector2(86f, 0f)); REPOButton val = Button("Info", OpenDescription, new Vector2(122f, 0f), new Vector2(44f, 30f), 12f); ModLocalization.BindLabel((TMP_Text)(object)val.labelTMP, "Info", "Инфо"); REPOButton val2 = Button("Confirm", Confirm, new Vector2(0f, -40f), new Vector2(200f, 30f)); ModLocalization.BindLabel((TMP_Text)(object)val2.labelTMP, "Confirm", "Подтвердить"); if (onConfirmed == null) { REPOButton val3 = Button(string.Empty, config.OpenMenu, new Vector2(122f, -40f), new Vector2(44f, 30f)); ((Object)((Component)val3).gameObject).name = "NajRoles Lobby Settings"; LobbySettingsIcon.Add(val3); } else { REPOLabel val4 = MenuAPI.CreateREPOLabel(string.Empty, ((Component)this).transform, new Vector2(0f, -73f)); ((REPOElement)val4).rectTransform.sizeDelta = new Vector2(230f, 22f); ((REPOElement)val4).rectTransform.pivot = new Vector2(0.5f, 0.5f); ((TMP_Text)val4.labelTMP).alignment = (TextAlignmentOptions)514; ((TMP_Text)val4.labelTMP).fontSize = 12f; ModLocalization.BindLabel((TMP_Text)(object)val4.labelTMP, "Esc to use your saved choice", "Esc — использовать сохранённый выбор"); } ModLocalization.LanguageChanged += Refresh; Refresh(); } private REPOButton Button(string text, Action click, Vector2 position, Vector2 size, float fontSize = 18f) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) return RoleMenuButton.Create(text, click, ((Component)this).transform, position, size, fontSize); } private void ArrowButton(bool right, Action click, Vector2 position) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Expected O, but got Unknown //IL_00fc: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0105: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_012c: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_0169: Unknown result type (might be due to invalid IL or missing references) //IL_017a: Unknown result type (might be due to invalid IL or missing references) REPOButton val = Button(string.Empty, click, position, new Vector2(28f, 30f)); ((Object)((Component)val).gameObject).name = (right ? "NajRoles Next Role" : "NajRoles Previous Role"); RawImage val2 = ((IEnumerable<RawImage>)Resources.FindObjectsOfTypeAll<RawImage>()).FirstOrDefault((Func<RawImage, bool>)((RawImage image) => (Object)(object)image.texture != (Object)null && ((Object)image.texture).name == "icon arrow")); if ((Object)(object)val2 == (Object)null) { NuageRolesPlugin.Logger.LogWarning((object)"Native 'icon arrow' is unavailable; using a directional arrow fallback."); ((TMP_Text)val.labelTMP).text = (right ? "→" : "←"); return; } GameObject val3 = new GameObject("Native Arrow", new Type[1] { typeof(RectTransform) }); val3.layer = ((Component)val).gameObject.layer; RawImage val4 = val3.AddComponent<RawImage>(); RectTransform rectTransform = ((Graphic)val4).rectTransform; ((Transform)rectTransform).SetParent((Transform)(object)((REPOElement)val).rectTransform, false); Vector2 val5 = default(Vector2); ((Vector2)(ref val5))..ctor(0.5f, 0.5f); rectTransform.pivot = val5; Vector2 anchorMin = (rectTransform.anchorMax = val5); rectTransform.anchorMin = anchorMin; rectTransform.anchoredPosition = Vector2.zero; rectTransform.sizeDelta = new Vector2(16f, 16f); ((Transform)rectTransform).localRotation = Quaternion.Euler(0f, 0f, right ? 0f : 180f); val4.texture = val2.texture; val4.uvRect = val2.uvRect; ((Graphic)val4).color = ((Graphic)val.labelTMP).color; ((Graphic)val4).raycastTarget = false; ((Selectable)((Component)val).GetComponent<Button>()).targetGraphic = (Graphic)(object)val4; } private void Previous() { Move(-1); } private void Next() { Move(1); } private void Move(int offset) { string[] availableRoleChoices = config.GetAvailableRoleChoices(); if (availableRoleChoices.Length != 0) { int num = Array.IndexOf(availableRoleChoices, draft); if (num < 0) { num = 0; } draft = availableRoleChoices[(num + offset + availableRoleChoices.Length) % availableRoleChoices.Length]; Refresh(); } } private void Confirm() { Func<bool>? func = canChoose; if (func == null || func()) { if (config.ConfirmRoleChoice(draft)) { draft = config.SelectedRoleChoice; onConfirmed?.Invoke(); } Refresh(); } } private void OpenDescription() { //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Expected O, but got Unknown if ((Object)(object)descriptionPage == (Object)null) { descriptionPage = RoleInfoWindow.Create(); RoleInfoWindow page = descriptionPage; page.Page.onEscapePressed = (ShouldCloseMenuDelegate)delegate { if ((Object)(object)MenuManager.instance.currentMenuPage != (Object)(object)page.Page.menuPage) { return false; } lastInfoEscapeFrame = Time.frameCount; return true; }; } RefreshDescription(); descriptionPage.Open(); } internal void CloseDescription() { if ((Object)(object)descriptionPage != (Object)null && (Object)(object)MenuManager.instance.currentMenuPage == (Object)(object)descriptionPage.Page.menuPage) { descriptionPage.Close(); } } private void Refresh() { if (config != null) { string[] availableRoleChoices = config.GetAvailableRoleChoices(); if (Array.IndexOf(availableRoleChoices, draft) < 0 && availableRoleChoices.Length != 0) { draft = ((Array.IndexOf(availableRoleChoices, config.SelectedRoleChoice) >= 0) ? config.SelectedRoleChoice : availableRoleChoices[0]); } if ((Object)(object)roleLabel != (Object)null) { ((TMP_Text)roleLabel.labelTMP).text = config.RoleDisplayName(draft); } RefreshDescription(); } } private void RefreshDescription() { if (!((Object)(object)descriptionPage == (Object)null)) { int role = Array.IndexOf(LobbyRoleChoice.Names, draft); descriptionPage.SetContent(role, config.RoleDisplayName(draft), config.RoleDescription(draft)); } } private void Update() { if (!(Time.unscaledTime < nextRefresh)) { nextRefresh = Time.unscaledTime + 1f; Refresh(); } } private void OnDestroy() { ModLocalization.LanguageChanged -= Refresh; if ((Object)(object)descriptionPage != (Object)null) { descriptionPage.Dispose(); } } } private readonly NuageRolesConfig config; internal LobbyRolePicker(NuageRolesConfig config) { this.config = config; } internal void Build(Transform parent) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) RectTransform val = (RectTransform)(object)((parent is RectTransform) ? parent : null); float num; Rect rect; if (!((Object)(object)val != (Object)null)) { num = 720f; } else { rect = val.rect; num = ((Rect)(ref rect)).xMax; } float num2 = num; float num3; if (!((Object)(object)val != (Object)null)) { num3 = 405f; } else { rect = val.rect; num3 = ((Rect)(ref rect)).yMax; } float num4 = num3; Build(parent, new Vector3(num2 - 150f, num4 - 120f, 0f)); } internal REPOPopupPage CreateLateJoinPage(Action useChosenRole, Func<bool> canChoose) { //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Expected O, but got Unknown string text = ModLocalization.Text("Choose your role", "Выберите роль"); REPOPopupPage page = MenuAPI.CreateREPOPopupPage(text, (PresetSide)0, false, true, 0f); ModLocalization.BindLabel((TMP_Text)(object)page.headerTMP, "Choose your role", "Выберите роль"); PickerView picker = Build(((Component)page).transform, new Vector3(-18f, 0f, 0f), useChosenRole, canChoose); page.onEscapePressed = (ShouldCloseMenuDelegate)delegate { if ((Object)(object)MenuManager.instance.currentMenuPage != (Object)(object)page.menuPage || picker.ReturnedFromInfoThisFrame || !canChoose()) { return false; } useChosenRole(); return true; }; page.OpenPage(false); return page; } internal static void CloseLateJoinPage(REPOPopupPage page) { //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Invalid comparison between Unknown and I4 if (!((Object)(object)MenuManager.instance == (Object)null)) { ((Component)page).GetComponentInChildren<PickerView>(true)?.CloseDescription(); if ((Object)(object)MenuManager.instance.currentMenuPage == (Object)(object)page.menuPage && (int)page.menuPage.currentPageState != 2) { page.ClosePage(false); } } } private PickerView Build(Transform parent, Vector3 position, Action? onConfirmed = null, Func<bool>? canChoose = null) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) GameObject val = new GameObject("NajRoles Lobby Role Picker", new Type[1] { typeof(RectTransform) }); val.layer = ((Component)parent).gameObject.layer; RectTransform component = val.GetComponent<RectTransform>(); ((Transform)component).SetParent(parent, false); ((Transform)component).localPosition = position; component.sizeDelta = new Vector2(235f, 75f); PickerView pickerView = val.AddComponent<PickerView>(); pickerView.Initialize(config, onConfirmed, canChoose); return pickerView; } } internal sealed class LobbySettings : MonoBehaviourPunCallbacks, IOnEventCallback { private const byte EventCode = 190; private const string Protocol = "NajRoles.LobbySettings.1"; private static LobbySettings? instance; private ConfigFile? config; private ConfigEntryBase[] entries = Array.Empty<ConfigEntryBase>(); private readonly Dictionary<ConfigEntryBase, int> indices = new Dictionary<ConfigEntryBase, int>(); private Action? changed; private object[]? hostValues; private int snapshotActor; private bool dirty; private float nextRequest; internal static bool UsesHost { get { if (PhotonNetwork.InRoom) { return !PhotonNetwork.IsMasterClient; } return false; } } internal static bool Ready { get { if (UsesHost) { return instance?.HasSnapshot ?? false; } return true; } } private bool HasSnapshot { get { if (hostValues != null) { int num = snapshotActor; Player masterClient = PhotonNetwork.MasterClient; return num == ((masterClient != null) ? new int?(masterClient.ActorNumber) : ((int?)null)); } return false; } } internal static T Read<T>(ConfigEntry<T> entry) { LobbySettings lobbySettings = instance; if (!UsesHost || (Object)(object)lobbySettings == (Object)null || !lobbySettings.indices.TryGetValue((ConfigEntryBase)(object)entry, out var value)) { return entry.Value; } if (!lobbySettings.HasSnapshot) { return (T)((ConfigEntryBase)entry).DefaultValue; } return (T)lobbySettings.hostValues[value]; } internal static bool IsLobbyRule(ConfigEntryBase entry) { ConfigDefinition definition = entry.Definition; bool flag = entry.SettingType != typeof(KeyCode) && definition.Section != "Internal"; bool flag2 = flag; if (flag2) { string section = definition.Section; string key = definition.Key; bool flag3; switch (section) { case "General": if (key == "Language") { goto IL_00bc; } goto default; case "GUI": if (key == "Show GUI when being assigned a role" || key == "Ability HUD Font Size Percent") { goto IL_00bc; } goto default; case "Role": if (key == "Your selected role" || key == "Place where mana is shown") { goto IL_00bc; } goto default; default: { flag3 = false; break; } IL_00bc: flag3 = true; break; } flag2 = !flag3; } return flag2; } internal void Bind(ConfigFile file, IEnumerable<ConfigEntryBase> baseEntries, Action onChanged) { entries = baseEntries.Where(IsLobbyRule).OrderBy<ConfigEntryBase, string>((ConfigEntryBase entry) => entry.Definition.Section, StringComparer.Ordinal).ThenBy<ConfigEntryBase, string>((ConfigEntryBase entry) => entry.Definition.Key, StringComparer.Ordinal) .ToArray(); for (int num = 0; num < entries.Length; num++) { indices.Add(entries[num], num); } instance = this; changed = onChanged; config = file; config.SettingChanged += SettingChanged; } private void SettingChanged(object? sender, SettingChangedEventArgs args) { if (!UsesHost && IsLobbyRule(args.ChangedSetting)) { dirty = true; } } private void Update() { //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Expected O, but got Unknown if (dirty) { dirty = false; if (!UsesHost) { if (PhotonNetwork.InRoom) { Publish(); } changed?.Invoke(); } } if (UsesHost && !HasSnapshot && Time.unscaledTime >= nextRequest && PhotonNetwork.MasterClient != null) { nextRequest = Time.unscaledTime + 2f; PhotonNetwork.RaiseEvent((byte)190, (object)new object[1] { "NajRoles.LobbySettings.1" }, new RaiseEventOptions { Receivers = (ReceiverGroup)2 }, SendOptions.SendReliable); } } private void Publish(int recipient = 0) { //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Expected O, but got Unknown //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003b: 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) object[] array = entries.Select((ConfigEntryBase entry) => entry.BoxedValue).ToArray(); object obj; if (recipient <= 0) { obj = (object)new RaiseEventOptions { Receivers = (ReceiverGroup)0 }; } else { RaiseEventOptions val = new RaiseEventOptions(); val.TargetActors = new int[1] { recipient }; obj = val; } RaiseEventOptions val2 = (RaiseEventOptions)obj; PhotonNetwork.RaiseEvent((byte)190, (object)new object[3] { "NajRoles.LobbySettings.1", array, RoleUpgradeSettings.Snapshot() }, val2, SendOptions.SendReliable); } public void OnEvent(EventData message) { if (!PhotonNetwork.InRoom || message.Code != 190 || !(message.CustomData is object[] array) || array.Length == 0 || !object.Equals(array[0], "NajRoles.LobbySettings.1")) { return; } if (PhotonNetwork.IsMasterClient) { if (array.Length == 1 && message.Sender > 0 && PhotonNetwork.CurrentRoom.Players.ContainsKey(message.Sender)) { Publish(message.Sender); } return; } int sender = message.Sender; Player masterClient = PhotonNetwork.MasterClient; if (sender != ((masterClient != null) ? new int?(masterClient.ActorNumber) : ((int?)null)) || array.Length != 3 || !(array[1] is object[] array2) || !(array[2] is float[] values) || array2.Length != entries.Length || !RoleUpgradeSettings.ValidateSnapshot(values)) { return; } for (int i = 0; i < entries.Length; i++) { ConfigEntryBase val = entries[i]; if (array2[i] != null && !(array2[i].GetType() != val.SettingType) && (!(array2[i] is float f) || (!float.IsNaN(f) && !float.IsInfinity(f)))) { AcceptableValueBase acceptableValues = val.Description.AcceptableValues; if (acceptableValues != null && !acceptableValues.IsValid(array2[i])) { return; } continue; } return; } hostValues = array2; snapshotActor = message.Sender; RoleUpgradeSettings.ReceiveSnapshot(values); changed?.Invoke(); } public override void OnJoinedRoom() { Reset(); } public override void OnLeftRoom() { Reset(); } public override void OnMasterClientSwitched(Player newMasterClient) { Reset(); if (PhotonNetwork.IsMasterClient) { Publish(); } } private void Reset() { hostValues = null; snapshotActor = 0; nextRequest = 0f; RoleUpgradeSettings.ResetSnapshot(); changed?.Invoke(); } private void OnDestroy() { if (config != null) { config.SettingChanged -= SettingChanged; } if ((Object)(object)instance == (Object)(object)this) { instance = null; } } } internal static class LobbySettingsIcon { private static Texture2D? texture; internal static void Add(REPOButton button) { //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Expected O, but got Unknown //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Expected O, but got Unknown if ((Object)(object)texture == (Object)null) { using Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("NajRoles.Assets.Settings.png"); using MemoryStream memoryStream = new MemoryStream(); stream.CopyTo(memoryStream); texture = new Texture2D(2, 2, (TextureFormat)4, false) { name = "NajRoles Settings Icon" }; ImageConversion.LoadImage(texture, memoryStream.ToArray(), true); } GameObject val = new GameObject("NajRoles Settings Gear", new Type[1] { typeof(RectTransform) }); val.layer = ((Component)button).gameObject.layer; RawImage val2 = val.AddComponent<RawImage>(); ((Transform)((Graphic)val2).rectTransform).SetParent((Transform)(object)((REPOElement)button).rectTransform, false); RectTransform rectTransform = ((Graphic)val2).rectTransform; RectTransform rectTransform2 = ((Graphic)val2).rectTransform; RectTransform rectTransform3 = ((Graphic)val2).rectTransform; Vector2 val3 = default(Vector2); ((Vector2)(ref val3))..ctor(0.5f, 0.5f); rectTransform3.pivot = val3; Vector2 anchorMin = (rectTransform2.anchorMax = val3); rectTransform.anchorMin = anchorMin; ((Graphic)val2).rectTransform.anchoredPosition = Vector2.zero; ((Graphic)val2).rectTransform.sizeDelta = new Vector2(18f, 18f); val2.texture = (Texture)(object)texture; ((Graphic)val2).raycastTarget = false; ((Selectable)((Component)button).GetComponent<Button>()).targetGraphic = (Graphic)(object)val2; } } internal sealed class LocalizedSettingsMenu { private readonly ConfigFile config; private REPOPopupPage? page; private readonly List<Action> refreshControls = new List<Action>(); public LocalizedSettingsMenu(ConfigFile file) { config = file; ModLocalization.LanguageChanged += Refresh; } public void Open() { if ((Object)(object)page == (Object)null) { Build(); } Refresh(); page.OpenPage(true); } private void Build() { //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Expected O, but got Unknown //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Expected O, but got Unknown //IL_0167: Unknown result type (might be due to invalid IL or missing references) //IL_017b: Expected O, but got Unknown //IL_01a1: Unknown result type (might be due to invalid IL or missing references) //IL_01b5: Expected O, but got Unknown refreshControls.Clear(); page = MenuAPI.CreateREPOPopupPage("NajRoles", (PresetSide)0, true, true, 5f); page.AddElement((BuilderDelegate)delegate(Transform parent) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) REPOButton val = MenuAPI.CreateREPOButton("Back", (Action)delegate { page.ClosePage(false); }, parent, new Vector2(66f, 18f)); ModLocalization.BindLabel((TMP_Text)(object)val.labelTMP, "Back", "Назад"); }); IOrderedEnumerable<IGrouping<(int, string, string), ConfigEntryBase>> orderedEnumerable = (from @group in ((IEnumerable<KeyValuePair<ConfigDefinition, ConfigEntryBase>>)config).Select((KeyValuePair<ConfigDefinition, ConfigEntryBase> pair) => pair.Value).Where(ModLocalization.IsVisibleSetting).GroupBy(SectionFor) orderby @group.Key.Order select @group).ThenBy<IGrouping<(int, string, string), ConfigEntryBase>, string>((IGrouping<(int Order, string English, string Russian), ConfigEntryBase> group) => group.Key.English, StringComparer.Ordinal); foreach (IGrouping<(int, string, string), ConfigEntryBase> item in orderedEnumerable) { (int Order, string English, string Russian) section = item.Key; page.AddElementToScrollView((ScrollViewBuilderDelegate)delegate(Transform parent) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) REPOLabel val = MenuAPI.CreateREPOLabel(section.English, parent, default(Vector2)); ModLocalization.BindLabel((TMP_Text)(object)val.labelTMP, section.English, section.Russian); ((TMP_Text)val.labelTMP).fontStyle = (FontStyles)1; return ((REPOElement)val).rectTransform; }, 10f, 4f); foreach (ConfigEntryBase entry in item.OrderBy(ControlOrder)) { page.AddElementToScrollView((ScrollViewBuilderDelegate)((Transform parent) => BuildControl(entry, parent)), 0f, 4f); if (!string.IsNullOrEmpty(entry.Description.Description)) { page.AddElementToScrollView((ScrollViewBuilderDelegate)delegate(Transform parent) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) REPOLabel help = MenuAPI.CreateREPOLabel(entry.Description.Description, parent, default(Vector2)); ((TMP_Text)help.labelTMP).fontSize = 16f; ((TMP_Text)help.labelTMP).enableWordWrapping = true; ((TMP_Text)help.labelTMP).alignment = (TextAlignmentOptions)513; ModLocalization.ApplyFont((TMP_Text)(object)help.labelTMP); ResizeHelp(); refreshControls.Add(ResizeHelp); return ((REPOElement)help).rectTransform; void ResizeHelp() { //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)help == (Object)null)) { string text = ModLocalization.Text(entry.Description.Description, ModLocalization.RussianDescription(entry)); float num = Mathf.Max(25f, ((TMP_Text)help.labelTMP).GetPreferredValues(text, 250f, float.PositiveInfinity).y + 8f); ((TMP_Text)help.labelTMP).text = text; RectTransform rectTransform = ((REPOElement)help).rectTransform; RectTransform rectTransform2 = ((TMP_Text)help.labelTMP).rectTransform; Vector2 sizeDelta = default(Vector2); ((Vector2)(ref sizeDelta))..ctor(250f, num); rectTransform2.sizeDelta = sizeDelta; rectTransform.sizeDelta = sizeDelta; } } }, 0f, 8f); } } } } private static (int Order, string English, string Russian) SectionFor(ConfigEntryBase entry) { string section = entry.Definition.Section; string key = entry.Definition.Key; string text = RoleUpgradeSettings.UpgradeIdForSection(section); if (text != null) { int num = (int)UpgradePresentation.Role(text); string id = ConfigTranslations.RoleIds[num]; (string, string) tuple = UpgradePresentation.Names(text); int num2 = ((!(text == "NajRolesEngineerCharging")) ? 1 : 2); return (Order: num * 10 + num2, English: ConfigTranslations.EnglishRoleName(id) + " · " + tuple.Item1, Russian: ConfigTranslations.RoleName(id) + " · " + tuple.Item2); } string text2; switch (section) { case "Role": if (key.StartsWith("Enable ", StringComparison.Ordinal)) { text2 = key.Substring(7); break; } if (key == "Place where mana is shown") { text2 = "Mage"; break; } goto default; case "Role Names": text2 = key.Substring(0, key.Length - " Name".Length); break; case "Role Descriptions": text2 = key.Substring(0, key.Length - " Description".Length); break; case "GUI": if ((key == "Activate Scout Ability" || key == "Scout Predator Sense") ? true : false) { text2 = "Scout"; break; } goto default; default: text2 = section; break; } string text3 = text2; int num3 = Array.IndexOf(ConfigTranslations.RoleIds, text3); if (num3 > 0) { return (Order: num3 * 10, English: ConfigTranslations.EnglishRoleName(text3), Russian: ConfigTranslations.RoleName(text3)); } return section switch { "General" => (Order: 0, English: "General", Russian: "Общие"), "Role" => (Order: 1, English: "Role Selection", Russian: "Выбор роли"), "GUI" => (Order: 2, English: "Interface", Russian: "Интерфейс"), "Upgrades" => (Order: 3, English: "Shop", Russian: "Магазин"), _ => (Order: int.MaxValue, English: section, Russian: ModLocalization.RussianSection(entry)), }; } private static int ControlOrder(ConfigEntryBase entry) { string key = entry.Definition.Key; if (key == "Enabled" || key.StartsWith("Enable ", StringComparison.Ordinal)) { return 0; } if (key.StartsWith("Starting ", StringComparison.Ordinal) || key.StartsWith("Base Regen", StringComparison.Ordinal) || key == "Base Reduction Percent") { return 10; } if (entry.SettingType == typeof(KeyCode)) { return 60; } if ((key == "Maximum Level" || key == "Maximum Rush Level") ? true : false) { return 70; } if (key == "Base Price") { return 80; } string section = entry.Definition.Section; if ((section == "Role Names" || section == "Role Descriptions") ? true : false) { return 90; } return 30; } private RectTransform BuildControl(ConfigEntryBase entry, Transform parent) { //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_03aa: Unknown result type (might be due to invalid IL or missing references) //IL_03fa: Unknown result type (might be due to invalid IL or missing references) //IL_0400: Unknown result type (might be due to invalid IL or missing references) //IL_05b4: Unknown result type (might be due to invalid IL or missing references) //IL_05ba: Unknown result type (might be due to invalid IL or missing references) //IL_0530: Unknown result type (might be due to invalid IL or missing references) //IL_0536: Unknown result type (might be due to invalid IL or missing references) //IL_01b3: Unknown result type (might be due to invalid IL or missing references) //IL_01b9: Unknown result type (might be due to invalid IL or missing references) //IL_02d9: Unknown result type (might be due to invalid IL or missing references) //IL_02df: Unknown result type (might be due to invalid IL or missing references) string key = entry.Definition.Key; ConfigEntry<bool> boolean = entry as ConfigEntry<bool>; if (boolean != null) { REPOToggle control = MenuAPI.CreateREPOToggle(key, (Action<bool>)delegate(bool flag) { Set(entry, flag); }, parent, Vector2.zero, "ON", "OFF", boolean.Value); Bind((TMP_Text)(object)control.labelTMP, entry); ModLocalization.BindLabel((TMP_Text)(object)control.leftButtonTMP, "ON", "ВКЛ"); ModLocalization.BindLabel((TMP_Text)(object)control.rightButtonTMP, "OFF", "ВЫКЛ"); refreshControls.Add(delegate { if ((Object)(object)control != (Object)null) { control.SetState(boolean.Value, false); } }); return ((REPOElement)control).rectTransform; } ConfigEntry<int> integer = entry as ConfigEntry<int>; if (integer != null) { AcceptableValueRange<int> val = entry.Description.AcceptableValues as AcceptableValueRange<int>; string empty = string.Empty; Action<int> obj = delegate(int num6) { Set(entry, num6); }; int num = val?.MinValue ?? 0; int num2 = val?.MaxValue ?? Math.Max(100, Math.Abs(integer.Value) * 3); int value = integer.Value; REPOSlider control2 = MenuAPI.CreateREPOSlider(key, empty, obj, parent, default(Vector2), num, num2, value, "", "", (BarBehavior)0); Bind((TMP_Text)(object)control2.labelTMP, entry); refreshControls.Add(delegate { if ((Object)(object)control2 != (Object)null) { control2.SetValue((float)integer.Value, false); } }); return ((REPOElement)control2).rectTransform; } ConfigEntry<float> number = entry as ConfigEntry<float>; if (number != null) { AcceptableValueRange<float> val2 = entry.Description.AcceptableValues as AcceptableValueRange<float>; string empty2 = string.Empty; Action<float> obj2 = delegate(float num6) { Set(entry, num6); }; float num3 = val2?.MinValue ?? 0f; float num4 = val2?.MaxValue ?? Math.Max(100f, Math.Abs(number.Value) * 3f); float value2 = number.Value; REPOSlider control3 = MenuAPI.CreateREPOSlider(key, empty2, obj2, parent, default(Vector2), num3, num4, 2, value2, "", "", (BarBehavior)0); Bind((TMP_Text)(object)control3.labelTMP, entry); refreshControls.Add(delegate { if ((Object)(object)control3 != (Object)null) { control3.SetValue(number.Value, false); } }); return ((REPOElement)control3).rectTransform; } if (entry.SettingType == typeof(KeyCode)) { KeyCode[] keys = Enum.GetValues(typeof(KeyCode)).Cast<KeyCode>().Distinct() .ToArray(); int val3 = Array.IndexOf(keys, (KeyCode)entry.BoxedValue); string[] array = keys.Select(ModLocalization.Key).ToArray(); REPOSlider control4 = MenuAPI.CreateREPOSlider(key, string.Empty, (Action<int>)delegate(int index) { if (index >= 0 && index < keys.Length) { Set(entry, keys[index]); } }, parent, array, array[Math.Max(0, val3)], default(Vector2), "", "", (BarBehavior)0); Bind((TMP_Text)(object)control4.labelTMP, entry); ModLocalization.ApplyFonts((Component)(object)control4); refreshControls.Add(delegate { //IL_0053: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)control4 == (Object)null)) { control4.stringOptions = keys.Select(ModLocalization.Key).ToArray(); control4.SetValue((float)Math.Max(0, Array.IndexOf(keys, (KeyCode)entry.BoxedValue)), false); } }); return ((REPOElement)control4).rectTransform; } ConfigEntry<string> text = entry as ConfigEntry<string>; if (text != null && entry.Description.AcceptableValues is AcceptableValueList<string> val4) { string[] ids = val4.AcceptableValues; Func<string, string> display = (string text3) => (!(entry.Definition.Key == "Your selected role")) ? text3 : NuageRolesPlugin.Settings.RoleDisplayName(text3); string[] array2 = ids.Select(display).ToArray(); int num5 = Math.Max(0, Array.IndexOf(ids, text.Value)); REPOSlider control5 = MenuAPI.CreateREPOSlider(key, string.Empty, (Action<int>)delegate(int index) { if (index >= 0 && index < ids.Length) { Set(entry, ids[index]); } }, parent, array2, array2[num5], default(Vector2), "", "", (BarBehavior)0); Bind((TMP_Text)(object)control5.labelTMP, entry); ModLocalization.ApplyFonts((Component)(object)control5); refreshControls.Add(delegate { if (!((Object)(object)control5 == (Object)null)) { control5.stringOptions = ids.Select(display).ToArray(); control5.SetValue((float)Math.Max(0, Array.IndexOf(ids, text.Value)), false); } }); return ((REPOElement)control5).rectTransform; } Action<string> obj3 = delegate(string text3) { if (!string.Equals(text3, DisplayInput(), StringComparison.Ordinal)) { Set(entry, text3); } }; string text2 = DisplayInput(); REPOInputField input = MenuAPI.CreateREPOInputField(key, obj3, parent, default(Vector2), true, "", text2); Bind((TMP_Text)(object)input.labelTMP, entry); ModLocalization.ApplyFonts((Component)(object)input); refreshControls.Add(delegate { if ((Object)(object)input != (Object)null) { input.inputStringSystem.SetValue(DisplayInput(), false); } }); return ((REPOElement)input).rectTransform; string DisplayInput() { string text3; if (!(entry is ConfigEntry<string> entry2)) { text3 = Convert.ToString(entry.BoxedValue); if (text3 == null) { return string.Empty; } } else { text3 = ModLocalization.Configured(entry2); } return text3; } } private static void Bind(TMP_Text label, ConfigEntryBase entry) { label.enableAutoSizing = true; label.fontSizeMax = label.fontSize; label.fontSizeMin = 10f; label.enableWordWrapping = true; ModLocalization.BindLabel(label, entry.Definition.Key, ModLocalization.RussianLabel(entry)); } private void Set(ConfigEntryBase entry, object value) { entry.BoxedValue = value; config.Save(); Sender.manager?.RefreshRoleText(); } private void Refresh() { foreach (Action refreshControl in refreshControls) { refreshControl(); } if ((Object)(object)page != (Object)null) { page.scrollView.UpdateElements(); } } } public static class ModLocalization { private sealed class SettingText { public string Label = string.Empty; public string Description = string.Empty; public string Section = string.Empty; } private static readonly Dictionary<ConfigEntryBase, SettingText> settings = new Dictionary<ConfigEntryBase, SettingText>(); private static readonly Dictionary<string, string> ui = new Dictionary<string, string>(StringComparer.Ordinal); private static ConfigFile? config; private static ConfigEntry<string>? language; private static Font? fallbackFont; private static TMP_FontAsset? tmpFont; private static bool initialized; public static bool IsRussian { get { if (language != null) { return string.Equals(language.Value, "RU", StringComparison.OrdinalIgnoreCase); } return true; } } public static string Language { get { if (!IsRussian) { return "EN"; } return "RU"; } } public static CultureInfo NumberCulture { get { if (!IsRussian) { return CultureInfo.InvariantCulture; } return CultureInfo.GetCultureInfo("ru-RU"); } } public static Font? GuiFont { get { Font customFont = guiManager.customFont; if ((Object)(object)customFont != (Object)null && customFont.HasCharacter('Я')) { return customFont; } if ((Object)(object)fallbackFont == (Object)null) { fallbackFont = Font.CreateDynamicFontFromOSFont(new string[3] { "Arial", "Noto Sans", "DejaVu Sans" }, 24); } return fallbackFont; } } public static event Action? LanguageChanged; public static void Initialize(ConfigFile file) { //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Expected O, but got Unknown if (!initialized) { initialized = true; config = file; language = file.Bind<string>("General", "Language", "RU", new ConfigDescription("Interface language. Applies immediately; saved setting keys do not change.", (AcceptableValueBase)(object)new AcceptableValueList<string>(new string[2] { "EN", "RU" }), Array.Empty<object>())); language.SettingChanged += delegate { ModLocalization.LanguageChanged?.Invoke(); }; RegisterSetting((ConfigEntryBase)(object)language, "Язык / Language", "Язык интерфейса. Применяется сразу; ключи сохранённых настроек не меняются.", "Общие"); AddUi("Back", "Назад"); AddUi("Save Changes", "Сохранить"); AddUi("Revert", "Отменить изменения"); AddUi("Reset To Default", "Сбросить настройки"); AddUi("ON", "ВКЛ"); AddUi("OFF", "ВЫКЛ"); AddUi("On", "Вкл"); AddUi("Off", "Выкл"); AddUi("Enabled", "Включено"); AddUi("Disabled", "Выключено"); string[] roleIds = ConfigTranslations.RoleIds; foreach (string text in roleIds) { AddUi(text, ConfigTranslations.RoleName(text)); } TryHookConfigPage(); } } public static string Text(string en, string ru) { if (!IsRussian) { return en; } return ru; } public static void SetLanguage(string value) { if (language != null) { language.Value = ((value == "EN") ? "EN" : "RU"); ConfigFile? obj = config; if (obj != null) { obj.Save(); } } } public static void RegisterSetting(ConfigEntryBase entry, string russianLabel, string russianDescription, string? russianSection = null) { settings[entry] = new SettingText { Label = russianLabel, Description = russianDescription, Section = (russianSection ?? ConfigTranslations.Section(entry.Definition.Section)) }; AddUi(entry.Definition.Key, russianLabel); AddUi(entry.Definition.Section, settings[entry].Section); AddUi(entry.Description.Description, russianDescription); } internal static string RussianLabel(ConfigEntryBase entry) { if (!settings.TryGetValue(entry, out SettingText value)) { return entry.Definition.Key; } return value.Label; } internal static string RussianDescription(ConfigEntryBase entry) { if (!settings.TryGetValue(entry, out SettingText value)) { return entry.Description.Description; } return value.Description; } internal static string RussianSection(ConfigEntryBase entry) { if (!settings.TryGetValue(entry, out SettingText value)) { return ConfigTranslations.Section(entry.Definition.Section); } return value.Section; } public unsafe static string Key(KeyCode key) { string text = ((object)(*(KeyCode*)(&key))/*cast due to .constrained prefix*/).ToString(); if (text.StartsWith("Alpha", StringComparison.Ordinal)) { return text.Substring(5); } if (!IsRussian) { return text; } switch (text) { case "None": return "Не назначена"; case "Space": return "Пробел"; case "Return": return "Enter"; case "Escape": return "Esc"; case "Backspace": return "Backspace"; case "LeftShift": return "Левый Shift"; case "RightShift": return "Правый Shift"; case "LeftControl": return "Левый Ctrl"; case "RightControl": return "Правый Ctrl"; case "LeftAlt": return "Левый Alt"; case "RightAlt": return "Правый Alt"; case "UpArrow": return "Стрелка вверх"; case "DownArrow": return "Стрелка вниз"; case "LeftArrow": return "Стрелка влево"; case "RightArrow": return "Стрелка вправо"; case "Mouse0": return "ЛКМ"; case "Mouse1": return "ПКМ"; case "Mouse2": return "СКМ"; default: if (text.StartsWith("Mouse", StringComparison.Ordinal)) { return "Кнопка мыши " + text.Substring(5); } if (text.StartsWith("Keypad", StringComparison.Ordinal)) { return "Num " + text.Substring(6); } if (text.StartsWith("Joystick", StringComparison.Ordinal)) { return text.Replace("Joystick", "Геймпад ").Replace("Button", ": кнопка "); } return text; } } public static string Configured(ConfigEntry<string> entry, string? value = null) { if (value == null) { value = entry.Value; } bool flag = ((ConfigEntryBase)entry).Definition.Section == "Role Descriptions" && ConfigTranslations.IsLegacyRoleDescription(value); if (!string.Equals(value, (string)((ConfigEntryBase)entry).DefaultValue, StringComparison.Ordinal) && !flag) { return value; } if (!IsRussian) { return (string)((ConfigEntryBase)entry).DefaultValue; } if (((ConfigEntryBase)entry).Definition.Section == "Role Names") { return ConfigTranslations.RoleName((string)((ConfigEntryBase)entry).DefaultValue); } if (((ConfigEntryBase)entry).Definition.Section == "Role Descriptions") { return ConfigTranslations.RoleDescription(((ConfigEntryBase)entry).Definition.Key); } return value; } private static void AddUi(string english, string russian) { if (!string.IsNullOrEmpty(english)) { ui[english] = russian; string input = Regex.Replace(english, "([a-z])([A-Z])", "$1 $2"); input = Regex.Replace(input, "([A-Z])([A-Z][a-z])", "$1 $2"); ui[Regex.Replace(input, "\\s+", " ").Trim()] = russian; } } internal static string TranslateUi(string source) { if (!IsRussian || !ui.TryGetValue(source, out string value)) { return source; } return value; } public static void ApplyFont(TMP_Text label) { if (!((Object)(object)label == (Object)null)) { TMP_FontAsset val = LocalizedTmpFont(); if ((Object)(object)val != (Object)null) { label.font = val; } } } internal static void EnsureCyrillicFallback(TMP_Text? label) { if ((Object)(object)label == (Object)null || (Object)(object)label.font == (Object)null || label.font.HasCharacter('Я', false, false)) { return; } TMP_FontAsset val = LocalizedTmpFont(); if (!((Object)(object)val == (Object)null) && !((Object)(object)val == (Object)(object)label.font)) { TMP_FontAsset font = label.font; List<TMP_FontAsset> list = font.fallbackFontAssetTable ?? (font.fallbackFontAssetTable = new List<TMP_FontAsset>()); if (!list.Contains(val)) { list.Add(val); } } } private static TMP_FontAsset? LocalizedTmpFont() { if ((Object)(object)tmpFont == (Object)null) { Font guiFont = GuiFont; if ((Object)(object)guiFont == (Object)null) { return null; } tmpFont = TMP_FontAsset.CreateFontAsset(guiFont); if ((Object)(object)tmpFont == (Object)null) { return null; } ((Object)tmpFont).name = "NajRoles_LocalizedFont"; } return tmpFont; } internal static void ApplyFonts(Component root) { TMP_Text[] componentsInChildren = root.GetComponentsInChildren<TMP_Text>(true); foreach (TMP_Text label in componentsInChildren) { ApplyFont(label); } } public static void BindLabel(TMP_Text label, string en, string ru) { if (!((Object)(object)label == (Object)null)) { LocalizedLabel localizedLabel = ((Component)label).GetComponent<LocalizedLabel>() ?? ((Component)label).gameObject.AddComponent<LocalizedLabel>(); localizedLabel.Configure(label, en, ru); } } private static void TryHookConfigPage() { //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Expected O, but got Unknown //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Expected O, but got Unknown //IL_009d: Expected O, but got Unknown //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_0118: Expected O, but got Unknown //IL_0160: Unknown result type (might be due to invalid IL or missing references) //IL_016d: Expected O, but got Unknown Type type = AccessTools.TypeByName("REPOConfig.ConfigMenu"); MethodInfo methodInfo = ((type == null) ? null : AccessTools.Method(type, "CreateModEntries", new Type[2] { typeof(REPOPopupPage), typeof(ConfigEntryBase[]) }, (Type[])null)); if (methodInfo == null) { NuageRolesPlugin.Logger.LogWarning((object)"REPOConfig labels could not be hooked; use NajRoles > All Settings for localized controls."); return; } try { Harmony val = new Harmony("com.najvlad.najroles.localization"); val.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(ModLocalization), "FilterHiddenConfigEntries", (Type[])null), new HarmonyMethod(typeof(ModLocalization), "ConfigEntriesCreated", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); MethodInfo methodInfo2 = type.GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic).SelectMany((Type nested) => nested.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)).FirstOrDefault((MethodInfo candidate) => candidate.Name.StartsWith("<CreateModEntries>b__", StringComparison.Ordinal) && candidate.ReturnType == typeof(string) && candidate.GetParameters().Length == 1 && candidate.GetParameters()[0].ParameterType == typeof(ConfigEntryBase)); if (methodInfo2 != null) { val.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, new HarmonyMethod(typeof(ModLocalization), "ConfigSectionSelected", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } else { NuageRolesPlugin.Logger.LogWarning((object)"REPOConfig section selector could not be hooked; Scout keys remain in Interface."); } MethodInfo methodInfo3 = AccessTools.Method(typeof(REPOSlider), "UpdateBarText", (Type[])null, (Type[])null); if (methodInfo3 != null) { val.Patch((MethodBase)methodInfo3, (HarmonyMethod)null, new HarmonyMethod(typeof(ModLocalization), "ConfigSliderValueChanged", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } catch (Exception ex) { NuageRolesPlugin.Logger.LogWarning((object)("REPOConfig labels could not be hooked: " + ex.Message)); } } internal static bool IsVisibleSetting(ConfigEntryBase entry) { return !(entry.Description.Tags?.Any((object tag) => object.Equals(tag, "HideFromREPOConfig")) ?? false); } private static void ConfigSectionSelected(ConfigEntryBase __0, ref string __result) { if (config != null && __0.Definition.Section == "GUI" && (__0.Definition.Key == "Activate Scout Ability" || __0.Definition.Key == "Scout Predator Sense") && ((IEnumerable<KeyValuePair<ConfigDefinition, ConfigEntryBase>>)config).Any((KeyValuePair<ConfigDefinition, ConfigEntryBase> pair) => pair.Value == __0)) { __result = "Scout"; } } private static void FilterHiddenConfigEntries(ref ConfigEntryBase[] __1) { if (config == null) { return; } __1 = __1.Where((ConfigEntryBase entry) => !((IEnumerable<KeyValuePair<ConfigDefinition, ConfigEntryBase>>)config).Any((KeyValuePair<ConfigDefinition, ConfigEntryBase> pair) => pair.Value == entry) || IsVisibleSetting(entry)).ToArray(); } private static void ConfigEntriesCreated(object[] __args) { REPOPopupPage val = __args.OfType<REPOPopupPage>().FirstOrDefault(); ConfigEntryBase[] array = __args.OfType<ConfigEntryBase[]>().FirstOrDefault(); if (!((Object)(object)val == (Object)null) && array != null && config != null && array.Any((ConfigEntryBase entry) => ((IEnumerable<KeyValuePair<ConfigDefinition, ConfigEntryBase>>)config).Any((KeyValuePair<ConfigDefinition, ConfigEntryBase> pair) => pair.Value == entry))) { LocalizedConfigPage localizedConfigPage = ((Component)val).GetComponent<LocalizedConfigPage>() ?? ((Component)val).gameObject.AddComponent<LocalizedConfigPage>(); localizedConfigPage.Refresh(); } } private static void ConfigSliderValueChanged(REPOSlider __instance, TextMeshProUGUI ___valueTMP, TextMeshProUGUI ___maskedValueTMP) { LocalizedConfigPage componentInParent = ((Component)__instance).GetComponentInParent<LocalizedConfigPage>(true); if ((Object)(object)componentInParent != (Object)null) { componentInParent.RefreshLabel((TMP_Text)(object)___valueTMP, sourceChanged: true); componentInParent.RefreshLabel((TMP_Text)(object)___maskedValueTMP, sourceChanged: true); } } } public sealed class LocalizedLabel : MonoBehaviour { private TMP_Text? label; private string en = string.Empty; private string ru = string.Empty; private void Awake() { ModLocalization.LanguageChanged += Refresh; } private void OnEnable() { Refresh(); } public void Configure(TMP_Text target, string english, string russian) { label = target; en = english; ru = russian; Refresh(); } private void Refresh() { if (!((Object)(object)label == (Object)null)) { label.text = ModLocalization.Text(en, ru); ModLocalization.ApplyFont(label); } } private void OnDestroy() { ModLocalization.LanguageChanged -= Refresh; } } public sealed class LocalizedConfigPage : MonoBehaviour { private sealed class LabelState { public string Source = string.Empty; public string Last = string.Empty; } private readonly Dictionary<TMP_Text, LabelState> labels = new Dictionary<TMP_Text, LabelState>(); private TMP_Text? resetLabel; private float resetMaskWidth; private void OnEnable() { ModLocalization.LanguageChanged += Refresh; Refresh(); } private void OnDisable() { ModLocalization.LanguageChanged -= Refresh; } private void LateUpdate() { //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) REPOPopupPage component = ((Component)this).GetComponent<REPOPopupPage>(); if ((Object)(object)resetLabel != (Object)null && (Object)(object)component != (Object)null && (Object)(object)component.maskRectTransform != (Object)null) { float num = resetMaskWidth; Rect rect = component.maskRectTransform.rect; if (!Mathf.Approximately(num, ((Rect)(ref rect)).width)) { FitResetButton(resetLabel); } } } internal void Refresh() { TMP_Text[] componentsInChildren = ((Component)this).GetComponentsInChildren<TMP_Text>(true); foreach (TMP_Text label in componentsInChildren) { RefreshLabel(label); } } internal void RefreshLabel(TMP_Text label, bool sourceChanged = false) { if ((Object)(object)label == (Object)null || (Object)(object)((Component)label).GetComponent<LocalizedLabel>() != (Object)null) { return; } REPOInputField componentInParent = ((Component)label).GetComponentInParent<REPOInputField>(); if ((Object)(object)componentInParent == (Object)null || (Object)(object)componentInParent.labelTMP == (Object)(object)label) { if (!labels.TryGetValue(label, out LabelState value)) { value = new LabelState { Source = label.text, Last = label.text }; labels[label] = value; } else if (sourceChanged || label.text != value.Last) { value.Source = label.text; } value.Last = ModLocalization.TranslateUi(value.Source); if (label.text != value.Last) { label.text = value.Last; } } ModLocalization.ApplyFont(label); if (labels.TryGetValue(label, out LabelState value2) && value2.Source == "Reset To Default") { FitResetButton(label); } } private void FitResetButton(TMP_Text label) { //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Unknown result type (might be due to invalid IL or missing references) //IL_0137: Unknown result type (might be due to invalid IL or missing references) //IL_014d: Unknown result type (might be due to invalid IL or missing references) REPOButton componentInParent = ((Component)label).GetComponentInParent<REPOButton>(); REPOPopupPage component = ((Component)this).GetComponent<REPOPopupPage>(); if (!((Object)(object)componentInParent == (Object)null) && !((Object)(object)componentInParent.labelTMP != (Object)(object)label) && !((Object)(object)component == (Object)null) && !((Object)(object)component.maskRectTransform == (Object)null)) { resetLabel = label; Rect rect = component.maskRectTransform.rect; float width = ((Rect)(ref rect)).width; if (!(width <= 16f)) { resetMaskWidth = width; float num = Mathf.Min(220f, width - 16f); componentInParent.overrideButtonSize = new Vector2(num, 26f); ((REPOElement)componentInParent).rectTransform.sizeDelta = new Vector2(num, 26f); Vector3 localPosition = ((Transform)((REPOElement)componentInParent).rectTransform).localPosition; localPosition.x = (width - num) * 0.5f; ((Transform)((REPOElement)componentInParent).rectTransform).localPosition = localPosition; label.enableWordWrapping = false; label.enableAutoSizing = true; label.fontSizeMin = 10f; label.fontSizeMax = 18f; label.fontSize = 18f; label.alignment = (TextAlignmentOptions)514; RectTransform rectTransform = label.rectTransform; rectTransform.anchorMin = Vector2.zero; rectTransform.anchorMax = Vector2.one; rectTransform.offsetMin = new Vector2(6f, 0f); rectTransform.offsetMax = new Vector2(-6f, 0f); } } } } public sealed class NuageRolesConfig { private const string RandomRoleName = "Random"; private const string DefaultRoleName = "Strongman"; private static readonly string[] AllRoleChoices = LobbyRoleChoice.Names; private readonly ConfigFile configFile; private REPOSlider? roleSlider; private REPOSlider? languageSlider; private REPOPopupPage? configPage; private REPOButton? buttonOpen; private REPOButton? buttonClose; private REPOToggle? afterDeathRoleToggle; private REPOToggle? mageTopMana; private Action? updateManaDisplay; private LocalizedSettingsMenu? allSettingsMenu; private LobbyRolePicker? lobbyRolePicker; public ConfigEntry<KeyCode> ToggleKey { get; private set; } public ConfigEntry<int> AbilityHudFontPercent { get; private set; } public ConfigEntry<KeyCode> ShowSpellsKey { get; private set; } public ConfigEntry<KeyCode> HealKey { get; private set; } public ConfigEntry<KeyCode> GodzillaKey { get; private set; } public ConfigEntry<KeyCode> JumpKey { get; private set; } public ConfigEntry<KeyCode> ShallNotPassKey { get; private set; } public ConfigEntry<KeyCode> StaminaKey { get; private set; } public ConfigEntry<KeyCode> ScoutKey { get; private set; } public ConfigEntry<KeyCode> ScoutPredatorKey { get; private set; } public ConfigEntry<KeyCode> ChargeItemKey { get; private set; } public ConfigEntry<KeyCode> MagnetPullKey { get; private set; } public ConfigEntry<KeyCode> MagnetLaunchKey { get; private set; } public ConfigEntry<float> RunnerSpeedMultiplier { get; private set; } public ConfigEntry<float> RunnerStaminaMultiplier { get; private set; } public ConfigEntry<float> TankHealthMultiplier { get; private set; } public ConfigEntry<float> TankSpeedMultiplier { get; private set; } public ConfigEntry<int> TankPassiveRegenAmount { get; private set; } public ConfigEntry<int> TankPassiveRegenIntervalSeconds { get; private set; } public ConfigEntry<float> StrongmanStrengthMultiplier { get; private set; } public ConfigEntry<float> StrongmanStrengthBonus { get; private set; } public ConfigEntry<int> StrongmanStaminaBonus { get; private set; } public ConfigEntry<float> StrongmanJumpForceBonus { get; private set; } public ConfigEntry<float> AthleticStrengthMultiplier { get; private set; } public ConfigEntry<int> AthleticStaminaBonus { get; private set; } public ConfigEntry<float> AthleticJumpForceBonus { get; private set; } public ConfigEntry<int> AthleticExtraJumps { get; private set; } public ConfigEntry<float> ReaperHealthMultiplier { get; private set; } public ConfigEntry<int> ReaperHealAmountPerKill { get; private set; } public ConfigEntry<int> ReaperBuffCooldownFrames { get; private set; } public ConfigEntry<float> ReaperVampirismRadius { get; private set; } public ConfigEntry<float> ScoutStaminaMultiplier { get; private set; } public ConfigEntry<float> ScoutSprintRechargeMultiplier { get; private set; } public ConfigEntry<int> ScoutAbilityCooldownSeconds { get; private set; } public ConfigEntry<int> ScoutSensorCooldownSeconds { get; private set; } public ConfigEntry<float> ScoutTreasureRadius { get; private set; } public ConfigEntry<int> MageMaxMana { get; private set; } public ConfigEntry<int> MageHealAmount { get; private set; } public ConfigEntry<int> EngineerChargeStaminaCost { get; private set; } public ConfigEntry<int> EngineerStaminaRestoreAmount { get; private set; } public ConfigEntry<int> EngineerStaminaRestoreIntervalSeconds { get; private set; } public ConfigEntry<string> CustomRoleNameRunner { get; private set; } public ConfigEntry<string> CustomRoleNameTank { get; private set; } public ConfigEntry<string> CustomRoleNameGambler { get; private set; } public ConfigEntry<string> CustomRoleNameStrongman { get; private set; } public ConfigEntry<string> CustomRoleNameAthletic { get; private set; } public ConfigEntry<string> CustomRoleNameMage { get; private set; } public ConfigEntry<string> CustomRoleNameReaper { get; private set; } public ConfigEntry<string> CustomRoleNameScout { get; private set; } public ConfigEntry<string> CustomRoleNameRegular { get; private set; } public ConfigEntry<string> CustomRoleNameEngineer { get; private set; } public ConfigEntry<string> CustomRoleNameMagnet { get; private set; } public ConfigEntry<string> CustomRoleDecRunner { get; private set; } public ConfigEntry<string> CustomRoleDecTank { get; private set; } public ConfigEntry<string> CustomRoleDecGambler { get; private set; } public ConfigEntry<string> CustomRoleDecStrongman { get; private set; } public ConfigEntry<string> CustomRoleDecAthletic { get; private set; } public ConfigEntry<string> CustomRoleDecMage { get; private set; } public ConfigEntry<string> CustomRoleDecReaper { get; private set; } public ConfigEntry<string> CustomRoleDecScout { get; private set; } public ConfigEntry<string> CustomRoleDecRegular { get; private set; } public ConfigEntry<string> CustomRoleDecEngineer { get; private set; } public ConfigEntry<stri