-
Notifications
You must be signed in to change notification settings - Fork 40
/
ItemManager.cs
804 lines (697 loc) · 31.8 KB
/
ItemManager.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
798
799
800
801
802
803
804
using System;
using System.Collections.Generic;
using System.Linq;
using BepInEx;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers.MockSystem;
using Jotunn.Utils;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace Jotunn.Managers
{
/// <summary>
/// Manager for handling all custom data added to the game related to items.
/// </summary>
public class ItemManager : IManager
{
private static ItemManager _instance;
/// <summary>
/// The singleton instance of this manager.
/// </summary>
public static ItemManager Instance => _instance ??= new ItemManager();
/// <summary>
/// Hide .ctor
/// </summary>
private ItemManager() { }
static ItemManager()
{
((IManager)Instance).Init();
}
/// <summary>
/// Event that gets fired after the vanilla items are in memory and available for cloning.
/// Your code will execute every time a new ObjectDB is copied (on every menu start).
/// If you want to execute just once you will need to unregister from the event after execution.
/// </summary>
[Obsolete("Use PrefabManager.OnVanillaPrefabsAvailable instead")]
public static event Action OnVanillaItemsAvailable;
/// <summary>
/// Internal event that gets fired after <see cref="OnVanillaItemsAvailable"/> did run.
/// On this point all mods should have their items and pieces registered with the managers.
/// </summary>
internal static event Action OnKitbashItemsAvailable;
/// <summary>
/// Event that gets fired after all items were added to the ObjectDB on the FejdStartup screen.
/// Your code will execute every time a new ObjectDB is copied (on every menu start).
/// If you want to execute just once you will need to unregister from the event after execution.
/// </summary>
public static event Action OnItemsRegisteredFejd;
/// <summary>
/// Event that gets fired after all items were added to the ObjectDB.
/// Your code will execute every time a new ObjectDB is created (on every game start).
/// If you want to execute just once you will need to unregister from the event after execution.
/// </summary>
public static event Action OnItemsRegistered;
// Internal lists of all custom entities added
internal readonly Dictionary<string, CustomItem> Items = new Dictionary<string, CustomItem>();
internal readonly HashSet<CustomRecipe> Recipes = new HashSet<CustomRecipe>();
internal readonly HashSet<CustomStatusEffect> StatusEffects = new HashSet<CustomStatusEffect>();
internal readonly HashSet<CustomItemConversion> ItemConversions = new HashSet<CustomItemConversion>();
/// <summary>
/// Registers all hooks.
/// </summary>
void IManager.Init()
{
Main.LogInit("ItemManager");
Main.Harmony.PatchAll(typeof(Patches));
PrefabManager.Instance.Activate();
}
private static class Patches
{
[HarmonyPatch(typeof(ObjectDB), nameof(ObjectDB.CopyOtherDB)), HarmonyPrefix, HarmonyPriority(-100)]
private static void RegisterCustomDataFejd(ObjectDB __instance, ObjectDB other) => Instance.RegisterCustomDataFejd(__instance, other);
[HarmonyPatch(typeof(ObjectDB), nameof(ObjectDB.Awake)), HarmonyPrefix]
private static void RegisterCustomData(ObjectDB __instance) => Instance.RegisterCustomData(__instance);
[HarmonyPatch(typeof(Player), nameof(Player.OnSpawned)), HarmonyPostfix]
private static void ReloadKnownRecipes(Player __instance) => Instance.ReloadKnownRecipes(__instance);
[HarmonyPatch(typeof(ObjectDB), nameof(ObjectDB.CopyOtherDB)), HarmonyPostfix, HarmonyPriority(Priority.Last)]
private static void InvokeOnItemsRegisteredFejd() => Instance.InvokeOnItemsRegisteredFejd();
[HarmonyPatch(typeof(ObjectDB), nameof(ObjectDB.Awake)), HarmonyPostfix, HarmonyPriority(Priority.Last)]
private static void InvokeOnItemsRegistered() => Instance.InvokeOnItemsRegistered();
}
/// <summary>
/// Add a <see cref="CustomItem"/> to the game.<br />
/// Checks if the custom item is valid and unique and adds it to the list of custom items.<br />
/// Also adds the prefab of the custom item to the <see cref="PrefabManager"/>.<br />
/// Custom items are added to the current <see cref="ObjectDB"/> on every <see cref="ObjectDB.Awake"/>.
/// </summary>
/// <param name="customItem">The custom item to add.</param>
/// <returns>true if the custom item was added to the manager.</returns>
public bool AddItem(CustomItem customItem)
{
if (!customItem.IsValid())
{
Logger.LogWarning(customItem.SourceMod, $"Custom item {customItem} is not valid");
return false;
}
if (Items.ContainsKey(customItem.ItemPrefab.name))
{
Logger.LogWarning(customItem.SourceMod, $"Custom item {customItem} already added");
return false;
}
// Add prefab to PrefabManager
if (!PrefabManager.Instance.AddPrefab(customItem.ItemPrefab, customItem.SourceMod))
{
return false;
}
// Add prefab to the right layer
if (customItem.ItemPrefab.layer == 0)
{
customItem.ItemPrefab.layer = LayerMask.NameToLayer("item");
}
// Add custom item to ItemManager
Items.Add(customItem.ItemPrefab.name, customItem);
// Add custom recipe if provided
if (customItem.Recipe != null)
{
AddRecipe(customItem.Recipe);
}
if (PrefabManager.Instance.MenuObjectDB)
{
RegisterItemInObjectDB(PrefabManager.Instance.MenuObjectDB, customItem.ItemPrefab, customItem.SourceMod);
}
return true;
}
/// <summary>
/// Get a custom item by its name.
/// </summary>
/// <param name="itemName">Name of the item to search.</param>
/// <returns></returns>
public CustomItem GetItem(string itemName)
{
if (Items.TryGetValue(itemName, out CustomItem item))
{
return item;
}
return null;
}
/// <summary>
/// Remove a custom item by its name. Removes the custom recipe, too.
/// </summary>
/// <param name="itemName">Name of the item to remove.</param>
public void RemoveItem(string itemName)
{
var item = GetItem(itemName);
if (item == null)
{
Logger.LogWarning($"Could not remove item {itemName}: Not found");
return;
}
RemoveItem(item);
}
/// <summary>
/// Remove a custom item by its ref. Removes the custom recipe, too.
/// </summary>
/// <param name="item"><see cref="CustomItem"/> to remove.</param>
public void RemoveItem(CustomItem item)
{
Items.Remove(item.ItemPrefab.name);
if (ObjectDB.instance && item.ItemPrefab)
{
ObjectDB.instance.m_items.Remove(item.ItemPrefab);
ObjectDB.instance.m_itemByHash.Remove(item.ItemPrefab.name.GetStableHashCode());
}
if (item.ItemPrefab)
{
PrefabManager.Instance.RemovePrefab(item.ItemPrefab.name);
}
if (item.Recipe != null)
{
RemoveRecipe(item.Recipe);
}
}
/// <summary>
/// Add a <see cref="CustomRecipe"/> to the game.<br />
/// Checks if the custom recipe is unique and adds it to the list of custom recipes.<br />
/// Custom recipes are added to the current <see cref="ObjectDB"/> on every <see cref="ObjectDB.Awake"/>.
/// </summary>
/// <param name="customRecipe">The custom recipe to add.</param>
/// <returns>true if the custom recipe was added to the manager.</returns>
public bool AddRecipe(CustomRecipe customRecipe)
{
if (!customRecipe.IsValid())
{
Logger.LogWarning(customRecipe.SourceMod, $"Custom recipe {customRecipe} is not valid");
return false;
}
if (Recipes.Contains(customRecipe))
{
Logger.LogWarning(customRecipe.SourceMod, $"Custom recipe {customRecipe} already added");
return false;
}
Recipes.Add(customRecipe);
return true;
}
/// <summary>
/// Adds recipes defined in a JSON file at given path, relative to BepInEx/plugins
/// </summary>
/// <param name="path">JSON file path, relative to BepInEx/plugins folder</param>
public void AddRecipesFromJson(string path)
{
string json = AssetUtils.LoadText(path);
if (string.IsNullOrEmpty(json))
{
Logger.LogError($"Failed to load recipes from invalid JSON: {path}");
return;
}
List<RecipeConfig> recipes = RecipeConfig.ListFromJson(json);
foreach (RecipeConfig recipe in recipes)
{
AddRecipe(new CustomRecipe(recipe));
}
}
/// <summary>
/// Get a custom recipe by its name.
/// </summary>
/// <param name="recipeName">Name of the recipe to search.</param>
/// <returns></returns>
public CustomRecipe GetRecipe(string recipeName)
{
return Recipes.FirstOrDefault(x => x.Recipe.name.Equals(recipeName));
}
/// <summary>
/// Remove a custom recipe by its name. Removes it from the manager and the <see cref="ObjectDB"/>, if instantiated.
/// </summary>
/// <param name="recipeName">Name of the recipe to remove.</param>
public void RemoveRecipe(string recipeName)
{
var recipe = GetRecipe(recipeName);
if (recipe == null)
{
Logger.LogWarning($"Could not remove recipe {recipeName}: Not found");
return;
}
RemoveRecipe(recipe);
}
/// <summary>
/// Remove a custom recipe by its ref. Removes it from the manager and the <see cref="ObjectDB"/>, if instantiated.
/// </summary>
/// <param name="recipe"><see cref="CustomRecipe"/> to remove.</param>
public void RemoveRecipe(CustomRecipe recipe)
{
Recipes.Remove(recipe);
if (ObjectDB.instance && recipe.Recipe)
{
ObjectDB.instance.m_recipes.Remove(recipe.Recipe);
}
}
/// <summary>
/// Add a <see cref="CustomStatusEffect"/> to the game.<br />
/// Checks if the custom status effect is unique and adds it to the list of custom status effects.<br />
/// Custom status effects are added to the current <see cref="ObjectDB"/> on every <see cref="ObjectDB.Awake"/>.
/// </summary>
/// <param name="customStatusEffect">The custom status effect to add.</param>
/// <returns>true if the custom status effect was added to the manager.</returns>
public bool AddStatusEffect(CustomStatusEffect customStatusEffect)
{
if (!customStatusEffect.IsValid())
{
Logger.LogWarning(customStatusEffect.SourceMod, $"Custom status effect {customStatusEffect} is not valid");
return false;
}
if (StatusEffects.Contains(customStatusEffect))
{
Logger.LogWarning(customStatusEffect.SourceMod, $"Custom status effect {customStatusEffect} already added");
return false;
}
StatusEffects.Add(customStatusEffect);
return true;
}
/// <summary>
/// Add a new item conversion
/// </summary>
/// <param name="itemConversion">Item conversion details</param>
/// <returns>Whether the addition was successful or not</returns>
public bool AddItemConversion(CustomItemConversion itemConversion)
{
if (!itemConversion.IsValid())
{
Logger.LogWarning(itemConversion.SourceMod, $"Custom item conversion {itemConversion} is not valid");
return false;
}
if (ItemConversions.Contains(itemConversion))
{
Logger.LogWarning(itemConversion.SourceMod, $"Custom item conversion {itemConversion} already added");
return false;
}
ItemConversions.Add(itemConversion);
return true;
}
/// <summary>
/// Remove an item conversion
/// </summary>
/// <param name="itemConversion">item conversion to remove</param>
/// <returns>Whether the removal was successful or not</returns>
public bool RemoveItemConversion(CustomItemConversion itemConversion)
{
if (!ItemConversions.Contains(itemConversion))
{
Logger.LogWarning($"Could not remove item conversion {itemConversion}: not found");
return false;
}
ItemConversions.Remove(itemConversion);
return true;
}
/*
/// <summary>
/// Adds item conversions defined in a JSON file at given path, relative to BepInEx/plugins
/// </summary>
/// <param name="path">JSON file path, relative to BepInEx/plugins folder</param>
public void AddItemConversionsFromJson(string path)
{
string json = AssetUtils.LoadText(path);
if (string.IsNullOrEmpty(json))
{
Logger.LogError($"Failed to load item conversions from invalid JSON: {path}");
return;
}
List<CustomItemConversion> configs = CustomItemConversion.ListFromJson(json);
foreach (var config in configs)
{
AddItemConversion(config);
}
}*/
/// <summary>
/// Register all custom items added to the manager to the given <see cref="ObjectDB"/>
/// </summary>
/// <param name="objectDB"></param>
private void RegisterCustomItems(ObjectDB objectDB)
{
if (Items.Count > 0)
{
Logger.LogInfo($"Adding {Items.Count} custom items to the ObjectDB");
List<CustomItem> toDelete = new List<CustomItem>();
foreach (var customItem in Items.Values)
{
try
{
var itemDrop = customItem.ItemDrop;
if (customItem.FixReference || customItem.FixConfig)
{
customItem.ItemPrefab.FixReferences(customItem.FixReference);
itemDrop.m_itemData.m_shared.FixReferences();
customItem.FixVariants();
customItem.FixReference = false;
customItem.FixConfig = false;
}
if (!itemDrop.m_itemData.m_dropPrefab)
{
itemDrop.m_itemData.m_dropPrefab = customItem.ItemPrefab;
}
RegisterItemInObjectDB(objectDB, customItem.ItemPrefab, customItem.SourceMod);
}
catch (MockResolveException ex)
{
Logger.LogWarning(customItem?.SourceMod, $"Skipping item {customItem}: {ex.Message}");
toDelete.Add(customItem);
}
catch (Exception ex)
{
Logger.LogWarning(customItem?.SourceMod, $"Error caught while adding item {customItem}: {ex}");
toDelete.Add(customItem);
}
}
// Delete custom items with errors
foreach (var item in toDelete)
{
if (item.ItemPrefab)
{
PrefabManager.Instance.DestroyPrefab(item.ItemPrefab.name);
}
RemoveItem(item);
}
}
}
/// <summary>
/// Register a single item in the current ObjectDB.
/// Also adds the prefab to the <see cref="PrefabManager"/> and <see cref="ZNetScene"/> if necessary.<br />
/// No mock references are fixed.
/// </summary>
/// <param name="prefab"><see cref="GameObject"/> with an <see cref="ItemDrop"/> component to add to the <see cref="ObjectDB"/></param>
public void RegisterItemInObjectDB(GameObject prefab) => RegisterItemInObjectDB(ObjectDB.instance, prefab, BepInExUtils.GetSourceModMetadata());
/// <summary>
/// Internal method for adding a prefab to a specific ObjectDB.
/// </summary>
/// <param name="objectDB"><see cref="ObjectDB"/> the prefab should be added to</param>
/// <param name="prefab"><see cref="GameObject"/> with an <see cref="ItemDrop"/> component to add</param>
/// <param name="sourceMod"><see cref="BepInPlugin"/> which created the prefab</param>
private void RegisterItemInObjectDB(ObjectDB objectDB, GameObject prefab, BepInPlugin sourceMod)
{
var itemDrop = prefab.GetComponent<ItemDrop>();
if (itemDrop == null)
{
throw new Exception($"Prefab {prefab.name} has no ItemDrop component attached");
}
var name = prefab.name;
var hash = name.GetStableHashCode();
if (objectDB.m_itemByHash.ContainsKey(hash))
{
Logger.LogDebug($"Already added item {prefab.name}");
}
else
{
if (!PrefabManager.Instance.Prefabs.ContainsKey(name))
{
PrefabManager.Instance.AddPrefab(prefab, sourceMod);
}
if (ZNetScene.instance != null && !ZNetScene.instance.m_namedPrefabs.ContainsKey(hash))
{
PrefabManager.Instance.RegisterToZNetScene(prefab);
}
objectDB.m_items.Add(prefab);
objectDB.m_itemByHash.Add(hash, prefab);
}
Logger.LogDebug($"Added item {prefab.name} | Token: {itemDrop.TokenName()}");
}
/// <summary>
/// Register the custom recipes added to the manager to the given <see cref="ObjectDB"/>
/// </summary>
/// <param name="objectDB"></param>
private void RegisterCustomRecipes(ObjectDB objectDB)
{
if (Recipes.Any())
{
Logger.LogInfo($"Adding {Recipes.Count} custom recipes to the ObjectDB");
List<CustomRecipe> toDelete = new List<CustomRecipe>();
foreach (var customRecipe in Recipes)
{
try
{
var recipe = customRecipe.Recipe;
if (customRecipe.FixReference)
{
recipe.FixReferences();
customRecipe.FixReference = false;
}
if (customRecipe.FixRequirementReferences)
{
foreach (var requirement in recipe.m_resources)
{
requirement.FixReferences();
}
customRecipe.FixRequirementReferences = false;
}
objectDB.m_recipes.Add(recipe);
Logger.LogDebug($"Added recipe for {recipe.m_item.TokenName()}");
}
catch (MockResolveException ex)
{
Logger.LogWarning(customRecipe?.SourceMod, $"Skipping recipe {customRecipe}: {ex.Message}");
toDelete.Add(customRecipe);
}
catch (Exception ex)
{
Logger.LogWarning(customRecipe?.SourceMod, $"Error caught while adding recipe {customRecipe}: {ex}");
toDelete.Add(customRecipe);
}
}
// Delete custom recipes with errors
foreach (var recipe in toDelete)
{
Recipes.Remove(recipe);
}
}
}
/// <summary>
/// Register the custom status effects added to the manager to the given <see cref="ObjectDB"/>
/// </summary>
/// <param name="objectDB"></param>
private void RegisterCustomStatusEffects(ObjectDB objectDB)
{
if (StatusEffects.Any())
{
Logger.LogInfo($"Adding {StatusEffects.Count} custom status effects to the ObjectDB");
List<CustomStatusEffect> toDelete = new List<CustomStatusEffect>();
foreach (var customStatusEffect in StatusEffects)
{
try
{
var statusEffect = customStatusEffect.StatusEffect;
if (customStatusEffect.FixReference)
{
statusEffect.FixReferences();
customStatusEffect.FixReference = false;
}
objectDB.m_StatusEffects.Add(statusEffect);
Logger.LogDebug($"Added status effect {customStatusEffect}");
}
catch (MockResolveException ex)
{
Logger.LogWarning(customStatusEffect?.SourceMod, $"Skipping status effect {customStatusEffect}: {ex.Message}");
toDelete.Add(customStatusEffect);
}
catch (Exception ex)
{
Logger.LogWarning(customStatusEffect?.SourceMod,$"Error caught while adding status effect {customStatusEffect}: {ex}");
toDelete.Add(customStatusEffect);
}
}
// Delete status effects with errors
foreach (var statusEffect in toDelete)
{
StatusEffects.Remove(statusEffect);
}
}
}
/// <summary>
/// Register the custom item conversions added to the manager
/// </summary>
private void RegisterCustomItemConversions()
{
if (ItemConversions.Any())
{
Logger.LogInfo($"Adding {ItemConversions.Count} custom item conversions");
List<CustomItemConversion> toDelete = new List<CustomItemConversion>();
foreach (var conversion in ItemConversions)
{
try
{
// Try to get the station prefab
GameObject stationPrefab = PrefabManager.Instance.GetPrefab(conversion.Config.Station);
if (!stationPrefab)
{
throw new Exception($"Invalid station prefab {conversion.Config.Station}");
}
// Fix references if needed
if (conversion.FixReference)
{
conversion.ItemConversion.FixReferences();
conversion.FixReference = false;
}
// Sure, make four almost identical classes but dont have a common base class, Iron Gate
switch (conversion.Type)
{
case CustomItemConversion.ConversionType.CookingStation:
var cookStation = stationPrefab.GetComponent<CookingStation>();
var cookConversion = (CookingStation.ItemConversion)conversion.ItemConversion;
if (cookStation.m_conversion.Exists(c => c.m_from == cookConversion.m_from))
{
Logger.LogDebug($"Already added conversion ${conversion}");
continue;
}
cookStation.m_conversion.Add(cookConversion);
break;
case CustomItemConversion.ConversionType.Fermenter:
var fermenterStation = stationPrefab.GetComponent<Fermenter>();
var fermenterConversion = (Fermenter.ItemConversion)conversion.ItemConversion;
if (fermenterStation.m_conversion.Exists(c => c.m_from == fermenterConversion.m_from))
{
Logger.LogDebug($"Already added conversion ${conversion}");
continue;
}
fermenterStation.m_conversion.Add(fermenterConversion);
break;
case CustomItemConversion.ConversionType.Smelter:
var smelterStation = stationPrefab.GetComponent<Smelter>();
var smelterConversion = (Smelter.ItemConversion)conversion.ItemConversion;
if (smelterStation.m_conversion.Exists(c => c.m_from == smelterConversion.m_from))
{
Logger.LogDebug($"Already added conversion ${conversion}");
continue;
}
smelterStation.m_conversion.Add(smelterConversion);
break;
case CustomItemConversion.ConversionType.Incinerator:
var incineratorStation = stationPrefab.GetComponent<Incinerator>();
var incineratorConversion = (Incinerator.IncineratorConversion)conversion.ItemConversion;
if (incineratorStation.m_conversions.Exists(c => c.m_requirements == incineratorConversion.m_requirements))
{
Logger.LogDebug($"Already added conversion ${conversion}");
continue;
}
incineratorStation.m_conversions.Add(incineratorConversion);
break;
default:
throw new Exception($"Unknown conversion type");
}
Logger.LogDebug($"Added item conversion {conversion}");
}
catch (MockResolveException ex)
{
Logger.LogWarning(conversion?.SourceMod, $"Skipping item conversion {conversion}: {ex.Message}");
toDelete.Add(conversion);
}
catch (Exception ex)
{
Logger.LogWarning(conversion?.SourceMod, $"Error caught while adding item conversion {conversion}: {ex}");
toDelete.Add(conversion);
}
}
// Delete item conversions with errors
foreach (var itemConversion in toDelete)
{
ItemConversions.Remove(itemConversion);
}
}
}
/// <summary>
/// Prefix on <see cref="ObjectDB.CopyOtherDB"/> to add custom items to FejdStartup screen (aka main menu)
/// </summary>
private void RegisterCustomDataFejd(ObjectDB self, ObjectDB other)
{
#pragma warning disable 612
InvokeOnVanillaItemsAvailable();
#pragma warning restore 612
InvokeOnKitbashItemsAvailable();
UpdateItemHashesSafe(other);
RegisterCustomItems(other);
}
/// <summary>
/// Safely invoke the <see cref="OnVanillaItemsAvailable"/> event
/// </summary>
[Obsolete]
private void InvokeOnVanillaItemsAvailable()
{
OnVanillaItemsAvailable?.SafeInvoke();
}
/// <summary>
/// Safely invoke the <see cref="OnKitbashItemsAvailable"/> event
/// </summary>
private void InvokeOnKitbashItemsAvailable()
{
OnKitbashItemsAvailable?.SafeInvoke();
}
/// <summary>
/// Safely invoke the <see cref="OnItemsRegisteredFejd"/> event late in the detour chain
/// </summary>
private void InvokeOnItemsRegisteredFejd()
{
OnItemsRegisteredFejd?.SafeInvoke();
}
/// <summary>
/// Hook on <see cref="ObjectDB.Awake"/> to register all custom entities from this manager to the <see cref="ObjectDB"/>.
/// </summary>
/// <param name="self"></param>
private void RegisterCustomData(ObjectDB self)
{
if (SceneManager.GetActiveScene().name == "main")
{
UpdateItemHashesSafe(self);
RegisterCustomItems(self);
RegisterCustomRecipes(self);
RegisterCustomStatusEffects(self);
RegisterCustomItemConversions();
}
}
/// <summary>
/// Safely invoke the <see cref="OnItemsRegistered"/> event
/// </summary>
private void InvokeOnItemsRegistered()
{
if (SceneManager.GetActiveScene().name == "main")
{
OnItemsRegistered?.SafeInvoke();
}
}
/// <summary>
/// Hook on <see cref="Player.OnSpawned"/> to refresh recipes for the custom items.
/// </summary>
/// <param name="self"></param>
private void ReloadKnownRecipes(Player self)
{
if (Items.Count > 0 || Recipes.Count > 0)
{
try
{
self.UpdateKnownRecipesList();
}
catch (Exception ex)
{
Logger.LogWarning($"Exception caught while reloading player recipes: {ex}");
}
}
}
private static void UpdateItemHashesSafe(ObjectDB objectDB)
{
objectDB.m_itemByHash.Clear();
foreach (GameObject item in objectDB.m_items)
{
if (!item)
{
Logger.LogWarning("Found null item in ObjectDB.m_items");
continue;
}
string name = item.name;
int hash = name.GetStableHashCode();
if (objectDB.m_itemByHash.ContainsKey(hash))
{
var mod = ModQuery.GetPrefab(name)?.SourceMod;
Logger.LogWarning(mod, $"Found duplicate item '{name}' ({hash}) in ObjectDB.m_items");
continue;
}
objectDB.m_itemByHash.Add(hash, item);
}
}
}
}