-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPatches.cs
More file actions
executable file
·416 lines (367 loc) · 19 KB
/
Copy pathPatches.cs
File metadata and controls
executable file
·416 lines (367 loc) · 19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using HarmonyLib;
using KMod;
using oni_vietnamese.Config;
using oni_vietnamese.Utils;
using TMPro;
using UnityEngine;
namespace oni_vietnamese {
public class Patches : UserMod2 {
private static readonly string ns = MethodBase.GetCurrentMethod().DeclaringType.Namespace;
public static string rootPath;
private static FontConfig fc;
private static bool fontLoadAttempted;
// Font assets for different game font families
private static TMP_FontAsset graystrokeFont;
private static TMP_FontAsset robotoRegularFont;
private static TMP_FontAsset robotoBoldFont;
private static TMP_FontAsset robotoItalicFont;
private static TMP_FontAsset robotoBoldItalicFont;
public override void OnLoad(Harmony harmony) {
harmony.PatchAll();
rootPath = mod.file_source.GetRoot();
ConfigManager.Instance.configPath = mod.file_source.GetRoot();
fc = ConfigManager.Instance.LoadConfigFile();
}
private static void EnsureFontLoaded() {
if (fontLoadAttempted) return;
fontLoadAttempted = true;
var fontsDir = Path.Combine(ConfigManager.Instance.configPath, "Fonts");
// Load GRAYSTROKE for heading fonts
var graystrokePath = Path.Combine(fontsDir, fc.Filename);
graystrokeFont = FontUtil.LoadFont(graystrokePath, "VNFont-Graystroke", fc.Scale);
// Load RobotoCondensed variants for body text
robotoRegularFont = FontUtil.LoadFont(
Path.Combine(fontsDir, "RobotoCondensed-Regular.ttf"), "VNFont-Roboto-Regular");
robotoBoldFont = FontUtil.LoadFont(
Path.Combine(fontsDir, "RobotoCondensed-Bold.ttf"), "VNFont-Roboto-Bold");
robotoItalicFont = FontUtil.LoadFont(
Path.Combine(fontsDir, "RobotoCondensed-Italic.ttf"), "VNFont-Roboto-Italic");
robotoBoldItalicFont = FontUtil.LoadFont(
Path.Combine(fontsDir, "RobotoCondensed-BoldItalic.ttf"), "VNFont-Roboto-BoldItalic");
int loaded = 0;
if (graystrokeFont != null) loaded++;
if (robotoRegularFont != null) loaded++;
if (robotoBoldFont != null) loaded++;
if (robotoItalicFont != null) loaded++;
if (robotoBoldItalicFont != null) loaded++;
Debug.Log($"[{ns}] Đã tải {loaded}/5 font");
}
/// <summary>
/// Check if a game font is a GRAYSTROKE variant (heading/display font).
/// </summary>
private static bool IsGraystroke(string fontName) {
return fontName.StartsWith("GRAYSTROKE", StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Check if a TMP_FontAsset is one of our custom fonts.
/// </summary>
private static bool IsOurFont(TMP_FontAsset font) {
return font == graystrokeFont || font == robotoRegularFont ||
font == robotoBoldFont || font == robotoItalicFont ||
font == robotoBoldItalicFont;
}
/// <summary>
/// Get the replacement font for a body text font based on its style.
/// </summary>
private static TMP_FontAsset GetBodyReplacement(string gameFontName) {
if (gameFontName.Contains("BoldItalic"))
return robotoBoldItalicFont ?? robotoBoldFont ?? robotoRegularFont;
if (gameFontName.Contains("Bold") || gameFontName.Contains("Economica"))
return robotoBoldFont ?? robotoRegularFont;
if (gameFontName.Contains("Italic"))
return robotoItalicFont ?? robotoRegularFont;
return robotoRegularFont;
}
internal static void ApplyFont() {
// --- Phase 1: Add fallback to GRAYSTROKE fonts (heading/display) ---
var allFonts = Resources.FindObjectsOfTypeAll<TMP_FontAsset>();
int fallbackCount = 0;
foreach (var gameFont in allFonts) {
if (gameFont == null || IsOurFont(gameFont)) continue;
if (!IsGraystroke(gameFont.name)) continue;
var fallbacks = gameFont.fallbackFontAssetTable;
if (fallbacks != null && fallbacks.Contains(graystrokeFont)) continue;
if (fallbacks == null)
gameFont.fallbackFontAssetTable = new List<TMP_FontAsset> { graystrokeFont };
else
fallbacks.Add(graystrokeFont);
fallbackCount++;
}
// --- Phase 2: Replace body text fonts directly on TextStyleSetting ---
var allStyles = Resources.FindObjectsOfTypeAll<TextStyleSetting>();
int styleCount = 0;
foreach (var style in allStyles) {
if (style == null || style.sdfFont == null) continue;
if (IsOurFont(style.sdfFont)) continue;
if (IsGraystroke(style.sdfFont.name)) continue;
var replacement = GetBodyReplacement(style.sdfFont.name);
if (replacement == null) continue;
style.sdfFont = replacement;
styleCount++;
}
// --- Phase 3: Replace body text fonts directly on LocText ---
var allLocTexts = Resources.FindObjectsOfTypeAll<LocText>();
bool isRTL = !fc.LeftToRight;
int locTextCount = 0;
foreach (var locText in allLocTexts) {
if (locText == null) continue;
var currentFont = locText.font;
if (currentFont == null) continue;
if (IsOurFont(currentFont)) continue;
if (IsGraystroke(currentFont.name)) continue;
var replacement = GetBodyReplacement(currentFont.name);
if (replacement == null) continue;
// Use reflection to call internal SwapFont(font, isRTL)
try {
var swapMethod = typeof(LocText).GetMethod("SwapFont",
BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public,
null, new Type[] { typeof(TMP_FontAsset), typeof(bool) }, null);
if (swapMethod != null) {
swapMethod.Invoke(locText, new object[] { replacement, isRTL });
} else {
locText.font = replacement;
}
} catch {
locText.font = replacement;
}
locTextCount++;
}
// --- Phase 4: Set Localization.sFontAsset for new LocText created later ---
try {
var sFontField = typeof(Localization).GetField("sFontAsset",
BindingFlags.Static | BindingFlags.NonPublic);
if (sFontField != null && robotoRegularFont != null) {
sFontField.SetValue(null, robotoRegularFont);
}
} catch (Exception ex) {
Debug.LogWarning($"[{ns}] Không thể set sFontAsset: {ex.Message}");
}
if (fallbackCount > 0 || styleCount > 0 || locTextCount > 0)
Debug.Log($"[{ns}] Applied: {fallbackCount} GRAYSTROKE fallbacks, {styleCount} TextStyleSettings, {locTextCount} LocTexts replaced");
}
[HarmonyPatch(typeof(Localization))]
[HarmonyPatch(nameof(Localization.GetLocale))]
[HarmonyPatch(new Type[] { typeof(string[]) })]
public static class Localization_GetLocale_Patch {
public static void Postfix(ref Localization.Locale __result) {
try {
EnsureFontLoaded();
// Set locale for Vietnamese but keep font name empty —
// we inject via fallback, not via SwapToLocalizedFont
var Language = fc.Code.Equals("zh") ? Localization.Language.Chinese : Localization.Language.Unspecified;
var Direction = fc.LeftToRight ? Localization.Direction.LeftToRight : Localization.Direction.RightToLeft;
__result = new Localization.Locale(Language, Direction, fc.Code, "");
} catch (Exception ex) {
DebugUtil.LogWarningArgs(new object[] { ex });
}
}
}
[HarmonyPatch(typeof(Localization))]
[HarmonyPatch("SwapToLocalizedFont")]
[HarmonyPatch(new Type[] { typeof(string) })]
public static class Localization_SwapToLocalizedFont_Patch {
public static void Postfix(string fontname) {
try {
ApplyFont();
} catch (Exception ex) {
Debug.LogWarning($"[{ns}] SwapToLocalizedFont patch error: {ex.Message}");
}
}
}
[HarmonyPatch(typeof(Db))]
[HarmonyPatch("Initialize")]
public static class Db_Initialize_Patch {
public static void Postfix() {
try {
EnsureFontLoaded();
ApplyFont();
} catch (Exception ex) {
Debug.LogWarning($"[{ns}] Db.Initialize patch error: {ex.Message}");
}
}
}
/// <summary>
/// Fix CustomGameSettings labels/tooltips not being translated.
///
/// Root cause: CustomGameSettingConfigs static fields are initialized before
/// translation loads. SettingLevel stores label/tooltip as plain strings
/// (copied from LocString at init time), so they remain in English.
///
/// This patch runs after Localization.LoadTranslation completes and
/// re-reads the now-translated LocString values back into SettingLevel/SettingConfig.
/// </summary>
[HarmonyPatch(typeof(Localization))]
[HarmonyPatch("LoadTranslation")]
[HarmonyPatch(new Type[] { typeof(string[]), typeof(bool) })]
public static class Localization_LoadTranslation_Patch {
public static void Postfix(bool __result) {
if (!__result) return;
try {
RefreshCustomGameSettingLabels();
} catch (Exception ex) {
Debug.LogWarning($"[{ns}] RefreshCustomGameSettingLabels error: {ex.Message}\n{ex.StackTrace}");
}
}
}
private static void RefreshCustomGameSettingLabels() {
// Get all static SettingConfig fields from CustomGameSettingConfigs
var configsType = typeof(Klei.CustomSettings.CustomGameSettingConfigs);
var settingFields = configsType.GetFields(BindingFlags.Static | BindingFlags.Public);
// Reflection setters for SettingConfig and SettingLevel
var configLabelSetter = typeof(Klei.CustomSettings.SettingConfig)
.GetProperty("label")?.GetSetMethod(true);
var configTooltipSetter = typeof(Klei.CustomSettings.SettingConfig)
.GetProperty("tooltip")?.GetSetMethod(true);
var levelLabelSetter = typeof(Klei.CustomSettings.SettingLevel)
.GetProperty("label")?.GetSetMethod(true);
var levelTooltipSetter = typeof(Klei.CustomSettings.SettingLevel)
.GetProperty("tooltip")?.GetSetMethod(true);
if (levelLabelSetter == null || levelTooltipSetter == null) {
Debug.LogWarning($"[{ns}] Cannot find SettingLevel label/tooltip setters");
return;
}
// Get the SETTINGS type: STRINGS.UI.FRONTEND.CUSTOMGAMESETTINGSSCREEN.SETTINGS
var settingsType = GetNestedType(typeof(STRINGS.UI), "FRONTEND", "CUSTOMGAMESETTINGSSCREEN", "SETTINGS");
if (settingsType == null) {
Debug.LogWarning($"[{ns}] Cannot find STRINGS.UI.FRONTEND.CUSTOMGAMESETTINGSSCREEN.SETTINGS type");
return;
}
int fixedCount = 0;
foreach (var field in settingFields) {
if (!typeof(Klei.CustomSettings.SettingConfig).IsAssignableFrom(field.FieldType))
continue;
var config = (Klei.CustomSettings.SettingConfig)field.GetValue(null);
if (config == null) continue;
// Find the corresponding STRINGS nested type for this setting
string stringsName = GetStringsName(field.Name);
if (stringsName == null) continue;
var settingType = settingsType.GetNestedType(stringsName,
BindingFlags.Public | BindingFlags.Static);
if (settingType == null) continue;
// Refresh SettingConfig.label and .tooltip from NAME/TOOLTIP LocString fields
var nameField = settingType.GetField("NAME", BindingFlags.Static | BindingFlags.Public);
var tooltipField = settingType.GetField("TOOLTIP", BindingFlags.Static | BindingFlags.Public);
if (nameField != null) {
var locStr = (LocString)nameField.GetValue(null);
if (locStr != null)
configLabelSetter?.Invoke(config, new object[] { locStr.text });
}
if (tooltipField != null) {
var locStr = (LocString)tooltipField.GetValue(null);
if (locStr != null)
configTooltipSetter?.Invoke(config, new object[] { locStr.text });
}
// Refresh each SettingLevel's label and tooltip
var levelsType = settingType.GetNestedType("LEVELS",
BindingFlags.Public | BindingFlags.Static);
if (levelsType == null) continue;
var levels = config.GetLevels();
if (levels == null) continue;
// Build a map of all LEVELS nested types and their NAME/TOOLTIP fields
var levelTypes = levelsType.GetNestedTypes(BindingFlags.Public | BindingFlags.Static);
var levelNameMap = new Dictionary<Type, string>(); // type -> NAME text
var levelTooltipMap = new Dictionary<Type, string>(); // type -> TOOLTIP text
foreach (var lt in levelTypes) {
var ltName = lt.GetField("NAME", BindingFlags.Static | BindingFlags.Public);
var ltTooltip = lt.GetField("TOOLTIP", BindingFlags.Static | BindingFlags.Public);
if (ltName != null) {
var ls = (LocString)ltName.GetValue(null);
if (ls != null) levelNameMap[lt] = ls.text;
}
if (ltTooltip != null) {
var ls = (LocString)ltTooltip.GetValue(null);
if (ls != null) levelTooltipMap[lt] = ls.text;
}
}
foreach (var level in levels) {
// Find matching STRINGS level type for this SettingLevel
Type matchedType = null;
foreach (var lt in levelTypes) {
if (!levelNameMap.ContainsKey(lt)) continue;
// Direct match (case-insensitive, ignore underscores)
if (lt.Name.Replace("_", "").Equals(
level.id.Replace("_", ""), StringComparison.OrdinalIgnoreCase)) {
matchedType = lt;
break;
}
}
// Handle known mismatches where level.id != STRINGS type name
if (matchedType == null) {
string mappedName = GetLevelStringsName(stringsName, level.id);
if (mappedName != null) {
foreach (var lt in levelTypes) {
if (lt.Name.Equals(mappedName, StringComparison.OrdinalIgnoreCase)) {
matchedType = lt;
break;
}
}
}
}
if (matchedType != null) {
string ltNameStr;
if (levelNameMap.TryGetValue(matchedType, out ltNameStr)) {
levelLabelSetter.Invoke(level, new object[] { ltNameStr });
fixedCount++;
}
string ltTooltipStr;
if (levelTooltipMap.TryGetValue(matchedType, out ltTooltipStr)) {
levelTooltipSetter.Invoke(level, new object[] { ltTooltipStr });
}
}
}
}
Debug.Log($"[{ns}] Refreshed {fixedCount} CustomGameSettings level labels after translation load");
}
private static Type GetNestedType(Type root, params string[] path) {
var current = root;
foreach (var name in path) {
current = current.GetNestedType(name, BindingFlags.Public | BindingFlags.Static);
if (current == null) return null;
}
return current;
}
/// <summary>
/// Maps field names from CustomGameSettingConfigs to their STRINGS nested type name.
/// </summary>
private static string GetStringsName(string fieldName) {
switch (fieldName) {
case "WorldgenSeed": return "WORLDGEN_SEED";
case "ClusterLayout": return "CLUSTER_CHOICE";
case "SandboxMode": return "SANDBOXMODE";
case "FastWorkersMode": return "FASTWORKERSMODE";
case "SaveToCloud": return "SAVETOCLOUD";
case "CalorieBurn": return "CALORIE_BURN";
case "BionicWattage": return "BIONICPOWERUSE";
case "ImmuneSystem": return "IMMUNESYSTEM";
case "Morale": return "MORALE";
case "Durability": return "DURABILITY";
case "Radiation": return "RADIATION";
case "Stress": return "STRESS";
case "StressBreaks": return "STRESS_BREAKS";
case "CarePackages": return "CAREPACKAGES";
case "Teleporters": return "TELEPORTERS";
case "MeteorShowers": return "METEORSHOWERS";
case "DemoliorDifficulty": return "DEMOLIORDIFFICULTY";
default: return null;
}
}
/// <summary>
/// Maps level ids that don't match their STRINGS type name.
/// Returns the STRINGS nested type name for the given level id, or null if no special mapping needed.
/// </summary>
private static string GetLevelStringsName(string settingStringsName, string levelId) {
// CarePackages: level "Disabled" -> STRINGS "DUPLICANTS_ONLY", "Enabled" -> "NORMAL"
if (settingStringsName == "CAREPACKAGES") {
switch (levelId) {
case "Disabled": return "DUPLICANTS_ONLY";
case "Enabled": return "NORMAL";
}
}
return null;
}
}
}