using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using TMPro;
using UnityEngine;
using UnityEngine.TextCore;
using UnityEngine.UI;
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace CloverPitPolishMod;
[BepInPlugin("pl.cloverpit.translation", "CloverPit Polish", "1.0.0")]
public class PolishPlugin : BaseUnityPlugin
{
private const string PolishCharacters = "ĄĆĘŁŃÓŚŹŻąćęłńóśźż";
private Dictionary<string, string> translations = new Dictionary<string, string>(StringComparer.Ordinal);
private float nextRun;
private bool loggedSuccess;
private static PolishPlugin instance;
private Texture2D shopSign;
private Texture shopSignSource;
private readonly Dictionary<Texture, Texture2D> patchedArtwork = new Dictionary<Texture, Texture2D>();
private Type managerType;
private string pluginDirectory;
private readonly HashSet<TMP_FontAsset> extendedFonts = new HashSet<TMP_FontAsset>();
private static readonly string[][] ShopLetters = new string[9][]
{
new string[7] { "1111111", "1011101", "0011100", "0011100", "0011100", "0011100", "0111110" },
new string[7] { "0011000", "0011100", "0101100", "0100110", "0111110", "1000110", "1101111" },
new string[7] { "1111100", "0111000", "0111000", "0111000", "0111001", "0111001", "1111111" },
new string[7] { "11111", "01110", "01110", "01110", "01110", "01110", "11111" },
new string[7] { "1111111", "1001110", "0011100", "0011000", "0110001", "1110001", "1111111" },
new string[7] { "111000111", "011101110", "011101110", "010111110", "010101110", "010001110", "111011111" },
new string[7] { "0011000", "0011100", "0101100", "0100110", "0111110", "1000110", "1101111" },
new string[7] { "11100111", "01100010", "01110010", "01011010", "01001110", "01000110", "11100010" },
new string[7] { "1110111", "0110010", "0011010", "0001100", "0001100", "0001100", "0011110" }
};
private void Awake()
{
pluginDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string path = Path.Combine(pluginDirectory, "tlumaczenia_pl.txt");
try
{
string[] array = File.ReadAllLines(path, Encoding.UTF8);
foreach (string text in array)
{
int num = text.IndexOf('\t');
if (num > 0)
{
string key = text.Substring(0, num);
string value = Encoding.UTF8.GetString(Convert.FromBase64String(text.Substring(num + 1)));
translations[key] = value;
}
}
((BaseUnityPlugin)this).Logger.LogInfo((object)("Loaded Polish entries: " + translations.Count));
instance = this;
InstallPatch("Panik.Translation", "Get", new Type[1] { typeof(string) }, "TranslateStartup");
InstallPatch("MatTextureSwitcher_Localizer", "Refresh", Type.EmptyTypes, "SelectSignTexture");
InstallPatch("MainMenuScript", "OptionsUpdateText_Desktop", Type.EmptyTypes, "LocalizeDlcBanner", postfix: true);
}
catch (Exception ex)
{
((BaseUnityPlugin)this).Logger.LogError((object)("Can't read Polish translations: " + ex));
}
}
private void Update()
{
if (translations.Count == 0 || Time.unscaledTime < nextRun)
{
return;
}
nextRun = Time.unscaledTime + 4f;
ExtendLoadedFonts();
LocalizeRealGraffiti();
try
{
ApplyTranslations();
}
catch (Exception ex)
{
if (!loggedSuccess)
{
((BaseUnityPlugin)this).Logger.LogWarning((object)("I2 initialization pending: " + ex.Message));
}
}
}
private void InstallPatch(string typeName, string methodName, Type[] parameters, string patchMethod, bool postfix = false)
{
//IL_003b: Unknown result type (might be due to invalid IL or missing references)
//IL_0041: Expected O, but got Unknown
//IL_0046: Unknown result type (might be due to invalid IL or missing references)
try
{
Type type = AccessTools.TypeByName(typeName);
MethodInfo methodInfo = ((type == null) ? null : AccessTools.Method(type, methodName, parameters, (Type[])null));
if (methodInfo == null)
{
throw new MissingMethodException(typeName, methodName);
}
HarmonyMethod val = new HarmonyMethod(typeof(PolishPlugin), patchMethod, (Type[])null);
new Harmony("pl.cloverpit.translation").Patch((MethodBase)methodInfo, postfix ? null : val, postfix ? val : null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
}
catch (Exception ex)
{
((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not patch " + typeName + "." + methodName + ": " + ex.Message));
}
}
private static bool TranslateStartup(string __0, ref string __result)
{
if (string.IsNullOrEmpty(__0) || (Object)(object)instance == (Object)null)
{
return true;
}
if (!__0.StartsWith("INTRO_", StringComparison.Ordinal) && __0 != "UI_PROMPT_CONTINUE" && __0 != "UI_PROMPT_YES" && __0 != "UI_PROMPT_NO" && __0 != "POP_UP_TITLE_WARNING")
{
return true;
}
if (!instance.translations.TryGetValue(__0, out var value))
{
return true;
}
__result = value;
return false;
}
private static bool SelectSignTexture(Material ___sharedMat, Texture ___textureEnglish)
{
if ((Object)(object)instance == (Object)null || !Object.op_Implicit((Object)(object)___sharedMat) || !Object.op_Implicit((Object)(object)___textureEnglish))
{
return true;
}
if (((Object)___textureEnglish).name == "Texture_DontTrustEveryone")
{
___sharedMat.mainTexture = instance.GetPatchedArtwork(___textureEnglish, "GraffitiTelefon");
return false;
}
if (((Object)___sharedMat).name != "Mat Lucky Charms Label" || ___textureEnglish.width != 96 || ___textureEnglish.height != 32)
{
return true;
}
try
{
if (!Object.op_Implicit((Object)(object)instance.shopSign) || (Object)(object)instance.shopSignSource != (Object)(object)___textureEnglish)
{
Texture2D val = CreateShopSign(___textureEnglish);
if (Object.op_Implicit((Object)(object)instance.shopSign))
{
Object.Destroy((Object)(object)instance.shopSign);
}
instance.shopSign = val;
instance.shopSignSource = ___textureEnglish;
((BaseUnityPlugin)instance).Logger.LogInfo((object)"Localized Lucky Charms sign: TALIZMANY");
}
___sharedMat.mainTexture = (Texture)(object)instance.shopSign;
return false;
}
catch (Exception ex)
{
((BaseUnityPlugin)instance).Logger.LogWarning((object)("Could not localize the Lucky Charms sign: " + ex.Message));
return true;
}
}
private static Texture2D CreateShopSign(Texture source)
{
//IL_0018: Unknown result type (might be due to invalid IL or missing references)
//IL_001e: Expected O, but got Unknown
//IL_0040: Unknown result type (might be due to invalid IL or missing references)
//IL_007a: Unknown result type (might be due to invalid IL or missing references)
//IL_007f: 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_01e3: Unknown result type (might be due to invalid IL or missing references)
//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
//IL_0181: Unknown result type (might be due to invalid IL or missing references)
//IL_0186: Unknown result type (might be due to invalid IL or missing references)
//IL_0102: Unknown result type (might be due to invalid IL or missing references)
//IL_0104: Unknown result type (might be due to invalid IL or missing references)
RenderTexture active = RenderTexture.active;
RenderTexture temporary = RenderTexture.GetTemporary(96, 32, 0, (RenderTextureFormat)0);
Texture2D val = new Texture2D(96, 32, (TextureFormat)4, true);
try
{
Graphics.Blit(source, temporary);
RenderTexture.active = temporary;
val.ReadPixels(new Rect(0f, 0f, 96f, 32f), 0, 0, false);
Color32[] pixels = val.GetPixels32();
for (int i = 12; i <= 19; i++)
{
int num = (31 - i) * 96;
for (int j = 4; j <= 92; j++)
{
Color32 val2 = pixels[num + j];
if (val2.a >= 128 && val2.r < 150)
{
int num2 = ((j % 2 == 0) ? 11 : 20);
Color32 val3 = pixels[(31 - num2) * 96 + j];
if (val3.a < 128 || val3.r < 150)
{
((Color32)(ref val3))..ctor((byte)189, (byte)163, (byte)121, byte.MaxValue);
}
pixels[num + j] = val3;
}
}
}
int num3 = 9;
string[][] shopLetters = ShopLetters;
foreach (string[] array in shopLetters)
{
for (int l = 0; l < array.Length; l++)
{
int num4 = (31 - (13 + l)) * 96;
for (int m = 0; m < array[l].Length; m++)
{
if (array[l][m] == '1')
{
ref Color32 reference = ref pixels[num4 + num3 + m];
reference = new Color32((byte)34, (byte)21, (byte)13, byte.MaxValue);
}
}
}
num3 += array[0].Length + 2;
}
val.SetPixels32(pixels);
((Texture)val).filterMode = source.filterMode;
((Texture)val).wrapMode = source.wrapMode;
((Texture)val).anisoLevel = source.anisoLevel;
((Object)val).name = "Texture_CharmLabel_PL";
val.Apply(true, true);
return val;
}
catch
{
Object.Destroy((Object)(object)val);
throw;
}
finally
{
RenderTexture.active = active;
RenderTexture.ReleaseTemporary(temporary);
}
}
private void LocalizeRealGraffiti()
{
Material[] array = Resources.FindObjectsOfTypeAll<Material>();
foreach (Material val in array)
{
if (Object.op_Implicit((Object)(object)val))
{
string patch;
string text;
switch (((Object)val).name)
{
case "Mat T Real Question":
patch = "GraffitiJawaPytanie";
text = "texture_real1";
break;
case "Mat T Real":
patch = "GraffitiJawaWykrzykniki";
text = "texture_real2";
break;
default:
continue;
}
Texture mainTexture = val.mainTexture;
if (Object.op_Implicit((Object)(object)mainTexture) && ((Object)mainTexture).name == text)
{
val.mainTexture = GetPatchedArtwork(mainTexture, patch);
}
}
}
}
private static void LocalizeDlcBanner(RawImage ___adDLC_RawImage, Texture[] ___adDlcTextures)
{
if ((Object)(object)instance == (Object)null || !Object.op_Implicit((Object)(object)___adDLC_RawImage) || ___adDlcTextures == null)
{
return;
}
foreach (Texture val in ___adDlcTextures)
{
if (Object.op_Implicit((Object)(object)val) && !(((Object)val).name != "EN_Unholy_Fusion_DLC_Available_now"))
{
Texture val2 = instance.GetPatchedArtwork(val, "BanerUnholyFusion");
if ((Object)(object)val2 != (Object)(object)val)
{
___adDLC_RawImage.texture = val2;
}
break;
}
}
}
private Texture GetPatchedArtwork(Texture original, string patch)
{
if (patchedArtwork.TryGetValue(original, out var value))
{
if (!Object.op_Implicit((Object)(object)value))
{
return original;
}
return (Texture)(object)value;
}
try
{
string path = Path.Combine(pluginDirectory, patch + ".bin");
using (BinaryReader patch2 = new BinaryReader(File.OpenRead(path)))
{
value = ApplyTexturePatch(original, patch2);
}
((BaseUnityPlugin)this).Logger.LogInfo((object)("Localized artwork: " + ((Object)original).name));
}
catch (Exception ex)
{
value = null;
((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not localize artwork " + ((Object)original).name + ": " + ex.Message));
}
patchedArtwork.Add(original, value);
if (!Object.op_Implicit((Object)(object)value))
{
return original;
}
return (Texture)(object)value;
}
private static Texture2D ApplyTexturePatch(Texture source, BinaryReader patch)
{
//IL_0051: Unknown result type (might be due to invalid IL or missing references)
//IL_0058: Expected O, but got Unknown
//IL_0077: Unknown result type (might be due to invalid IL or missing references)
//IL_015b: Unknown result type (might be due to invalid IL or missing references)
//IL_0168: Unknown result type (might be due to invalid IL or missing references)
//IL_0175: 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_00f9: Unknown result type (might be due to invalid IL or missing references)
int num = patch.ReadInt32();
int num2 = patch.ReadInt32();
int num3 = patch.ReadInt32();
if (num != source.width || num2 != source.height || num3 < 1 || num3 > num * num2)
{
throw new InvalidDataException("Texture dimensions or patch length do not match");
}
RenderTexture active = RenderTexture.active;
RenderTexture temporary = RenderTexture.GetTemporary(num, num2, 0, (RenderTextureFormat)0);
Texture2D val = new Texture2D(num, num2, (TextureFormat)4, true);
try
{
Graphics.Blit(source, temporary);
RenderTexture.active = temporary;
val.ReadPixels(new Rect(0f, 0f, (float)num, (float)num2), 0, 0, false);
Color32[] pixels = val.GetPixels32();
int num4 = 0;
for (int i = 0; i < num3; i++)
{
int num5 = patch.ReadInt32();
int num6 = patch.ReadInt32();
if (num5 < num4 || num6 < 1 || num5 > pixels.Length - num6)
{
throw new InvalidDataException("Invalid texture patch span");
}
num4 = num5 + num6;
for (int j = num5; j < num4; j++)
{
ref Color32 reference = ref pixels[j];
reference = new Color32(patch.ReadByte(), patch.ReadByte(), patch.ReadByte(), patch.ReadByte());
}
}
if (patch.BaseStream.Position != patch.BaseStream.Length)
{
throw new InvalidDataException("Unexpected data after texture patch");
}
val.SetPixels32(pixels);
((Object)val).name = ((Object)source).name + "_PL";
((Texture)val).filterMode = source.filterMode;
((Texture)val).wrapModeU = source.wrapModeU;
((Texture)val).wrapModeV = source.wrapModeV;
((Texture)val).anisoLevel = source.anisoLevel;
((Texture)val).mipMapBias = source.mipMapBias;
val.Apply(true, true);
return val;
}
catch
{
Object.Destroy((Object)(object)val);
throw;
}
finally
{
RenderTexture.active = active;
RenderTexture.ReleaseTemporary(temporary);
}
}
private static object GetMember(object obj, string name)
{
Type type = obj as Type;
object obj2 = ((type != null) ? null : obj);
if (type == null)
{
type = obj.GetType();
}
BindingFlags bindingAttr = (BindingFlags)(0x30 | ((obj2 == null) ? 8 : 4));
PropertyInfo property = type.GetProperty(name, bindingAttr);
if (property != null)
{
return property.GetValue(obj2, null);
}
FieldInfo field = type.GetField(name, bindingAttr);
if (!(field != null))
{
return null;
}
return field.GetValue(obj2);
}
private static void SetMember(object obj, string name, object value)
{
Type type = obj as Type;
object obj2 = ((type != null) ? null : obj);
if (type == null)
{
type = obj.GetType();
}
BindingFlags bindingAttr = (BindingFlags)(0x30 | ((obj2 == null) ? 8 : 4));
PropertyInfo property = type.GetProperty(name, bindingAttr);
if (property != null && property.CanWrite)
{
property.SetValue(obj2, value, null);
return;
}
FieldInfo field = type.GetField(name, bindingAttr);
if (field != null)
{
field.SetValue(obj2, value);
}
}
private static object Call(object obj, string name, params object[] args)
{
Type type = obj as Type;
object obj2 = ((type != null) ? null : obj);
if (type == null)
{
type = obj.GetType();
}
BindingFlags bindingAttr = (BindingFlags)(0x30 | ((obj2 == null) ? 8 : 4));
MethodInfo[] methods = type.GetMethods(bindingAttr);
foreach (MethodInfo methodInfo in methods)
{
if (methodInfo.Name != name)
{
continue;
}
ParameterInfo[] parameters = methodInfo.GetParameters();
if (parameters.Length == args.Length)
{
try
{
return methodInfo.Invoke(obj2, args);
}
catch (ArgumentException)
{
}
}
}
return null;
}
private void ApplyTranslations()
{
if (managerType == null)
{
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly assembly in assemblies)
{
managerType = assembly.GetType("I2.Loc.LocalizationManager", throwOnError: false);
if (managerType != null)
{
break;
}
}
}
if (managerType == null || !(GetMember(managerType, "Sources") is IEnumerable enumerable))
{
return;
}
int num = 0;
int num2 = 0;
foreach (object item in enumerable)
{
if (item == null)
{
continue;
}
num2++;
int num3 = -1;
object obj = Call(item, "GetLanguageIndex", "Polish", false, false);
if (obj is int)
{
num3 = (int)obj;
}
if (num3 < 0)
{
Call(item, "AddLanguage", "Polish", "pl");
obj = Call(item, "GetLanguageIndex", "Polish", false, false);
if (obj is int)
{
num3 = (int)obj;
}
}
if (num3 < 0 || !(GetMember(item, "mTerms") is IEnumerable enumerable2))
{
continue;
}
foreach (object item2 in enumerable2)
{
if (item2 == null)
{
continue;
}
string text = GetMember(item2, "Term") as string;
if (string.IsNullOrEmpty(text) || !translations.TryGetValue(text, out var value))
{
continue;
}
string[] array = GetMember(item2, "Languages") as string[];
if (array != null)
{
if (array.Length <= num3)
{
string[] array2 = new string[num3 + 1];
Array.Copy(array, array2, array.Length);
array = array2;
SetMember(item2, "Languages", array);
}
if (array[num3] != value)
{
array[num3] = value;
num++;
}
}
}
if (num > 0)
{
Call(item, "UpdateDictionary", true);
}
}
if (num2 != 0)
{
string text2 = GetMember(managerType, "CurrentLanguage") as string;
if (text2 != "Polish")
{
SetMember(managerType, "CurrentLanguage", "Polish");
Call(managerType, "LocalizeAll", true);
}
else if (num > 0)
{
Call(managerType, "LocalizeAll", true);
}
if (!loggedSuccess)
{
((BaseUnityPlugin)this).Logger.LogInfo((object)("I2 found, sources: " + num2 + ", updated translations: " + num + ", language: " + GetMember(managerType, "CurrentLanguage")));
loggedSuccess = true;
}
}
}
private void ExtendLoadedFonts()
{
//IL_0071: Unknown result type (might be due to invalid IL or missing references)
//IL_0076: Unknown result type (might be due to invalid IL or missing references)
HashSet<TMP_FontAsset> hashSet = new HashSet<TMP_FontAsset>();
TMP_FontAsset[] array = Resources.FindObjectsOfTypeAll<TMP_FontAsset>();
foreach (TMP_FontAsset val in array)
{
if (!Object.op_Implicit((Object)(object)val) || extendedFonts.Contains(val) || (((Object)val).name != "FontMain" && ((Object)val).name != "FontSlot" && ((Object)val).name != "FontMenuDyslexic"))
{
continue;
}
FaceInfo faceInfo = ((TMP_Asset)val).faceInfo;
string fileName;
switch (((FaceInfo)(ref faceInfo)).familyName)
{
case "Bebas Neue":
fileName = "BebasNeue-Regular.ttf";
break;
case "OpenDyslexic":
fileName = "OpenDyslexic-Regular.otf";
break;
default:
continue;
}
extendedFonts.Add(val);
try
{
if (AttachPolishGlyphs(val, fileName))
{
hashSet.Add(val);
}
}
catch (Exception ex)
{
((BaseUnityPlugin)this).Logger.LogWarning((object)("Polish glyphs for " + ((Object)val).name + ": " + ex));
}
}
if (hashSet.Count == 0)
{
return;
}
TMP_Text[] array2 = Resources.FindObjectsOfTypeAll<TMP_Text>();
foreach (TMP_Text val2 in array2)
{
if (Object.op_Implicit((Object)(object)val2) && ((Behaviour)val2).isActiveAndEnabled && hashSet.Contains(val2.font))
{
val2.havePropertiesChanged = true;
((Graphic)val2).SetAllDirty();
}
}
}
private bool AttachPolishGlyphs(TMP_FontAsset original, string fileName)
{
//IL_0089: Unknown result type (might be due to invalid IL or missing references)
//IL_008e: Unknown result type (might be due to invalid IL or missing references)
//IL_009f: Unknown result type (might be due to invalid IL or missing references)
//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
StringBuilder stringBuilder = new StringBuilder();
string text = "ĄĆĘŁŃÓŚŹŻąćęłńóśźż";
foreach (char letter in text)
{
List<TMP_Character> characterTable = original.characterTable;
Predicate<TMP_Character> match = (TMP_Character character) => ((TMP_TextElement)character).unicode == letter;
if (!characterTable.Exists(match))
{
stringBuilder.Append(letter);
}
}
if (stringBuilder.Length == 0)
{
return false;
}
string text2 = Path.Combine(Path.Combine(pluginDirectory, "fonts"), fileName);
FaceInfo faceInfo = ((TMP_Asset)original).faceInfo;
TMP_FontAsset val = TMP_FontAsset.CreateFontAsset(text2, 0, (int)((FaceInfo)(ref faceInfo)).pointSize, original.atlasPadding, original.atlasRenderMode, 1024, 1024);
if (!Object.op_Implicit((Object)(object)val))
{
throw new InvalidOperationException("Cannot load " + fileName);
}
string text3 = default(string);
if (!val.TryAddCharacters(stringBuilder.ToString(), ref text3, false))
{
Object.Destroy((Object)(object)val);
throw new InvalidOperationException("Missing characters in " + fileName + ": " + text3);
}
val.normalSpacingOffset = original.normalSpacingOffset;
val.boldSpacing = original.boldSpacing;
val.normalStyle = original.normalStyle;
val.boldStyle = original.boldStyle;
val.italicStyle = original.italicStyle;
((Object)val).name = ((Object)original).name + " Polish";
val.atlasPopulationMode = (AtlasPopulationMode)0;
if (original.fallbackFontAssetTable == null)
{
original.fallbackFontAssetTable = new List<TMP_FontAsset>();
}
original.fallbackFontAssetTable.Insert(0, val);
string text4 = stringBuilder.ToString();
foreach (char key in text4)
{
original.characterLookupTable.Remove(key);
}
ManualLogSource logger = ((BaseUnityPlugin)this).Logger;
object[] array = new object[5]
{
((Object)original).name,
" added ",
stringBuilder,
" from ",
null
};
FaceInfo faceInfo2 = ((TMP_Asset)val).faceInfo;
array[4] = ((FaceInfo)(ref faceInfo2)).familyName;
logger.LogInfo((object)string.Concat(array));
return true;
}
}