Decompiled source of Scout LanguagePack v1.0.0

plugins/ScoutFormatFix.dll

Decompiled 3 days ago
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.CompilerServices;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using On.RoR2;
using RoR2;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[BepInPlugin("jaosnake.scout.formatfix", "Scout localization format fix", "0.1.0")]
public sealed class ScoutFormatFix : BaseUnityPlugin
{
	private Harmony harmony;

	private void Awake()
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: Expected O, but got Unknown
		harmony = new Harmony("jaosnake.scout.formatfix");
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Scout localized dynamic formatting enabled");
	}

	private void Start()
	{
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_0012: Expected O, but got Unknown
		Language.GetLocalizedStringByToken += new hook_GetLocalizedStringByToken(ScoutFormatPatch.OnGet);
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Scout outer language hook enabled");
	}

	private void OnDestroy()
	{
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_0012: Expected O, but got Unknown
		Language.GetLocalizedStringByToken -= new hook_GetLocalizedStringByToken(ScoutFormatPatch.OnGet);
		if (harmony != null)
		{
			harmony.UnpatchSelf();
		}
	}
}
[HarmonyPatch(typeof(Language), "GetLocalizedStringByToken")]
internal static class ScoutFormatPatch
{
	private static readonly Dictionary<string, string> fields = new Dictionary<string, string>
	{
		{ "KENKO_SCOUT_PRIMARY_SPLATTERGUN_DESCRIPTION", "shotgunDamageCoefficient" },
		{ "KENKO_SCOUT_PRIMARY_RIFLE_DESCRIPTION", "rifleDamageCoefficient" },
		{ "KENKO_SCOUT_PRIMARY_BONK_DESCRIPTION", "baseballDamageCoefficient" },
		{ "KENKO_SCOUT_SECONDARY_CLEAVER_DESCRIPTION", "cleaverDamageCoefficient" },
		{ "KENKO_SCOUT_SECONDARY_SPIKEDBALL_DESCRIPTION", "baseballDamageCoefficient" },
		{ "KENKO_SCOUT_UTILITY_ATOMICBLAST_DESCRIPTION", "atomicBlastDamageCoefficient" }
	};

	private static readonly Dictionary<string, string[]> keywordTranslations = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase)
	{
		{
			"pt-BR",
			new string[4] { "Ágil", "A habilidade pode ser usada enquanto corre.", "Críticos Atômicos", "O dano aumenta em 125% e todos os ataques aplicam Enfraquecimento." }
		},
		{
			"de",
			new string[4] { "Flink", "Die Fähigkeit kann beim Sprinten eingesetzt werden.", "Atomare kritische Treffer", "Der Schaden wird um 125 % erhöht und alle Angriffe schwächen." }
		},
		{
			"FR",
			new string[4] { "Agile", "La compétence peut être utilisée en sprintant.", "Coups critiques atomiques", "Les dégâts augmentent de 125 % et toutes les attaques affaiblissent." }
		},
		{
			"IT",
			new string[4] { "Agile", "L’abilità può essere usata durante lo scatto.", "Critici atomici", "I danni aumentano del 125% e tutti gli attacchi applicano Indebolimento." }
		},
		{
			"es-ES",
			new string[4] { "Ágil", "La habilidad se puede usar mientras corres.", "Críticos atómicos", "El daño aumenta un 125% y todos los ataques aplican debilitación." }
		},
		{
			"es-419",
			new string[4] { "Ágil", "La habilidad se puede usar mientras corres.", "Críticos atómicos", "El daño aumenta un 125% y todos los ataques aplican debilitamiento." }
		},
		{
			"RU",
			new string[4] { "Проворство", "Умение можно использовать во время бега.", "Атомные критические удары", "Урон увеличивается на 125%, и все атаки накладывают ослабление." }
		},
		{
			"UA",
			new string[4] { "Спритність", "Здібність можна використовувати під час бігу.", "Атомні критичні удари", "Шкода збільшується на 125%, а всі атаки накладають ослаблення." }
		},
		{
			"uk",
			new string[4] { "Спритність", "Здібність можна використовувати під час бігу.", "Атомні критичні удари", "Шкода збільшується на 125%, а всі атаки накладають ослаблення." }
		},
		{
			"ja",
			new string[4] { "俊敏", "ダッシュ中にスキルを使用できます。", "原子クリティカル", "ダメージが125%増加し、すべての攻撃が弱体化を付与します。" }
		},
		{
			"ko",
			new string[4] { "민첩", "질주 중에도 스킬을 사용할 수 있습니다.", "원자 치명타", "피해량이 125% 증가하고 모든 공격이 약화를 부여합니다." }
		},
		{
			"zh-CN",
			new string[4] { "敏捷", "奔跑时可以使用此技能。", "原子暴击", "伤害提高125%,所有攻击都会施加虚弱。" }
		},
		{
			"tr",
			new string[4] { "Çevik", "Yetenek koşarken kullanılabilir.", "Atomik Kritikler", "Hasar %125 artar ve tüm saldırılar Zayıflatma uygular." }
		},
		{
			"eo",
			new string[4] { "Lerta", "La kapablo uzeblas dum sprintado.", "Atomaj kritikoj", "Damagxo pligrandigxas je 125% kaj cxiuj atakoj aplikas malfortigon." }
		},
		{
			"la",
			new string[4] { "Agilis", "Haec facultas dum curris adhiberi potest.", "Ictus atomici critici", "Damnum augetur 125% et omnes impetus debilitationem inferunt." }
		}
	};

	private static Type configType;

	internal static string OnGet(orig_GetLocalizedStringByToken orig, Language self, string token)
	{
		string __result = orig.Invoke(self, token);
		if (self != null && !string.IsNullOrEmpty(__result) && keywordTranslations.TryGetValue(self.name, out var value))
		{
			__result = __result.Replace("The skill can be used while sprinting.", value[1]).Replace("Atomic Crits", value[2]).Replace("Damage is increased by 125% and all attacks apply Weaken.", value[3]);
			if (__result.Contains(value[1]))
			{
				__result = __result.Replace("Agile", value[0]);
			}
		}
		Postfix(token, ref __result);
		return __result;
	}

	private static void Postfix(string token, ref string __result)
	{
		if (__result == null || __result.IndexOf("{0}", StringComparison.Ordinal) < 0 || !fields.TryGetValue(token, out var value))
		{
			return;
		}
		try
		{
			if (configType == null)
			{
				Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
				foreach (Assembly assembly in assemblies)
				{
					configType = assembly.GetType("OfficialScoutMod.Scout.Content.ScoutConfig", throwOnError: false);
					if (configType != null)
					{
						break;
					}
				}
			}
			if (configType == null)
			{
				return;
			}
			FieldInfo field = configType.GetField(value, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			object obj = ((field == null) ? null : field.GetValue(null));
			PropertyInfo propertyInfo = obj?.GetType().GetProperty("Value");
			if (!(propertyInfo == null))
			{
				float num = Convert.ToSingle(propertyInfo.GetValue(obj, null)) * 100f;
				if (value == "atomicBlastDamageCoefficient")
				{
					__result = string.Format(__result, 100f, num);
				}
				else
				{
					__result = string.Format(__result, num);
				}
			}
		}
		catch (Exception ex)
		{
			Logger.CreateLogSource("ScoutFormatFix").LogWarning((object)ex.Message);
		}
	}
}