-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathChatItemLink.cs
More file actions
708 lines (617 loc) · 24.7 KB
/
Copy pathChatItemLink.cs
File metadata and controls
708 lines (617 loc) · 24.7 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
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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using Godot;
using MegaCrit.Sts2.Core.Entities.Cards;
using MegaCrit.Sts2.Core.Entities.Creatures;
using MegaCrit.Sts2.Core.Entities.Potions;
using MegaCrit.Sts2.Core.Entities.Powers;
using MegaCrit.Sts2.Core.Entities.Relics;
using MegaCrit.Sts2.Core.Helpers;
using MegaCrit.Sts2.Core.HoverTips;
using MegaCrit.Sts2.Core.Localization;
using MegaCrit.Sts2.Core.Localization.DynamicVars;
using MegaCrit.Sts2.Core.Models;
namespace Typing;
public enum ItemLinkType
{
Card,
Potion,
Relic,
Power,
Target
}
public readonly record struct ItemLinkData(ItemLinkType Type, string ModelIdStr, int UpgradeLevel = 0)
{
public string Encode()
{
return Type == ItemLinkType.Card
? $"{{{{{Type.ToString().ToLowerInvariant()}:{ModelIdStr}:{UpgradeLevel}}}}}"
: $"{{{{{Type.ToString().ToLowerInvariant()}:{ModelIdStr}}}}}";
}
public string MetaTag => Type == ItemLinkType.Card
? $"{Type.ToString().ToLowerInvariant()}:{ModelIdStr}:{UpgradeLevel}"
: $"{Type.ToString().ToLowerInvariant()}:{ModelIdStr}";
}
public readonly record struct PowerLinkData(
string PowerIdStr, int Amount, string CreatureName, string CreatureColorHex,
string ApplierName = "");
public readonly record struct TargetData(
string CreatureName, string CreatureColorHex);
public abstract record MessageSegment;
public sealed record TextSegment(string Text) : MessageSegment;
public sealed record LinkSegment(ItemLinkData Link, string DisplayName) : MessageSegment;
public sealed record PowerSegment(PowerLinkData Power, string DisplayName) : MessageSegment;
public sealed record TargetSegment(TargetData Target) : MessageSegment;
public readonly record struct ItemAutocompleteEntry(string DisplayName, ItemLinkData Link);
public static class ChatItemLink
{
static readonly StringComparer ItemNameComparer = StringComparer.CurrentCultureIgnoreCase;
static readonly Regex LinkPattern = new(
@"\{\{(card|potion|relic|power):([A-Za-z0-9_-]+\.[A-Za-z0-9_-]+)(?::(\d+))?\}\}",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
static readonly Regex PowerPattern = new(
@"\{\{power:([A-Za-z0-9_-]+\.[A-Za-z0-9_-]+):(-?\d+)\|(.+?)\|([0-9A-Fa-f]{6,8})(?:\|(.*?))?\}\}",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
static readonly Regex TargetPattern = new(
@"\{\{target\|(.+?)\|([0-9A-Fa-f]{6,8})\}\}",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
static readonly Regex ItemShortcutPattern = new(@"\[([^\[\]\r\n]+)\]", RegexOptions.Compiled);
static string? _itemAutocompleteLocale;
static int _itemAutocompleteModelCount;
static IReadOnlyList<ItemAutocompleteEntry>? _itemAutocompleteEntries;
static Dictionary<string, ItemLinkData>? _itemLinkByLocalizedTitle;
public static string EncodeCard(CardModel card)
{
var data = new ItemLinkData(ItemLinkType.Card, card.Id.ToString(), card.CurrentUpgradeLevel);
return data.Encode();
}
public static string EncodePotion(PotionModel potion)
{
var data = new ItemLinkData(ItemLinkType.Potion, potion.Id.ToString());
return data.Encode();
}
public static string EncodeRelic(RelicModel relic)
{
var data = new ItemLinkData(ItemLinkType.Relic, relic.Id.ToString());
return data.Encode();
}
public static string EncodePower(PowerModel power, Creature owner)
{
string colorHex = GetCreatureColorHex(owner);
string applierName = power.Applier?.Name ?? "";
return $"{{{{power:{power.Id}:{power.Amount}|{owner.Name}|{colorHex}|{applierName}}}}}";
}
public static string EncodeTarget(Creature creature)
{
string colorHex = GetCreatureColorHex(creature);
return $"{{{{target|{creature.Name}|{colorHex}}}}}";
}
public static IReadOnlyList<ItemAutocompleteEntry> FindAutocompleteEntries(string prefix)
{
EnsureItemAutocompleteCache();
if (_itemAutocompleteEntries is null || string.IsNullOrWhiteSpace(prefix))
return Array.Empty<ItemAutocompleteEntry>();
prefix = prefix.Trim();
return _itemAutocompleteEntries
.Where(entry => entry.DisplayName.StartsWith(prefix, StringComparison.CurrentCultureIgnoreCase))
.ToArray();
}
public static string ReplaceLocalizedItemShortcuts(string text)
{
EnsureItemAutocompleteCache();
if (_itemLinkByLocalizedTitle is null || _itemLinkByLocalizedTitle.Count == 0)
return text;
return ItemShortcutPattern.Replace(text, match =>
{
string localizedName = match.Groups[1].Value.Trim();
int upgradeLevel = 0;
while (localizedName.EndsWith('+'))
{
upgradeLevel++;
localizedName = localizedName[..^1].TrimEnd();
}
if (!_itemLinkByLocalizedTitle.TryGetValue(localizedName, out var link))
return match.Value;
if (link.Type == ItemLinkType.Card)
link = link with { UpgradeLevel = upgradeLevel };
return link.Encode();
});
}
public static string GetCreatureColorHex(Creature creature)
{
if (creature.IsPlayer)
return creature.Player!.Character.NameColor.ToHtml(false);
if (creature.IsPet)
return creature.PetOwner!.Character.NameColor.ToHtml(false);
return "FF5555";
}
public static List<MessageSegment> Parse(string text)
{
var segments = new List<MessageSegment>();
var allMatches = new List<(Match Match, string Kind)>();
foreach (Match m in LinkPattern.Matches(text))
allMatches.Add((m, "link"));
foreach (Match m in PowerPattern.Matches(text))
allMatches.Add((m, "power"));
foreach (Match m in TargetPattern.Matches(text))
allMatches.Add((m, "target"));
allMatches.Sort((a, b) => a.Match.Index.CompareTo(b.Match.Index));
int lastIndex = 0;
foreach (var (match, kind) in allMatches)
{
if (match.Index < lastIndex) continue;
if (match.Index > lastIndex)
segments.Add(new TextSegment(text[lastIndex..match.Index]));
switch (kind)
{
case "link":
{
string typeStr = match.Groups[1].Value.ToLowerInvariant();
string idStr = match.Groups[2].Value;
int upgrade = match.Groups[3].Success ? int.Parse(match.Groups[3].Value) : 0;
if (!TryParseType(typeStr, out var linkType))
{
segments.Add(new TextSegment(match.Value));
break;
}
var link = new ItemLinkData(linkType, idStr, upgrade);
string? displayName = ResolveDisplayName(link);
segments.Add(displayName is null
? new TextSegment(match.Value)
: new LinkSegment(link, displayName));
break;
}
case "power":
{
string powerId = match.Groups[1].Value;
int amount = int.Parse(match.Groups[2].Value);
string creatureName = match.Groups[3].Value;
string colorHex = match.Groups[4].Value;
string applierName = match.Groups[5].Success ? match.Groups[5].Value : "";
var data = new PowerLinkData(powerId, amount, creatureName, colorHex, applierName);
string? displayName = ResolvePowerDisplayName(data);
segments.Add(displayName is null
? new TextSegment(match.Value)
: new PowerSegment(data, displayName));
break;
}
case "target":
{
string creatureName = match.Groups[1].Value;
string colorHex = match.Groups[2].Value;
segments.Add(new TargetSegment(new TargetData(creatureName, colorHex)));
break;
}
}
lastIndex = match.Index + match.Length;
}
if (lastIndex < text.Length)
segments.Add(new TextSegment(text[lastIndex..]));
return segments;
}
public static bool ContainsLink(string text) =>
LinkPattern.IsMatch(text) || PowerPattern.IsMatch(text) || TargetPattern.IsMatch(text);
public static bool TryParseMeta(string meta, out ItemLinkData link)
{
link = default;
string[] parts = meta.Split(':');
if (parts.Length < 2) return false;
if (!TryParseType(parts[0], out var linkType)) return false;
string idStr = parts[1];
int upgrade = parts.Length >= 3 && int.TryParse(parts[2], out int u) ? u : 0;
link = new ItemLinkData(linkType, idStr, upgrade);
return true;
}
public static CardModel? ResolveCard(ItemLinkData link)
{
try
{
var modelId = ModelId.Deserialize(link.ModelIdStr);
var canonical = ModelDb.GetById<CardModel>(modelId);
var mutable = canonical.ToMutable();
for (int i = 0; i < link.UpgradeLevel; i++)
{
mutable.UpgradeInternal();
mutable.FinalizeUpgradeInternal();
}
return mutable;
}
catch { return null; }
}
public static PotionModel? ResolvePotion(ItemLinkData link)
{
try
{
var modelId = ModelId.Deserialize(link.ModelIdStr);
return ModelDb.GetById<PotionModel>(modelId);
}
catch { return null; }
}
public static RelicModel? ResolveRelic(ItemLinkData link)
{
try
{
var modelId = ModelId.Deserialize(link.ModelIdStr);
return ModelDb.GetById<RelicModel>(modelId);
}
catch { return null; }
}
public static PowerModel? ResolvePower(ItemLinkData link)
{
try
{
var modelId = ModelId.Deserialize(link.ModelIdStr);
return ModelDb.GetById<PowerModel>(modelId);
}
catch { return null; }
}
public static PowerModel? ResolvePower(PowerLinkData data)
{
try
{
var modelId = ModelId.Deserialize(data.PowerIdStr);
return ModelDb.GetById<PowerModel>(modelId);
}
catch { return null; }
}
public static HoverTip? ResolvePowerHoverTip(ItemLinkData link)
{
var power = ResolvePower(link);
if (power is null)
return null;
if (!power.HasSmartDescription)
return power.DumbHoverTip;
var desc = power.SmartDescription;
desc.Add("Amount", 1m);
desc.Add("OnPlayer", true);
desc.Add("IsMultiplayer", true);
desc.Add("PlayerCount", 2m);
desc.Add("OwnerName", "");
desc.Add("ApplierName", "");
desc.Add("TargetName", "");
desc.Add("singleStarIcon", "[img]res://images/packed/sprite_fonts/star_icon.png[/img]");
desc.Add("energyPrefix", EnergyIconHelper.GetPrefix(power));
try { power.DynamicVars.AddTo(desc); } catch { }
return new HoverTip(power, desc.GetFormattedText(), true);
}
public static HoverTip? ResolvePowerHoverTip(PowerLinkData data, bool isPlayer)
{
try
{
var modelId = ModelId.Deserialize(data.PowerIdStr);
var power = ModelDb.GetById<PowerModel>(modelId);
if (!power.HasSmartDescription)
return power.DumbHoverTip;
var desc = power.SmartDescription;
desc.Add("Amount", (decimal)data.Amount);
desc.Add("OnPlayer", isPlayer);
desc.Add("IsMultiplayer", true);
desc.Add("PlayerCount", 2m);
desc.Add("OwnerName", data.CreatureName);
desc.Add("ApplierName", data.ApplierName);
desc.Add("TargetName", "");
desc.Add("singleStarIcon", "[img]res://images/packed/sprite_fonts/star_icon.png[/img]");
desc.Add("energyPrefix", EnergyIconHelper.GetPrefix(power));
try { power.DynamicVars.AddTo(desc); } catch { }
if (!string.IsNullOrEmpty(data.ApplierName))
{
desc.AddObj("ApplierName", new StringVar("ApplierName", data.ApplierName));
desc.AddObj("Applier", new StringVar("Applier", data.ApplierName));
}
if (!string.IsNullOrEmpty(data.CreatureName))
desc.Add("OwnerName", data.CreatureName);
return new HoverTip(power, desc.GetFormattedText(), true);
}
catch { return null; }
}
static string? ResolvePowerDisplayName(PowerLinkData data)
{
var power = ResolvePower(data);
return power?.Title.GetFormattedText();
}
public static Color GetPowerColor(PowerLinkData data)
{
var power = ResolvePower(data);
var type = power?.GetTypeForAmount(data.Amount) ?? PowerType.None;
return type switch
{
PowerType.Buff => new Color("77ff67"),
PowerType.Debuff => new Color("ff6563"),
_ => new Color("FFF6E2")
};
}
static string? ResolveDisplayName(ItemLinkData link)
{
try
{
return link.Type switch
{
ItemLinkType.Card => ResolveCard(link)?.Title,
ItemLinkType.Potion => ResolvePotion(link)?.Title.GetFormattedText(),
ItemLinkType.Relic => ResolveRelic(link)?.Title.GetFormattedText(),
ItemLinkType.Power => ResolvePower(link)?.Title.GetFormattedText(),
_ => null
};
}
catch { return null; }
}
public static string GetItemTypeLabel(ItemLinkType type) => type switch
{
ItemLinkType.Card => L10n.Get("shared_card"),
ItemLinkType.Potion => L10n.Get("shared_potion"),
ItemLinkType.Relic => L10n.Get("shared_relic"),
ItemLinkType.Power => L10n.Get("shared_power"),
_ => ""
};
public static Color GetRarityColor(ItemLinkData link)
{
try
{
return link.Type switch
{
ItemLinkType.Card => GetCardRarityColor(ResolveCard(link)?.Rarity ?? CardRarity.Common),
ItemLinkType.Potion => GetPotionRarityColor(ResolvePotion(link)?.Rarity ?? PotionRarity.Common),
ItemLinkType.Relic => GetRelicRarityColor(ResolveRelic(link)?.Rarity ?? RelicRarity.Common),
ItemLinkType.Power => GetPowerTypeColor(ResolvePower(link)?.GetTypeForAmount(1) ?? PowerType.None),
_ => Colors.White
};
}
catch { return Colors.White; }
}
static Color GetCardRarityColor(CardRarity rarity) => rarity switch
{
CardRarity.Basic or CardRarity.Common => new Color("9C9C9C"),
CardRarity.Uncommon => new Color("64FFFF"),
CardRarity.Rare => new Color("FFDA36"),
CardRarity.Curse => new Color("E669FF"),
CardRarity.Event => new Color("13BE1A"),
CardRarity.Quest => new Color("F46836"),
_ => new Color("9C9C9C")
};
static Color GetRelicRarityColor(RelicRarity rarity) => rarity switch
{
RelicRarity.Uncommon or RelicRarity.Shop => new Color("87CEEB"),
RelicRarity.Rare => new Color("EFC851"),
RelicRarity.Event => new Color("7FFF00"),
RelicRarity.Ancient => new Color("FF5555"),
_ => new Color("FFF6E2")
};
static Color GetPotionRarityColor(PotionRarity rarity) => rarity switch
{
PotionRarity.Uncommon => new Color("87CEEB"),
PotionRarity.Rare => new Color("EFC851"),
PotionRarity.Event => new Color("7FFF00"),
_ => new Color("FFF6E2")
};
static Color GetPowerTypeColor(PowerType type) => type switch
{
PowerType.Buff => new Color("77ff67"),
PowerType.Debuff => new Color("ff6563"),
_ => new Color("FFF6E2")
};
static bool TryParseType(string typeStr, out ItemLinkType type)
{
type = default;
switch (typeStr)
{
case "card": type = ItemLinkType.Card; return true;
case "potion": type = ItemLinkType.Potion; return true;
case "relic": type = ItemLinkType.Relic; return true;
case "power": type = ItemLinkType.Power; return true;
default: return false;
}
}
public static string GetAutocompleteTypeLabel(ItemLinkType type) => type switch
{
ItemLinkType.Card => "C",
ItemLinkType.Relic => "R",
ItemLinkType.Power => "P",
_ => type.ToString()
};
static void EnsureItemAutocompleteCache()
{
string locale = TranslationServer.GetLocale();
// Rebuild when the model registry grows/shrinks too, so items injected by
// other mods after the first build (lazy-loading mods) still show up.
int modelCount = 0;
try { modelCount = GetRegisteredModelsDirect().Count(); }
catch { }
if (_itemAutocompleteEntries is not null
&& _itemLinkByLocalizedTitle is not null
&& _itemAutocompleteLocale == locale
&& _itemAutocompleteModelCount == modelCount)
return;
_itemAutocompleteLocale = locale;
_itemAutocompleteModelCount = modelCount;
var entries = new List<ItemAutocompleteEntry>();
try
{
CollectItemAutocompleteEntries(entries);
}
catch
{
// Keep whatever was collected before the failure. The cache fields below are
// always assigned so a bad game model can't force a full rescan on every send.
}
var deduped = entries
.GroupBy(entry => entry.DisplayName, ItemNameComparer)
.Select(group => group
.OrderBy(entry => GetAutocompleteSortOrder(entry.Link.Type))
.ThenBy(entry => entry.Link.ModelIdStr, StringComparer.Ordinal)
.First())
.OrderBy(entry => GetAutocompleteSortOrder(entry.Link.Type))
.ThenBy(entry => entry.DisplayName, ItemNameComparer)
.ThenBy(entry => entry.Link.ModelIdStr, StringComparer.Ordinal)
.ToArray();
_itemAutocompleteEntries = deduped;
_itemLinkByLocalizedTitle = deduped.ToDictionary(
entry => entry.DisplayName,
entry => entry.Link,
ItemNameComparer);
}
static void CollectItemAutocompleteEntries(List<ItemAutocompleteEntry> entries)
{
var registered = GetRegisteredModelsSafe();
CollectCategory(entries, registered, ItemLinkType.Card, "AllCards", "AllCardIds",
static (CardModel card) => card.Title?.Trim() ?? string.Empty);
CollectCategory(entries, registered, ItemLinkType.Relic, "AllRelics", "AllRelicIds",
static (RelicModel relic) => relic.Title.GetFormattedText().Trim());
CollectCategory(entries, registered, ItemLinkType.Power, "AllPowers", "AllPowerIds",
static (PowerModel power) => power.Title.GetFormattedText().Trim());
}
static void CollectCategory<T>(
List<ItemAutocompleteEntry> entries,
List<AbstractModel> registeredModels,
ItemLinkType linkType,
string allPropertyName,
string idsPropertyName,
Func<T, string> getTitle)
where T : AbstractModel
{
var modelsById = new Dictionary<string, T>(StringComparer.Ordinal);
// Primary source: the model registry snapshot. Unlike the pool-based lazy
// queries (ModelDb.AllCards/AllPowers/...), it also contains models injected
// by other mods and can't abort mid-enumeration on a single bad model.
foreach (var model in registeredModels)
{
if (model is not T typed)
continue;
try { modelsById.TryAdd(typed.Id.ToString(), typed); }
catch { }
}
// Fallbacks for game versions where the registry isn't reachable: the
// reflection scan over static "AllX" properties, then "AllXIds" + GetById.
if (modelsById.Count == 0)
{
foreach (var model in EnumerateStaticPropertyValues<T>(allPropertyName))
{
try { modelsById.TryAdd(model.Id.ToString(), model); }
catch { }
}
}
if (modelsById.Count == 0)
{
foreach (var modelId in EnumerateStaticPropertyValues<ModelId>(idsPropertyName))
{
try
{
var model = ModelDb.GetById<T>(modelId);
modelsById.TryAdd(model.Id.ToString(), model);
}
catch { }
}
}
foreach (var model in modelsById.Values)
{
// Skip test-only mock models (game's or other mods'). A throwing IsMock
// getter from a badly behaved mod is treated as "not a mock".
bool isMock = false;
try { isMock = model.IsMock; }
catch { }
if (isMock)
continue;
// Title resolution can throw for models without localization entries
// (e.g. the test-only MockRecordCardChangedPilesPower added in game v0.110
// has no ".title" loc key, and LocTable.GetRawText throws on missing keys;
// mod-added models frequently miss loc entries too). Skip such entries
// instead of failing the whole cache build.
string displayName;
try { displayName = getTitle(model); }
catch { continue; }
if (string.IsNullOrEmpty(displayName))
continue;
entries.Add(new ItemAutocompleteEntry(
displayName,
new ItemLinkData(linkType, model.Id.ToString(), 0)));
}
}
// Isolated in a non-inlined helper: if a future game version removes ModelDb.All,
// the MissingMethodException surfaces when this method is invoked and is caught by
// the caller, instead of failing the caller's own JIT compilation.
[MethodImpl(MethodImplOptions.NoInlining)]
static IEnumerable<AbstractModel> GetRegisteredModelsDirect() => ModelDb.All;
static List<AbstractModel> GetRegisteredModelsSafe()
{
var models = new List<AbstractModel>();
try
{
foreach (var model in GetRegisteredModelsDirect())
{
if (model is not null)
models.Add(model);
}
}
catch
{
// Keep whatever was snapshotted before the failure; the reflection
// fallbacks kick in when this comes back empty.
}
return models;
}
static int GetAutocompleteSortOrder(ItemLinkType type) => type switch
{
ItemLinkType.Card => 0,
ItemLinkType.Power => 1,
ItemLinkType.Relic => 2,
ItemLinkType.Potion => 3,
_ => 4
};
static IEnumerable<T> EnumerateStaticPropertyValues<T>(string propertyName)
{
foreach (var type in GetAssemblyTypesSafe(typeof(CardModel).Assembly))
{
PropertyInfo? property = null;
try
{
property = type.GetProperty(
propertyName,
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
}
catch { }
if (property is null || property.GetIndexParameters().Length != 0)
continue;
object? value;
try
{
value = property.GetValue(null);
}
catch
{
continue;
}
if (value is not IEnumerable enumerable)
continue;
// Game properties like ModelDb.AllPowers are lazy LINQ queries; enumerating
// them can throw mid-iteration, so buffer inside a try/catch and keep the
// items that were produced before any failure.
var buffered = new List<T>();
try
{
foreach (var item in enumerable)
{
if (item is T typed)
buffered.Add(typed);
}
}
catch { }
foreach (var typed in buffered)
yield return typed;
}
}
static IEnumerable<Type> GetAssemblyTypesSafe(Assembly assembly)
{
try
{
return assembly.GetTypes();
}
catch (ReflectionTypeLoadException ex)
{
return ex.Types.OfType<Type>();
}
}
}