-
Notifications
You must be signed in to change notification settings - Fork 0
/
RimLanguageHotReload.cs
797 lines (685 loc) · 30.9 KB
/
RimLanguageHotReload.cs
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
using LordFanger.IO;
using RimWorld;
using RimWorld.IO;
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using Verse;
using Verse.Grammar;
using File = System.IO.File;
using static LordFanger.Log;
namespace LordFanger
{
[StaticConstructorOnStartup]
public static partial class RimLanguageHotReload
{
private static readonly IDictionary<string, string> _tkeyToDefPath = new Dictionary<string, string>();
private static readonly IDictionary<DefUniqueKey, IList<Def>> _definitions = new Dictionary<DefUniqueKey, IList<Def>>();
private static readonly IDictionary<KeyedUniqueKey, LoadedLanguage.KeyedReplacement> _keyed = new Dictionary<KeyedUniqueKey, LoadedLanguage.KeyedReplacement>();
private static readonly TemplateDefsResolver _templateDefsResolver = new TemplateDefsResolver();
private static DateTime _delayedFswTo;
private static FileSystemWatcher _fsw;
private static readonly ICollection<DirectoryHandle> _languageDirectories = new List<DirectoryHandle>();
private static readonly ConcurrentDictionary<string, bool> _changedFiles = new ConcurrentDictionary<string, bool>();
private static LoadedLanguage ActiveLanguage => LanguageDatabase.activeLanguage;
static RimLanguageHotReload()
{
LoadDefinitions();
LoadKeyed();
LoadTKeys();
Task.Run(() =>
{
LoadDirectories();
StartUpdateLoop();
StartFileSystemWatcher();
});
}
private static void LoadDefinitions()
{
Util.SafeExecute(
() =>
{
var defTypes = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(a => a.GetTypes())
.Where(t => typeof(Def).IsAssignableFrom(t));
var defsDbType = typeof(DefDatabase<>);
foreach (var defType in defTypes)
{
Util.SafeExecute(
() =>
{
var defDbType = defsDbType.MakeGenericType(defType);
var defDbProperty = defDbType.GetRuntimeProperties()
.First(p => p.Name == nameof(DefDatabase<Def>.AllDefs));
if (!(defDbProperty.GetValue(null) is IEnumerable defDb)) return;
foreach (Def def in defDb)
{
var directoryName = def.GetType().Name;
var fileName = def.fileName;
var defName = def.defName;
var key = new DefUniqueKey(defName, Path.GetFileNameWithoutExtension(fileName), directoryName);
if (!_definitions.TryGetValue(key, out var defList))
{
defList = new List<Def>();
_definitions.Add(key, defList);
}
defList.Add(def);
}
});
}
// register implied defs
foreach (var def in _definitions.Values.SelectMany(d => d))
{
_templateDefsResolver.AddImpliedDefIfAny(def);
}
Message("Definitions loaded.");
});
}
private static void ReloadKeyed()
{
_keyed.Clear();
LoadKeyed();
}
private static void LoadKeyed()
{
if (ActiveLanguage?.keyedReplacements == null) return;
foreach (var kv in ActiveLanguage.keyedReplacements)
{
var keyed = kv.Value;
if (keyed == null || keyed.fileSourceFullPath == null || keyed.key == null) continue;
_keyed.Add(new KeyedUniqueKey(keyed.key, keyed.fileSourceFullPath.ToLower()), keyed);
}
Message("Keyed loaded.");
}
private static void LoadTKeys()
{
var tKeyToNormalizedTranslationKey = (IDictionary<string, string>)Util.GetStaticField(typeof(TKeySystem), "tKeyToNormalizedTranslationKey").GetValue(null);
foreach (var kv in tKeyToNormalizedTranslationKey)
{
_tkeyToDefPath.Add(kv.Key, kv.Value);
}
Message("TKeys loaded.");
}
private static void StartFileSystemWatcher()
{
var fsw = new FileSystemWatcher
{
Path = AppDomain.CurrentDomain.BaseDirectory,
IncludeSubdirectories = true,
Filter = "*"
};
fsw.Changed += (_, e) => EnqueueFileChange(e.FullPath);
fsw.Created += (_, e) => EnqueueFileChange(e.FullPath);
fsw.Error += (_, e) =>
{
Util.SafeExecute(fsw.Dispose);
Warning($"Error in file system watching - {e.GetException().Message}\nRestarting file system watcher.");
StartFileSystemWatcher();
};
_fsw = fsw;
_fsw.EnableRaisingEvents = true;
}
private static void EnqueueFileChange(string filePath)
{
_changedFiles.TryAdd(filePath, true);
_delayedFswTo = DateTime.Now.AddMilliseconds(500);
}
private static void LoadDirectories()
{
foreach (var (virtualDirectory, _, _) in ActiveLanguage.AllDirectories)
{
_languageDirectories.Add(virtualDirectory.FullPath.AsDirectory());
}
}
private static void StartUpdateLoop()
{
Task.Run(async () =>
{
while (true)
{
await Task.Delay(10);
if (_changedFiles.Count == 0) continue;
if (_delayedFswTo > DateTime.Now) continue;
Util.SafeExecute(UpdateChangedFiles);
}
// ReSharper disable once FunctionNeverReturns
});
}
private static void UpdateChangedFiles()
{
var filePaths = _changedFiles.Keys.ToArray();
foreach (var filePath in filePaths)
{
_changedFiles.TryRemove(filePath, out _);
}
if (filePaths.Length == 0) return;
Message($"Updating changed files ({filePaths.Length})");
UpdateFiles(filePaths.AsFiles());
ClearCaches();
}
private static void UpdateFiles(IEnumerable<FileHandle> filePaths)
{
foreach (var filePath in filePaths) UpdateFile(filePath);
}
private static void UpdateFile(FileHandle file)
{
Util.SafeExecute(
() =>
{
var directory = file.Directory;
if (!IsActiveLanguageSubfolder(directory, out var rootDirectory))
{
return;
}
if (!file.Exists())
{
return;
}
if (file.HasExtension(".xml"))
{
UpdateXmlFile(file, directory);
return;
}
if (file.HasExtension(".txt"))
{
UpdateTxtFile(file, directory, rootDirectory);
return;
}
});
}
private static void UpdateXmlFile(FileHandle file, DirectoryHandle directory)
{
var directoryName = directory.DirectoryName;
XDocument xml;
try
{
var xmlContent = file.ReadAllText();
xml = XDocument.Parse(xmlContent);
}
catch
{
return;
}
var root = xml.Root;
if (root == null) throw new Exception("Invalid XML");
if (root.Name == "LanguageData")
{
UpdateLanguageData(file, directoryName, root);
}
}
private static void UpdateLanguageData(FileHandle file, string directoryName, XElement root)
{
foreach (var item in root.Elements())
{
if (item.NodeType != XmlNodeType.Element) continue;
var defFieldName = item.Name.LocalName;
var tkeyMatch = Regex.Match(defFieldName, @"^(?<TKEY>[^\.]+\.[^\.]+)");
if (tkeyMatch.Success)
{
var tkey = tkeyMatch.Groups["TKEY"].Value;
if (_tkeyToDefPath.TryGetValue(tkey, out var tkeyDefPath))
{
defFieldName = $"{tkeyDefPath}{defFieldName.Substring(tkey.Length)}";
}
}
var match = Regex.Match(defFieldName, @"^(?<DEF_NAME>[^\.]+)\.(?<FIELD_PATH>.+)$");
if (match.Success)
{
var defName = match.Groups["DEF_NAME"].Value;
var fieldPathRaw = match.Groups["FIELD_PATH"].Value;
UpdateDefinition(defName, fieldPathRaw, file, directoryName, item);
}
else
{
UpdateKeyed(file, item);
}
}
}
private static void UpdateDefinition(string defName, string fieldPathRaw, FileHandle file, string directoryName, XElement item)
{
var fieldPath = fieldPathRaw.Split('.');
if (!_definitions.TryGetValue(new DefUniqueKey(defName, file, directoryName), out var defs))
{
return;
}
foreach (var def in defs)
{
UpdateDefinitionFieldByPath(def, fieldPath[0], fieldPath, 1, item, null);
}
}
private static void UpdateDefinitionFieldByPath(object obj, string fieldName, string[] fieldPath, int fieldPathOffset, XElement item, Attribute[] fieldAttributes)
{
fieldAttributes ??= Array.Empty<Attribute>();
var objType = obj.GetType();
var fieldByName = Util.GetTypeInstanceFieldsWithAtrtibutesByName(objType);
if (TryUpdateInUntranslantedCollection(obj, fieldName, fieldPath, fieldPathOffset, item, fieldAttributes))
{
return;
}
if (!fieldByName.TryGetValue(fieldName, out var field) || field == null)
{
return;
}
var fieldInfo = field.FieldInfo;
var fieldValue = fieldInfo.GetValue(obj);
if (fieldPathOffset < fieldPath.Length)
{
if (fieldValue == null)
{
return;
}
UpdateDefinitionFieldByPath(fieldValue, fieldPath[fieldPathOffset], fieldPath, fieldPathOffset + 1, item, field.Attributes);
}
else
{
if (fieldInfo.FieldType == typeof(string))
{
UpdateStringDefinition(obj, objType, fieldName, fieldInfo, fieldPath, fieldPathOffset, item);
return;
}
if (objType == typeof(RulePack) && typeof(IList<string>).IsAssignableFrom(fieldInfo.FieldType))
{
if (TryUpdateRulesDefinition(obj, objType, fieldName, fieldInfo, fieldPath, fieldPathOffset, item))
{
TryClearCachedValue(obj, "cachedRules", item);
}
return;
}
}
}
private static void UpdateStringDefinition(object obj, Type objType, string fieldName, FieldInfo fieldInfo, string[] fieldPath, int fieldPathOffset, XElement item)
{
var oldValue = (string)fieldInfo.GetValue(obj);
var newValue = GetNewValue(item);
if (newValue == null)
{
return;
}
if (newValue == oldValue)
{
return;
}
if (string.IsNullOrWhiteSpace(oldValue) && string.IsNullOrWhiteSpace(newValue))
{
return;
}
var fieldsByName = Util.GetTypeInstanceFieldsByName(objType);
Message($"Setting new value {string.Join(", ", fieldPath)} '{oldValue}'->'{newValue}'");
fieldInfo.SetValue(obj, newValue);
TryClearCachedValue(obj, fieldName.ToCachedName(), item, fieldsByName);
TryClearCachedValue(obj, fieldName.ToCachedName() + "Cap", item, fieldsByName);
if (obj is Def def)
{
_templateDefsResolver.NotifyDefChanged(def);
}
}
private static bool TryUpdateRulesDefinition(object obj, Type objType, string fieldName, FieldInfo fieldInfo, string[] fieldPath, int fieldPathOffset, XElement item)
{
var oldValue = (IList<string>)fieldInfo.GetValue(obj);
var newValue = new List<string>();
foreach (var li in item.Elements())
{
if (li.Name != "li") throw new Exception($"Unknown element {li} found");
var value = li.Value;
var rule = value.Replace("\\n", "\n");
newValue.Add(rule);
}
if (oldValue.SequenceEqual(newValue))
{
return false;
}
newValue.TrimExcess();
// clear local rules cache
fieldInfo.SetValue(obj, newValue);
TryClearCachedValue(obj, "rulesResolved", item);
// clear global rules cache
TryClearCachedValue(RulePackDefOf.GlobalUtility, "cachedRules", item);
return true;
}
private static bool TryUpdateInUntranslantedCollection(object obj, string fieldName, string[] fieldPath, int fieldPathOffset, XElement item, Attribute[] fieldAttributes)
{
if (!(obj is ICollection collection)) return false;
if (int.TryParse(fieldName, out var index) && index >= 0 && index < collection.Count)
{
if (fieldPath.Length == fieldPathOffset && collection is IList<string> list/* && fieldAttributes.Any<MustTranslateAttribute>()*/)
{
var oldValue = list[index];
var newValue = GetNewValue(item);
if (newValue == null)
{
return false;
}
if (oldValue == newValue)
{
return true;
}
if (string.IsNullOrWhiteSpace(oldValue) && string.IsNullOrWhiteSpace(newValue))
{
return true;
}
list[index] = newValue;
}
else
{
UpdateDefinitionFieldByPath(collection.ElementAt(index), fieldPath[fieldPathOffset], fieldPath, fieldPathOffset + 1, item, null);
}
return true;
}
var match = Regex.Match(fieldName, @"^(?<NAME>.+?)(\-(?<INDEX>\d+))?$");
var untranslantedName = match.Groups["NAME"].Value;
var untranslantedIndex = 0;
var validItemIndex = 0;
if (match.Groups["INDEX"].Success) untranslantedIndex = int.Parse(match.Groups["INDEX"].Value);
foreach (var collectionItem in collection)
{
if (collectionItem == null) continue;
var untranslantedFields = Util.GetTypeUntranslantedFieldsWithAttributes(collectionItem.GetType());
foreach (var untranslantedField in untranslantedFields)
{
var rawValueForTranslation = untranslantedField.FieldInfo.GetValue(collectionItem);
var valueForTranslation = (rawValueForTranslation as string).ToNormalizedHandle();
if (valueForTranslation == null && rawValueForTranslation is Def def) valueForTranslation = def.defName;
if (valueForTranslation == null && rawValueForTranslation is Type type)
{
valueForTranslation = type.Name.ToNormalizedHandle();
if (valueForTranslation != untranslantedName)
{
valueForTranslation = type.FullName.ToNormalizedHandle();
if (valueForTranslation != untranslantedName) continue;
}
}
else if (valueForTranslation != untranslantedName) continue;
// index of valid item by untranslanted
if (untranslantedIndex != validItemIndex)
{
validItemIndex++;
continue;
}
UpdateDefinitionFieldByPath(collectionItem, fieldPath[fieldPathOffset], fieldPath, fieldPathOffset + 1, item, untranslantedField.Attributes);
return true;
}
}
return false;
}
private static void UpdateKeyed(FileHandle file, XElement item)
{
var keyedName = item.Name.LocalName;
if (!_keyed.TryGetValue(new KeyedUniqueKey(keyedName, file.FilePathLower), out var keyed))
{
// try to reload file keyed file if was missing at game initialization
// TODO could take very long when many files are missing
ReloadKeyedFile(file);
if (!_keyed.TryGetValue(new KeyedUniqueKey(keyedName, file.FilePathLower), out keyed))
{
return;
}
}
var oldValue = keyed.value;
var newValue = GetNewValue(item);
if (newValue == oldValue)
{
return;
}
if (string.IsNullOrWhiteSpace(oldValue) && string.IsNullOrWhiteSpace(newValue))
{
return;
}
Message($"Updating keyed {keyed.key} '{keyed.value}' -> '{newValue}'");
keyed.value = newValue;
keyed.isPlaceholder = string.IsNullOrWhiteSpace(newValue);
}
private static void ReloadKeyedFile(FileHandle file)
{
Util.SafeExecute(
() =>
{
var virtualDirectory = AbstractFilesystem.GetDirectory(file.Directory.DirectoryPath);
var virtualFile = virtualDirectory.GetFile(file.FileName);
// reload translation file in game
ActiveLanguage.InvokeInstanceMethod("LoadFromFile_Keyed", virtualFile);
// reload hot reload keyed cache
ReloadKeyed();
});
}
private static void TryClearCachedValue(object obj, string cachedFieldName, XElement item, IDictionary<string, FieldInfo> fieldByName = null)
{
fieldByName ??= Util.GetTypeInstanceFieldsByName(obj.GetType());
if (!fieldByName.TryGetValue(cachedFieldName, out var cachedField)) return;
if (cachedField.GetValue(obj) == null) return;
cachedField.SetValue(obj, null);
}
private static string GetNewValue(XElement item)
{
var value = item.Value;
var unescapedValue = value.Replace("\\n", "\n"); // only escape character used
return unescapedValue == "TODO" ? null : unescapedValue;
}
private static void UpdateTxtFile(FileHandle file, DirectoryHandle directory, DirectoryHandle rootDirectory)
{
var relativePath = directory.GetRelativePathTo(rootDirectory);
if (relativePath.Count == 0) return;
if (relativePath[0].Equals("WordInfo"))
{
var directoryName = relativePath[1];
if (directoryName == "Gender")
{
UpdateWordInfoGenderFile();
}
else
{
UpdateWordInfoLookupFile(file, relativePath);
}
return;
}
if (relativePath[0].Equals("Strings"))
{
UpdateStringsFile(file, relativePath);
}
}
private static void UpdateWordInfoGenderFile()
{
Util.SafeExecute(
() =>
{
var wordInfo = ActiveLanguage.WordInfo;
var genders = wordInfo.GetInstanceFieldValue<Dictionary<string, Gender>>("genders");
genders.Clear();
foreach (var directory in ActiveLanguage.AllDirectories)
{
RemoveCachedGenderFiles(directory.Item2);
wordInfo.LoadFrom(directory, ActiveLanguage);
}
});
void RemoveCachedGenderFiles(ModContentPack modContentPack)
{
var alreadyLoadedFiles = ActiveLanguage.GetInstanceFieldValue<Dictionary<ModContentPack, HashSet<string>>>("tmpAlreadyLoadedFiles");
var modLoadedFiles = alreadyLoadedFiles[modContentPack];
var loadedFiles = modLoadedFiles.ToList();
foreach (var file in loadedFiles)
{
if (file.EndsWith(@"\WordInfo\Gender\Male.txt", StringComparison.OrdinalIgnoreCase)) modLoadedFiles.Remove(file);
if (file.EndsWith(@"\WordInfo\Gender\Female.txt", StringComparison.OrdinalIgnoreCase)) modLoadedFiles.Remove(file);
if (file.EndsWith(@"\WordInfo\Gender\Neuter.txt", StringComparison.OrdinalIgnoreCase)) modLoadedFiles.Remove(file);
}
}
}
private static void UpdateWordInfoLookupFile(FileHandle file, IReadOnlyList<string> relativePath)
{
Util.SafeExecute(
() =>
{
var databaseName = $"{string.Join("\\", relativePath.Skip(1))}\\{file.FileNameWithoutExtension}".ToLower();
var wordInfo = ActiveLanguage.WordInfo;
var lookupTables = wordInfo.GetInstanceFieldValue<Dictionary<string, Dictionary<string, string[]>>>("lookupTables");
lookupTables.Remove(databaseName);
wordInfo.RegisterLut(databaseName);
});
}
private static void UpdateStringsFile(FileHandle file, IReadOnlyList<string> relativePath)
{
var stringsCache = ActiveLanguage.GetInstanceFieldValue<Dictionary<string, List<string>>>("stringFiles");
var relativeStringsFile = $"{string.Join("\\", relativePath.Skip(1))}\\{file.FileNameWithoutExtension}";
var relativeStringsFileKey = relativeStringsFile.Replace('\\', '/');
stringsCache.Remove(relativeStringsFileKey);
var stringsList = new List<string>();
foreach (var (directory, _, _) in ActiveLanguage.AllDirectories)
{
var filePath = $"{directory}\\Strings\\{relativeStringsFile}.txt";
if (!File.Exists(filePath)) continue;
var text = File.ReadAllText(filePath);
var lines = GenText.LinesFromString(text);
stringsList.AddRange(lines);
}
stringsList.TrimExcess();
stringsCache.Add(relativeStringsFileKey, stringsList);
}
private static bool IsActiveLanguageSubfolder(DirectoryHandle directoryHandle, out DirectoryHandle languageRootHandle)
{
foreach (var directory in _languageDirectories)
{
if (!directoryHandle.StartsWith(directory)) continue;
languageRootHandle = directory;
return true;
}
languageRootHandle = null;
return false;
}
private static void ClearCaches()
{
// label cache
GenLabel.ClearCache();
// art tab cache
Util.ClearStaticField(typeof(ITab_Art), "cachedImageDescription");
Util.ClearStaticField(typeof(ITab_Art), "cachedImageSource");
Util.ClearStaticField(typeof(ITab_Art), "cachedTaleRef");
// cache for colorization
ColoredText.ClearCache();
ColoredText.ResetStaticData();
// designators cache
Find.ReverseDesignatorDatabase.Reinit();
// cache only in game
if (Current.Game.Maps.Count > 0)
{
ClearInGameCaches();
}
// rewrite templated defs if needed
_templateDefsResolver.ReleaseChanges();
}
private static void ClearInGameCaches()
{
// log entry cache
var cachedStringField = Util.GetInstanceField(typeof(LogEntry), "cachedString");
var cachedStringPovField = Util.GetInstanceField(typeof(LogEntry), "cachedStringPov");
var cachedHeightWidthField = Util.GetInstanceField(typeof(LogEntry), "cachedHeightWidth");
var cachedHeightField = Util.GetInstanceField(typeof(LogEntry), "cachedHeight");
foreach (var entry in Find.PlayLog.AllEntries)
{
cachedStringField.SetValue(entry, null);
cachedStringPovField.SetValue(entry, null);
cachedHeightWidthField.SetValue(entry, null);
cachedHeightField.SetValue(entry, null);
}
// memory thoughts
var cachedLabelCapField = Util.GetInstanceField(typeof(Thought_Memory), "cachedLabelCap");
foreach (var pawn in Find.Maps.Select(m => m.mapPawns.AllPawns).Concat(Find.WorldPawns.AllPawnsAliveOrDead).SelectMany(p => p))
{
foreach (var memory in (IReadOnlyList<Thought_Memory>)pawn.needs?.mood?.thoughts?.memories?.Memories ?? Array.Empty<Thought_Memory>())
{
var cachedValue = cachedLabelCapField.GetValue(memory);
if (cachedValue == null) continue;
cachedLabelCapField.SetValue(memory, null);
}
}
// stats in info dialog
var newEntryList = new List<StatDrawEntry>();
var drawEntriesField = Util.GetStaticField(typeof(StatsReportUtility), "cachedDrawEntries");
var oldEntryList = (List<StatDrawEntry>)drawEntriesField.GetValue(null);
drawEntriesField.SetValue(null, newEntryList);
// dispose later, whan should not by in use
Task.Run(
async () =>
{
await Task.Delay(500);
oldEntryList.Clear();
});
// clear cached lights texts
var mouseoverReadout = Find.MapUI.GetInstanceFieldValue<MouseoverReadout>("mouseoverReadout");
Util.SafeExecute(() =>
{
mouseoverReadout.InvokeInstanceMethod("MakePermaCache");
mouseoverReadout.ClearInstanceField("cachedTerrain");
});
// clear cached alerts
Util.SafeExecute(
() =>
{
var alertsReadout = ((UIRoot_Play)Find.UIRoot).alerts;
var allAlerts = alertsReadout.GetInstanceFieldValue<List<Alert>>("AllAlerts");
// recreate all alerts
// TODO can be dangerous for some cached fields, that will not be initialized properlly
// TODO maybe can be enough copy all string values (namely defaultLabel and defaultExplanation
for (var i = 0; i < allAlerts.Count; i++)
{
var alert = allAlerts[i];
var alertType = alert.GetType();
var newAlert = (Alert)Activator.CreateInstance(alertType);
allAlerts[i] = newAlert;
}
// remove old alerts
var oldAlerts = alertsReadout.GetInstanceFieldValue<List<Alert>>("activeAlerts");
oldAlerts.Clear();
// remove cached precept alerts
var oldPreceptAlerts = alertsReadout.GetInstanceFieldValue<Dictionary<Precept, List<Alert>>>("activePreceptAlerts");
oldPreceptAlerts.Clear();
// reload active alerts from new ones
alertsReadout.AlertsReadoutUpdate();
});
// clear cached date
DateReadout.Reset();
// clear cache from main thread
Current.Game.GetComponent<RimLanguageHotReloadGameComponent>().InvalidateCache();
// clear cached detailed descriptions
Util.SafeExecute(
() =>
{
foreach (var def in _definitions.Values.SelectMany(d => d))
{
Util.SafeExecute(() => def.ClearInstanceField("descriptionDetailedCached"));
// clear cached labels for void provocation ritual
if (def is PsychicRitualDef_InvocationCircle)
{
Util.SafeExecute(() => def.ClearInstanceField("timeAndOfferingLabelCached"));
}
}
});
// clear ideo precepts cache
Util.SafeExecute(() =>
{
foreach (var ideo in Find.IdeoManager.IdeosInViewOrder)
{
foreach (var item in ideo.PreceptsListForReading.OfType<Precept_Ritual>())
{
var groupTag = item.patternGroupTag ?? item.def.ritualPatternBase?.patternGroupTag;
var ritualPatternDef = DefDatabase<RitualPatternDef>.AllDefs
.Where(d => d.patternGroupTag == groupTag && !ideo.PreceptsListForReading.OfType<Precept_Ritual>().Any(p => p.behavior != null && p.sourcePattern == d))
.RandomElementWithFallback();
ritualPatternDef?.Fill(item);
}
}
});
// clear cached activities string
Util.SafeExecute(() =>
{
Util.GetStaticField(typeof(Need_Learning), "learningActivitiesLineList").SetValue(null, null);
});
}
}
}